context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.IO.Abstractions; using System.Linq; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Reactive.Threading.Tasks; using NuGet; using ReactiveUIMicro; using Squirrel.Core; // NB: These are whitelisted types from System.IO, so that we always end up // using fileSystem instead. using Squirrel.Core.Extensions; using FileAccess = System.IO.FileAccess; using FileMode = System.IO.FileMode; using MemoryStream = System.IO.MemoryStream; using Path = System.IO.Path; using StreamReader = System.IO.StreamReader; namespace Squirrel.Client { public sealed class UpdateManager : IUpdateManager, IEnableLogger { readonly IRxUIFullLogger log; readonly IFileSystemFactory fileSystem; readonly string rootAppDirectory; readonly string applicationName; readonly IUrlDownloader urlDownloader; readonly string updateUrlOrPath; readonly FrameworkVersion appFrameworkVersion; IDisposable updateLock; public UpdateManager(string urlOrPath, string applicationName, FrameworkVersion appFrameworkVersion, string rootDirectory = null, IFileSystemFactory fileSystem = null, IUrlDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); // XXX: ALWAYS BE LOGGING log = new WrappingFullLogger(new FileLogger(applicationName), typeof(UpdateManager)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName; this.appFrameworkVersion = appFrameworkVersion; this.rootAppDirectory = Path.Combine(rootDirectory ?? getLocalAppDataDirectory(), applicationName); this.fileSystem = fileSystem ?? AnonFileSystem.Default; this.urlDownloader = urlDownloader ?? new DirectUrlDownloader(fileSystem); } public string PackageDirectory { get { return Path.Combine(rootAppDirectory, "packages"); } } public string LocalReleaseFile { get { return Path.Combine(PackageDirectory, "RELEASES"); } } public IObservable<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, IObserver<int> progress = null) { return acquireUpdateLock().SelectMany(_ => checkForUpdate(ignoreDeltaUpdates, progress)); } IObservable<UpdateInfo> checkForUpdate(bool ignoreDeltaUpdates = false, IObserver<int> progress = null) { var localReleases = Enumerable.Empty<ReleaseEntry>(); progress = progress ?? new Subject<int>(); try { var file = fileSystem.GetFileInfo(LocalReleaseFile).OpenRead(); // NB: sr disposes file using (var sr = new StreamReader(file, Encoding.UTF8)) { localReleases = ReleaseEntry.ParseReleaseFile(sr.ReadToEnd()); } } catch (Exception ex) { // Something has gone wrong, we'll start from scratch. log.WarnException("Failed to load local release list", ex); initializeClientAppDirectory(); } IObservable<string> releaseFile; // Fetch the remote RELEASES file, whether it's a local dir or an // HTTP URL try { if (isHttpUrl(updateUrlOrPath)) { log.Info("Downloading RELEASES file from {0}", updateUrlOrPath); releaseFile = urlDownloader.DownloadUrl(String.Format("{0}/{1}", updateUrlOrPath, "RELEASES"), progress); } else { log.Info("Reading RELEASES file from {0}", updateUrlOrPath); if (!fileSystem.GetDirectoryInfo(updateUrlOrPath).Exists) { var message = String.Format( "The directory {0} does not exist, something is probably broken with your application", updateUrlOrPath); var ex = new SquirrelConfigurationException(message); return Observable.Throw<UpdateInfo>(ex); } var fi = fileSystem.GetFileInfo(Path.Combine(updateUrlOrPath, "RELEASES")); if (!fi.Exists) { var message = String.Format( "The file {0} does not exist, something is probably broken with your application", fi.FullName); log.Warn(message); var packages = fileSystem.GetDirectoryInfo(updateUrlOrPath).GetFiles("*.nupkg"); if (packages.Length == 0) { var ex = new SquirrelConfigurationException(message); return Observable.Throw<UpdateInfo>(ex); } // NB: Create a new RELEASES file since we've got a directory of packages ReleaseEntry.WriteReleaseFile( packages.Select(x => ReleaseEntry.GenerateFromFile(x.FullName)), fi.FullName); } using (var sr = new StreamReader(fi.OpenRead(), Encoding.UTF8)) { var text = sr.ReadToEnd(); releaseFile = Observable.Return(text); } progress.OnNext(100); progress.OnCompleted(); } } catch (Exception ex) { progress.OnCompleted(); return Observable.Throw<UpdateInfo>(ex); } var ret = releaseFile .Select(ReleaseEntry.ParseReleaseFile) .SelectMany(releases => determineUpdateInfo(localReleases, releases, ignoreDeltaUpdates)) .PublishLast(); ret.Connect(); return ret; } public IObservable<Unit> DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, IObserver<int> progress = null) { return acquireUpdateLock().SelectMany(_ => downloadReleases(releasesToDownload, progress)); } IObservable<Unit> downloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, IObserver<int> progress = null) { progress = progress ?? new Subject<int>(); IObservable<Unit> downloadResult = null; if (isHttpUrl(updateUrlOrPath)) { var urls = releasesToDownload.Select(x => String.Format("{0}/{1}", updateUrlOrPath, x.Filename)); var paths = releasesToDownload.Select(x => Path.Combine(rootAppDirectory, "packages", x.Filename)); downloadResult = urlDownloader.QueueBackgroundDownloads(urls, paths, progress); } else { var toIncrement = 100.0 / releasesToDownload.Count(); // Do a parallel copy from the remote directory to the local var downloads = releasesToDownload.ToObservable() .Select(x => fileSystem.CopyAsync( Path.Combine(updateUrlOrPath, x.Filename), Path.Combine(rootAppDirectory, "packages", x.Filename))) .Merge(4) .Publish(); downloads .Scan(0.0, (acc, _) => acc + toIncrement) .Select(x => (int) x) .Subscribe(progress); downloadResult = downloads.TakeLast(1); downloads.Connect(); } return downloadResult.SelectMany(_ => checksumAllPackages(releasesToDownload)); } public IObservable<List<string>> ApplyReleases(UpdateInfo updateInfo, IObserver<int> progress = null) { progress = progress ?? new Subject<int>(); // NB: It's important that we update the local releases file *only* // once the entire operation has completed, even though we technically // could do it after DownloadUpdates finishes. We do this so that if // we get interrupted / killed during this operation, we'll start over return Observable.Using(_ => acquireUpdateLock().ToTask(), (dontcare, ct) => { var obs = cleanDeadVersions(updateInfo.CurrentlyInstalledVersion != null ? updateInfo.CurrentlyInstalledVersion.Version : null) .Do(_ => progress.OnNext(10)) .SelectMany(_ => createFullPackagesFromDeltas(updateInfo.ReleasesToApply, updateInfo.CurrentlyInstalledVersion)) .Do(_ => progress.OnNext(50)) .Select(release => installPackageToAppDir(updateInfo, release)) .Do(_ => progress.OnNext(95)) .SelectMany(ret => UpdateLocalReleasesFile().Select(_ => ret)) .Finally(() => progress.OnCompleted()) .PublishLast(); obs.Connect(); // NB: This overload of Using is high as a kite. var tcs = new TaskCompletionSource<IObservable<List<string>>>(); tcs.SetResult(obs); return tcs.Task; }); } public IObservable<Unit> UpdateLocalReleasesFile() { return acquireUpdateLock().SelectMany(_ => Observable.Start(() => ReleaseEntry.BuildReleasesFile(PackageDirectory, fileSystem), RxApp.TaskpoolScheduler)); } public IObservable<Unit> FullUninstall(Version version = null) { version = version ?? new Version(255, 255, 255, 255); log.Info("Uninstalling version '{0}'", version); return acquireUpdateLock().SelectMany(_ => fullUninstall(version)); } IEnumerable<DirectoryInfoBase> getReleases() { var rootDirectory = fileSystem.GetDirectoryInfo(rootAppDirectory); if (!rootDirectory.Exists) return Enumerable.Empty<DirectoryInfoBase>(); return rootDirectory.GetDirectories() .Where(x => x.Name.StartsWith("app-", StringComparison.InvariantCultureIgnoreCase)); } IEnumerable<DirectoryInfoBase> getOldReleases(Version version) { return getReleases() .Where(x => x.Name.ToVersion() < version) .ToArray(); } IObservable<Unit> fullUninstall(Version version) { // find all the old releases (and this one) return getOldReleases(version) .Concat(new [] { getDirectoryForRelease(version) }) .Where(d => d.Exists) .OrderBy(d => d.Name) .Select(d => d.FullName) .ToObservable() .SelectMany(dir => { // cleanup each version runAppCleanup(dir); runAppUninstall(dir); // and then force a delete on each folder return Utility.DeleteDirectory(dir) .Catch<Unit, Exception>(ex => { var message = String.Format("Uninstall failed to delete dir '{0}', punting to next reboot", dir); log.WarnException(message, ex); return Observable.Start( () => Utility.DeleteDirectoryAtNextReboot(rootAppDirectory)); }); }) .Aggregate(Unit.Default, (acc, x) => acc) .SelectMany(_ => { // if there are no other relases found // delete the root directory too if (!getReleases().Any()) { return Utility.DeleteDirectory(rootAppDirectory); } return Observable.Return(Unit.Default); }); } public void Dispose() { var disp = Interlocked.Exchange(ref updateLock, null); if (disp != null) { disp.Dispose(); } } ~UpdateManager() { if (updateLock != null) { throw new Exception("You must dispose UpdateManager!"); } } IObservable<IDisposable> acquireUpdateLock() { if (updateLock != null) return Observable.Return(updateLock); return Observable.Start(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); IDisposable theLock; try { theLock = RxApp.InUnitTestRunner() ? Disposable.Empty : new SingleGlobalInstance(key, 2000); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; }); } static string getLocalAppDataDirectory() { return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } DirectoryInfoBase getDirectoryForRelease(Version releaseVersion) { return fileSystem.GetDirectoryInfo(Path.Combine(rootAppDirectory, "app-" + releaseVersion)); } // // CheckForUpdate methods // void initializeClientAppDirectory() { // On bootstrap, we won't have any of our directories, create them var pkgDir = Path.Combine(rootAppDirectory, "packages"); if (fileSystem.GetDirectoryInfo(pkgDir).Exists) { fileSystem.DeleteDirectoryRecursive(pkgDir); } fileSystem.CreateDirectoryRecursive(pkgDir); } IObservable<UpdateInfo> determineUpdateInfo(IEnumerable<ReleaseEntry> localReleases, IEnumerable<ReleaseEntry> remoteReleases, bool ignoreDeltaUpdates) { localReleases = localReleases ?? Enumerable.Empty<ReleaseEntry>(); if (remoteReleases == null) { log.Warn("Release information couldn't be determined due to remote corrupt RELEASES file"); return Observable.Throw<UpdateInfo>(new Exception("Corrupt remote RELEASES file")); } if (localReleases.Count() == remoteReleases.Count()) { log.Info("No updates, remote and local are the same"); var latestFullRelease = findCurrentVersion(remoteReleases); var currentRelease = findCurrentVersion(localReleases); var info = UpdateInfo.Create(currentRelease, new[] {latestFullRelease}, PackageDirectory,appFrameworkVersion); return Observable.Return(info); } if (ignoreDeltaUpdates) { remoteReleases = remoteReleases.Where(x => !x.IsDelta); } if (!localReleases.Any()) { log.Warn("First run or local directory is corrupt, starting from scratch"); var latestFullRelease = findCurrentVersion(remoteReleases); return Observable.Return(UpdateInfo.Create(findCurrentVersion(localReleases), new[] {latestFullRelease}, PackageDirectory, appFrameworkVersion)); } if (localReleases.Max(x => x.Version) > remoteReleases.Max(x => x.Version)) { log.Warn("hwhat, local version is greater than remote version"); var latestFullRelease = findCurrentVersion(remoteReleases); return Observable.Return(UpdateInfo.Create(findCurrentVersion(localReleases), new[] {latestFullRelease}, PackageDirectory, appFrameworkVersion)); } return Observable.Return(UpdateInfo.Create(findCurrentVersion(localReleases), remoteReleases, PackageDirectory, appFrameworkVersion)); } static ReleaseEntry findCurrentVersion(IEnumerable<ReleaseEntry> localReleases) { if (!localReleases.Any()) { return null; } return localReleases.MaxBy(x => x.Version).SingleOrDefault(x => !x.IsDelta); } // // DownloadReleases methods // static bool isHttpUrl(string urlOrPath) { try { var url = new Uri(urlOrPath); return new[] {"https", "http"}.Contains(url.Scheme.ToLowerInvariant()); } catch (Exception) { return false; } } IObservable<Unit> checksumAllPackages(IEnumerable<ReleaseEntry> releasesDownloaded) { return releasesDownloaded .MapReduce(x => Observable.Start(() => checksumPackage(x))) .Select(_ => Unit.Default); } void checksumPackage(ReleaseEntry downloadedRelease) { var targetPackage = fileSystem.GetFileInfo( Path.Combine(rootAppDirectory, "packages", downloadedRelease.Filename)); if (!targetPackage.Exists) { log.Error("File {0} should exist but doesn't", targetPackage.FullName); throw new Exception("Checksummed file doesn't exist: " + targetPackage.FullName); } if (targetPackage.Length != downloadedRelease.Filesize) { log.Error("File Length should be {0}, is {1}", downloadedRelease.Filesize, targetPackage.Length); targetPackage.Delete(); throw new Exception("Checksummed file size doesn't match: " + targetPackage.FullName); } using (var file = targetPackage.OpenRead()) { var hash = Utility.CalculateStreamSHA1(file); if (!hash.Equals(downloadedRelease.SHA1,StringComparison.OrdinalIgnoreCase)) { log.Error("File SHA1 should be {0}, is {1}", downloadedRelease.SHA1, hash); targetPackage.Delete(); throw new Exception("Checksum doesn't match: " + targetPackage.FullName); } } } // // ApplyReleases methods // List<string> installPackageToAppDir(UpdateInfo updateInfo, ReleaseEntry release) { var pkg = new ZipPackage(Path.Combine(updateInfo.PackageDirectory, release.Filename)); var target = getDirectoryForRelease(release.Version); // NB: This might happen if we got killed partially through applying the release if (target.Exists) { Utility.DeleteDirectory(target.FullName).Wait(); } target.Create(); // Copy all of the files out of the lib/ dirs in the NuGet package // into our target App directory. // // NB: We sort this list in order to guarantee that if a Net20 // and a Net40 version of a DLL get shipped, we always end up // with the 4.0 version. log.Info("Writing files to app directory: {0}", target.FullName); pkg.GetLibFiles().Where(x => pathIsInFrameworkProfile(x, appFrameworkVersion)) .OrderBy(x => x.Path) .ForEach(x => CopyFileToLocation(target, x)); pkg.GetContentFiles().ForEach(x => CopyFileToLocation(target, x)); var newCurrentVersion = updateInfo.FutureReleaseEntry.Version; // Perform post-install; clean up the previous version by asking it // which shortcuts to install, and nuking them. Then, run the app's // post install and set up shortcuts. return runPostInstallAndCleanup(newCurrentVersion, updateInfo.IsBootstrapping); } void CopyFileToLocation(FileSystemInfoBase target, IPackageFile x) { var targetPath = Path.Combine(target.FullName, x.EffectivePath); var fi = fileSystem.GetFileInfo(targetPath); if (fi.Exists) fi.Delete(); var dir = fileSystem.GetDirectoryInfo(Path.GetDirectoryName(targetPath)); if (!dir.Exists) dir.Create(); using (var inf = x.GetStream()) using (var of = fi.Open(FileMode.CreateNew, FileAccess.Write)) { inf.CopyTo(of); } } List<string> runPostInstallAndCleanup(Version newCurrentVersion, bool isBootstrapping) { log.Debug("AppDomain ID: {0}", AppDomain.CurrentDomain.Id); fixPinnedExecutables(newCurrentVersion); log.Info("runPostInstallAndCleanup: finished fixPinnedExecutables"); var shortcutsToIgnore = cleanUpOldVersions(newCurrentVersion); var targetPath = getDirectoryForRelease(newCurrentVersion); return runPostInstallOnDirectory(targetPath.FullName, isBootstrapping, newCurrentVersion, shortcutsToIgnore); } List<string> runPostInstallOnDirectory(string newAppDirectoryRoot, bool isFirstInstall, Version newCurrentVersion, IEnumerable<ShortcutCreationRequest> shortcutRequestsToIgnore) { var postInstallInfo = new PostInstallInfo { NewAppDirectoryRoot = newAppDirectoryRoot, IsFirstInstall = isFirstInstall, NewCurrentVersion = newCurrentVersion, ShortcutRequestsToIgnore = shortcutRequestsToIgnore.ToArray() }; var installerHooks = new InstallerHookOperations(fileSystem, applicationName); return AppDomainHelper.ExecuteInNewAppDomain(postInstallInfo, installerHooks.RunAppSetupInstallers).ToList(); } static bool pathIsInFrameworkProfile(IPackageFile packageFile, FrameworkVersion appFrameworkVersion) { if (!packageFile.Path.StartsWith("lib", StringComparison.InvariantCultureIgnoreCase)) { return false; } if (appFrameworkVersion == FrameworkVersion.Net40 && packageFile.Path.StartsWith("lib\\net45", StringComparison.InvariantCultureIgnoreCase)) { return false; } return true; } IObservable<ReleaseEntry> createFullPackagesFromDeltas(IEnumerable<ReleaseEntry> releasesToApply, ReleaseEntry currentVersion) { Contract.Requires(releasesToApply != null); // If there are no deltas in our list, we're already done if (!releasesToApply.Any() || releasesToApply.All(x => !x.IsDelta)) { return Observable.Return(releasesToApply.MaxBy(x => x.Version).First()); } if (!releasesToApply.All(x => x.IsDelta)) { return Observable.Throw<ReleaseEntry>(new Exception("Cannot apply combinations of delta and full packages")); } // Smash together our base full package and the nearest delta var ret = Observable.Start(() => { var basePkg = new ReleasePackage(Path.Combine(rootAppDirectory, "packages", currentVersion.Filename)); var deltaPkg = new ReleasePackage(Path.Combine(rootAppDirectory, "packages", releasesToApply.First().Filename)); var deltaBuilder = new DeltaPackageBuilder(); return deltaBuilder.ApplyDeltaPackage(basePkg, deltaPkg, Regex.Replace(deltaPkg.InputPackageFile, @"-delta.nupkg$", ".nupkg", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)); }, RxApp.TaskpoolScheduler); if (releasesToApply.Count() == 1) { return ret.Select(x => ReleaseEntry.GenerateFromFile(x.InputPackageFile)); } return ret.SelectMany(x => { var fi = fileSystem.GetFileInfo(x.InputPackageFile); var entry = ReleaseEntry.GenerateFromFile(fi.OpenRead(), fi.Name); // Recursively combine the rest of them return createFullPackagesFromDeltas(releasesToApply.Skip(1), entry); }); } IEnumerable<ShortcutCreationRequest> cleanUpOldVersions(Version newCurrentVersion) { var directory = fileSystem.GetDirectoryInfo(rootAppDirectory); if (!directory.Exists) { log.Warn("cleanUpOldVersions: the directory '{0}' does not exist", rootAppDirectory); return Enumerable.Empty<ShortcutCreationRequest>(); } return getOldReleases(newCurrentVersion) .OrderBy(x => x.Name) .Select(d => d.FullName) .SelectMany(runAppCleanup); } IEnumerable<ShortcutCreationRequest> runAppCleanup(string path) { var installerHooks = new InstallerHookOperations(fileSystem, applicationName); var ret = AppDomainHelper.ExecuteInNewAppDomain(path, installerHooks.RunAppSetupCleanups); try { Utility.DeleteDirectoryAtNextReboot(path); } catch (Exception ex) { var message = String.Format("Couldn't delete old app directory on next reboot {0}", path); log.WarnException(message, ex); } return ret; } IEnumerable<ShortcutCreationRequest> runAppUninstall(string path) { var installerHooks = new InstallerHookOperations(fileSystem, applicationName); var ret = AppDomainHelper.ExecuteInNewAppDomain(path, installerHooks.RunAppUninstall); try { Utility.DeleteDirectoryAtNextReboot(path); } catch (Exception ex) { var message = String.Format("Couldn't delete old app directory on next reboot {0}", path); log.WarnException(message, ex); } return ret; } void fixPinnedExecutables(Version newCurrentVersion) { if (Environment.OSVersion.Version < new Version(6, 1)) { log.Warn("fixPinnedExecutables: Found OS Version '{0}', exiting...", Environment.OSVersion.VersionString); return; } var newCurrentFolder = "app-" + newCurrentVersion; var oldAppDirectories = fileSystem.GetDirectoryInfo(rootAppDirectory).GetDirectories() .Where(x => x.Name.StartsWith("app-", StringComparison.InvariantCultureIgnoreCase)) .Where(x => x.Name != newCurrentFolder) .Select(x => x.FullName) .ToArray(); if (!oldAppDirectories.Any()) { log.Info("fixPinnedExecutables: oldAppDirectories is empty, this is pointless"); return; } var newAppPath = Path.Combine(rootAppDirectory, newCurrentFolder); var taskbarPath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar"); Func<FileInfoBase, ShellLink> resolveLink = file => { try { return new ShellLink(file.FullName); } catch (Exception ex) { var message = String.Format("File '{0}' could not be converted into a valid ShellLink", file.FullName); log.WarnException(message, ex); return null; } }; var shellLinks = fileSystem.GetDirectoryInfo(taskbarPath) .GetFiles("*.lnk") .Select(resolveLink) .Where(x => x != null) .ToArray(); foreach (var shortcut in shellLinks) { try { updateLink(shortcut, oldAppDirectories, newAppPath); } catch (Exception ex) { var message = String.Format("fixPinnedExecutables: shortcut failed: {0}", shortcut.Target); log.ErrorException(message, ex); } } } void updateLink(ShellLink shortcut, string[] oldAppDirectories, string newAppPath) { log.Info("Processing shortcut '{0}'", shortcut.Target); foreach (var oldAppDirectory in oldAppDirectories) { if (!shortcut.Target.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase)) { log.Info("Does not match '{0}', continuing to next directory", oldAppDirectory); continue; } // replace old app path with new app path and check, if executable still exists var newTarget = Path.Combine(newAppPath, shortcut.Target.Substring(oldAppDirectory.Length + 1)); if (fileSystem.GetFileInfo(newTarget).Exists) { shortcut.Target = newTarget; // replace working directory too if appropriate if (shortcut.WorkingDirectory.StartsWith(oldAppDirectory, StringComparison.OrdinalIgnoreCase)) { log.Info("Changing new directory to '{0}'", newAppPath); shortcut.WorkingDirectory = Path.Combine(newAppPath, shortcut.WorkingDirectory.Substring(oldAppDirectory.Length + 1)); } shortcut.Save(); } else { log.Info("Unpinning {0} from taskbar", shortcut.Target); TaskbarHelper.UnpinFromTaskbar(shortcut.Target); } break; } } // NB: Once we uninstall the old version of the app, we try to schedule // it to be deleted at next reboot. Unfortunately, depending on whether // the user has admin permissions, this can fail. So as a failsafe, // before we try to apply any update, we assume previous versions in the // directory are "dead" (i.e. already uninstalled, but not deleted), and // we blow them away. This is to make sure that we don't attempt to run // an uninstaller on an already-uninstalled version. IObservable<Unit> cleanDeadVersions(Version currentVersion) { if (currentVersion == null) return Observable.Return(Unit.Default); var di = fileSystem.GetDirectoryInfo(rootAppDirectory); if (!di.Exists) return Observable.Return(Unit.Default); log.Info("cleanDeadVersions: for version {0}", currentVersion); string currentVersionFolder = null; if (currentVersion != null) { currentVersionFolder = getDirectoryForRelease(currentVersion).Name; log.Info("cleanDeadVersions: exclude folder {0}", currentVersionFolder); } // NB: If we try to access a directory that has already been // scheduled for deletion by MoveFileEx it throws what seems like // NT's only error code, ERROR_ACCESS_DENIED. Squelch errors that // come from here. return di.GetDirectories().ToObservable() .Where(x => x.Name.ToLowerInvariant().Contains("app-")) .Where(x => x.Name != currentVersionFolder) .SelectMany(x => Utility.DeleteDirectory(x.FullName, RxApp.TaskpoolScheduler)) .LoggedCatch<Unit, UpdateManager, UnauthorizedAccessException>(this, _ => Observable.Return(Unit.Default)) .Aggregate(Unit.Default, (acc, x) => acc); } } }
using System; using System.IO; using System.Collections.Generic; using System.Xml.Serialization; using Microsoft.Extensions.Logging; using Server.BuildConfig; using Server.Runtime; using System.Text; using System.Linq; using Server.Services.Stats; namespace Server.Services { public class StatService : IService { public string ContainerPath { get; private set; } ILogger _logger; BuildServer _server; BuildProcess _process; StatContainer _container; bool _skipShortTasks; public StatService(string containerPath, LoggerFactory loggerFactory, bool skipShortTasks) { ContainerPath = containerPath; _logger = loggerFactory.CreateLogger<StatService>(); _skipShortTasks = skipShortTasks; } public bool TryInit(BuildServer server, Project project) { _server = server; _server.OnInitBuild += OnInitBuild; _server.AddCommand("stats", "show builds stats (build count, min, max, average build times)", OnStatsRequested); _server.AddCommand("history", "show builds history (last completed builds list)", OnHistoryRequested); LoadContainer(); _logger.LogDebug($"Container: {_container.Builds.Count} builds"); return true; } XmlSerializer CreateSerializer() { return XmlSerializer.FromTypes(new[] { typeof(StatContainer) })[0]; } void LoadContainer() { if ( !File.Exists(ContainerPath) ) { _container = new StatContainer(); _logger.LogDebug($"Not found stat file at '{ContainerPath}', initialize as empty."); return; } var serializer = CreateSerializer(); using ( var stream = new FileStream(ContainerPath, FileMode.OpenOrCreate) ) { try { _container = serializer.Deserialize(stream) as StatContainer; } catch (Exception e) { _logger.LogError($"Can't load stat file from '{ContainerPath}': \"{e}\""); _container = new StatContainer(); } } } void SaveContainer() { _logger.LogDebug("SaveContainer"); var serializer = CreateSerializer(); using ( var stream = new FileStream(ContainerPath, FileMode.OpenOrCreate) ) { try { serializer.Serialize(stream, _container); } catch ( Exception e ) { _logger.LogError($"Can't save stat file to '{ContainerPath}': \"{e}\""); } } } private void OnInitBuild(RequestContext _, BuildProcess process) { _logger.LogDebug("OnInitBuild"); _process = process; process.BuildDone += OnBuildDone; } private void OnBuildDone() { if ( _process != null ) { _logger.LogDebug($"OnBuildDone: {_process.Name}: {_process.IsSuccess}"); _process.BuildDone -= OnBuildDone; if ( _process.IsSuccess ) { AddBuildStat(_process); SaveContainer(); } } } void AddBuildStat(BuildProcess process) { var stat = new BuildStat(process.Name, _server.FindCurrentBuildArgs(), process.StartTime, process.WorkTime); foreach ( var task in process.Tasks ) { stat.Tasks.Add(new TaskStat(task.Node.Name, task.StartTime, task.EndTime - task.StartTime)); } _container.Builds.Add(stat); } void OnStatsRequested(RequestContext context, RequestArgs args) { _logger.LogDebug($"OnStatsRequested ({args.Count})"); var sb = new StringBuilder(); string buildName = args.Count > 0 ? args[0] : null; sb.Append(buildName == null ? "Stats:\n" : $"Stats ({buildName}):\n"); var table = new StatTable(); FormatStatHeader(table); AppendBuildStats(_container.Builds, buildName, table, buildName != null); table.Append(sb); _server.RaiseCommonMessage(context, sb.ToString()); } void OnHistoryRequested(RequestContext context, RequestArgs args) { _logger.LogDebug($"OnHistoryRequested: ({args.Count})"); var sb = new StringBuilder(); string buildName = args.Count > 0 ? args[0] : null; sb.Append(buildName == null ? "History:\n" : $"History ({buildName}):\n"); var table = new StatTable(); FormatHistoryHeader(table); AppendHistoryStats(_container.Builds, buildName, table); table.Append(sb); _server.RaiseCommonMessage(context, sb.ToString()); } void FormatStatHeader(StatTable table) { table.AddNewRow("BUILD", "COUNT", "MIN", "MAX", "AVG", "LAST"); } void FormatHistoryHeader(StatTable table) { table.AddNewRow("BUILD", "ARGS", "DATE", "DURATION"); } void AppendBuildStats(List<BuildStat> stats, string name, StatTable table, bool withTaskDetails) { if ( string.IsNullOrEmpty(name) ) { var builds = _server.FindBuilds(); foreach ( var buildName in builds.Keys ) { var statsByName = stats.FindAll(s => IsSameName(s, buildName)); _logger.LogDebug($"Stats for {buildName}: {statsByName.Count}"); AppendBuildStats(statsByName, buildName, table, withTaskDetails); } return; } if ( stats.Count > 0 ) { var statsByName = stats.FindAll(s => IsSameName(s, name)); AppendCommonBuildStats(statsByName, name, table); if ( withTaskDetails ) { AppendBuildTaskStats(statsByName, table); } } } void AppendHistoryStats(List<BuildStat> stats, string buildName, StatTable table) { var actualStats = string.IsNullOrEmpty(buildName) ? stats : stats.FindAll(s => IsSameName(s, buildName)); foreach ( var stat in actualStats ) { var name = stat.Name; var args = stat.Args; var date = stat.Start; var duration = stat.Duration; table.AddNewRow(name, FormatArgs(args), date.ToShortDateString(), Utils.FormatTimeSpan(duration)); } } string FormatArgs(List<DictItem> items) { var str = ""; foreach ( var item in items ) { str += $"{item.Key}:{item.Value}"; } return str; } void AppendCommonInfo<T>(List<T> stats, string name, StatTable table) where T : ICommonStat { table.AddNewRow(name); table.AddToRow(stats.Count.ToString()); if ( stats.Count > 1 ) { var history = new List<T>(stats); history.Reverse(); history = history.Skip(1).ToList(); var min = history.Min(s => s.Duration.TotalSeconds); var max = history.Max(s => s.Duration.TotalSeconds); var avg = history.Average(s => s.Duration.TotalSeconds); table.AddToRow(Utils.FormatSeconds(min), Utils.FormatSeconds(max), Utils.FormatSeconds(avg)); } else { table.AddToRow("", "", ""); } var last = stats.Last().Duration.TotalSeconds; table.AddToRow(Utils.FormatSeconds(last)); } void AppendCommonBuildStats(List<BuildStat> stats, string name, StatTable table) { AppendCommonInfo(stats, name, table); } void AppendBuildTaskStats(List<BuildStat> stats, StatTable table) { table.FillNewRow("---"); var tasks = CollectTaskStatsByName(stats); foreach (var taskList in tasks ) { var taskName = taskList.First().Name; AppendCommonInfo(taskList, taskName, table); } } List<List<TaskStat>> CollectTaskStatsByName(List<BuildStat> stats) { var lastBuild = stats.Last(); var tasks = new List<List<TaskStat>>(); var taskMap = new Dictionary<string, List<TaskStat>>(); foreach ( var build in stats ) { foreach ( var task in build.Tasks ) { if ( lastBuild.Tasks.Find(t => t.Name == task.Name) == null ) { continue; } if(_skipShortTasks && (task.Duration.TotalSeconds < 1) ) { continue; } List<TaskStat> taskStats; if ( !taskMap.TryGetValue(task.Name, out taskStats) ) { taskStats = new List<TaskStat>(); tasks.Add(taskStats); taskMap.Add(task.Name, taskStats); } taskStats.Add(task); } } return tasks; } static bool IsSameName(BuildStat stat, string name) { return stat.Name == name; } List<BuildStat> FindBuildsByName(string name) { return _container.Builds.FindAll(b => IsSameName(b, name)); } public bool HasStatistics(string buildName) { return FindBuildsByName(buildName).Count > 0; } public DateTime FindEstimateEndTime(string buildName, DateTime startTime) { var buildStats = FindBuildsByName(buildName); if ( buildStats.Count > 0 ) { var avgDuration = buildStats.Average(b => b.Duration.TotalSeconds); return startTime.AddSeconds(avgDuration); } return DateTime.MinValue; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TwitterSentiment.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 MinInt16() { var test = new SimpleBinaryOpTest__MinInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinInt16 { 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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); 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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinInt16 testClass) { var result = Sse2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinInt16 testClass) { fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Min( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public SimpleBinaryOpTest__MinInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Min( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Min( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Min( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int16>* pClsVar1 = &_clsVar1) fixed (Vector128<Int16>* pClsVar2 = &_clsVar2) { var result = Sse2.Min( Sse2.LoadVector128((Int16*)(pClsVar1)), Sse2.LoadVector128((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinInt16(); var result = Sse2.Min(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__MinInt16(); fixed (Vector128<Int16>* pFld1 = &test._fld1) fixed (Vector128<Int16>* pFld2 = &test._fld2) { var result = Sse2.Min( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int16>* pFld1 = &_fld1) fixed (Vector128<Int16>* pFld2 = &_fld2) { var result = Sse2.Min( Sse2.LoadVector128((Int16*)(pFld1)), Sse2.LoadVector128((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Min( Sse2.LoadVector128((Int16*)(&test._fld1)), Sse2.LoadVector128((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Math.Min(left[0], right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (Math.Min(left[i], right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Int16>(Vector128<Int16>, Vector128<Int16>): {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; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using OpenMetaverse; using log4net; using Nini.Config; using System.Reflection; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.InventoryService; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Server.Base; namespace OpenSim.Services.HypergridService { /// <summary> /// Hypergrid inventory service. It serves the IInventoryService interface, /// but implements it in ways that are appropriate for inter-grid /// inventory exchanges. Specifically, it does not performs deletions /// and it responds to GetRootFolder requests with the ID of the /// Suitcase folder, not the actual "My Inventory" folder. /// </summary> public class HGSuitcaseInventoryService : XInventoryService, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_HomeURL; private IUserAccountService m_UserAccountService; private IAvatarService m_AvatarService; // private UserAccountCache m_Cache; private ExpiringCache<UUID, List<XInventoryFolder>> m_SuitcaseTrees = new ExpiringCache<UUID, List<XInventoryFolder>>(); private ExpiringCache<UUID, AvatarAppearance> m_Appearances = new ExpiringCache<UUID, AvatarAppearance>(); public HGSuitcaseInventoryService(IConfigSource config, string configName) : base(config, configName) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Starting with config name {0}", configName); if (configName != string.Empty) m_ConfigName = configName; if (m_Database == null) m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: m_Database is null!"); // // Try reading the [InventoryService] section, if it exists // IConfig invConfig = config.Configs[m_ConfigName]; if (invConfig != null) { string userAccountsDll = invConfig.GetString("UserAccountsService", string.Empty); if (userAccountsDll == string.Empty) throw new Exception("Please specify UserAccountsService in HGInventoryService configuration"); Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountsDll, args); if (m_UserAccountService == null) throw new Exception(String.Format("Unable to create UserAccountService from {0}", userAccountsDll)); string avatarDll = invConfig.GetString("AvatarService", string.Empty); if (avatarDll == string.Empty) throw new Exception("Please specify AvatarService in HGInventoryService configuration"); m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarDll, args); if (m_AvatarService == null) throw new Exception(String.Format("Unable to create m_AvatarService from {0}", avatarDll)); m_HomeURL = Util.GetConfigVarFromSections<string>(config, "HomeURI", new string[] { "Startup", "Hypergrid", m_ConfigName }, String.Empty); // m_Cache = UserAccountCache.CreateUserAccountCache(m_UserAccountService); } m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Starting..."); } public override bool CreateUserInventory(UUID principalID) { // NOGO return false; } public override List<InventoryFolderBase> GetInventorySkeleton(UUID principalID) { XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); List<XInventoryFolder> tree = GetFolderTree(principalID, suitcase.folderID); if (tree == null || (tree != null && tree.Count == 0)) return null; List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); foreach (XInventoryFolder x in tree) { folders.Add(ConvertToOpenSim(x)); } SetAsNormalFolder(suitcase); folders.Add(ConvertToOpenSim(suitcase)); return folders; } public override InventoryCollection GetUserInventory(UUID userID) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Get Suitcase inventory for user {0}", userID); InventoryCollection userInventory = new InventoryCollection(); userInventory.UserID = userID; userInventory.Folders = new List<InventoryFolderBase>(); userInventory.Items = new List<InventoryItemBase>(); XInventoryFolder suitcase = GetSuitcaseXFolder(userID); List<XInventoryFolder> tree = GetFolderTree(userID, suitcase.folderID); if (tree == null || (tree != null && tree.Count == 0)) { SetAsNormalFolder(suitcase); userInventory.Folders.Add(ConvertToOpenSim(suitcase)); return userInventory; } List<InventoryItemBase> items; foreach (XInventoryFolder f in tree) { // Add the items of this subfolder items = GetFolderItems(userID, f.folderID); if (items != null && items.Count > 0) { userInventory.Items.AddRange(items); } // Add the folder itself userInventory.Folders.Add(ConvertToOpenSim(f)); } items = GetFolderItems(userID, suitcase.folderID); if (items != null && items.Count > 0) { userInventory.Items.AddRange(items); } SetAsNormalFolder(suitcase); userInventory.Folders.Add(ConvertToOpenSim(suitcase)); m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: GetUserInventory for user {0} returning {1} folders and {2} items", userID, userInventory.Folders.Count, userInventory.Items.Count); return userInventory; } public override InventoryFolderBase GetRootFolder(UUID principalID) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: GetRootFolder for {0}", principalID); // Let's find out the local root folder XInventoryFolder root = GetRootXFolder(principalID); ; if (root == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve local root folder for user {0}", principalID); return null; } // Warp! Root folder for travelers is the suitcase folder XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder. Creating it...", principalID); // make one, and let's add it to the user's inventory as a direct child of the root folder // In the DB we tag it as type 100, but we use -1 (Unknown) outside suitcase = CreateFolder(principalID, root.folderID, 100, "My Suitcase"); if (suitcase == null) m_log.ErrorFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to create suitcase folder"); m_Database.StoreFolder(suitcase); // Create System folders CreateSystemFolders(principalID, suitcase.folderID); } SetAsNormalFolder(suitcase); return ConvertToOpenSim(suitcase); } protected void CreateSystemFolders(UUID principalID, UUID rootID) { m_log.Debug("[HG SUITCASE INVENTORY SERVICE]: Creating System folders under Suitcase..."); XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootID); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Animation, "Animations"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Bodypart, "Body Parts"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.CallingCard, "Calling Cards"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Clothing, "Clothing"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Gesture, "Gestures"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Landmark, "Landmarks"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.LostAndFoundFolder, "Lost And Found"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Notecard, "Notecards"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Object, "Objects"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.SnapshotFolder, "Photo Album"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.LSLText, "Scripts"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Sound, "Sounds"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.Texture, "Textures"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.TrashFolder, "Trash"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.FavoriteFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.FavoriteFolder, "Favorites"); if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)AssetType.CurrentOutfitFolder) return true; return false; })) CreateFolder(principalID, rootID, (int)AssetType.CurrentOutfitFolder, "Current Outfit"); } public override InventoryFolderBase GetFolderForType(UUID principalID, AssetType type) { //m_log.DebugFormat("[HG INVENTORY SERVICE]: GetFolderForType for {0} {0}", principalID, type); XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type", "parentFolderID" }, new string[] { principalID.ToString(), ((int)type).ToString(), suitcase.folderID.ToString() }); if (folders.Length == 0) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Found no folder for type {0} for user {1}", type, principalID); return null; } m_log.DebugFormat( "[HG SUITCASE INVENTORY SERVICE]: Found folder {0} {1} for type {2} for user {3}", folders[0].folderName, folders[0].folderID, type, principalID); return ConvertToOpenSim(folders[0]); } public override InventoryCollection GetFolderContent(UUID principalID, UUID folderID) { InventoryCollection coll = null; if (!IsWithinSuitcaseTree(principalID, folderID)) return new InventoryCollection(); coll = base.GetFolderContent(principalID, folderID); if (coll == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: Something wrong with user {0}'s suitcase folder", principalID); coll = new InventoryCollection(); } return coll; } public override List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID) { // Let's do a bit of sanity checking, more than the base service does // make sure the given folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(principalID, folderID)) return new List<InventoryItemBase>(); return base.GetFolderItems(principalID, folderID); } public override bool AddFolder(InventoryFolderBase folder) { //m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: AddFolder {0} {1}", folder.Name, folder.ParentID); // Let's do a bit of sanity checking, more than the base service does // make sure the given folder's parent folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(folder.Owner, folder.ParentID)) return false; // OK, it's legit if (base.AddFolder(folder)) { List<XInventoryFolder> tree; if (m_SuitcaseTrees.TryGetValue(folder.Owner, out tree)) tree.Add(ConvertFromOpenSim(folder)); return true; } return false; } public override bool UpdateFolder(InventoryFolderBase folder) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Update folder {0}, version {1}", folder.ID, folder.Version); if (!IsWithinSuitcaseTree(folder.Owner, folder.ID)) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: folder {0} not within Suitcase tree", folder.Name); return false; } // For all others return base.UpdateFolder(folder); } public override bool MoveFolder(InventoryFolderBase folder) { if (!IsWithinSuitcaseTree(folder.Owner, folder.ID) || !IsWithinSuitcaseTree(folder.Owner, folder.ParentID)) return false; return base.MoveFolder(folder); } public override bool DeleteFolders(UUID principalID, List<UUID> folderIDs) { // NOGO return false; } public override bool PurgeFolder(InventoryFolderBase folder) { // NOGO return false; } public override bool AddItem(InventoryItemBase item) { // Let's do a bit of sanity checking, more than the base service does // make sure the given folder's parent folder exists under the suitcase tree of this user if (!IsWithinSuitcaseTree(item.Owner, item.Folder)) return false; // OK, it's legit return base.AddItem(item); } public override bool UpdateItem(InventoryItemBase item) { if (!IsWithinSuitcaseTree(item.Owner, item.Folder)) return false; return base.UpdateItem(item); } public override bool MoveItems(UUID principalID, List<InventoryItemBase> items) { // Principal is b0rked. *sigh* if (!IsWithinSuitcaseTree(items[0].Owner, items[0].Folder)) return false; return base.MoveItems(principalID, items); } public override bool DeleteItems(UUID principalID, List<UUID> itemIDs) { return false; } public new InventoryItemBase GetItem(InventoryItemBase item) { InventoryItemBase it = base.GetItem(item); if (it == null) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Unable to retrieve item {0} ({1}) in folder {2}", item.Name, item.ID, item.Folder); return null; } if (!IsWithinSuitcaseTree(it.Owner, it.Folder) && !IsPartOfAppearance(it.Owner, it.ID)) { m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: Item {0} (folder {1}) is not within Suitcase", it.Name, it.Folder); return null; } // UserAccount user = m_Cache.GetUser(it.CreatorId); // // Adjust the creator data // if (user != null && it != null && (it.CreatorData == null || it.CreatorData == string.Empty)) // it.CreatorData = m_HomeURL + ";" + user.FirstName + " " + user.LastName; //} return it; } public new InventoryFolderBase GetFolder(InventoryFolderBase folder) { InventoryFolderBase f = base.GetFolder(folder); if (f != null) { if (!IsWithinSuitcaseTree(f.Owner, f.ID)) return null; } return f; } //public List<InventoryItemBase> GetActiveGestures(UUID principalID) //{ //} //public int GetAssetPermissions(UUID principalID, UUID assetID) //{ //} #region Auxiliary functions private XInventoryFolder GetXFolder(UUID userID, UUID folderID) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "folderID" }, new string[] { userID.ToString(), folderID.ToString() }); if (folders.Length == 0) return null; return folders[0]; } private XInventoryFolder GetRootXFolder(UUID principalID) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "type" }, new string[] { principalID.ToString(), "My Inventory", ((int)AssetType.RootFolder).ToString() }); if (folders != null && folders.Length > 0) return folders[0]; // OK, so the RootFolder type didn't work. Let's look for any type with parent UUID.Zero. folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "parentFolderID" }, new string[] { principalID.ToString(), "My Inventory", UUID.Zero.ToString() }); if (folders != null && folders.Length > 0) return folders[0]; return null; } private XInventoryFolder GetSuitcaseXFolder(UUID principalID) { // Warp! Root folder for travelers XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type" }, new string[] { principalID.ToString(), "100" }); // This is a special folder type... if (folders != null && folders.Length > 0) return folders[0]; // check to see if we have the old Suitcase folder folders = m_Database.GetFolders( new string[] { "agentID", "folderName", "parentFolderID" }, new string[] { principalID.ToString(), "My Suitcase", UUID.Zero.ToString() }); if (folders != null && folders.Length > 0) { // Move it to under the root folder XInventoryFolder root = GetRootXFolder(principalID); folders[0].parentFolderID = root.folderID; folders[0].type = 100; m_Database.StoreFolder(folders[0]); return folders[0]; } return null; } private void SetAsNormalFolder(XInventoryFolder suitcase) { suitcase.type = (short)AssetType.Folder; } private List<XInventoryFolder> GetFolderTree(UUID principalID, UUID folder) { List<XInventoryFolder> t = null; if (m_SuitcaseTrees.TryGetValue(principalID, out t)) return t; t = GetFolderTreeRecursive(folder); m_SuitcaseTrees.AddOrUpdate(principalID, t, 5*60); // 5minutes return t; } private List<XInventoryFolder> GetFolderTreeRecursive(UUID root) { List<XInventoryFolder> tree = new List<XInventoryFolder>(); XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "parentFolderID" }, new string[] { root.ToString() }); if (folders == null || (folders != null && folders.Length == 0)) return tree; // empty tree else { foreach (XInventoryFolder f in folders) { tree.Add(f); tree.AddRange(GetFolderTreeRecursive(f.folderID)); } return tree; } } /// <summary> /// Return true if the folderID is a subfolder of the Suitcase or the suitcase folder itself /// </summary> /// <param name="folderID"></param> /// <param name="root"></param> /// <param name="suitcase"></param> /// <returns></returns> private bool IsWithinSuitcaseTree(UUID principalID, UUID folderID) { XInventoryFolder suitcase = GetSuitcaseXFolder(principalID); if (suitcase == null) { m_log.WarnFormat("[HG SUITCASE INVENTORY SERVICE]: User {0} does not have a Suitcase folder", principalID); return false; } List<XInventoryFolder> tree = new List<XInventoryFolder>(); tree.Add(suitcase); // Warp! the tree is the real root folder plus the children of the suitcase folder tree.AddRange(GetFolderTree(principalID, suitcase.folderID)); XInventoryFolder f = tree.Find(delegate(XInventoryFolder fl) { if (fl.folderID == folderID) return true; else return false; }); if (f == null) return false; else return true; } #endregion #region Avatar Appearance private AvatarAppearance GetAppearance(UUID principalID) { AvatarAppearance a = null; if (m_Appearances.TryGetValue(principalID, out a)) return a; a = m_AvatarService.GetAppearance(principalID); m_Appearances.AddOrUpdate(principalID, a, 5 * 60); // 5minutes return a; } private bool IsPartOfAppearance(UUID principalID, UUID itemID) { AvatarAppearance a = GetAppearance(principalID); if (a == null) return false; // Check wearables (body parts and clothes) for (int i = 0; i < a.Wearables.Length; i++) { for (int j = 0; j < a.Wearables[i].Count; j++) { if (a.Wearables[i][j].ItemID == itemID) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is a wearable", itemID); return true; } } } // Check attachments if (a.GetAttachmentForItem(itemID) != null) { //m_log.DebugFormat("[HG SUITCASE INVENTORY SERVICE]: item {0} is an attachment", itemID); return true; } return false; } #endregion } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ComputeNodeOperations operations. /// </summary> public partial interface IComputeNodeOperations { /// <summary> /// Adds a user account to the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to create a user account. /// </param> /// <param name='user'> /// The user account to be created. /// </param> /// <param name='computeNodeAddUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeAddUserHeaders>> AddUserWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeUser user, ComputeNodeAddUserOptions computeNodeAddUserOptions = default(ComputeNodeAddUserOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a user account from the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to delete a user account. /// </param> /// <param name='userName'> /// The name of the user account to delete. /// </param> /// <param name='computeNodeDeleteUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeDeleteUserHeaders>> DeleteUserWithHttpMessagesAsync(string poolId, string nodeId, string userName, ComputeNodeDeleteUserOptions computeNodeDeleteUserOptions = default(ComputeNodeDeleteUserOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the password or expiration time of a user account on the /// specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the machine on which you want to update a user account. /// </param> /// <param name='userName'> /// The name of the user account to update. /// </param> /// <param name='nodeUpdateUserParameter'> /// The parameters for the request. /// </param> /// <param name='computeNodeUpdateUserOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeUpdateUserHeaders>> UpdateUserWithHttpMessagesAsync(string poolId, string nodeId, string userName, NodeUpdateUserParameter nodeUpdateUserParameter, ComputeNodeUpdateUserOptions computeNodeUpdateUserOptions = default(ComputeNodeUpdateUserOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to get information about. /// </param> /// <param name='computeNodeGetOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// 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> Task<AzureOperationResponse<ComputeNode,ComputeNodeGetHeaders>> GetWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeGetOptions computeNodeGetOptions = default(ComputeNodeGetOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Restarts the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeRebootOption'> /// When to reboot the compute node and what to do with currently /// running tasks. The default value is requeue. Possible values /// include: 'requeue', 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeRebootOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeRebootHeaders>> RebootWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?), ComputeNodeRebootOptions computeNodeRebootOptions = default(ComputeNodeRebootOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reinstalls the operating system on the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node that you want to restart. /// </param> /// <param name='nodeReimageOption'> /// When to reimage the compute node and what to do with currently /// running tasks. The default value is requeue. Possible values /// include: 'requeue', 'terminate', 'taskcompletion', 'retaineddata' /// </param> /// <param name='computeNodeReimageOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeReimageHeaders>> ReimageWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeReimageOption? nodeReimageOption = default(ComputeNodeReimageOption?), ComputeNodeReimageOptions computeNodeReimageOptions = default(ComputeNodeReimageOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Disables task scheduling on the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to disable task /// scheduling. /// </param> /// <param name='nodeDisableSchedulingOption'> /// What to do with currently running tasks when disable task /// scheduling on the compute node. The default value is requeue. /// Possible values include: 'requeue', 'terminate', 'taskcompletion' /// </param> /// <param name='computeNodeDisableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeDisableSchedulingHeaders>> DisableSchedulingWithHttpMessagesAsync(string poolId, string nodeId, DisableComputeNodeSchedulingOption? nodeDisableSchedulingOption = default(DisableComputeNodeSchedulingOption?), ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions = default(ComputeNodeDisableSchedulingOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Enables task scheduling on the specified compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node on which you want to enable task /// scheduling. /// </param> /// <param name='computeNodeEnableSchedulingOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<ComputeNodeEnableSchedulingHeaders>> EnableSchedulingWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeEnableSchedulingOptions computeNodeEnableSchedulingOptions = default(ComputeNodeEnableSchedulingOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which to obtain the remote login /// settings. /// </param> /// <param name='computeNodeGetRemoteLoginSettingsOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// 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> Task<AzureOperationResponse<ComputeNodeGetRemoteLoginSettingsResult,ComputeNodeGetRemoteLoginSettingsHeaders>> GetRemoteLoginSettingsWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeGetRemoteLoginSettingsOptions computeNodeGetRemoteLoginSettingsOptions = default(ComputeNodeGetRemoteLoginSettingsOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the Remote Desktop Protocol file for the specified compute /// node. /// </summary> /// <param name='poolId'> /// The id of the pool that contains the compute node. /// </param> /// <param name='nodeId'> /// The id of the compute node for which you want to get the Remote /// Desktop Protocol file. /// </param> /// <param name='computeNodeGetRemoteDesktopOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// 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> Task<AzureOperationResponse<System.IO.Stream,ComputeNodeGetRemoteDesktopHeaders>> GetRemoteDesktopWithHttpMessagesAsync(string poolId, string nodeId, ComputeNodeGetRemoteDesktopOptions computeNodeGetRemoteDesktopOptions = default(ComputeNodeGetRemoteDesktopOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='poolId'> /// The id of the pool from which you want to list nodes. /// </param> /// <param name='computeNodeListOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// 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> Task<AzureOperationResponse<IPage<ComputeNode>,ComputeNodeListHeaders>> ListWithHttpMessagesAsync(string poolId, ComputeNodeListOptions computeNodeListOptions = default(ComputeNodeListOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the compute nodes in the specified pool. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='computeNodeListNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="BatchErrorException"> /// 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> Task<AzureOperationResponse<IPage<ComputeNode>,ComputeNodeListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, ComputeNodeListNextOptions computeNodeListNextOptions = default(ComputeNodeListNextOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// 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.ComponentModel; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project.Automation; namespace Microsoft.VisualStudioTools.Project { [ComVisible(true)] [ClassInterface(ClassInterfaceType.AutoDual)] public class CommonProjectNodeProperties : ProjectNodeProperties, IVsCfgBrowseObject, VSLangProj.ProjectProperties { private OAProjectConfigurationProperties _activeCfgSettings; internal CommonProjectNodeProperties(ProjectNode node) : base(node) { } #region properties /// <summary> /// Returns/Sets the StartupFile project property /// </summary> [SRCategoryAttribute(SR.General)] [SRDisplayName(SR.StartupFile)] [SRDescriptionAttribute(SR.StartupFileDescription)] public string StartupFile { get { return this.Node.Site.GetUIThread().Invoke(() => { var res = this.Node.ProjectMgr.GetProjectProperty(CommonConstants.StartupFile, true); if (res != null && !Path.IsPathRooted(res)) { res = CommonUtils.GetAbsoluteFilePath(this.Node.ProjectMgr.ProjectHome, res); } return res; }); } set { this.Node.Site.GetUIThread().Invoke(() => { this.Node.ProjectMgr.SetProjectProperty( CommonConstants.StartupFile, CommonUtils.GetRelativeFilePath( this.Node.ProjectMgr.ProjectHome, Path.Combine(this.Node.ProjectMgr.ProjectHome, value) ) ); }); } } /// <summary> /// Returns/Sets the WorkingDirectory project property /// </summary> [SRCategoryAttribute(SR.General)] [SRDisplayName(SR.WorkingDirectory)] [SRDescriptionAttribute(SR.WorkingDirectoryDescription)] public string WorkingDirectory { get { return this.Node.Site.GetUIThread().Invoke(() => { return this.Node.ProjectMgr.GetProjectProperty(CommonConstants.WorkingDirectory, true); }); } set { this.Node.Site.GetUIThread().Invoke(() => { this.Node.ProjectMgr.SetProjectProperty(CommonConstants.WorkingDirectory, value); }); } } /// <summary> /// Returns/Sets the PublishUrl project property which is where the project is published to /// </summary> [Browsable(false)] public string PublishUrl { get { return this.Node.Site.GetUIThread().Invoke(() => { return this.Node.ProjectMgr.GetProjectProperty(CommonConstants.PublishUrl, true); }); } set { this.Node.Site.GetUIThread().Invoke(() => { this.Node.ProjectMgr.SetProjectProperty(CommonConstants.PublishUrl, value); }); } } //We don't need this property, but still have to provide it, otherwise //Add New Item wizard (which seems to be unmanaged) fails. [Browsable(false)] public string RootNamespace { get { return ""; } set { //Do nothing } } /// <summary> /// Gets the home directory for the project. /// </summary> [SRCategoryAttribute(SR.Misc)] [SRDisplayName(SR.ProjectHome)] [SRDescriptionAttribute(SR.ProjectHomeDescription)] public string ProjectHome => this.Node.ProjectMgr.ProjectHome; #endregion #region IVsCfgBrowseObject Members int IVsCfgBrowseObject.GetCfg(out IVsCfg ppCfg) { return this.Node.ProjectMgr.ConfigProvider.GetCfgOfName( this.Node.ProjectMgr.CurrentConfig.GetPropertyValue(ProjectFileConstants.Configuration), this.Node.ProjectMgr.CurrentConfig.GetPropertyValue(ProjectFileConstants.Platform), out ppCfg); } #endregion #region ProjectProperties Members [Browsable(false)] public string AbsoluteProjectDirectory => this.Node.ProjectMgr.ProjectFolder; [Browsable(false)] public VSLangProj.ProjectConfigurationProperties ActiveConfigurationSettings { get { if (this._activeCfgSettings == null) { this._activeCfgSettings = new OAProjectConfigurationProperties(this.Node.ProjectMgr); } return this._activeCfgSettings; } } [Browsable(false)] public string ActiveFileSharePath => throw new NotImplementedException(); [Browsable(false)] public VSLangProj.prjWebAccessMethod ActiveWebAccessMethod => throw new NotImplementedException(); [Browsable(false)] public string ApplicationIcon { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string AssemblyKeyContainerName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string AssemblyName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string AssemblyOriginatorKeyFile { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjOriginatorKeyMode AssemblyOriginatorKeyMode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjScriptLanguage DefaultClientScript { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjHTMLPageLayout DefaultHTMLPageLayout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string DefaultNamespace { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjTargetSchema DefaultTargetSchema { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public bool DelaySign { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public new object ExtenderNames => throw new NotImplementedException(); [Browsable(false)] public string FileSharePath { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public bool LinkRepair { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string LocalPath => throw new NotImplementedException(); [Browsable(false)] public string OfflineURL => throw new NotImplementedException(); [Browsable(false)] public VSLangProj.prjCompare OptionCompare { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjOptionExplicit OptionExplicit { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjOptionStrict OptionStrict { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string OutputFileName => throw new NotImplementedException(); [Browsable(false)] public VSLangProj.prjOutputType OutputType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public VSLangProj.prjProjectType ProjectType => throw new NotImplementedException(); [Browsable(false)] public string ReferencePath { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string ServerExtensionsVersion => throw new NotImplementedException(); [Browsable(false)] public string StartupObject { get { return this.Node.Site.GetUIThread().Invoke(() => { return this.Node.ProjectMgr.GetProjectProperty(CommonConstants.StartupFile); }); } set { this.Node.Site.GetUIThread().Invoke(() => { this.Node.ProjectMgr.SetProjectProperty( CommonConstants.StartupFile, CommonUtils.GetRelativeFilePath(this.Node.ProjectMgr.ProjectHome, value) ); }); } } [Browsable(false)] public string URL => CommonUtils.MakeUri(this.Node.ProjectMgr.Url, false, UriKind.Absolute).AbsoluteUri; [Browsable(false)] public VSLangProj.prjWebAccessMethod WebAccessMethod { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } [Browsable(false)] public string WebServer => throw new NotImplementedException(); [Browsable(false)] public string WebServerVersion => throw new NotImplementedException(); [Browsable(false)] public string __id => throw new NotImplementedException(); [Browsable(false)] public object __project => throw new NotImplementedException(); [Browsable(false)] public object get_Extender(string ExtenderName) { throw new NotImplementedException(); } #endregion } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Telephony.Gsm.cs // // 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. #pragma warning disable 1717 namespace Android.Telephony.Gsm { /// <java-name> /// android/telephony/gsm/SmsMessage /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage", AccessFlags = 33)] public partial class SmsMessage /* scope: __dot42__ */ { /// <java-name> /// ENCODING_UNKNOWN /// </java-name> [Dot42.DexImport("ENCODING_UNKNOWN", "I", AccessFlags = 25)] public const int ENCODING_UNKNOWN = 0; /// <java-name> /// ENCODING_7BIT /// </java-name> [Dot42.DexImport("ENCODING_7BIT", "I", AccessFlags = 25)] public const int ENCODING_7BIT = 1; /// <java-name> /// ENCODING_8BIT /// </java-name> [Dot42.DexImport("ENCODING_8BIT", "I", AccessFlags = 25)] public const int ENCODING_8BIT = 2; /// <java-name> /// ENCODING_16BIT /// </java-name> [Dot42.DexImport("ENCODING_16BIT", "I", AccessFlags = 25)] public const int ENCODING_16BIT = 3; /// <java-name> /// MAX_USER_DATA_BYTES /// </java-name> [Dot42.DexImport("MAX_USER_DATA_BYTES", "I", AccessFlags = 25)] public const int MAX_USER_DATA_BYTES = 140; /// <java-name> /// MAX_USER_DATA_SEPTETS /// </java-name> [Dot42.DexImport("MAX_USER_DATA_SEPTETS", "I", AccessFlags = 25)] public const int MAX_USER_DATA_SEPTETS = 160; /// <java-name> /// MAX_USER_DATA_SEPTETS_WITH_HEADER /// </java-name> [Dot42.DexImport("MAX_USER_DATA_SEPTETS_WITH_HEADER", "I", AccessFlags = 25)] public const int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SmsMessage() /* MethodBuilder.Create */ { } /// <java-name> /// createFromPdu /// </java-name> [Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(sbyte[] sByte) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage); } /// <java-name> /// createFromPdu /// </java-name> [Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9, IgnoreFromJava = true)] public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(byte[] @byte) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage); } /// <java-name> /// getTPLayerLengthForPDU /// </java-name> [Dot42.DexImport("getTPLayerLengthForPDU", "(Ljava/lang/String;)I", AccessFlags = 9)] public static int GetTPLayerLengthForPDU(string @string) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// calculateLength /// </java-name> [Dot42.DexImport("calculateLength", "(Ljava/lang/CharSequence;Z)[I", AccessFlags = 9)] public static int[] CalculateLength(global::Java.Lang.ICharSequence charSequence, bool boolean) /* MethodBuilder.Create */ { return default(int[]); } /// <java-name> /// calculateLength /// </java-name> [Dot42.DexImport("calculateLength", "(Ljava/lang/String;Z)[I", AccessFlags = 9)] public static int[] CalculateLength(string @string, bool boolean) /* MethodBuilder.Create */ { return default(int[]); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/gsm/S" + "msMessage$SubmitPdu;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, string string2, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" + "tPdu;", AccessFlags = 9)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, sbyte[] sByte, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getSubmitPdu /// </java-name> [Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" + "tPdu;", AccessFlags = 9, IgnoreFromJava = true)] public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, byte[] @byte, bool boolean) /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu); } /// <java-name> /// getServiceCenterAddress /// </java-name> [Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetServiceCenterAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getOriginatingAddress /// </java-name> [Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetOriginatingAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getDisplayOriginatingAddress /// </java-name> [Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetDisplayOriginatingAddress() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getMessageBody /// </java-name> [Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetMessageBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getMessageClass /// </java-name> [Dot42.DexImport("getMessageClass", "()Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 1)] public virtual global::Android.Telephony.Gsm.SmsMessage.MessageClass GetMessageClass() /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsMessage.MessageClass); } /// <java-name> /// getDisplayMessageBody /// </java-name> [Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetDisplayMessageBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getPseudoSubject /// </java-name> [Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPseudoSubject() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getTimestampMillis /// </java-name> [Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)] public virtual long GetTimestampMillis() /* MethodBuilder.Create */ { return default(long); } /// <java-name> /// isEmail /// </java-name> [Dot42.DexImport("isEmail", "()Z", AccessFlags = 1)] public virtual bool IsEmail() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getEmailBody /// </java-name> [Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetEmailBody() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getEmailFrom /// </java-name> [Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetEmailFrom() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getProtocolIdentifier /// </java-name> [Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)] public virtual int GetProtocolIdentifier() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isReplace /// </java-name> [Dot42.DexImport("isReplace", "()Z", AccessFlags = 1)] public virtual bool IsReplace() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isCphsMwiMessage /// </java-name> [Dot42.DexImport("isCphsMwiMessage", "()Z", AccessFlags = 1)] public virtual bool IsCphsMwiMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMWIClearMessage /// </java-name> [Dot42.DexImport("isMWIClearMessage", "()Z", AccessFlags = 1)] public virtual bool IsMWIClearMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMWISetMessage /// </java-name> [Dot42.DexImport("isMWISetMessage", "()Z", AccessFlags = 1)] public virtual bool IsMWISetMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isMwiDontStore /// </java-name> [Dot42.DexImport("isMwiDontStore", "()Z", AccessFlags = 1)] public virtual bool IsMwiDontStore() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getUserData /// </java-name> [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1)] public virtual sbyte[] JavaGetUserData() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// getUserData /// </java-name> [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public virtual byte[] GetUserData() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// getPdu /// </java-name> [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1)] public virtual sbyte[] JavaGetPdu() /* MethodBuilder.Create */ { return default(sbyte[]); } /// <java-name> /// getPdu /// </java-name> [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)] public virtual byte[] GetPdu() /* MethodBuilder.Create */ { return default(byte[]); } /// <java-name> /// getStatusOnSim /// </java-name> [Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)] public virtual int GetStatusOnSim() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// getIndexOnSim /// </java-name> [Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)] public virtual int GetIndexOnSim() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// getStatus /// </java-name> [Dot42.DexImport("getStatus", "()I", AccessFlags = 1)] public virtual int GetStatus() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// isStatusReportMessage /// </java-name> [Dot42.DexImport("isStatusReportMessage", "()Z", AccessFlags = 1)] public virtual bool IsStatusReportMessage() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// isReplyPathPresent /// </java-name> [Dot42.DexImport("isReplyPathPresent", "()Z", AccessFlags = 1)] public virtual bool IsReplyPathPresent() /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// getServiceCenterAddress /// </java-name> public string ServiceCenterAddress { [Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetServiceCenterAddress(); } } /// <java-name> /// getOriginatingAddress /// </java-name> public string OriginatingAddress { [Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetOriginatingAddress(); } } /// <java-name> /// getDisplayOriginatingAddress /// </java-name> public string DisplayOriginatingAddress { [Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetDisplayOriginatingAddress(); } } /// <java-name> /// getMessageBody /// </java-name> public string MessageBody { [Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetMessageBody(); } } /// <java-name> /// getDisplayMessageBody /// </java-name> public string DisplayMessageBody { [Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetDisplayMessageBody(); } } /// <java-name> /// getPseudoSubject /// </java-name> public string PseudoSubject { [Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPseudoSubject(); } } /// <java-name> /// getTimestampMillis /// </java-name> public long TimestampMillis { [Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)] get{ return GetTimestampMillis(); } } /// <java-name> /// getEmailBody /// </java-name> public string EmailBody { [Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetEmailBody(); } } /// <java-name> /// getEmailFrom /// </java-name> public string EmailFrom { [Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetEmailFrom(); } } /// <java-name> /// getProtocolIdentifier /// </java-name> public int ProtocolIdentifier { [Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)] get{ return GetProtocolIdentifier(); } } /// <java-name> /// getUserData /// </java-name> public byte[] UserData { [Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)] get{ return GetUserData(); } } /// <java-name> /// getPdu /// </java-name> public byte[] Pdu { [Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)] get{ return GetPdu(); } } /// <java-name> /// getStatusOnSim /// </java-name> public int StatusOnSim { [Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)] get{ return GetStatusOnSim(); } } /// <java-name> /// getIndexOnSim /// </java-name> public int IndexOnSim { [Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)] get{ return GetIndexOnSim(); } } /// <java-name> /// getStatus /// </java-name> public int Status { [Dot42.DexImport("getStatus", "()I", AccessFlags = 1)] get{ return GetStatus(); } } /// <java-name> /// android/telephony/gsm/SmsMessage$SubmitPdu /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage$SubmitPdu", AccessFlags = 9)] public partial class SubmitPdu /* scope: __dot42__ */ { /// <java-name> /// encodedScAddress /// </java-name> [Dot42.DexImport("encodedScAddress", "[B", AccessFlags = 1)] public sbyte[] EncodedScAddress; /// <java-name> /// encodedMessage /// </java-name> [Dot42.DexImport("encodedMessage", "[B", AccessFlags = 1)] public sbyte[] EncodedMessage; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public SubmitPdu() /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } } /// <java-name> /// android/telephony/gsm/SmsMessage$MessageClass /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsMessage$MessageClass", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Landroid/telephony/gsm/SmsMessage$MessageClass;>;")] public sealed class MessageClass /* scope: __dot42__ */ { /// <java-name> /// CLASS_0 /// </java-name> [Dot42.DexImport("CLASS_0", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_0; /// <java-name> /// CLASS_1 /// </java-name> [Dot42.DexImport("CLASS_1", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_1; /// <java-name> /// CLASS_2 /// </java-name> [Dot42.DexImport("CLASS_2", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_2; /// <java-name> /// CLASS_3 /// </java-name> [Dot42.DexImport("CLASS_3", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass CLASS_3; /// <java-name> /// UNKNOWN /// </java-name> [Dot42.DexImport("UNKNOWN", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)] public static readonly MessageClass UNKNOWN; private MessageClass() /* TypeBuilder.AddPrivateDefaultCtor */ { } } } /// <summary> /// <para>Represents the cell location on a GSM phone. </para> /// </summary> /// <java-name> /// android/telephony/gsm/GsmCellLocation /// </java-name> [Dot42.DexImport("android/telephony/gsm/GsmCellLocation", AccessFlags = 33)] public partial class GsmCellLocation : global::Android.Telephony.CellLocation /* scope: __dot42__ */ { /// <summary> /// <para>Empty constructor. Initializes the LAC and CID to -1. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public GsmCellLocation() /* MethodBuilder.Create */ { } /// <summary> /// <para>Initialize the object from a bundle. </para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public GsmCellLocation(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getLac /// </java-name> [Dot42.DexImport("getLac", "()I", AccessFlags = 1)] public virtual int GetLac() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getCid /// </java-name> [Dot42.DexImport("getCid", "()I", AccessFlags = 1)] public virtual int GetCid() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para> /// </summary> /// <returns> /// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para> /// </returns> /// <java-name> /// getPsc /// </java-name> [Dot42.DexImport("getPsc", "()I", AccessFlags = 1)] public virtual int GetPsc() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Invalidate this object. The location area code and the cell id are set to -1. </para> /// </summary> /// <java-name> /// setStateInvalid /// </java-name> [Dot42.DexImport("setStateInvalid", "()V", AccessFlags = 1)] public virtual void SetStateInvalid() /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the location area code and the cell id. </para> /// </summary> /// <java-name> /// setLacAndCid /// </java-name> [Dot42.DexImport("setLacAndCid", "(II)V", AccessFlags = 1)] public virtual void SetLacAndCid(int lac, int cid) /* MethodBuilder.Create */ { } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object o) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Set intent notifier Bundle based on service state</para><para></para> /// </summary> /// <java-name> /// fillInNotifierBundle /// </java-name> [Dot42.DexImport("fillInNotifierBundle", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public virtual void FillInNotifierBundle(global::Android.Os.Bundle m) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getLac /// </java-name> public int Lac { [Dot42.DexImport("getLac", "()I", AccessFlags = 1)] get{ return GetLac(); } } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para> /// </returns> /// <java-name> /// getCid /// </java-name> public int Cid { [Dot42.DexImport("getCid", "()I", AccessFlags = 1)] get{ return GetCid(); } } /// <summary> /// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para> /// </summary> /// <returns> /// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para> /// </returns> /// <java-name> /// getPsc /// </java-name> public int Psc { [Dot42.DexImport("getPsc", "()I", AccessFlags = 1)] get{ return GetPsc(); } } } /// <java-name> /// android/telephony/gsm/SmsManager /// </java-name> [Dot42.DexImport("android/telephony/gsm/SmsManager", AccessFlags = 49)] public sealed partial class SmsManager /* scope: __dot42__ */ { /// <java-name> /// STATUS_ON_SIM_FREE /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_FREE", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_FREE = 0; /// <java-name> /// STATUS_ON_SIM_READ /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_READ", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_READ = 1; /// <java-name> /// STATUS_ON_SIM_UNREAD /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_UNREAD", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_UNREAD = 3; /// <java-name> /// STATUS_ON_SIM_SENT /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_SENT", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_SENT = 5; /// <java-name> /// STATUS_ON_SIM_UNSENT /// </java-name> [Dot42.DexImport("STATUS_ON_SIM_UNSENT", "I", AccessFlags = 25)] public const int STATUS_ON_SIM_UNSENT = 7; /// <java-name> /// RESULT_ERROR_GENERIC_FAILURE /// </java-name> [Dot42.DexImport("RESULT_ERROR_GENERIC_FAILURE", "I", AccessFlags = 25)] public const int RESULT_ERROR_GENERIC_FAILURE = 1; /// <java-name> /// RESULT_ERROR_RADIO_OFF /// </java-name> [Dot42.DexImport("RESULT_ERROR_RADIO_OFF", "I", AccessFlags = 25)] public const int RESULT_ERROR_RADIO_OFF = 2; /// <java-name> /// RESULT_ERROR_NULL_PDU /// </java-name> [Dot42.DexImport("RESULT_ERROR_NULL_PDU", "I", AccessFlags = 25)] public const int RESULT_ERROR_NULL_PDU = 3; /// <java-name> /// RESULT_ERROR_NO_SERVICE /// </java-name> [Dot42.DexImport("RESULT_ERROR_NO_SERVICE", "I", AccessFlags = 25)] public const int RESULT_ERROR_NO_SERVICE = 4; [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal SmsManager() /* MethodBuilder.Create */ { } /// <java-name> /// getDefault /// </java-name> [Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)] public static global::Android.Telephony.Gsm.SmsManager GetDefault() /* MethodBuilder.Create */ { return default(global::Android.Telephony.Gsm.SmsManager); } /// <java-name> /// sendTextMessage /// </java-name> [Dot42.DexImport("sendTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent" + ";Landroid/app/PendingIntent;)V", AccessFlags = 17)] public void SendTextMessage(string @string, string string1, string string2, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// divideMessage /// </java-name> [Dot42.DexImport("divideMessage", "(Ljava/lang/String;)Ljava/util/ArrayList;", AccessFlags = 17, Signature = "(Ljava/lang/String;)Ljava/util/ArrayList<Ljava/lang/String;>;")] public global::Java.Util.ArrayList<string> DivideMessage(string @string) /* MethodBuilder.Create */ { return default(global::Java.Util.ArrayList<string>); } /// <java-name> /// sendMultipartTextMessage /// </java-name> [Dot42.DexImport("sendMultipartTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList;Ljava/util/ArrayList;Lj" + "ava/util/ArrayList;)V", AccessFlags = 17, Signature = "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList<Ljava/lang/String;>;Lja" + "va/util/ArrayList<Landroid/app/PendingIntent;>;Ljava/util/ArrayList<Landroid/app" + "/PendingIntent;>;)V")] public void SendMultipartTextMessage(string @string, string string1, global::Java.Util.ArrayList<string> arrayList, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList1, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList2) /* MethodBuilder.Create */ { } /// <java-name> /// sendDataMessage /// </java-name> [Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" + "endingIntent;)V", AccessFlags = 17)] public void SendDataMessage(string @string, string string1, short int16, sbyte[] sByte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// sendDataMessage /// </java-name> [Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" + "endingIntent;)V", AccessFlags = 17, IgnoreFromJava = true)] public void SendDataMessage(string @string, string string1, short int16, byte[] @byte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */ { } /// <java-name> /// getDefault /// </java-name> public static global::Android.Telephony.Gsm.SmsManager Default { [Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)] get{ return GetDefault(); } } } }
// --------------------------------------------------------------------------- // <copyright file="RuleActions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the RuleActions class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System.Collections.ObjectModel; /// <summary> /// Represents the set of actions available for a rule. /// </summary> public sealed class RuleActions : ComplexProperty { /// <summary> /// SMS recipient address type. /// </summary> private const string MobileType = "MOBILE"; /// <summary> /// The AssignCategories action. /// </summary> private StringList assignCategories; /// <summary> /// The CopyToFolder action. /// </summary> private FolderId copyToFolder; /// <summary> /// The Delete action. /// </summary> private bool delete; /// <summary> /// The ForwardAsAttachmentToRecipients action. /// </summary> private EmailAddressCollection forwardAsAttachmentToRecipients; /// <summary> /// The ForwardToRecipients action. /// </summary> private EmailAddressCollection forwardToRecipients; /// <summary> /// The MarkImportance action. /// </summary> private Importance? markImportance; /// <summary> /// The MarkAsRead action. /// </summary> private bool markAsRead; /// <summary> /// The MoveToFolder action. /// </summary> private FolderId moveToFolder; /// <summary> /// The PermanentDelete action. /// </summary> private bool permanentDelete; /// <summary> /// The RedirectToRecipients action. /// </summary> private EmailAddressCollection redirectToRecipients; /// <summary> /// The SendSMSAlertToRecipients action. /// </summary> private Collection<MobilePhone> sendSMSAlertToRecipients; /// <summary> /// The ServerReplyWithMessage action. /// </summary> private ItemId serverReplyWithMessage; /// <summary> /// The StopProcessingRules action. /// </summary> private bool stopProcessingRules; /// <summary> /// Initializes a new instance of the <see cref="RulePredicates"/> class. /// </summary> internal RuleActions() : base() { this.assignCategories = new StringList(); this.forwardAsAttachmentToRecipients = new EmailAddressCollection(XmlElementNames.Address); this.forwardToRecipients = new EmailAddressCollection(XmlElementNames.Address); this.redirectToRecipients = new EmailAddressCollection(XmlElementNames.Address); this.sendSMSAlertToRecipients = new Collection<MobilePhone>(); } /// <summary> /// Gets the categories that should be stamped on incoming messages. /// To disable stamping incoming messages with categories, set /// AssignCategories to null. /// </summary> public StringList AssignCategories { get { return this.assignCategories; } } /// <summary> /// Gets or sets the Id of the folder incoming messages should be copied to. /// To disable copying incoming messages to a folder, set CopyToFolder to null. /// </summary> public FolderId CopyToFolder { get { return this.copyToFolder; } set { this.SetFieldValue<FolderId>(ref this.copyToFolder, value); } } /// <summary> /// Gets or sets a value indicating whether incoming messages should be /// automatically moved to the Deleted Items folder. /// </summary> public bool Delete { get { return this.delete; } set { this.SetFieldValue<bool>(ref this.delete, value); } } /// <summary> /// Gets the e-mail addresses to which incoming messages should be /// forwarded as attachments. To disable forwarding incoming messages /// as attachments, empty the ForwardAsAttachmentToRecipients list. /// </summary> public EmailAddressCollection ForwardAsAttachmentToRecipients { get { return this.forwardAsAttachmentToRecipients; } } /// <summary> /// Gets the e-mail addresses to which incoming messages should be forwarded. /// To disable forwarding incoming messages, empty the ForwardToRecipients list. /// </summary> public EmailAddressCollection ForwardToRecipients { get { return this.forwardToRecipients; } } /// <summary> /// Gets or sets the importance that should be stamped on incoming /// messages. To disable the stamping of incoming messages with an /// importance, set MarkImportance to null. /// </summary> public Importance? MarkImportance { get { return this.markImportance; } set { this.SetFieldValue<Importance?>(ref this.markImportance, value); } } /// <summary> /// Gets or sets a value indicating whether incoming messages should be /// marked as read. /// </summary> public bool MarkAsRead { get { return this.markAsRead; } set { this.SetFieldValue<bool>(ref this.markAsRead, value); } } /// <summary> /// Gets or sets the Id of the folder to which incoming messages should be /// moved. To disable the moving of incoming messages to a folder, set /// CopyToFolder to null. /// </summary> public FolderId MoveToFolder { get { return this.moveToFolder; } set { this.SetFieldValue<FolderId>(ref this.moveToFolder, value); } } /// <summary> /// Gets or sets a value indicating whether incoming messages should be /// permanently deleted. When a message is permanently deleted, it is never /// saved into the recipient's mailbox. To delete a message after it has /// been saved into the recipient's mailbox, use the Delete action. /// </summary> public bool PermanentDelete { get { return this.permanentDelete; } set { this.SetFieldValue<bool>(ref this.permanentDelete, value); } } /// <summary> /// Gets the e-mail addresses to which incoming messages should be /// redirecteded. To disable redirection of incoming messages, empty /// the RedirectToRecipients list. Unlike forwarded mail, redirected mail /// maintains the original sender and recipients. /// </summary> public EmailAddressCollection RedirectToRecipients { get { return this.redirectToRecipients; } } /// <summary> /// Gets the phone numbers to which an SMS alert should be sent. To disable /// sending SMS alerts for incoming messages, empty the /// SendSMSAlertToRecipients list. /// </summary> public Collection<MobilePhone> SendSMSAlertToRecipients { get { return this.sendSMSAlertToRecipients; } } /// <summary> /// Gets or sets the Id of the template message that should be sent /// as a reply to incoming messages. To disable automatic replies, set /// ServerReplyWithMessage to null. /// </summary> public ItemId ServerReplyWithMessage { get { return this.serverReplyWithMessage; } set { this.SetFieldValue<ItemId>(ref this.serverReplyWithMessage, value); } } /// <summary> /// Gets or sets a value indicating whether subsequent rules should be /// evaluated. /// </summary> public bool StopProcessingRules { get { return this.stopProcessingRules; } set { this.SetFieldValue<bool>(ref this.stopProcessingRules, value); } } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.AssignCategories: this.assignCategories.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.CopyToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.copyToFolder = new FolderId(); this.copyToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.CopyToFolder); return true; case XmlElementNames.Delete: this.delete = reader.ReadElementValue<bool>(); return true; case XmlElementNames.ForwardAsAttachmentToRecipients: this.forwardAsAttachmentToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.ForwardToRecipients: this.forwardToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.MarkImportance: this.markImportance = reader.ReadElementValue<Importance>(); return true; case XmlElementNames.MarkAsRead: this.markAsRead = reader.ReadElementValue<bool>(); return true; case XmlElementNames.MoveToFolder: reader.ReadStartElement(XmlNamespace.NotSpecified, XmlElementNames.FolderId); this.moveToFolder = new FolderId(); this.moveToFolder.LoadFromXml(reader, XmlElementNames.FolderId); reader.ReadEndElement(XmlNamespace.NotSpecified, XmlElementNames.MoveToFolder); return true; case XmlElementNames.PermanentDelete: this.permanentDelete = reader.ReadElementValue<bool>(); return true; case XmlElementNames.RedirectToRecipients: this.redirectToRecipients.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.SendSMSAlertToRecipients: EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address); smsRecipientCollection.LoadFromXml(reader, reader.LocalName); this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection); return true; case XmlElementNames.ServerReplyWithMessage: this.serverReplyWithMessage = new ItemId(); this.serverReplyWithMessage.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.StopProcessingRules: this.stopProcessingRules = reader.ReadElementValue<bool>(); return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.AssignCategories: this.assignCategories.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.CopyToFolder: this.copyToFolder = new FolderId(); this.copyToFolder.LoadFromJson( jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.Delete: this.delete = jsonProperty.ReadAsBool(key); break; case XmlElementNames.ForwardAsAttachmentToRecipients: this.forwardAsAttachmentToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.ForwardToRecipients: this.forwardToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.MarkImportance: this.markImportance = jsonProperty.ReadEnumValue<Importance>(key); break; case XmlElementNames.MarkAsRead: this.markAsRead = jsonProperty.ReadAsBool(key); break; case XmlElementNames.MoveToFolder: this.moveToFolder = new FolderId(); this.moveToFolder.LoadFromJson( jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.PermanentDelete: this.permanentDelete = jsonProperty.ReadAsBool(key); break; case XmlElementNames.RedirectToRecipients: this.redirectToRecipients.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.SendSMSAlertToRecipients: EmailAddressCollection smsRecipientCollection = new EmailAddressCollection(XmlElementNames.Address); smsRecipientCollection.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); this.sendSMSAlertToRecipients = ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(smsRecipientCollection); break; case XmlElementNames.ServerReplyWithMessage: this.serverReplyWithMessage = new ItemId(); this.serverReplyWithMessage.LoadFromJson(jsonProperty.ReadAsJsonObject(key), service); break; case XmlElementNames.StopProcessingRules: this.stopProcessingRules = jsonProperty.ReadAsBool(key); break; default: break; } } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { if (this.AssignCategories.Count > 0) { this.AssignCategories.WriteToXml(writer, XmlElementNames.AssignCategories); } if (this.CopyToFolder != null) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.CopyToFolder); this.CopyToFolder.WriteToXml(writer); writer.WriteEndElement(); } if (this.Delete != false) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Delete, this.Delete); } if (this.ForwardAsAttachmentToRecipients.Count > 0) { this.ForwardAsAttachmentToRecipients.WriteToXml(writer, XmlElementNames.ForwardAsAttachmentToRecipients); } if (this.ForwardToRecipients.Count > 0) { this.ForwardToRecipients.WriteToXml(writer, XmlElementNames.ForwardToRecipients); } if (this.MarkImportance.HasValue) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.MarkImportance, this.MarkImportance.Value); } if (this.MarkAsRead != false) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.MarkAsRead, this.MarkAsRead); } if (this.MoveToFolder != null) { writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MoveToFolder); this.MoveToFolder.WriteToXml(writer); writer.WriteEndElement(); } if (this.PermanentDelete != false) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.PermanentDelete, this.PermanentDelete); } if (this.RedirectToRecipients.Count > 0) { this.RedirectToRecipients.WriteToXml(writer, XmlElementNames.RedirectToRecipients); } if (this.SendSMSAlertToRecipients.Count > 0) { EmailAddressCollection emailCollection = ConvertSMSRecipientsFromMobilePhoneCollectionToEmailAddressCollection(this.SendSMSAlertToRecipients); emailCollection.WriteToXml(writer, XmlElementNames.SendSMSAlertToRecipients); } if (this.ServerReplyWithMessage != null) { this.ServerReplyWithMessage.WriteToXml(writer, XmlElementNames.ServerReplyWithMessage); } if (this.StopProcessingRules != false) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.StopProcessingRules, this.StopProcessingRules); } } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonProperty = new JsonObject(); if (this.AssignCategories.Count > 0) { jsonProperty.Add(XmlElementNames.AssignCategories, this.AssignCategories.InternalToJson(service)); } if (this.CopyToFolder != null) { jsonProperty.Add(XmlElementNames.CopyToFolder, this.CopyToFolder.InternalToJson(service)); } if (this.Delete != false) { jsonProperty.Add(XmlElementNames.Delete, this.Delete); } if (this.ForwardAsAttachmentToRecipients.Count > 0) { jsonProperty.Add(XmlElementNames.ForwardAsAttachmentToRecipients, this.ForwardAsAttachmentToRecipients.InternalToJson(service)); } if (this.ForwardToRecipients.Count > 0) { jsonProperty.Add(XmlElementNames.ForwardToRecipients, this.ForwardToRecipients.InternalToJson(service)); } if (this.MarkImportance.HasValue) { jsonProperty.Add(XmlElementNames.MarkImportance, this.MarkImportance.Value); } if (this.MarkAsRead != false) { jsonProperty.Add(XmlElementNames.MarkAsRead, this.MarkAsRead); } if (this.MoveToFolder != null) { jsonProperty.Add(XmlElementNames.MoveToFolder, this.MoveToFolder.InternalToJson(service)); } if (this.PermanentDelete != false) { jsonProperty.Add(XmlElementNames.PermanentDelete, this.PermanentDelete); } if (this.RedirectToRecipients.Count > 0) { jsonProperty.Add(XmlElementNames.RedirectToRecipients, this.RedirectToRecipients.InternalToJson(service)); } if (this.SendSMSAlertToRecipients.Count > 0) { EmailAddressCollection emailCollection = ConvertSMSRecipientsFromMobilePhoneCollectionToEmailAddressCollection(this.SendSMSAlertToRecipients); jsonProperty.Add(XmlElementNames.SendSMSAlertToRecipients, emailCollection.InternalToJson(service)); } if (this.ServerReplyWithMessage != null) { jsonProperty.Add(XmlElementNames.ServerReplyWithMessage, this.ServerReplyWithMessage.InternalToJson(service)); } if (this.StopProcessingRules != false) { jsonProperty.Add(XmlElementNames.StopProcessingRules, this.StopProcessingRules); } return jsonProperty; } /// <summary> /// Validates this instance. /// </summary> internal override void InternalValidate() { base.InternalValidate(); EwsUtilities.ValidateParam(this.forwardAsAttachmentToRecipients, "ForwardAsAttachmentToRecipients"); EwsUtilities.ValidateParam(this.forwardToRecipients, "ForwardToRecipients"); EwsUtilities.ValidateParam(this.redirectToRecipients, "RedirectToRecipients"); foreach (MobilePhone sendSMSAlertToRecipient in this.sendSMSAlertToRecipients) { EwsUtilities.ValidateParam(sendSMSAlertToRecipient, "SendSMSAlertToRecipient"); } } /// <summary> /// Convert the SMS recipient list from EmailAddressCollection type to MobilePhone collection type. /// </summary> /// <param name="emailCollection">Recipient list in EmailAddressCollection type.</param> /// <returns>A MobilePhone collection object containing all SMS recipient in MobilePhone type. </returns> private static Collection<MobilePhone> ConvertSMSRecipientsFromEmailAddressCollectionToMobilePhoneCollection(EmailAddressCollection emailCollection) { Collection<MobilePhone> mobilePhoneCollection = new Collection<MobilePhone>(); foreach (EmailAddress emailAddress in emailCollection) { mobilePhoneCollection.Add(new MobilePhone(emailAddress.Name, emailAddress.Address)); } return mobilePhoneCollection; } /// <summary> /// Convert the SMS recipient list from MobilePhone collection type to EmailAddressCollection type. /// </summary> /// <param name="recipientCollection">Recipient list in a MobilePhone collection type.</param> /// <returns>An EmailAddressCollection object containing recipients with "MOBILE" address type. </returns> private static EmailAddressCollection ConvertSMSRecipientsFromMobilePhoneCollectionToEmailAddressCollection(Collection<MobilePhone> recipientCollection) { EmailAddressCollection emailCollection = new EmailAddressCollection(XmlElementNames.Address); foreach (MobilePhone recipient in recipientCollection) { EmailAddress emailAddress = new EmailAddress( recipient.Name, recipient.PhoneNumber, RuleActions.MobileType); emailCollection.Add(emailAddress); } return emailCollection; } } }
// 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 UnpackLowUInt16() { var test = new SimpleBinaryOpTest__UnpackLowUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__UnpackLowUInt16 { 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(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); 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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<UInt16> _fld1; public Vector128<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__UnpackLowUInt16 testClass) { var result = Sse2.UnpackLow(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnpackLowUInt16 testClass) { fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__UnpackLowUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleBinaryOpTest__UnpackLowUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.UnpackLow( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.UnpackLow( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackLow), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.UnpackLow( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt16>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt16>* pClsVar2 = &_clsVar2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(pClsVar1)), Sse2.LoadVector128((UInt16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse2.UnpackLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.UnpackLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse2.UnpackLow(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__UnpackLowUInt16(); var result = Sse2.UnpackLow(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__UnpackLowUInt16(); fixed (Vector128<UInt16>* pFld1 = &test._fld1) fixed (Vector128<UInt16>* pFld2 = &test._fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.UnpackLow(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt16>* pFld1 = &_fld1) fixed (Vector128<UInt16>* pFld2 = &_fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(pFld1)), Sse2.LoadVector128((UInt16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.UnpackLow(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt16*)(&test._fld1)), Sse2.LoadVector128((UInt16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt16> op1, Vector128<UInt16> op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i % 2 == 0) ? result[i] != left[i/2] : result[i] != right[(i - 1)/2]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.UnpackLow)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {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; } } } }
// 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.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { internal abstract class MulInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64, s_Single, s_Double; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "Mul"; private MulInstruction() { } private sealed class MulInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((short)((short)l * (short)r)); } frame.StackIndex--; return 1; } } private sealed class MulInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((int)l * (int)r)); } frame.StackIndex--; return 1; } } private sealed class MulInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((long)l * (long)r); } frame.StackIndex--; return 1; } } private sealed class MulUInt16 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((ushort)((ushort)l * (ushort)r)); } frame.StackIndex--; return 1; } } private sealed class MulUInt32 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((uint)l * (uint)r); } frame.StackIndex--; return 1; } } private sealed class MulUInt64 : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((ulong)l * (ulong)r); } frame.StackIndex--; return 1; } } private sealed class MulSingle : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (float)l * (float)r; } frame.StackIndex--; return 1; } } private sealed class MulDouble : MulInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (double)l * (double)r; } frame.StackIndex--; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new MulInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new MulInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new MulInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); case TypeCode.Single: return s_Single ?? (s_Single = new MulSingle()); case TypeCode.Double: return s_Double ?? (s_Double = new MulDouble()); default: throw ContractUtils.Unreachable; } } } internal abstract class MulOvfInstruction : Instruction { private static Instruction s_Int16, s_Int32, s_Int64, s_UInt16, s_UInt32, s_UInt64; public override int ConsumedStack => 2; public override int ProducedStack => 1; public override string InstructionName => "MulOvf"; private MulOvfInstruction() { } private sealed class MulOvfInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((short)((short)l * (short)r)); } frame.StackIndex--; return 1; } } private sealed class MulOvfInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((int)l * (int)r)); } frame.StackIndex--; return 1; } } private sealed class MulOvfInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((long)l * (long)r); } frame.StackIndex--; return 1; } } private sealed class MulOvfUInt16 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((ushort)((ushort)l * (ushort)r)); } frame.StackIndex--; return 1; } } private sealed class MulOvfUInt32 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((uint)l * (uint)r); } frame.StackIndex--; return 1; } } private sealed class MulOvfUInt64 : MulOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((ulong)l * (ulong)r); } frame.StackIndex--; return 1; } } public static Instruction Create(Type type) { Debug.Assert(type.IsArithmetic()); switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Int16: return s_Int16 ?? (s_Int16 = new MulOvfInt16()); case TypeCode.Int32: return s_Int32 ?? (s_Int32 = new MulOvfInt32()); case TypeCode.Int64: return s_Int64 ?? (s_Int64 = new MulOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); default: return MulInstruction.Create(type); } } } }
#region MIT License /* MIT License Copyright (c) 2018 Darin Higgins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Build.Utilities; using Microsoft.VisualBasic.ApplicationServices; namespace GenerateLineMap { /// <summary> /// Root name space for the GenerateLineMap command line utility to embed line number resources into /// .Net executables. /// </summary> internal class NamespaceDoc { } /// <summary> /// Main Module for the GenerateLineMap utility /// (c) 2008-2011 Darin Higgins All Rights Reserved /// This is a command line utility, so this is the main entry point. /// </summary> /// <remarks></remarks> public static class Program { static AssemblyInfo AsmInfo = new Microsoft.VisualBasic.ApplicationServices.AssemblyInfo(Assembly.GetExecutingAssembly()); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern void LoadLibrary(string lpFileName); static Program() { //default to using the console logger Log.Logger = new ConsoleLogger(); } /// <summary> /// Write only prop allows the build task to tell us to use the MSBuild logger instead. /// You can also supply your own class that implements TaskLoggingHelper and set it here /// to redirect all logging to your own code. /// </summary> public static TaskLoggingHelper MSBuildLogger { set { Log.Logger = new MSBuildLogger(value); } } /// <summary> /// Invoke the main GenerateLineMap functionality as if executed from the command line. /// This is primarily intended to be invoked by the MSBuild Task for generating a line map /// resource after a successful build. /// </summary> /// <param name="args">string array containing command line arguments to use. These are /// the same arguments as those described in GenerateLineMap Command Line Usage. /// </param> public static void Main(string[] args) { string fileName = args.Length > 0 ? args[0] : ""; bool bReport = false; bool bFile = false; bool bAPIResource = true; bool bNETResource = false; string outfile = ""; //assume success Environment.ExitCode = 0; try { //skip the first arg cause it's this apps filename var cmdArgs = args.Skip(1).ToList(); foreach (string s in cmdArgs) { var bHandled = false; if (s.Length == 2 && (s.Contains("?") || s.ToLower().Contains("h"))) { ShowHelp(); bHandled = true; } if (string.Compare(s, "/report", true) == 0) { bReport = true; bHandled = true; } if (s.StartsWith("/out:", StringComparison.InvariantCultureIgnoreCase)) { bHandled = true; outfile = s.Substring(5).Trim(); if (outfile.StartsWith("\"")) { outfile = outfile.Substring(1); if (outfile.EndsWith("\"")) { outfile = outfile.Substring(0, outfile.Length - 1); } } } if (string.Compare(s, "/file", true) == 0) { // write the line map to a separate file // normally, it's written back into the EXE as a resource bFile = true; bAPIResource = false; bNETResource = false; bHandled = true; } if (string.Compare(s, "/apiresource", true) == 0) { // write the line map to a winAPI resource // normally, it's written back into the EXE as a.net resource bAPIResource = true; bNETResource = false; bHandled = true; } if (string.Compare(s, "/resource", true) == 0) { // write the line map to a .net resource bAPIResource = false; bNETResource = true; bHandled = true; } if (!bHandled) { if (File.Exists(s)) { fileName = s; } } } Log.LogMessage("{0} v{1}", AsmInfo.Title, AsmInfo.Version); Log.LogMessage(AsmInfo.Description); Log.LogMessage(" {0}", AsmInfo.Copyright); Log.LogMessage(""); if (fileName.Length == 0) { ShowHelp(); return; } // extract the necessary dbghelp.dll if (ExtractDbgHelp()) { Log.LogWarning("Unable to extract dbghelp.dll to this folder."); return; } var lmb = new LineMapBuilder(fileName, outfile); if (bReport) { // just set a flag to gen a report lmb.CreateMapReport = true; } if (bFile) { Log.LogMessage("Creating linemap file for file {0}...", fileName); lmb.CreateLineMapFile(); } if (bAPIResource) { Log.LogMessage("Adding linemap WIN resource in file {0}...", fileName); lmb.CreateLineMapAPIResource(); } if (bNETResource) { String.Format("Adding linemap .NET resource in file {0}...", fileName); lmb.CreateLineMapResource(); } } catch (Exception ex) { // let em know we had a failure Log.LogError(ex, "Unable to complete operation."); Environment.ExitCode = 1; } // Return an exit code of 0 on success, 1 on failure // NOTE that there are several early returns in this routine } private static void ShowHelp() { Log.LogMessage(""); Log.LogMessage("Usage:"); Log.LogMessage(" {0} FilenameOfExeOrDllFile [options]", AsmInfo); Log.LogMessage("where options are:"); Log.LogMessage(" [/report][[/file]|[/resource]|[/apiresource]]"); Log.LogMessage(""); Log.LogMessage("/resource (default) Create a linemap .NET resource in the target"); Log.LogMessage(" EXE/DLL file"); Log.LogMessage("/report Generate report of contents of PDB file"); Log.LogMessage("/file Output a linemap file with the symbol and line num buffers"); Log.LogMessage("/apiresource Create a linemap windows resource in the target EXE/DLL file"); Log.LogMessage(""); Log.LogMessage("The default is 'apiresource' which embeds the linemap into"); Log.LogMessage("the target executable as a standard windows resource."); Log.LogMessage("The 'file' option is mainly for testing. The resulting *.lmp"); Log.LogMessage("file will contain source names and line numbers but no other"); Log.LogMessage("information commonly found in PDB files."); Log.LogMessage(""); Log.LogMessage("Returns an exitcode of 0 on success, 1 on failure"); } /// <summary> /// Extract the dbghelp.dll file from the exe /// </summary> /// <returns>true on failure</returns> /// <remarks></remarks> static private bool ExtractDbgHelp() { try { // Get our assembly var executing_assembly = Assembly.GetExecutingAssembly(); // Get our namespace // Note that this is different from the Appname because we compile to a // file call *Raw so that we can run ILMerge and result in the final filename var my_namespace = executing_assembly.EntryPoint.DeclaringType.Namespace; // write the file back out Stream dbghelp_stream; dbghelp_stream = executing_assembly.GetManifestResourceStream(my_namespace + ".dbghelp.dll"); if (dbghelp_stream != null) { // write stream to file var AppPath = Path.GetDirectoryName(executing_assembly.Location); var outname = Path.Combine(AppPath, "dbghelp.dll"); var bExtract = true; if (File.Exists(outname)) { // is it the right file (just check length for now) if ((new FileInfo(outname)).Length == dbghelp_stream.Length) { bExtract = false; } } if (bExtract) { var reader = new BinaryReader(dbghelp_stream); var buffer = reader.ReadBytes((int)dbghelp_stream.Length); var output = new FileStream(outname, FileMode.Create); output.Write(buffer, 0, (int)dbghelp_stream.Length); output.Close(); reader.Close(); } } } catch (Exception ex) { Log.LogError(ex, "\r\n!!! Unable to extract dbghelp.dll to current directory."); return true; } return false; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Reflection; using Ctrip.Log4.Appender; using Ctrip.Log4.Util; using Ctrip.Log4.Repository; namespace Ctrip.Log4.Core { /// <summary> /// The implementation of the <see cref="IRepositorySelector"/> interface suitable /// for use with the compact framework /// </summary> /// <remarks> /// <para> /// This <see cref="IRepositorySelector"/> implementation is a simple /// mapping between repository name and <see cref="ILoggerRepository"/> /// object. /// </para> /// <para> /// The .NET Compact Framework 1.0 does not support retrieving assembly /// level attributes therefore unlike the <c>DefaultRepositorySelector</c> /// this selector does not examine the calling assembly for attributes. /// </para> /// </remarks> /// <author>Nicko Cadell</author> public class CompactRepositorySelector : IRepositorySelector { #region Member Variables private const string DefaultRepositoryName = "Ctrip-default-repository"; private readonly Hashtable m_name2repositoryMap = new Hashtable(); private readonly Type m_defaultRepositoryType; private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; #endregion #region Constructors /// <summary> /// Create a new repository selector /// </summary> /// <param name="defaultRepositoryType">the type of the repositories to create, must implement <see cref="ILoggerRepository"/></param> /// <remarks> /// <para> /// Create an new compact repository selector. /// The default type for repositories must be specified, /// an appropriate value would be <see cref="Ctrip.Log4.Repository.Hierarchy.Hierarchy"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">throw if <paramref name="defaultRepositoryType"/> is null</exception> /// <exception cref="ArgumentOutOfRangeException">throw if <paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/></exception> public CompactRepositorySelector(Type defaultRepositoryType) { if (defaultRepositoryType == null) { throw new ArgumentNullException("defaultRepositoryType"); } // Check that the type is a repository if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) { throw Ctrip.Log4.Util.SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", (object)defaultRepositoryType, "Parameter: defaultRepositoryType, Value: ["+defaultRepositoryType+"] out of range. Argument must implement the ILoggerRepository interface"); } m_defaultRepositoryType = defaultRepositoryType; LogLog.Debug(declaringType, "defaultRepositoryType ["+m_defaultRepositoryType+"]"); } #endregion #region Implementation of IRepositorySelector /// <summary> /// Get the <see cref="ILoggerRepository"/> for the specified assembly /// </summary> /// <param name="assembly">not used</param> /// <returns>The default <see cref="ILoggerRepository"/></returns> /// <remarks> /// <para> /// The <paramref name="assembly"/> argument is not used. This selector does not create a /// separate repository for each assembly. /// </para> /// <para> /// As a named repository is not specified the default repository is /// returned. The default repository is named <c>Ctrip-default-repository</c>. /// </para> /// </remarks> public ILoggerRepository GetRepository(Assembly assembly) { return CreateRepository(assembly, m_defaultRepositoryType); } /// <summary> /// Get the named <see cref="ILoggerRepository"/> /// </summary> /// <param name="repositoryName">the name of the repository to lookup</param> /// <returns>The named <see cref="ILoggerRepository"/></returns> /// <remarks> /// <para> /// Get the named <see cref="ILoggerRepository"/>. The default /// repository is <c>Ctrip-default-repository</c>. Other repositories /// must be created using the <see cref="M:CreateRepository(string, Type)"/>. /// If the named repository does not exist an exception is thrown. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">throw if <paramref name="repositoryName"/> is null</exception> /// <exception cref="LogException">throw if the <paramref name="repositoryName"/> does not exist</exception> public ILoggerRepository GetRepository(string repositoryName) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } lock(this) { // Lookup in map ILoggerRepository rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep == null) { throw new LogException("Repository ["+repositoryName+"] is NOT defined."); } return rep; } } /// <summary> /// Create a new repository for the assembly specified /// </summary> /// <param name="assembly">not used</param> /// <param name="repositoryType">the type of repository to create, must implement <see cref="ILoggerRepository"/></param> /// <returns>the repository created</returns> /// <remarks> /// <para> /// The <paramref name="assembly"/> argument is not used. This selector does not create a /// separate repository for each assembly. /// </para> /// <para> /// If the <paramref name="repositoryType"/> is <c>null</c> then the /// default repository type specified to the constructor is used. /// </para> /// <para> /// As a named repository is not specified the default repository is /// returned. The default repository is named <c>Ctrip-default-repository</c>. /// </para> /// </remarks> public ILoggerRepository CreateRepository(Assembly assembly, Type repositoryType) { // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { // This method should not throw if the default repository already exists. // First check that the repository does not exist ILoggerRepository rep = m_name2repositoryMap[DefaultRepositoryName] as ILoggerRepository; if (rep == null) { // Must create the repository rep = CreateRepository(DefaultRepositoryName, repositoryType); } return rep; } } /// <summary> /// Create a new repository for the repository specified /// </summary> /// <param name="repositoryName">the repository to associate with the <see cref="ILoggerRepository"/></param> /// <param name="repositoryType">the type of repository to create, must implement <see cref="ILoggerRepository"/>. /// If this param is null then the default repository type is used.</param> /// <returns>the repository created</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(string)"/> with the /// same repository specified will return the same repository instance. /// </para> /// <para> /// If the named repository already exists an exception will be thrown. /// </para> /// <para> /// If <paramref name="repositoryType"/> is <c>null</c> then the default /// repository type specified to the constructor is used. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">throw if <paramref name="repositoryName"/> is null</exception> /// <exception cref="LogException">throw if the <paramref name="repositoryName"/> already exists</exception> public ILoggerRepository CreateRepository(string repositoryName, Type repositoryType) { if (repositoryName == null) { throw new ArgumentNullException("repositoryName"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { ILoggerRepository rep = null; // First check that the repository does not exist rep = m_name2repositoryMap[repositoryName] as ILoggerRepository; if (rep != null) { throw new LogException("Repository ["+repositoryName+"] is already defined. Repositories cannot be redefined."); } else { LogLog.Debug(declaringType, "Creating repository ["+repositoryName+"] using type ["+repositoryType+"]"); // Call the no arg constructor for the repositoryType rep = (ILoggerRepository)Activator.CreateInstance(repositoryType); // Set the name of the repository rep.Name = repositoryName; // Store in map m_name2repositoryMap[repositoryName] = rep; // Notify listeners that the repository has been created OnLoggerRepositoryCreatedEvent(rep); } return rep; } } /// <summary> /// Test if a named repository exists /// </summary> /// <param name="repositoryName">the named repository to check</param> /// <returns><c>true</c> if the repository exists</returns> /// <remarks> /// <para> /// Test if a named repository exists. Use <see cref="M:CreateRepository(string, Type)"/> /// to create a new repository and <see cref="M:GetRepository(string)"/> to retrieve /// a repository. /// </para> /// </remarks> public bool ExistsRepository(string repositoryName) { lock(this) { return m_name2repositoryMap.ContainsKey(repositoryName); } } /// <summary> /// Gets a list of <see cref="ILoggerRepository"/> objects /// </summary> /// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns> /// <remarks> /// <para> /// Gets an array of all of the repositories created by this selector. /// </para> /// </remarks> public ILoggerRepository[] GetAllRepositories() { lock(this) { ICollection reps = m_name2repositoryMap.Values; ILoggerRepository[] all = new ILoggerRepository[reps.Count]; reps.CopyTo(all, 0); return all; } } #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the CompactRepositorySelector class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(CompactRepositorySelector); #endregion Private Static Fields /// <summary> /// Event to notify that a logger repository has been created. /// </summary> /// <value> /// Event to notify that a logger repository has been created. /// </value> /// <remarks> /// <para> /// Event raised when a new repository is created. /// The event source will be this selector. The event args will /// be a <see cref="LoggerRepositoryCreationEventArgs"/> which /// holds the newly created <see cref="ILoggerRepository"/>. /// </para> /// </remarks> public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent { add { m_loggerRepositoryCreatedEvent += value; } remove { m_loggerRepositoryCreatedEvent -= value; } } /// <summary> /// Notify the registered listeners that the repository has been created /// </summary> /// <param name="repository">The repository that has been created</param> /// <remarks> /// <para> /// Raises the <event cref="LoggerRepositoryCreatedEvent">LoggerRepositoryCreatedEvent</event> /// event. /// </para> /// </remarks> protected virtual void OnLoggerRepositoryCreatedEvent(ILoggerRepository repository) { LoggerRepositoryCreationEventHandler handler = m_loggerRepositoryCreatedEvent; if (handler != null) { handler(this, new LoggerRepositoryCreationEventArgs(repository)); } } } }
// Copyright 2008-2009 Louis DeJardin - http://whereslou.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. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spark.Compiler.ChunkVisitors; using Spark.Parser.Code; namespace Spark.Compiler.VisualBasic.ChunkVisitors { public class GeneratedCodeVisitor : GeneratedCodeVisitorBase { private readonly SourceWriter _source; private readonly NullBehaviour _nullBehaviour; public GeneratedCodeVisitor(SourceWriter source, Dictionary<string, object> globalSymbols, NullBehaviour nullBehaviour) { _nullBehaviour = nullBehaviour; _source = source; _scope = new Scope(new Scope(null) { Variables = globalSymbols }); } private SourceWriter CodeIndent(Chunk chunk) { if (_source.AdjustDebugSymbols) { if (chunk != null && chunk.Position != null) { _source.StartOfLine = false; return _source .WriteDirective("#ExternalSource(\"{1}\", {0})", chunk.Position.Line, chunk.Position.SourceContext.FileName) .Indent(chunk.Position.Column - 1); } return _source.WriteDirective("#ExternalSource(\"\", 16707566)"); } return _source; } private void CodeHidden() { if (_source.AdjustDebugSymbols) _source.WriteLine("#ExternalSource(\"\", 16707566)"); } private void CodeDefault() { if (_source.AdjustDebugSymbols) _source.WriteLine("#End ExternalSource"); } private void AppendOpenScope() { PushScope(); _source.WriteLine("If True Then").AddIndent(); } private void AppendCloseScope() { _source.RemoveIndent().WriteLine("End If"); PopScope(); } class Scope { public Scope(Scope prior) { Variables = new Dictionary<string, object>(); Prior = prior; } public Dictionary<string, object> Variables { get; set; } public Scope Prior { get; private set; } } private Scope _scope; void PushScope() { _scope = new Scope(_scope); } void PopScope() { _scope = _scope.Prior; } void DeclareVariable(string name) { _scope.Variables.Add(name, null); } bool IsVariableDeclared(string name) { var scan = _scope; while (scan != null) { if (scan.Variables.ContainsKey(name)) return true; scan = scan.Prior; } return false; } protected override void Visit(SendLiteralChunk chunk) { if (string.IsNullOrEmpty(chunk.Text)) return; CodeHidden(); _source.Write("Output.Write(\"").Write(EscapeStringContents(chunk.Text)).WriteLine("\")"); CodeDefault(); } protected override void Visit(SendExpressionChunk chunk) { var automaticallyEncode = chunk.AutomaticallyEncode; if (chunk.Code.ToString().StartsWith("H(")) automaticallyEncode = false; _source.WriteLine("Try").AddIndent(); CodeIndent(chunk) .Write("Output.Write(") .Write(automaticallyEncode ? "H(" : "") .WriteCode(chunk.Code) .Write(automaticallyEncode ? ")" : "") .WriteLine(")") .RemoveIndent(); CodeDefault(); if (_nullBehaviour == NullBehaviour.Lenient) { _source.WriteLine("Catch ex As Global.System.NullReferenceException"); if (!chunk.SilentNulls) { _source .AddIndent() .Write("Output.Write(\"${") .Write(EscapeStringContents(chunk.Code)) .WriteLine("}\")") .RemoveIndent(); } _source.WriteLine("End Try"); } else { _source.WriteLine("Catch ex As Global.System.NullReferenceException"); _source .AddIndent() .Write("Throw New Global.System.ArgumentNullException(\"${") .Write(EscapeStringContents(chunk.Code)) .WriteLine("}\", ex)") .RemoveIndent(); _source.WriteLine("End Try"); } } static string EscapeStringContents(string text) { return text .Replace("\"", "[\"]") .Replace("\t", "\" & vbTab & \"") .Replace("\r\n", "\" & vbCrLf & \"") .Replace("\r", "\" & vbCr & \"") .Replace("\n", "\" & vbLf & \"") .Replace(" & \"\"", "") .Replace("[\"]", "\"\""); } protected override void Visit(MacroChunk chunk) { } protected override void Visit(CodeStatementChunk chunk) { CodeIndent(chunk).WriteCode(chunk.Code).WriteLine(); CodeDefault(); } protected override void Visit(LocalVariableChunk chunk) { LocalVariableImpl(chunk, chunk.Name, chunk.Type, chunk.Value); } protected override void Visit(DefaultVariableChunk chunk) { if (IsVariableDeclared(chunk.Name)) return; LocalVariableImpl(chunk, chunk.Name, chunk.Type, chunk.Value); } private void LocalVariableImpl(Chunk chunk, Snippets name, Snippets type, Snippets value) { DeclareVariable(name); if (Snippets.IsNullOrEmpty(type) || String.Equals(type, "var")) { CodeIndent(chunk) .Write("Dim ") .WriteCode(name); } else { CodeIndent(chunk) .Write("Dim ") .WriteCode(name) .Write(" As ") .WriteCode(type); } if (!Snippets.IsNullOrEmpty(value)) { _source.Write(" = ").WriteCode(value); } _source.WriteLine(); CodeDefault(); } protected override void Visit(UseMasterChunk chunk) { //no-op } static bool IsInOrAs(string part) { return string.Equals(part, "In", StringComparison.InvariantCultureIgnoreCase) || string.Equals(part, "As", StringComparison.InvariantCultureIgnoreCase); } static bool IsIn(string part) { return string.Equals(part, "In", StringComparison.InvariantCultureIgnoreCase); } protected override void Visit(ForEachChunk chunk) { var terms = chunk.Code.ToString().Split(' ', '\r', '\n', '\t').ToList(); var inIndex = terms.FindIndex(IsIn); var inOrAsIndex = terms.FindIndex(IsInOrAs); var variableName = (inOrAsIndex < 1 ? null : terms[inOrAsIndex - 1]); if (variableName == null) { CodeIndent(chunk) .Write("For Each ") .WriteLine(chunk.Code) .AddIndent(); CodeDefault(); PushScope(); Accept(chunk.Body); _source .RemoveIndent() .WriteLine("Next"); PopScope(); } else { var detect = new DetectCodeExpressionVisitor(OuterPartial); var autoIndex = detect.Add(variableName + "Index"); var autoCount = detect.Add(variableName + "Count"); var autoIsFirst = detect.Add(variableName + "IsFirst"); var autoIsLast = detect.Add(variableName + "IsLast"); detect.Accept(chunk.Body); if (autoIsLast.Detected) { autoIndex.Detected = true; autoCount.Detected = true; } AppendOpenScope(); if (autoIndex.Detected) { DeclareVariable(variableName + "Index"); _source.WriteLine("Dim {0}Index As Integer = 0", variableName); } if (autoIsFirst.Detected) { DeclareVariable(variableName + "IsFirst"); _source.WriteLine("Dim {0}IsFirst As Boolean = True", variableName); } if (autoCount.Detected) { DeclareVariable(variableName + "Count"); var collectionCode = string.Join(" ", terms.ToArray(), inIndex + 1, terms.Count - inIndex - 1); _source.WriteLine("Dim {0}Count As Integer = Global.Spark.Compiler.CollectionUtility.Count({1})", variableName, collectionCode); } CodeIndent(chunk) .Write("For Each ") .WriteLine(chunk.Code) .AddIndent(); CodeDefault(); PushScope(); DeclareVariable(variableName); CodeHidden(); if (autoIsLast.Detected) { DeclareVariable(variableName + "IsLast"); _source.WriteLine("Dim {0}IsLast As Boolean = ({0}Index = {0}Count - 1)", variableName); } CodeDefault(); Accept(chunk.Body); CodeHidden(); if (autoIndex.Detected) _source.WriteLine("{0}Index = {0}Index + 1", variableName); if (autoIsFirst.Detected) _source.WriteLine("{0}IsFirst = False", variableName); CodeDefault(); PopScope(); _source.RemoveIndent().WriteLine("Next"); AppendCloseScope(); } } protected override void Visit(ScopeChunk chunk) { AppendOpenScope(); Accept(chunk.Body); AppendCloseScope(); } protected override void Visit(GlobalVariableChunk chunk) { } protected override void Visit(AssignVariableChunk chunk) { CodeIndent(chunk) .Write(chunk.Name) .Write(" = ") .WriteLine(chunk.Value); CodeDefault(); } protected override void Visit(ContentChunk chunk) { CodeIndent(chunk) .Write("Using OutputScope(\"") .Write(chunk.Name) .WriteLine("\")") .AddIndent(); PushScope(); Accept(chunk.Body); PopScope(); _source .RemoveIndent() .WriteLine("End Using"); } protected override void Visit(UseImportChunk chunk) { } protected override void Visit(ContentSetChunk chunk) { CodeIndent(chunk) .WriteLine("Using OutputScope(new System.IO.StringWriter())") .AddIndent(); CodeDefault(); PushScope(); Accept(chunk.Body); CodeHidden(); string format; switch (chunk.AddType) { case ContentAddType.AppendAfter: format = "{0} = {0} + Output.ToString()"; break; case ContentAddType.InsertBefore: format = "{0} = Output.ToString() + {0}"; break; default: format = "{0} = Output.ToString()"; break; } _source.WriteFormat(format, chunk.Variable).WriteLine(); PopScope(); _source.RemoveIndent().WriteLine("End Using"); CodeDefault(); } protected override void Visit(UseContentChunk chunk) { CodeIndent(chunk) .Write("If Content.ContainsKey(\"") .Write(chunk.Name) .WriteLine("\") Then").AddIndent() .Write("Global.Spark.Spool.TextWriterExtensions.WriteTo(Content(\"") .Write(chunk.Name) .WriteLine("\"), Output)").RemoveIndent(); if (chunk.Default.Any()) { _source .WriteLine("Else").AddIndent(); PushScope(); Accept(chunk.Default); PopScope(); _source.RemoveIndent(); } _source.WriteLine("End If"); } protected override void Visit(ViewDataChunk chunk) { } protected override void Visit(UseNamespaceChunk chunk) { } protected override void Visit(UseAssemblyChunk chunk) { } protected override void Visit(ExtensionChunk chunk) { chunk.Extension.VisitChunk(this, OutputLocation.RenderMethod, chunk.Body, _source.GetStringBuilder()); } protected override void Visit(ConditionalChunk chunk) { switch (chunk.Type) { case ConditionalType.If: CodeIndent(chunk).Write("If ").WriteCode(chunk.Condition).WriteLine(" Then"); break; case ConditionalType.ElseIf: _source.ClearEscrowLine(); CodeIndent(chunk).Write("ElseIf ").WriteCode(chunk.Condition).WriteLine(" Then"); break; case ConditionalType.Else: _source.ClearEscrowLine(); _source.WriteLine("Else"); break; case ConditionalType.Once: _source.Write("If Once(").WriteCode(chunk.Condition).WriteLine(") Then"); break; case ConditionalType.Unless: CodeIndent(chunk).Write("If Not ").WriteCode(chunk.Condition).WriteLine(" Then"); break; default: throw new CompilerException(string.Format("Unknown ConditionalChunk type {0}", chunk.Type)); } _source .AddIndent(); PushScope(); Accept(chunk.Body); PopScope(); _source .RemoveIndent() .EscrowLine("End If"); } protected override void Visit(ViewDataModelChunk chunk) { } protected override void Visit(PageBaseTypeChunk chunk) { } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Envelopes/AuthTicket.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Envelopes { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Envelopes/AuthTicket.proto</summary> public static partial class AuthTicketReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Envelopes/AuthTicket.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AuthTicketReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjBQT0dPUHJvdG9zL05ldHdvcmtpbmcvRW52ZWxvcGVzL0F1dGhUaWNrZXQu", "cHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5FbnZlbG9wZXMiRQoKQXV0", "aFRpY2tldBINCgVzdGFydBgBIAEoDBIbChNleHBpcmVfdGltZXN0YW1wX21z", "GAIgASgEEgsKA2VuZBgDIAEoDGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Envelopes.AuthTicket), global::POGOProtos.Networking.Envelopes.AuthTicket.Parser, new[]{ "Start", "ExpireTimestampMs", "End" }, null, null, null) })); } #endregion } #region Messages public sealed partial class AuthTicket : pb::IMessage<AuthTicket> { private static readonly pb::MessageParser<AuthTicket> _parser = new pb::MessageParser<AuthTicket>(() => new AuthTicket()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AuthTicket> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Envelopes.AuthTicketReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthTicket() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthTicket(AuthTicket other) : this() { start_ = other.start_; expireTimestampMs_ = other.expireTimestampMs_; end_ = other.end_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthTicket Clone() { return new AuthTicket(this); } /// <summary>Field number for the "start" field.</summary> public const int StartFieldNumber = 1; private pb::ByteString start_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Start { get { return start_; } set { start_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "expire_timestamp_ms" field.</summary> public const int ExpireTimestampMsFieldNumber = 2; private ulong expireTimestampMs_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong ExpireTimestampMs { get { return expireTimestampMs_; } set { expireTimestampMs_ = value; } } /// <summary>Field number for the "end" field.</summary> public const int EndFieldNumber = 3; private pb::ByteString end_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString End { get { return end_; } set { end_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AuthTicket); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AuthTicket other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Start != other.Start) return false; if (ExpireTimestampMs != other.ExpireTimestampMs) return false; if (End != other.End) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Start.Length != 0) hash ^= Start.GetHashCode(); if (ExpireTimestampMs != 0UL) hash ^= ExpireTimestampMs.GetHashCode(); if (End.Length != 0) hash ^= End.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Start.Length != 0) { output.WriteRawTag(10); output.WriteBytes(Start); } if (ExpireTimestampMs != 0UL) { output.WriteRawTag(16); output.WriteUInt64(ExpireTimestampMs); } if (End.Length != 0) { output.WriteRawTag(26); output.WriteBytes(End); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Start.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Start); } if (ExpireTimestampMs != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ExpireTimestampMs); } if (End.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(End); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AuthTicket other) { if (other == null) { return; } if (other.Start.Length != 0) { Start = other.Start; } if (other.ExpireTimestampMs != 0UL) { ExpireTimestampMs = other.ExpireTimestampMs; } if (other.End.Length != 0) { End = other.End; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Start = input.ReadBytes(); break; } case 16: { ExpireTimestampMs = input.ReadUInt64(); break; } case 26: { End = input.ReadBytes(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Threading; using System.Runtime.InteropServices; using Symbol; namespace CS_Barcode2Sample1 { /// <summary> /// The SelectDevice class provides a dialog for displaying and selecting a /// list of available Symbol.Barcode2.Device objects. /// </summary> /// <remarks> /// A SelectDevice dialog is displayed with the list of device choices /// and the user selects one of them to be accessed. /// </remarks> public class SelectDevice : System.Windows.Forms.Form { private System.Windows.Forms.Button CancelButton; private System.Windows.Forms.ListBox AvailableDevicesListBox; private System.Windows.Forms.Label AvailableDevicesLabel; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.Button OKButton; private int MySelection = -1; static private Symbol.Barcode2.Device[] OurAvailableDevices = null; static private string OurTitle; static private int DefaultIndex; private static bool bPortrait = true; // The default dispaly orientation // has been set to Portrait. private bool bSkipMaxLen = false; // The restriction on the maximum // physical length is considered by default. private bool bInitialScale = true; // The flag to track whether the // scaling logic is applied for // the first time (from scatch) or not. // Based on that, the (outer) width/height values // of the form will be set or not. // Initially set to true. private int resWidthReference = 248; // The (cached) width of the form. // INITIALLY HAS TO BE SET TO THE WIDTH OF THE FORM AT DESIGN TIME (IN PIXELS). // This setting is also obtained from the platform only on // Windows CE devices before running the application on the device, as a verification. // For PocketPC (& Windows Mobile) devices, the failure to set this properly may result in the distortion of GUI/viewability. private int resHeightReference = 289; // The (cached) height of the form. // INITIALLY HAS TO BE SET TO THE HEIGHT OF THE FORM AT DESIGN TIME (IN PIXELS). // This setting is also obtained from the platform only on // Windows CE devices before running the application on the device, as a verification. // For PocketPC (& Windows Mobile) devices, the failure to set this properly may result in the distortion of GUI/viewability. private const double maxLength = 4; // The maximum physical width/height of the sample (in inches). // The actual value on the device may slightly deviate from this // since the calculations based on the (received) DPI & resolution values // would provide only an approximation, so not 100% accurate. /// <summary> /// This function does the (initial) scaling of the form /// by re-setting the related parameters (if required) and /// then calling the Scale(...) internally. /// </summary> /// public void DoScale() { if (Screen.PrimaryScreen.Bounds.Width > Screen.PrimaryScreen.Bounds.Height) { bPortrait = false; // If the display orientation is not portrait (so it's landscape), set the flag to false. } if (this.WindowState == FormWindowState.Maximized) // If the form is maximized by default. { this.bSkipMaxLen = true; // we need to skip the max. length restriction } if ((Symbol.Win32.PlatformType.IndexOf("WinCE") != -1) || (Symbol.Win32.PlatformType.IndexOf("WindowsCE") != -1) || (Symbol.Win32.PlatformType.IndexOf("Windows CE") != -1)) // Only on Windows CE devices { this.resWidthReference = this.Width; // The width of the form at design time (in pixels) is obtained from the platorm. this.resHeightReference = this.Height; // The height of the form at design time (in pixels) is obtained from the platform. } Scale(this); // Initial scaling of the GUI } /// <summary> /// This function scales the given Form and its child controls in order to /// make them completely viewable, based on the screen width and height. /// </summary> private static void Scale(SelectDevice frm) { int PSWAW = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; // The width of the working area (in pixels). int PSWAH = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; // The height of the working area (in pixels). // The entire screen has been taken in to account below // in order to decide the half (S)VGA settings etc. if (!((Screen.PrimaryScreen.Bounds.Width <= (1.5) * (Screen.PrimaryScreen.Bounds.Height)) && (Screen.PrimaryScreen.Bounds.Height <= (1.5) * (Screen.PrimaryScreen.Bounds.Width)))) { if ((Screen.PrimaryScreen.Bounds.Width) > (Screen.PrimaryScreen.Bounds.Height)) { PSWAW = (int)((1.33) * PSWAH); // If the width/height ratio goes beyond 1.5, // the (longer) effective width is made shorter. } } float dpiX = GetDPIX(); // Get the horizontal DPI value. if (frm.bInitialScale == true) // If an initial scale (from scratch) { if (Symbol.Win32.PlatformType.IndexOf("PocketPC") != -1) // If the platform is either Pocket PC or Windows Mobile { frm.Width = PSWAW; // Set the form width. However this setting // would be the ultimate one for Pocket PC (& Windows Mobile)devices. // Just for the sake of consistency, it's explicitely specified here. } else { frm.Width = (int)((frm.Width) * (PSWAW)) / (frm.resWidthReference); // Set the form width for others (Windows CE devices). } } if ((frm.Width <= maxLength * dpiX) || frm.bSkipMaxLen == true) // The calculation of the width & left values for each control // without taking the maximum length restriction into consideration. { foreach (System.Windows.Forms.Control cntrl in frm.Controls) { cntrl.Width = ((cntrl.Width) * (frm.Width)) / (frm.resWidthReference); cntrl.Left = ((cntrl.Left) * (frm.Width)) / (frm.resWidthReference); if (cntrl is System.Windows.Forms.TabControl) { foreach (System.Windows.Forms.TabPage tabPg in cntrl.Controls) { foreach (System.Windows.Forms.Control cntrl2 in tabPg.Controls) { cntrl2.Width = (((cntrl2.Width) * (frm.Width)) / (frm.resWidthReference)); cntrl2.Left = (((cntrl2.Left) * (frm.Width)) / (frm.resWidthReference)); } } } } } else { // The calculation of the width & left values for each control // with the maximum length restriction taken into consideration. foreach (System.Windows.Forms.Control cntrl in frm.Controls) { cntrl.Width = (int)(((cntrl.Width) * (PSWAW) * (maxLength * dpiX)) / (frm.resWidthReference * (frm.Width))); cntrl.Left = (int)(((cntrl.Left) * (PSWAW) * (maxLength * dpiX)) / (frm.resWidthReference * (frm.Width))); if (cntrl is System.Windows.Forms.TabControl) { foreach (System.Windows.Forms.TabPage tabPg in cntrl.Controls) { foreach (System.Windows.Forms.Control cntrl2 in tabPg.Controls) { cntrl2.Width = (int)(((cntrl2.Width) * (PSWAW) * (maxLength * dpiX)) / (frm.resWidthReference * (frm.Width))); cntrl2.Left = (int)(((cntrl2.Left) * (PSWAW) * (maxLength * dpiX)) / (frm.resWidthReference * (frm.Width))); } } } } frm.Width = (int)((frm.Width) * (maxLength * dpiX)) / (frm.Width); } frm.resWidthReference = frm.Width; // Set the reference width to the new value. // A similar calculation is performed below for the height & top values for each control ... if (!((Screen.PrimaryScreen.Bounds.Width <= (1.5) * (Screen.PrimaryScreen.Bounds.Height)) && (Screen.PrimaryScreen.Bounds.Height <= (1.5) * (Screen.PrimaryScreen.Bounds.Width)))) { if ((Screen.PrimaryScreen.Bounds.Height) > (Screen.PrimaryScreen.Bounds.Width)) { PSWAH = (int)((1.33) * PSWAW); } } float dpiY = GetDPIY(); if (frm.bInitialScale == true) { if (Symbol.Win32.PlatformType.IndexOf("PocketPC") != -1) { frm.Height = PSWAH; } else { frm.Height = (int)((frm.Height) * (PSWAH)) / (frm.resHeightReference); } } if ((frm.Height <= maxLength * dpiY) || frm.bSkipMaxLen == true) { foreach (System.Windows.Forms.Control cntrl in frm.Controls) { cntrl.Height = ((cntrl.Height) * (frm.Height)) / (frm.resHeightReference); cntrl.Top = ((cntrl.Top) * (frm.Height)) / (frm.resHeightReference); if (cntrl is System.Windows.Forms.TabControl) { foreach (System.Windows.Forms.TabPage tabPg in cntrl.Controls) { foreach (System.Windows.Forms.Control cntrl2 in tabPg.Controls) { cntrl2.Height = ((cntrl2.Height) * (frm.Height)) / (frm.resHeightReference); cntrl2.Top = ((cntrl2.Top) * (frm.Height)) / (frm.resHeightReference); } } } } } else { foreach (System.Windows.Forms.Control cntrl in frm.Controls) { cntrl.Height = (int)(((cntrl.Height) * (PSWAH) * (maxLength * dpiY)) / (frm.resHeightReference * (frm.Height))); cntrl.Top = (int)(((cntrl.Top) * (PSWAH) * (maxLength * dpiY)) / (frm.resHeightReference * (frm.Height))); if (cntrl is System.Windows.Forms.TabControl) { foreach (System.Windows.Forms.TabPage tabPg in cntrl.Controls) { foreach (System.Windows.Forms.Control cntrl2 in tabPg.Controls) { cntrl2.Height = (int)(((cntrl2.Height) * (PSWAH) * (maxLength * dpiY)) / (frm.resHeightReference * (frm.Height))); cntrl2.Top = (int)(((cntrl2.Top) * (PSWAH) * (maxLength * dpiY)) / (frm.resHeightReference * (frm.Height))); } } } } frm.Height = (int)((frm.Height) * (maxLength * dpiY)) / (frm.Height); } frm.resHeightReference = frm.Height; if (frm.bInitialScale == true) { frm.bInitialScale = false; // If this was the initial scaling (from scratch), it's now complete. } if (frm.bSkipMaxLen == true) { frm.bSkipMaxLen = false; // No need to consider the maximum length restriction now. } } // DPI values have to be taken via PInvokes on VS2003/CF1.0. The 2 proerties, System.Drawing.Graphics.DpiX // & System.Drawing.Graphics.DpiY, are not supported by VS2003/CF1.0. // For DpiX private static float GetDPIX() { IntPtr hwnd = (IntPtr)(GetCapture()); float dpiX = GetDeviceCaps(hwnd, 88); // 88 for DPIX value return dpiX; } // For DpiY private static float GetDPIY() { IntPtr hwnd = (IntPtr)(GetCapture()); float dpiY = GetDeviceCaps(hwnd, 90); // 90 for DPIY value return dpiY; } /// <summary> /// The static Select method is the recommended way to create the SelectDevice /// dialog. /// </summary> /// <remarks> /// This method will display the SelectDevice dialog and block until a /// selection has been made. /// </remarks> /// <param name="Title">A string that will be displayed as the title to the /// SelectDevice dialog.</param> /// <param name="AvailableDevices">An array of available Symbol.Device objects. /// </param> /// <returns>The selected device object.</returns> public static Symbol.Barcode2.Device Select( string Title, Symbol.Barcode2.Device[] AvailableDevices) { OurAvailableDevices = AvailableDevices; if ( OurAvailableDevices.Length == 0 ) { return null; } if ( OurAvailableDevices.Length == 1 ) { return OurAvailableDevices[0]; } OurTitle = Title; DefaultIndex = 0; int nSelection = new SelectDevice().Selection; if ( nSelection < 0 ) { return null; } return OurAvailableDevices[nSelection]; } /// <summary> /// The static Select method is the recommended way to create the SelectDevice /// dialog. /// </summary> /// <remarks> /// This method will display the SelectDevice dialog and block until a /// selection has been made. /// </remarks> /// <param name="Title">A string that will be displayed as the title to the /// SelectDevice dialog.</param> /// <param name="AvailableDevices">An array of available Symbol.Device objects. /// </param> /// <param name="SelectIndex">The index of the initially selected device /// object.</param> /// <returns>The selected device object.</returns> public static Symbol.Barcode2.Device Select(string Title, Symbol.Barcode2.Device[] AvailableDevices, int SelectIndex) { OurAvailableDevices = AvailableDevices; if ( OurAvailableDevices.Length == 0 ) { return null; } if ( OurAvailableDevices.Length == 1 ) { return OurAvailableDevices[0]; } OurTitle = Title; DefaultIndex = SelectIndex; int nSelection = new SelectDevice().Selection; if ( nSelection < 0 ) { return null; } return OurAvailableDevices[nSelection]; } /// <summary> /// Default SelectDevice constructor. /// </summary> internal SelectDevice() { InitializeComponent(); this.DoScale(); this.OKButton.Focus(); } #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.CancelButton = new System.Windows.Forms.Button(); this.OKButton = new System.Windows.Forms.Button(); this.AvailableDevicesListBox = new System.Windows.Forms.ListBox(); this.AvailableDevicesLabel = new System.Windows.Forms.Label(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); // // CancelButton // this.CancelButton.Location = new System.Drawing.Point(8, 232); this.CancelButton.Size = new System.Drawing.Size(64, 25); this.CancelButton.Text = "Cancel"; this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click); this.CancelButton.KeyDown += new System.Windows.Forms.KeyEventHandler(this.CancelButton_KeyDown); // // OKButton // this.OKButton.Location = new System.Drawing.Point(168, 232); this.OKButton.Size = new System.Drawing.Size(64, 25); this.OKButton.Text = "OK"; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); this.OKButton.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OKButton_KeyDown); // // AvailableDevicesListBox // this.AvailableDevicesListBox.Location = new System.Drawing.Point(8, 40); this.AvailableDevicesListBox.Size = new System.Drawing.Size(224, 170); // // AvailableDevicesLabel // this.AvailableDevicesLabel.Location = new System.Drawing.Point(8, 8); this.AvailableDevicesLabel.Size = new System.Drawing.Size(224, 24); this.AvailableDevicesLabel.Text = "Available Devices:"; // // SelectDevice // this.ClientSize = new System.Drawing.Size(242, 264); this.Controls.Add(this.AvailableDevicesLabel); this.Controls.Add(this.AvailableDevicesListBox); this.Controls.Add(this.CancelButton); this.Controls.Add(this.OKButton); this.Menu = this.mainMenu1; this.Text = "Select"; this.Resize += new System.EventHandler(this.SelectDevice_Resize); this.Load += new System.EventHandler(this.SelectDevice_Load); this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.SelectDevice_KeyUp); } #endregion // Private: SelectDevice_Load private void SelectDevice_Load(object sender, System.EventArgs e) { //// Set wait cursor. //bool SaveWaitCursor = Symbol.Win32.WaitCursor; //Symbol.Win32.WaitCursor = true; try { this.AvailableDevicesListBox.Hide(); foreach (Symbol.Barcode2.Device d in OurAvailableDevices) { if (d.DeviceType != Symbol.Barcode2.DEVICETYPES.UNKNOWN) { this.AvailableDevicesListBox.Items.Add(d.DeviceType + " - " + d.FriendlyName); } else { this.AvailableDevicesListBox.Items.Add(d.FriendlyName); } } this.AvailableDevicesListBox.SelectedIndex = 0; this.AvailableDevicesListBox.Show(); this.KeyDown += new KeyEventHandler(SelectDevice_KeyDown); // Add MainMenu if Pocket PC if (Symbol.Win32.PlatformType.IndexOf("PocketPC") != -1) { this.Menu = new MainMenu(); } } finally { // restore wait cursor //Symbol.Win32.WaitCursor = SaveWaitCursor; } } // Private: Selection private int Selection { get { this.AvailableDevicesLabel.Text = "Select " + OurTitle + ":"; this.ShowDialog(); return MySelection; } } // Private: OKButton_Click private void OKButton_Click(object sender, System.EventArgs e) { MySelection = AvailableDevicesListBox.SelectedIndex; this.Close(); } // Private: CancelButton_Click private void CancelButton_Click(object sender, System.EventArgs e) { MySelection = -1; this.Close(); } private void OKButton_KeyDown(object sender, KeyEventArgs e) { // Checks if the key pressed was an enter button (character code 13) if (e.KeyValue == (char)13) OKButton_Click(this, e); } private void CancelButton_KeyDown(object sender, KeyEventArgs e) { // Checks if the key pressed was an enter button (character code 13) if (e.KeyValue == (char)13) CancelButton_Click(this, e); } private void SelectDevice_KeyUp(object sender, KeyEventArgs e) { this.OKButton.Focus(); } // Private: SelectDevice_KeyDown private void SelectDevice_KeyDown(object sender,KeyEventArgs e) { switch(e.KeyCode) { case Keys.Enter: this.OKButton_Click(this,EventArgs.Empty); return; case Keys.Up: if ( this.AvailableDevicesListBox.SelectedIndex > 0 ) { this.AvailableDevicesListBox.SelectedIndex--; } return; case Keys.Down: if ( this.AvailableDevicesListBox.SelectedIndex < this.AvailableDevicesListBox.Items.Count-1 ) { this.AvailableDevicesListBox.SelectedIndex++; } return; } } private void SelectDevice_Resize(object sender, System.EventArgs e) { if (bInitialScale == true) { return; // Return if the initial scaling (from scratch)is not complete. } if (Screen.PrimaryScreen.Bounds.Width > Screen.PrimaryScreen.Bounds.Height) // If landscape orientation { if (bPortrait != false) // If an orientation change has occured to landscape { bPortrait = false; // Set the orientation flag accordingly. bInitialScale = true; // An initial scaling is required due to orientation change. Scale(this); // Scale the GUI. } else { // No orientation change has occured bSkipMaxLen = true; // Initial scaling is now complete, so skipping the max. length restriction is now possible. Scale(this); // Scale the GUI. } } else { // Similarly for the portrait orientation... if (bPortrait != true) { bPortrait = true; bInitialScale = true; Scale(this); } else { bSkipMaxLen = true; Scale(this); } } } [DllImport("coredll.dll")] internal static extern Int32 GetDeviceCaps(IntPtr hdc, Int32 index); [DllImport("coredll.dll")] internal static extern Int32 GetCapture(); } }
// 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 Xunit; public class Capacity { public const int MAX_RND_CAPACITY = 512; public const int LARGE_CAPACITY = 1024; public static readonly int DEFAULT_CAPACITY = new ArrayList().Capacity; private int _numErrors = 0; private int _numTestcases = 0; private int _retValue = 100; public delegate bool TestDelegate(); [Fact] public static void CapacityTests() { Capacity objTest = new Capacity(); try { objTest.RunTest(); } catch (Exception e) { Console.WriteLine(" : FAIL The following exception was thorwn in RunTest(): \n" + e.ToString()); objTest._numErrors++; objTest._retValue = 1; } Assert.Equal(objTest._retValue, 100); } public bool RunTest() { bool retValue = true; retValue &= BeginTestcase(new TestDelegate(Capacity_Int32MinValue)); retValue &= BeginTestcase(new TestDelegate(Capacity_NegRnd)); retValue &= BeginTestcase(new TestDelegate(Capacity_Neg1)); retValue &= BeginTestcase(new TestDelegate(Capacity_0)); retValue &= BeginTestcase(new TestDelegate(Capacity_1)); retValue &= BeginTestcase(new TestDelegate(Capacity_PosRnd)); retValue &= BeginTestcase(new TestDelegate(Capacity_Large)); retValue &= BeginTestcase(new TestDelegate(Capacity_Int32MaxValue)); retValue &= BeginTestcase(new TestDelegate(Capacity_2_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_Neg1_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_0_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_1_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_3_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_64_With2Elements)); retValue &= BeginTestcase(new TestDelegate(Capacity_Grow)); retValue &= BeginTestcase(new TestDelegate(Capacity_Remove)); retValue &= BeginTestcase(new TestDelegate(Capacity_GrowRemove)); retValue &= BeginTestcase(new TestDelegate(Capacity_EqualNumElements)); return retValue; } public bool Capacity_Int32MinValue() { bool retValue = true; retValue &= SetCapacityAndVerify(Int32.MinValue, typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_001!!! Verifying Int32.MinValue Capacity FAILED"); } return retValue; } public bool Capacity_NegRnd() { bool retValue = true; Random rndGen = new Random(-55); retValue &= SetCapacityAndVerify(rndGen.Next(Int32.MinValue, 0), typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_002!!! Verifying negative random Capacity FAILED"); } return retValue; } public bool Capacity_Neg1() { bool retValue = true; retValue &= SetCapacityAndVerify(-1, typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_003!!! Verifying -1 Capacity FAILED"); } return retValue; } public bool Capacity_0() { bool retValue = true; retValue &= SetCapacityAndVerify(0, 0, null); if (!retValue) { Console.WriteLine("Err_004!!! Verifying 0 Capacity FAILED"); } return retValue; } public bool Capacity_1() { bool retValue = true; retValue &= SetCapacityAndVerify(1, 1, null); if (!retValue) { Console.WriteLine("Err_005!!! Verifying 1 Capacity FAILED"); } return retValue; } public bool Capacity_PosRnd() { bool retValue = true; Random rndGen = new Random(-55); int rndCapacity = rndGen.Next(2, MAX_RND_CAPACITY); retValue &= SetCapacityAndVerify(rndCapacity, rndCapacity, null); if (!retValue) { Console.WriteLine("Err_006!!! Verifying positive random Capacity FAILED"); } return retValue; } public bool Capacity_Large() { bool retValue = true; retValue &= SetCapacityAndVerify(LARGE_CAPACITY, LARGE_CAPACITY, null); if (!retValue) { Console.WriteLine("Err_007!!! Verifying1 Capacity FAILED"); } return retValue; } public bool Capacity_Int32MaxValue() { bool retValue = true; retValue &= SetCapacityAndVerify(Int32.MaxValue, typeof(OutOfMemoryException)); if (!retValue) { Console.WriteLine("Err_008!!! Verifying Int32.MaxValue Capacity FAILED"); } return retValue; } public bool Capacity_2_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, 2, 2, null); if (!retValue) { Console.WriteLine("Err_009!!! Verifying setting capacity to 2 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_Neg1_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, -1, mc.Capacity, typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_010!!! Verifying setting capacity to -1 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_0_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, 0, mc.Capacity, typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_011!!! Verifying setting capacity to 0 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_1_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, 1, mc.Capacity, typeof(ArgumentOutOfRangeException)); if (!retValue) { Console.WriteLine("Err_012!!! Verifying setting capacity to 1 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_3_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, 3, 3, null); if (!retValue) { Console.WriteLine("Err_012!!! Verifying setting capacity to 3 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_64_With2Elements() { bool retValue = true; MyCollection mc = new MyCollection(); Random rndGen = new Random(-55); mc.Add(rndGen.Next()); mc.Add(rndGen.Next()); retValue &= SetCapacityAndVerify(mc, 64, 64, null); if (!retValue) { Console.WriteLine("Err_013!!! Verifying setting capacity to 64 with 2 elements in the collection FAILED"); } return retValue; } public bool Capacity_Grow() { bool retValue = true; MyCollection mc = new MyCollection(4); int initialCapacity = mc.Capacity; Random rndGen = new Random(-55); for (int i = 0; i < initialCapacity + 1; i++) { mc.Add(rndGen.Next()); } retValue &= VerifyCapacity(mc, initialCapacity * 2); if (!retValue) { Console.WriteLine("Err_014!!! Verifying growing the capacity by adding elements tot he collection FAILED"); } return retValue; } public bool Capacity_Remove() { bool retValue = true; MyCollection mc = new MyCollection(4); int initialCapacity = mc.Capacity; Random rndGen = new Random(-55); for (int i = 0; i < initialCapacity; i++) { mc.Add(rndGen.Next()); } mc.RemoveAt(initialCapacity - 1); retValue &= SetCapacityAndVerify(mc, initialCapacity - 1, initialCapacity - 1, null); if (!retValue) { Console.WriteLine("Err_015!!! Verifying adding the same number of elements to the collection as the Capacity then remoiving one FAILED"); } return retValue; } public bool Capacity_GrowRemove() { bool retValue = true; MyCollection mc = new MyCollection(4); int initialCapacity = mc.Capacity; Random rndGen = new Random(-55); for (int i = 0; i < initialCapacity + 1; i++) { mc.Add(rndGen.Next()); } mc.RemoveAt(initialCapacity); retValue &= SetCapacityAndVerify(mc, initialCapacity, initialCapacity, null); if (!retValue) { Console.WriteLine("Err_016!!! Verifying growing the capacity by adding elements tot he collection then removing one FAILED"); } return retValue; } public bool Capacity_EqualNumElements() { bool retValue = true; MyCollection mc = new MyCollection(4); int initialCapacity = mc.Capacity; Random rndGen = new Random(-55); for (int i = 0; i < initialCapacity; i++) { mc.Add(rndGen.Next()); } retValue &= VerifyCapacity(mc, 4); if (!retValue) { Console.WriteLine("Err_017!!! Verifying adding the same number of elements to the collection as the Capacity then remoiving one FAILED"); } return retValue; } public bool SetCapacityAndVerify(int capacity, Type expectedException) { return SetCapacityAndVerify(capacity, DEFAULT_CAPACITY, expectedException); } public bool SetCapacityAndVerify(int capacity, int expectedCapacity, Type expectedException) { MyCollection mc = new MyCollection(); return SetCapacityAndVerify(mc, capacity, expectedCapacity, expectedException); } public bool SetCapacityAndVerify(MyCollection mc, int capacity, int expectedCapacity, Type expectedException) { bool retValue = true; try { mc.Capacity = capacity; if (null != expectedException) { Console.WriteLine("ERROR!!! Expected exception {0} and NOTHING was thrown", expectedException); retValue = false; } } catch (System.Exception e) { if (null == expectedException) { Console.WriteLine("ERROR!!! Expected NO exception to be thrown and {0} was thrown", e.GetType()); retValue = false; } else if (e.GetType() != expectedException) { Console.WriteLine("ERROR!!! Expected exception {0} and {1} was thrown", expectedException, e.GetType()); retValue = false; } } retValue &= VerifyCapacity(mc, expectedCapacity); return retValue; } public bool VerifyCapacity(MyCollection mc, int expectedCapacity) { bool retValue = true; if (mc.Capacity != expectedCapacity) { Console.WriteLine("ERROR!!! MyCollection.Capacity={0} expected={1}", mc.Capacity, expectedCapacity); retValue = false; } if (mc.InnerListCapacity != expectedCapacity) { Console.WriteLine("ERROR!!! MyCollection.InnerList.Capacity={0} expected={1}", mc.InnerListCapacity, expectedCapacity); retValue = false; } return retValue; } private bool BeginTestcase(TestDelegate test) { bool retValue = true; if (test()) { _numTestcases++; retValue = true; } else { _numErrors++; retValue = false; } return retValue; } public class MyCollection : CollectionBase { public MyCollection() : base() { } public MyCollection(int capacity) : base(capacity) { } public void Add(int value) { InnerList.Add(value); } public int InnerListCapacity { get { return InnerList.Capacity; } } } }
// 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 BroadcastScalarToVector128Single() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Single(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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 SimpleUnaryOpTest__BroadcastScalarToVector128Single { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector128<Single> _clsVar; private Vector128<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static SimpleUnaryOpTest__BroadcastScalarToVector128Single() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__BroadcastScalarToVector128Single() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.BroadcastScalarToVector128<Single>( Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.BroadcastScalarToVector128<Single>( Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.BroadcastScalarToVector128<Single>( Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.BroadcastScalarToVector128)) .MakeGenericMethod( new Type[] { typeof(Single) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.BroadcastScalarToVector128<Single>( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Single>>(_dataTable.inArrayPtr); var result = Avx2.BroadcastScalarToVector128<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse.LoadVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse.LoadAlignedVector128((Single*)(_dataTable.inArrayPtr)); var result = Avx2.BroadcastScalarToVector128<Single>(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__BroadcastScalarToVector128Single(); var result = Avx2.BroadcastScalarToVector128<Single>(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.BroadcastScalarToVector128<Single>(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((BitConverter.SingleToInt32Bits(firstOp[0]) != BitConverter.SingleToInt32Bits(result[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BroadcastScalarToVector128)}<Single>(Vector128<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Net; using MindTouch.Tasking; using MindTouch.Web; using MindTouch.Xml; using NUnit.Framework; namespace MindTouch.Dream.Test { [TestFixture] public class CookieTests { [Test] public void ParseCookies1() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\""); Assert.AreEqual(1, cookies.Count, "failed to parse cookies"); Assert.AreEqual("Customer", cookies[0].Name, "bad cookie name"); Assert.AreEqual("WILE_E_COYOTE", cookies[0].Value, "bad cookie value"); Assert.AreEqual("/acme", cookies[0].Path, "bad cookie path"); } [Test] public void ParseCookies2() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\""); Assert.AreEqual(1, cookies.Count, "failed to parse cookies"); Assert.AreEqual("Customer", cookies[0].Name, "bad cookie name"); Assert.AreEqual("WILE_E_COYOTE", cookies[0].Value, "bad cookie value"); Assert.AreEqual("/acme", cookies[0].Path, "bad cookie path"); } [Test] public void ParseCookies3() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\", Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\", Shipping=\"FedEx\"; $Path=\"/acme\""); Assert.AreEqual(3, cookies.Count, "failed to parse cookies"); Assert.AreEqual("Customer", cookies[0].Name, "bad cookie 0 name"); Assert.AreEqual("Part_Number", cookies[1].Name, "bad cookie 1 name"); Assert.AreEqual("Shipping", cookies[2].Name, "bad cookie 2 name"); Assert.AreEqual("WILE_E_COYOTE", cookies[0].Value, "bad cookie 0 value"); Assert.AreEqual("Rocket_Launcher_0001", cookies[1].Value, "bad cookie 1 value"); Assert.AreEqual("FedEx", cookies[2].Value, "bad cookie 2 value"); Assert.AreEqual("/acme", cookies[0].Path, "bad cookie 0 path"); Assert.AreEqual("/acme", cookies[1].Path, "bad cookie 1 path"); Assert.AreEqual("/acme", cookies[2].Path, "bad cookie 2 path"); } [Test] public void ParseCookies4() { List<DreamCookie> result = DreamCookie.ParseCookieHeader("$Version=\"1\"; Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\", Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""); Assert.AreEqual(2, result.Count); Assert.AreEqual("Customer", result[0].Name); Assert.AreEqual("WILE_E_COYOTE", result[0].Value); Assert.AreEqual("/acme", result[0].Path); Assert.AreEqual("Part_Number", result[1].Name); Assert.AreEqual("Rocket_Launcher_0001", result[1].Value); Assert.AreEqual("/acme", result[1].Path); } [Test] public void ParseCookies5() { List<DreamCookie> result = DreamCookie.ParseCookieHeader("Customer=WILE_E_COYOTE; $Path=\"/acme\", Part_Number=\"Rocket \\\"Launcher\\\" 0001\"; $Path=\"/acme\""); Assert.AreEqual(2, result.Count); Assert.AreEqual("Customer", result[0].Name); Assert.AreEqual("WILE_E_COYOTE", result[0].Value); Assert.AreEqual("/acme", result[0].Path); Assert.AreEqual("Part_Number", result[1].Name); Assert.AreEqual("Rocket \"Launcher\" 0001", result[1].Value); Assert.AreEqual("/acme", result[1].Path); } [Test] public void ParseCookies6() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("$Version=\"1\", Customer=\"WILE_E_COYOTE\"; $Path=\"/acme\""); Assert.AreEqual(1, cookies.Count, "failed to parse cookies"); Assert.AreEqual("Customer", cookies[0].Name, "bad cookie name"); Assert.AreEqual("WILE_E_COYOTE", cookies[0].Value, "bad cookie value"); Assert.AreEqual("/acme", cookies[0].Path, "bad cookie path"); } [Test] public void ParseCookies7() { List<DreamCookie> cookies = new List<DreamCookie>(); cookies.Add(new DreamCookie("Customer", "WILE_E_COYOTE", new XUri("http://localhost/acme"))); string header = DreamCookie.RenderCookieHeader(cookies); cookies = DreamCookie.ParseCookieHeader(header); Assert.AreEqual(1, cookies.Count, "failed to parse cookies"); Assert.AreEqual("Customer", cookies[0].Name, "bad cookie name"); Assert.AreEqual("WILE_E_COYOTE", cookies[0].Value, "bad cookie value"); Assert.AreEqual("/acme", cookies[0].Path, "bad cookie path"); } [Test] public void ParseBadCookie1() { var cookies = DreamCookie.ParseCookieHeader("foo=\"bar\"; [index.php]scayt_verLang=5; authtoken=\"1234\""); Assert.AreEqual(3, cookies.Count, "Failed to parse cookies, wrong number of resulting cookies"); Assert.AreEqual(cookies[0].Name, "foo", "bad cookie name"); Assert.AreEqual(cookies[0].Value, "bar", "bad cookie value"); Assert.AreEqual(cookies[2].Name, "authtoken", "bad cookie name"); Assert.AreEqual(cookies[2].Value, "1234", "bad cookie value"); } [Test] public void ParseBadCookie2() { var cookies = DreamCookie.ParseCookieHeader(" foo=\"bar\"; lithiumLogin:successfactors=~2acHBr09HxytcqIXV~eVqhSr8s74VfDTjhQ8XU615EaYeGn-7OdDSN70BshVnsYG71yPbJvKPoZzHl05KP; authtoken=\"1234\" "); Assert.AreEqual(3, cookies.Count, "Failed to parse cookies, wrong number of resulting cookies"); Assert.AreEqual(cookies[0].Name, "foo", "bad cookie name"); Assert.AreEqual(cookies[0].Value, "bar", "bad cookie value"); Assert.AreEqual(cookies[2].Name, "authtoken", "bad cookie name"); Assert.AreEqual(cookies[2].Value, "1234", "bad cookie value"); } [Test] public void ParseBadCookie3() { var cookies = DreamCookie.ParseCookieHeader(" foo=\"bar\", lithiumLogin:successfactors=~2acHBr09HxytcqIXV~eVqhSr8s74VfDTjhQ8XU615EaYeGn-7OdDSN70BshVnsYG71yPbJvKPoZzHl05KP; authtoken=\"1234\" "); Assert.AreEqual(3, cookies.Count, "Failed to parse cookies, wrong number of resulting cookies"); Assert.AreEqual(cookies[0].Name, "foo", "bad cookie name"); Assert.AreEqual(cookies[0].Value, "bar", "bad cookie value"); Assert.AreEqual(cookies[2].Name, "authtoken", "bad cookie name"); Assert.AreEqual(cookies[2].Value, "1234", "bad cookie value"); } [Test] public void ParseBadCookie4() { var cookies = DreamCookie.ParseCookieHeader(" foo=\"bar\"; hel,lo=\"wo,~rld\"; authtoken=\"1234\" "); Assert.AreEqual(4, cookies.Count, "Failed to parse cookies, wrong number of resulting cookies"); Assert.AreEqual(cookies[0].Name, "foo", "bad cookie name"); Assert.AreEqual(cookies[0].Value, "bar", "bad cookie value"); Assert.AreEqual(cookies[1].Name, "hel", "bad cookie name"); Assert.IsNull(cookies[1].Value, null, "bad cookie value"); Assert.AreEqual(cookies[2].Name, "lo", "bad cookie name"); Assert.AreEqual(cookies[2].Value, "wo,~rld", "bad cookie value"); Assert.AreEqual(cookies[3].Name, "authtoken", "bad cookie name"); Assert.AreEqual(cookies[3].Value, "1234", "bad cookie value"); } [Test] public void ParseBadCookie5() { var cookies = DreamCookie.ParseCookieHeader(" foo=\"bar\", hello=wo;;rld; authtoken=\"1234\" "); Assert.AreEqual(4, cookies.Count, "Failed to parse cookies, wrong number of resulting cookies"); Assert.AreEqual(cookies[0].Name, "foo", "bad cookie name"); Assert.AreEqual(cookies[0].Value, "bar", "bad cookie value"); Assert.AreEqual(cookies[3].Name, "authtoken", "bad cookie name"); Assert.AreEqual(cookies[3].Value, "1234", "bad cookie value"); } [Test] public void ParseCookies_with_unquoted_values() { List<DreamCookie> result = DreamCookie.ParseCookieHeader("__utma=134392366.697651776.1256325927.1256943466.1256946079.27; __utmz=134392366.1256946079.27.2.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:SteveB/Bugs; LOOPFUSE=78fe6a69-de6f-494f-9cf1-7e4fbe7a1c38; __kti=1256208055528,http%3A%2F%2Fwww.mindtouch.com%2F,; __ktv=9f88-8fb4-514a-a2cb1247bd5bce8; _mkto_trk=id:954-WGP-507&token:_mch-mindtouch.com-1256705011527-41439; __utma=249966356.478917817.1256718580.1256718580.1256946891.2; __utmz=249966356.1256946891.2.2.utmcsr=bugs.developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/view.php; __utmc=134392366; __utmb=134392366.7.10.1256946079; PHPSESSID=bed8f2d85712b33f1a3804856045b374; __utmb=249966356.1.10.1256946891; __utmc=249966356; __kts=1256946891198,http%3A%2F%2Fcampaign.mindtouch.com%2FEvents%2FSharepoint,http%3A%2F%2Fbugs.developer.mindtouch.com%2Fview.php%3Fid%3D7255; __ktt=c2e3-a511-ce1b-438b124a7df79be,abc,"); Assert.AreEqual(15, result.Count); Assert.AreEqual("__utma", result[0].Name); Assert.AreEqual("134392366.697651776.1256325927.1256943466.1256946079.27", result[0].Value); Assert.AreEqual("__utmz", result[1].Name); Assert.AreEqual("134392366.1256946079.27.2.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:SteveB/Bugs", result[1].Value); Assert.AreEqual("LOOPFUSE", result[2].Name); Assert.AreEqual("78fe6a69-de6f-494f-9cf1-7e4fbe7a1c38", result[2].Value); Assert.AreEqual("__kti", result[3].Name); Assert.AreEqual("1256208055528,http%3A%2F%2Fwww.mindtouch.com%2F,", result[3].Value); Assert.AreEqual("__ktv", result[4].Name); Assert.AreEqual("9f88-8fb4-514a-a2cb1247bd5bce8", result[4].Value); Assert.AreEqual("_mkto_trk", result[5].Name); Assert.AreEqual("id:954-WGP-507&token:_mch-mindtouch.com-1256705011527-41439", result[5].Value); Assert.AreEqual("__utma", result[6].Name); Assert.AreEqual("249966356.478917817.1256718580.1256718580.1256946891.2", result[6].Value); Assert.AreEqual("__utmz", result[7].Name); Assert.AreEqual("249966356.1256946891.2.2.utmcsr=bugs.developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/view.php", result[7].Value); Assert.AreEqual("__utmc", result[8].Name); Assert.AreEqual("134392366", result[8].Value); Assert.AreEqual("__utmb", result[9].Name); Assert.AreEqual("134392366.7.10.1256946079", result[9].Value); Assert.AreEqual("PHPSESSID", result[10].Name); Assert.AreEqual("bed8f2d85712b33f1a3804856045b374", result[10].Value); Assert.AreEqual("__utmb", result[11].Name); Assert.AreEqual("249966356.1.10.1256946891", result[11].Value); Assert.AreEqual("__utmc", result[12].Name); Assert.AreEqual("249966356", result[12].Value); Assert.AreEqual("__kts", result[13].Name); Assert.AreEqual("1256946891198,http%3A%2F%2Fcampaign.mindtouch.com%2FEvents%2FSharepoint,http%3A%2F%2Fbugs.developer.mindtouch.com%2Fview.php%3Fid%3D7255", result[13].Value); Assert.AreEqual("__ktt", result[14].Name); Assert.AreEqual("c2e3-a511-ce1b-438b124a7df79be,abc,", result[14].Value); } [Test] public void ParseCookies_with_unquoted_values2() { List<DreamCookie> result = DreamCookie.ParseCookieHeader("__utma=134392366.2030730348.1275932450.1276553042.1276556836.19; __utmz=134392366.1276207881.9.3.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:arnec/bugs; _mkto_trk=id:954-WGP-507&token:_mch-mindtouch.com-1270756717014-83706; WRUID=0; __kti=1274382964652,http%3A%2F%2Fwww.mindtouch.com%2F,; __ktv=2f4-f02d-634b-51e2128b724d7c2; __qca=P0-2102347259-1274460371553; PHPSESSID=307e779182909ab37932b4dffe77c40a; __utmc=134392366; __kts=1274382964673,http%3A%2F%2Fwww.mindtouch.com%2F,; __ktt=631f-d0a2-648e-e0b128b724d7c2; authtoken=\"1_634121336269193470_4254e33b49bc1ee0a72c5716200e296b\"; __utmb=134392366.6.10.1276556836"); Assert.AreEqual(13, result.Count); Assert.AreEqual("__utma", result[0].Name); Assert.AreEqual("134392366.2030730348.1275932450.1276553042.1276556836.19", result[0].Value); Assert.AreEqual("__utmz", result[1].Name); Assert.AreEqual("134392366.1276207881.9.3.utmcsr=developer.mindtouch.com|utmccn=(referral)|utmcmd=referral|utmcct=/User:arnec/bugs", result[1].Value); Assert.AreEqual("_mkto_trk", result[2].Name); Assert.AreEqual("id:954-WGP-507&token:_mch-mindtouch.com-1270756717014-83706", result[2].Value); Assert.AreEqual("WRUID", result[3].Name); Assert.AreEqual("0", result[3].Value); Assert.AreEqual("__kti", result[4].Name); Assert.AreEqual("1274382964652,http%3A%2F%2Fwww.mindtouch.com%2F,", result[4].Value); Assert.AreEqual("__ktv", result[5].Name); Assert.AreEqual("2f4-f02d-634b-51e2128b724d7c2", result[5].Value); Assert.AreEqual("__qca", result[6].Name); Assert.AreEqual("P0-2102347259-1274460371553", result[6].Value); Assert.AreEqual("PHPSESSID", result[7].Name); Assert.AreEqual("307e779182909ab37932b4dffe77c40a", result[7].Value); Assert.AreEqual("__utmc", result[8].Name); Assert.AreEqual("134392366", result[8].Value); Assert.AreEqual("__kts", result[9].Name); Assert.AreEqual("1274382964673,http%3A%2F%2Fwww.mindtouch.com%2F,", result[9].Value); Assert.AreEqual("__ktt", result[10].Name); Assert.AreEqual("631f-d0a2-648e-e0b128b724d7c2", result[10].Value); Assert.AreEqual("authtoken", result[11].Name); Assert.AreEqual("1_634121336269193470_4254e33b49bc1ee0a72c5716200e296b", result[11].Value); Assert.AreEqual("__utmb", result[12].Name); Assert.AreEqual("134392366.6.10.1276556836", result[12].Value); } [Test] public void Parse_SetCookie() { List<DreamCookie> result = DreamCookie.ParseSetCookieHeader("Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\", Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\""); Assert.AreEqual(2, result.Count); Assert.AreEqual("Customer", result[0].Name); Assert.AreEqual("WILE_E_COYOTE", result[0].Value); Assert.AreEqual(1, result[0].Version); Assert.AreEqual("/acme", result[0].Path); Assert.AreEqual(false, result[0].HttpOnly); Assert.AreEqual("Part_Number", result[1].Name); Assert.AreEqual("Rocket_Launcher_0001", result[1].Value); Assert.AreEqual(1, result[1].Version); Assert.AreEqual("/acme", result[1].Path); Assert.AreEqual(false, result[1].HttpOnly); } [Test] public void Parse_SetCookie_with_HttpOnly() { List<DreamCookie> result = DreamCookie.ParseSetCookieHeader("Customer=\"WILE_E_COYOTE\"; Version=\"1\"; Path=\"/acme\"; HttpOnly, Part_Number=\"Rocket_Launcher_0001\"; Version=\"1\"; Path=\"/acme\"; HttpOnly"); Assert.AreEqual(2, result.Count); Assert.AreEqual("Customer", result[0].Name); Assert.AreEqual("WILE_E_COYOTE", result[0].Value); Assert.AreEqual(1, result[0].Version); Assert.AreEqual(true, result[0].HttpOnly); Assert.AreEqual("/acme", result[0].Path); Assert.AreEqual("Part_Number", result[1].Name); Assert.AreEqual("Rocket_Launcher_0001", result[1].Value); Assert.AreEqual(1, result[1].Version); Assert.AreEqual("/acme", result[1].Path); Assert.AreEqual(true, result[1].HttpOnly); } [Test] public void Parse_5_cookies_separated_by_semicolon() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("authtoken=\"3_633644459231333750_74b1192b1846f065523d01ac18c772c5\"; PHPSESSID=34c4b18a50a91dd99adb1ed1e6b570cb; __utma=14492279.2835659202033839600.1228849092.1228849092.1228849092.1; __utmc=14492279; __utmz=14492279.1228849092.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"); Assert.AreEqual(5, cookies.Count); Assert.AreEqual("authtoken", cookies[0].Name); Assert.AreEqual("3_633644459231333750_74b1192b1846f065523d01ac18c772c5", cookies[0].Value); Assert.AreEqual("PHPSESSID", cookies[1].Name); Assert.AreEqual("34c4b18a50a91dd99adb1ed1e6b570cb", cookies[1].Value); } [Test] public void Parse_2_cookies_separated_by_semicolon() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("PHPSESSID=663e17bc2eaef4e355c6e6fe1bb86c04; authtoken=1_633644446772281250_c3dd88ad4539197ef12f3614e91fec8f"); Assert.AreEqual(2, cookies.Count); Assert.AreEqual("PHPSESSID", cookies[0].Name); Assert.AreEqual("663e17bc2eaef4e355c6e6fe1bb86c04", cookies[0].Value); Assert.AreEqual("authtoken", cookies[1].Name); Assert.AreEqual("1_633644446772281250_c3dd88ad4539197ef12f3614e91fec8f", cookies[1].Value); } [Test] public void Parse_cookie_without_path_or_domain() { List<DreamCookie> cookies = DreamCookie.ParseCookieHeader("foo=\"bar\""); Assert.IsNull(cookies[0].Path); Assert.IsNull(cookies[0].Domain); } [Test] public void Parse_cookie_sample_from_wikipedia() { List<DreamCookie> cookies = DreamCookie.ParseSetCookieHeader("RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT; path=/; domain=.example.net; HttpOnly"); Assert.AreEqual(1, cookies.Count); Assert.AreEqual("RMID", cookies[0].Name); Assert.AreEqual("732423sdfs73242", cookies[0].Value); DateTime expires = DateTimeUtil.ParseExactInvariant("Fri, 31-Dec-2010 23:59:59 GMT", "ddd, dd-MMM-yyyy HH:mm:ss 'GMT'"); Assert.AreEqual(expires, cookies[0].Expires); Assert.AreEqual("/", cookies[0].Path); // TODO (steveb): it seems wrong that we check for 'example.net' instead of '.example.net' Assert.AreEqual("example.net", cookies[0].Domain); Assert.AreEqual(true, cookies[0].HttpOnly); } [Test] public void GetCookie_with_no_path() { List<DreamCookie> cookies = new List<DreamCookie>(); cookies.Add(new DreamCookie("foo", "bar", null)); DreamCookie c = DreamCookie.GetCookie(cookies, "foo"); Assert.IsNotNull(c); Assert.AreEqual("bar", c.Value); } [Test] public void SetCookie_without_uri() { DreamCookie cookie = DreamCookie.NewSetCookie("foo", "bar", null); Assert.IsNull(cookie.Path); Assert.IsNull(cookie.Domain); string cookieHeader = cookie.ToSetCookieHeader(); Assert.IsFalse(cookieHeader.Contains("Path")); Assert.IsFalse(cookieHeader.Contains("Domain")); } [Test] public void Render_SetCookie_header_for_hostname_does_not_start_with_dot() { string header = DreamCookie.NewSetCookie("foo", "bar", new XUri("http://myhost/x/y/z")).ToSetCookieHeader(); Assert.IsTrue(header.Contains("Path=/x/y/z"), "path is bad: " + header); Assert.IsFalse(header.Contains("Domain"), "domain found: " + header); } [Test] public void Render_SetCookie_header_for_localhost_does_not_start_with_dot() { string header = DreamCookie.NewSetCookie("foo", "bar", new XUri("http://localhost/x/y/z")).ToSetCookieHeader(); Assert.IsTrue(header.Contains("Path=/x/y/z"), "path is bad: " + header); Assert.IsFalse(header.Contains("Domain"), "domain found: " + header); } [Test] public void Render_SetCookie_header_for_domainname_does_start_with_dot() { string header = DreamCookie.NewSetCookie("foo", "bar", new XUri("http://foo.com/x/y/z")).ToSetCookieHeader(); Assert.IsTrue(header.Contains("Path=/x/y/z"), "path is bad: " + header); Assert.IsTrue(header.Contains("Domain=.foo.com"), "domain is bad: " + header); } [Test] public void Render_SetCookied_with_HttpOnly() { string header = DreamCookie.NewSetCookie("foo", "bar", new XUri("http://foo.com/x/y/z"), DateTime.MaxValue, false, null, null, true).ToSetCookieHeader(); Assert.IsTrue(header.Contains("; HttpOnly"), "missing HttpOnly"); } [Test] public void SetCookie_to_Xml_and_back() { DreamCookie cookie1 = DreamCookie.NewSetCookie( "foo", "bar", new XUri("http://abc.com/path"), GlobalClock.UtcNow.AddDays(1), true, "blah blah", new XUri("http://comment.com/blah")); XDoc cookieDoc = cookie1.AsSetCookieDocument; DreamCookie cookie2 = DreamCookie.ParseSetCookie(cookieDoc); Assert.AreEqual(cookie1.Comment, cookie2.Comment); Assert.AreEqual(cookie1.CommentUri, cookie2.CommentUri); Assert.AreEqual(cookie1.Domain, cookie2.Domain); Assert.AreEqual(cookie1.Expired, cookie2.Expired); Assert.AreEqual(cookie1.Expires, cookie2.Expires); Assert.AreEqual(cookie1.Name, cookie2.Name); Assert.AreEqual(cookie1.Path, cookie2.Path); Assert.AreEqual(cookie1.Secure, cookie2.Secure); Assert.AreEqual(cookie1.Uri, cookie2.Uri); Assert.AreEqual(cookie1.Value, cookie2.Value); } [Test] public void SetCookie_to_header_and_back() { DreamCookie cookie1 = DreamCookie.NewSetCookie( "foo", "bar", new XUri("http://abc.com/path"), GlobalClock.UtcNow.AddDays(1), true, "blah blah", new XUri("http://comment.com/blah")); string header = cookie1.ToSetCookieHeader(); List<DreamCookie> cookies = DreamCookie.ParseSetCookieHeader(header); Assert.AreEqual(1, cookies.Count); DreamCookie cookie2 = cookies[0]; Assert.AreEqual(cookie1.Comment, cookie2.Comment); Assert.AreEqual(cookie1.CommentUri, cookie2.CommentUri); Assert.AreEqual(cookie1.Domain, cookie2.Domain); Assert.AreEqual(cookie1.Expires, cookie2.Expires); Assert.AreEqual(cookie1.Expired, cookie2.Expired); Assert.AreEqual(cookie1.Name, cookie2.Name); Assert.AreEqual(cookie1.Path, cookie2.Path); Assert.AreEqual(cookie1.Secure, cookie2.Secure); Assert.AreEqual(cookie1.Uri, cookie2.Uri); Assert.AreEqual(cookie1.Value, cookie2.Value); } [Test] public void Create_SetCookie_header() { DreamCookie setcookie = DreamCookie.NewSetCookie("test", "123", new XUri("http://bar.com/foo")); Assert.AreEqual("/foo", setcookie.Path); Assert.AreEqual("bar.com", setcookie.Domain); string setcookieString = setcookie.ToSetCookieHeader(); Assert.AreEqual("test=\"123\"; Domain=.bar.com; Version=1; Path=/foo", setcookieString); List<DreamCookie> cookies = DreamCookie.ParseSetCookieHeader(setcookieString); Assert.AreEqual(1, cookies.Count); Assert.AreEqual("/foo", cookies[0].Path); Assert.AreEqual("bar.com", cookies[0].Domain); } [Test] public void Fetch_cookie_from_jar() { DreamCookie setcookie = DreamCookie.NewSetCookie("test", "123", new XUri("http://bar.com/foo")); List<DreamCookie> cookies = new List<DreamCookie>(); cookies.Add(setcookie); DreamCookieJar jar = new DreamCookieJar(); jar.Update(cookies, null); List<DreamCookie> cookies2 = jar.Fetch(new XUri("http://bar.com/foo/baz")); Assert.AreEqual(1, cookies2.Count); Assert.AreEqual("/foo", cookies2[0].Path); Assert.AreEqual("bar.com", cookies2[0].Domain); } [Test] public void Set_Fetch_cookie_from_jar_for_https() { List<DreamCookie> setcookies = new List<DreamCookie>(); setcookies.Add(DreamCookie.NewSetCookie("authtoken", "1_633698885517217440_64e1d64e732341bde1797f20fe2ab824", new XUri("http:///"), GlobalClock.UtcNow.AddDays(2))); DreamCookieJar jar = new DreamCookieJar(); jar.Update(setcookies,new XUri("https://admin:pass@wikiaddress//@api/deki/users/authenticate")); List<DreamCookie> cookies = jar.Fetch(new XUri("https://wikiaddress//@api/deki/Pages/home/files,subpages")); Assert.AreEqual(1,cookies.Count); Assert.AreEqual("/", cookies[0].Path); Assert.AreEqual("1_633698885517217440_64e1d64e732341bde1797f20fe2ab824", cookies[0].Value); Assert.AreEqual("authtoken", cookies[0].Name); } [Test] public void Fetch_cookie_from_dreamcontext_jar_with_local_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("uri.public", "/foo/bar"))) { MockServiceInfo mock = MockService.CreateMockService(hostInfo); List<DreamCookie> cookies = null; mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { context.Service.Cookies.Update(new DreamCookie("public", "bar", mock.AtLocalHost.Uri), null); context.Service.Cookies.Update(new DreamCookie("local", "baz", mock.AtLocalMachine.Uri), null); cookies = context.Service.Cookies.Fetch(mock.AtLocalHost.Uri); response2.Return(DreamMessage.Ok()); }; mock.AtLocalHost.Post(); bool foundPublic = false; bool foundLocal = false; foreach(DreamCookie cookie in cookies) { switch(cookie.Name) { case "public": foundPublic = true; break; case "local": foundLocal = true; break; } } Assert.IsTrue(foundPublic, "didn't find public"); Assert.IsTrue(foundLocal, "didn't find local"); } } [Test] public void SetCookie_header_passed_between_services_uses_local_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost()) { MockServiceInfo mock1 = MockService.CreateMockService(hostInfo); MockServiceInfo mock2 = MockService.CreateMockService(hostInfo); List<DreamCookie> cookies = null; mock1.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage r = Plug.New(mock2.AtLocalMachine).Post(DreamMessage.Ok()); cookies = context.Service.Cookies.Fetch(mock2.AtLocalMachine); Assert.AreEqual(1, cookies.Count); Assert.AreEqual(mock2.AtLocalMachine.Uri, cookies[0].Uri); response2.Return(DreamMessage.Ok()); }; mock2.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri)); response2.Return(msg); }; mock1.AtLocalHost.Post(); Assert.AreEqual(1, cookies.Count); } } [Test] public void SetCookie_header_passed_from_service_over_webrequest_uses_public_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost()) { MockServiceInfo mock = MockService.CreateMockService(hostInfo); mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri)); response2.Return(msg); }; XUri localUri = mock.AtLocalHost.Uri; HttpWebRequest r = WebRequest.Create(localUri.ToString()) as HttpWebRequest; CookieContainer cookies = new CookieContainer(); r.CookieContainer = cookies; r.Method = "GET"; HttpWebResponse response = (HttpWebResponse)r.GetResponse(); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual(1, response.Cookies.Count); Assert.AreEqual("localhost", response.Cookies[0].Domain); Assert.AreEqual(mock.AtLocalHost.Uri.Path, response.Cookies[0].Path); } } [Test] public void SetCookie_header_passed_from_service_to_external_uses_public_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost()) { MockServiceInfo mock = MockService.CreateMockService(hostInfo); mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri)); response2.Return(msg); }; mock.AtLocalHost.Post(); List<DreamCookie> cookies = Plug.GlobalCookies.Fetch(mock.AtLocalHost); Assert.AreEqual(1, cookies.Count); Assert.AreEqual(mock.AtLocalHost.Uri, cookies[0].Uri); } } [Test] public void SetCookie_header_passed_between_services_uses_local_uri_on_host_non_root_public_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("uri.public", "/foo/bar"))) { MockServiceInfo mock1 = MockService.CreateMockService(hostInfo); MockServiceInfo mock2 = MockService.CreateMockService(hostInfo); List<DreamCookie> cookies = null; mock1.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage r = Plug.New(mock2.AtLocalMachine).Post(DreamMessage.Ok()); cookies = context.Service.Cookies.Fetch(mock2.AtLocalMachine); Assert.AreEqual(1, cookies.Count); Assert.AreEqual(mock2.AtLocalMachine.Uri, cookies[0].Uri); response2.Return(DreamMessage.Ok()); }; mock2.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri)); response2.Return(msg); }; mock1.AtLocalHost.Post(); Assert.AreEqual(1, cookies.Count); } } [Test] public void SetCookie_header_passed_from_service_to_external_uses_public_uri_on_host_non_root_public_uri() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("uri.public", "/foo/bar"))) { MockServiceInfo mock = MockService.CreateMockService(hostInfo); mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri)); response2.Return(msg); }; mock.AtLocalHost.Post(); List<DreamCookie> cookies = Plug.GlobalCookies.Fetch(mock.AtLocalHost); Assert.AreEqual(1, cookies.Count); Assert.AreEqual(mock.AtLocalHost.Uri, cookies[0].Uri); } } [Test] public void SetCookie_header_passed_from_service_to_external_but_rooted_at_external() { using(DreamHostInfo hostInfo = DreamTestHelper.CreateRandomPortHost(new XDoc("config").Elem("uri.public", "/foo/bar"))) { MockServiceInfo mock = MockService.CreateMockService(hostInfo); mock.Service.CatchAllCallback = delegate(DreamContext context, DreamMessage request, Result<DreamMessage> response2) { DreamMessage msg = DreamMessage.Ok(); msg.Cookies.Add(DreamCookie.NewSetCookie("foo", "bar", context.Uri.AsPublicUri().WithoutPathQueryFragment())); response2.Return(msg); }; mock.AtLocalHost.Post(); List<DreamCookie> cookies = Plug.GlobalCookies.Fetch(mock.AtLocalHost); Assert.AreEqual(1, cookies.Count); Assert.AreEqual("/", cookies[0].Path); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Support.UI; using Signum.Utilities; namespace Signum.React.Selenium { public static class SeleniumExtensions { public static TimeSpan DefaultTimeout = TimeSpan.FromMilliseconds(20 * 1000); public static TimeSpan ThrowExceptionForDeveloperAfter = TimeSpan.FromMilliseconds(5 * 1000); public static TimeSpan DefaultPoolingInterval = TimeSpan.FromMilliseconds(200); public static T Wait<T>(this RemoteWebDriver selenium, Func<T> condition, Func<string>? actionDescription = null, TimeSpan? timeout = null) { try { var wait = new DefaultWait<string>("") { Timeout = timeout ?? DefaultTimeout, PollingInterval = DefaultPoolingInterval }; wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(NoAlertPresentException), typeof(StaleElementReferenceException)); var throwExceptionAfter = Debugger.IsAttached ? DateTime.Now.Add(ThrowExceptionForDeveloperAfter) : (DateTime?)null; return wait.Until(str => { var result = condition(); if ((result == null || result.Equals(false)) && throwExceptionAfter < DateTime.Now) { try { throw new WaitTakingTooLongException("Hey Developer! looks like this condition is taking too long"); } catch (WaitTakingTooLongException) { throwExceptionAfter = null; return result; } } return result; }); } catch (WebDriverTimeoutException ex) { throw new WebDriverTimeoutException(ex.Message + ": waiting for {0} in page {1}({2})".FormatWith( actionDescription == null ? "visual condition" : actionDescription(), selenium.Title, selenium.Url)); } } [Serializable] public class WaitTakingTooLongException : Exception { public WaitTakingTooLongException() { } public WaitTakingTooLongException(string message) : base(message) { } public WaitTakingTooLongException(string message, Exception inner) : base(message, inner) { } protected WaitTakingTooLongException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } public static string WaitNewWindow(this RemoteWebDriver selenium, Action action) { var old = selenium.WindowHandles.ToHashSet(); action(); return selenium.Wait(() => selenium.WindowHandles.SingleOrDefaultEx(a => !old.Contains(a)))!; } public static void WaitEquals<T>(this RemoteWebDriver selenium, T expectedValue, Func<T> value, TimeSpan? timeout = null) { T lastValue = default(T)!; selenium.Wait(() => EqualityComparer<T>.Default.Equals(lastValue = value(), expectedValue), () => "expression to be " + expectedValue + " but is " + lastValue, timeout); } public static IWebElement? TryFindElement(this RemoteWebDriver selenium, By locator) { return selenium.FindElements(locator).FirstOrDefault(); } public static IWebElement? TryFindElement(this IWebElement element, By locator) { return element.FindElements(locator).FirstOrDefault(); } public static IWebElement WaitElementPresent(this RemoteWebDriver selenium, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { return selenium.Wait(() => selenium.FindElements(locator).FirstOrDefault(), actionDescription ?? (Func<string>)(() => "{0} to be present".FormatWith(locator)), timeout)!; } public static IWebElement WaitElementPresent(this IWebElement element, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { return element.GetDriver().Wait(() => element.FindElements(locator).FirstOrDefault(), actionDescription ?? (Func<string>)(() => "{0} to be present".FormatWith(locator)), timeout)!; } public static void AssertElementPresent(this RemoteWebDriver selenium, By locator) { if (!selenium.IsElementPresent(locator)) throw new InvalidOperationException("{0} not found".FormatWith(locator)); } public static void AssertElementPresent(this IWebElement element, By locator) { if (!element.IsElementPresent(locator)) throw new InvalidOperationException("{0} not found".FormatWith(locator)); } public static bool IsElementPresent(this RemoteWebDriver selenium, By locator) { return selenium.FindElements(locator).Any(); } public static bool IsElementPresent(this IWebElement element, By locator) { return element.FindElements(locator).Any(); } public static void WaitElementNotPresent(this RemoteWebDriver selenium, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { selenium.Wait(() => !selenium.IsElementPresent(locator), actionDescription ?? (Func<string>)(() => "{0} to be not present".FormatWith(locator)), timeout); } public static void WaitElementNotPresent(this IWebElement element, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { element.GetDriver().Wait(() => !element.IsElementPresent(locator), actionDescription ?? (Func<string>)(() => "{0} to be not present".FormatWith(locator)), timeout); } public static void AssertElementNotPresent(this RemoteWebDriver selenium, By locator) { if (selenium.IsElementPresent(locator)) throw new InvalidOperationException("{0} is found".FormatWith(locator)); } public static void AssertElementNotPresent(this IWebElement element, By locator) { if (element.IsElementPresent(locator)) throw new InvalidOperationException("{0} is found".FormatWith(locator)); } //[DebuggerHidden] public static bool IsStale(this IWebElement element) { //try //{ // // Calling any method forces a staleness check // return element == null || !element.Enabled; //} //catch (StaleElementReferenceException) //{ // return true; //} return SeleniumExtras.WaitHelpers.ExpectedConditions.StalenessOf(element)(element.GetDriver()); } public static IWebElement WaitElementVisible(this RemoteWebDriver selenium, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { return selenium.Wait(() => selenium.FindElements(locator).FirstOrDefault(a => a.Displayed), actionDescription ?? (Func<string>)(() => "{0} to be visible".FormatWith(locator)), timeout)!; } public static IWebElement WaitElementVisible(this IWebElement element, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { return element.GetDriver().Wait(() => element.FindElements(locator).FirstOrDefault(a => a.Displayed), actionDescription ?? (Func<string>)(() => "{0} to be visible".FormatWith(locator)), timeout)!; } public static void AssertElementVisible(this RemoteWebDriver selenium, By locator) { var elements = selenium.FindElements(locator); if (!elements.Any()) throw new InvalidOperationException("{0} not found".FormatWith(locator)); if (!elements.First().Displayed) throw new InvalidOperationException("{0} found but not visible".FormatWith(locator)); } public static bool IsElementVisible(this RemoteWebDriver selenium, By locator) { var elements = selenium.FindElements(locator); try { return elements.Any() && elements.First().Displayed; } catch (StaleElementReferenceException) { return false; } } public static bool IsElementVisible(this IWebElement element, By locator) { var elements = element.FindElements(locator); try { return elements.Any() && elements.First().Displayed; } catch (StaleElementReferenceException) { return false; } } public static void WaitElementNotVisible(this RemoteWebDriver selenium, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { selenium.Wait(() => !selenium.IsElementVisible(locator), actionDescription ?? (Func<string>)(() => "{0} to be not visible".FormatWith(locator)), timeout); } public static void WaitElementNotVisible(this IWebElement element, By locator, Func<string>? actionDescription = null, TimeSpan? timeout = null) { element.GetDriver().Wait(() => !element.IsElementVisible(locator), actionDescription ?? (Func<string>)(() => "{0} to be not visible".FormatWith(locator)), timeout); } public static void AssertElementNotVisible(this RemoteWebDriver selenium, By locator) { if (selenium.IsElementVisible(locator)) throw new InvalidOperationException("{0} is visible".FormatWith(locator)); } public static void AssertElementNotVisible(this IWebElement element, By locator) { if (element.IsElementVisible(locator)) throw new InvalidOperationException("{0} is visible".FormatWith(locator)); } public static RemoteWebDriver GetDriver(this IWebElement element) { return (RemoteWebDriver)((IWrapsDriver)element).WrappedDriver; } public static void SetChecked(this IWebElement element, bool isChecked) { if (element.Selected == isChecked) return; element.Click(); element.GetDriver().Wait(() => element.Selected == isChecked, () => "Set Checkbox to " + isChecked); } //[DebuggerStepThrough] //public static bool IsAlertPresent(this RemoteWebDriver selenium) //{ // try // { // selenium.SwitchTo().Alert(); // return true; // } // catch (NoAlertPresentException) // { // return false; // } //} public static void ConsumeAlert(this RemoteWebDriver selenium) { var alertPresent = selenium.Wait(() => MessageModalProxyExtensions.IsMessageModalPresent(selenium)); var alert = selenium.Wait(() => selenium.SwitchTo().Alert()); alert.Accept(); } public static string CssSelector(this By by) { string str = by.ToString(); var after = str.After(": "); switch (str.Before(":")) { case "By.CssSelector": return after; case "By.Id": return "#" + after; case "By.Name": return "[name=" + after + "]"; case "By.ClassName[Contains]": return "." + after; default: throw new InvalidOperationException("Impossible to combine: " + str); } } public static By CombineCss(this By by, string cssSelectorSuffix) { return By.CssSelector(by.CssSelector() + cssSelectorSuffix); } public static bool ContainsText(this IWebElement element, string text) { return element.Text.Contains(text) || element.FindElements(By.XPath("descendant::*[contains(text(), '" + text + "')]")).Any(); } public static SelectElement SelectElement(this IWebElement element) { return new SelectElement(element); } public static string GetID(this IWebElement element) { return element.GetAttribute("id"); } public static IEnumerable<string> GetClasses(this IWebElement element) { return element.GetAttribute("class").Split(' '); } public static bool HasClass(this IWebElement element, string className) { return element.GetClasses().Contains(className); } public static bool HasClass(this IWebElement element, params string[] classNames) { var classes = element.GetClasses(); return classNames.All(cn => classes.Contains(cn)); } public static IWebElement GetParent(this IWebElement e) { return e.FindElement(By.XPath("./..")); } public static IWebElement GetAscendant(this IWebElement e, Func<IWebElement, bool> predicate) { return e.Follow(a => a.GetParent()).FirstEx(predicate); } public static IWebElement? TryGetAscendant(this IWebElement e, Func<IWebElement, bool> predicate) { return e.Follow(a => a.GetParent()).FirstOrDefault(predicate); } public static void SelectByPredicate(this SelectElement element, Func<IWebElement, bool> predicate) { element.Options.SingleEx(predicate).Click(); } public static IWebElement CaptureOnClick(this IWebElement button) { return button.GetDriver().CapturePopup(() => button.Click()); } public static IWebElement CaptureOnDoubleClick(this IWebElement button) { return button.GetDriver().CapturePopup(() => button.DoubleClick()); } public static IWebElement CapturePopup(this RemoteWebDriver selenium, Action clickToOpen) { var body = selenium.FindElement(By.TagName("body")); var oldDialogs = body.FindElements(By.CssSelector("div.modal.fade.show")); clickToOpen(); var result = selenium.Wait(() => { var newDialogs = body.FindElements(By.CssSelector("div.modal.fade.show")); var newTop = newDialogs.SingleOrDefaultEx(a => !oldDialogs.Contains(a)); if (newTop == null) return null; return newTop; })!; return result; } public static void ContextClick(this IWebElement element) { Actions builder = new Actions(element.GetDriver()); builder.MoveToElement(element, 2, 2).ContextClick().Build().Perform(); } public static void DoubleClick(this IWebElement element) { Actions builder = new Actions(element.GetDriver()); builder.MoveToElement(element, 2, 2).DoubleClick().Build().Perform(); } public static void SafeSendKeys(this IWebElement element, string? text) { new Actions(element.GetDriver()).MoveToElement(element).Perform(); while(element.GetAttribute("value").Length > 0) element.SendKeys(Keys.Backspace); if (text.HasText()) element.SendKeys(text); Thread.Sleep(0); element.GetDriver().Wait(() => element.GetAttribute("value") == (text ?? "")); } public static string Value(this IWebElement e) => e.GetAttribute("value"); public static void ButtonClick(this IWebElement button) { if (!button.Enabled) throw new InvalidOperationException("Button is not enabled"); if (!button.Displayed) { var menu = button.FindElement(By.XPath("ancestor::*[contains(@class,'dropdown-menu')]")); var superButton = menu.GetParent().FindElement(By.CssSelector("a[data-toggle='dropdown']")); superButton.Click(); } try { button.ScrollTo(); button.Click(); } catch (InvalidOperationException e) { if (e.Message.Contains("Element is not clickable")) //Scrolling problems button.Click(); } } public static void SafeClick(this IWebElement element) { element.ScrollTo(); element.Click(); } public static IWebElement ScrollTo(this IWebElement element) { IJavaScriptExecutor js = (IJavaScriptExecutor)element.GetDriver(); js.ExecuteScript("arguments[0].scrollIntoView(false);", element); Thread.Sleep(500); return element; } public static void LoseFocus(this IWebElement element) { IJavaScriptExecutor js = (IJavaScriptExecutor)element.GetDriver(); js.ExecuteScript("arguments[0].focus(); arguments[0].blur(); return true", element); } public static void Retry<T>(this RemoteWebDriver driver, int times, Action action) where T : Exception { for (int i = 0; i < times; i++) { try { action(); return; } catch (T) { if (i >= times - 1) throw; } } } public static WebElementLocator WithLocator(this IWebElement element, By locator) { return new WebElementLocator(element, locator); } } }
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 IdentityServer4Tests.ApiResource.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="ExtendedBindingList.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Extends BindingList of T by adding extra</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using Csla.Serialization.Mobile; #if NETFX_CORE || (ANDROID || IOS) using System.Collections.Generic; using System.Collections.Specialized; #endif namespace Csla.Core { /// <summary> /// Extends BindingList of T by adding extra /// behaviors. /// </summary> /// <typeparam name="T">Type of item contained in list.</typeparam> [Serializable] public class ExtendedBindingList<T> : MobileBindingList<T>, IExtendedBindingList, IMobileList, INotifyBusy, INotifyChildChanged, ISerializationNotification { [NonSerialized()] private EventHandler<RemovingItemEventArgs> _nonSerializableHandlers; private EventHandler<RemovingItemEventArgs> _serializableHandlers; /// <summary> /// Implements a serialization-safe RemovingItem event. /// </summary> public event EventHandler<RemovingItemEventArgs> RemovingItem { add { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableHandlers = (EventHandler<RemovingItemEventArgs>) System.Delegate.Combine(_serializableHandlers, value); else _nonSerializableHandlers = (EventHandler<RemovingItemEventArgs>) System.Delegate.Combine(_nonSerializableHandlers, value); } remove { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableHandlers = (EventHandler<RemovingItemEventArgs>) System.Delegate.Remove(_serializableHandlers, value); else _nonSerializableHandlers = (EventHandler<RemovingItemEventArgs>) System.Delegate.Remove(_nonSerializableHandlers, value); } } /// <summary> /// Raise the RemovingItem event. /// </summary> /// <param name="removedItem"> /// A reference to the item that /// is being removed. /// </param> [EditorBrowsable(EditorBrowsableState.Advanced)] protected void OnRemovingItem(T removedItem) { if (_nonSerializableHandlers != null) _nonSerializableHandlers.Invoke(this, new RemovingItemEventArgs(removedItem)); if (_serializableHandlers != null) _serializableHandlers.Invoke(this, new RemovingItemEventArgs(removedItem)); } /// <summary> /// Remove the item at the /// specified index. /// </summary> /// <param name="index"> /// The zero-based index of the item /// to remove. /// </param> protected override void RemoveItem(int index) { OnRemovingItem(this[index]); OnRemoveEventHooks(this[index]); base.RemoveItem(index); } /// <summary> /// Add a range of items to the list. /// </summary> /// <param name="range">List of items to add.</param> public void AddRange(System.Collections.Generic.IEnumerable<T> range) { foreach (var element in range) this.Add(element); } [NotUndoable] [NonSerialized] private BusyChangedEventHandler _busyChanged = null; /// <summary> /// Event indicating that the busy status of the /// object has changed. /// </summary> public event BusyChangedEventHandler BusyChanged { add { _busyChanged = (BusyChangedEventHandler)Delegate.Combine(_busyChanged, value); } remove { _busyChanged = (BusyChangedEventHandler)Delegate.Remove(_busyChanged, value); } } /// <summary> /// Override this method to be notified when the /// IsBusy property has changed. /// </summary> /// <param name="args">Event arguments.</param> protected virtual void OnBusyChanged(BusyChangedEventArgs args) { if (_busyChanged != null) _busyChanged(this, args); } /// <summary> /// Raises the BusyChanged event for a specific property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="busy">New busy value.</param> protected void OnBusyChanged(string propertyName, bool busy) { OnBusyChanged(new BusyChangedEventArgs(propertyName, busy)); } /// <summary> /// Gets the busy status for this object and its child objects. /// </summary> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public virtual bool IsBusy { get { throw new NotImplementedException(); } } /// <summary> /// Gets the busy status for this object. /// </summary> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public virtual bool IsSelfBusy { get { return IsBusy; } } void busy_BusyChanged(object sender, BusyChangedEventArgs e) { OnBusyChanged(e); } [NotUndoable] [NonSerialized] private EventHandler<ErrorEventArgs> _unhandledAsyncException; /// <summary> /// Event indicating that an exception occurred during /// an async operation. /// </summary> public event EventHandler<ErrorEventArgs> UnhandledAsyncException { add { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Combine(_unhandledAsyncException, value); } remove { _unhandledAsyncException = (EventHandler<ErrorEventArgs>)Delegate.Remove(_unhandledAsyncException, value); } } /// <summary> /// Method invoked when an unhandled async exception has /// occurred. /// </summary> /// <param name="error">Event arguments.</param> protected virtual void OnUnhandledAsyncException(ErrorEventArgs error) { if (_unhandledAsyncException != null) _unhandledAsyncException(this, error); } /// <summary> /// Raises the UnhandledAsyncException event. /// </summary> /// <param name="originalSender">Original sender of event.</param> /// <param name="error">Exception that occurred.</param> protected void OnUnhandledAsyncException(object originalSender, Exception error) { OnUnhandledAsyncException(new ErrorEventArgs(originalSender, error)); } void unhandled_UnhandledAsyncException(object sender, ErrorEventArgs e) { OnUnhandledAsyncException(e); } /// <summary> /// Invoked when an item is inserted into the list. /// </summary> /// <param name="index">Index of new item.</param> /// <param name="item">Reference to new item.</param> protected override void InsertItem(int index, T item) { base.InsertItem(index, item); OnAddEventHooks(item); } /// <summary> /// Method invoked when events are hooked for a child /// object. /// </summary> /// <param name="item">Reference to child object.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void OnAddEventHooks(T item) { INotifyBusy busy = item as INotifyBusy; if (busy != null) busy.BusyChanged += new BusyChangedEventHandler(busy_BusyChanged); INotifyUnhandledAsyncException unhandled = item as INotifyUnhandledAsyncException; if (unhandled != null) unhandled.UnhandledAsyncException += new EventHandler<ErrorEventArgs>(unhandled_UnhandledAsyncException); INotifyPropertyChanged c = item as INotifyPropertyChanged; if (c != null) c.PropertyChanged += Child_PropertyChanged; INotifyChildChanged child = item as INotifyChildChanged; if (child != null) child.ChildChanged += Child_Changed; } /// <summary> /// Method invoked when events are unhooked for a child /// object. /// </summary> /// <param name="item">Reference to child object.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void OnRemoveEventHooks(T item) { INotifyBusy busy = item as INotifyBusy; if (busy != null) busy.BusyChanged -= new BusyChangedEventHandler(busy_BusyChanged); INotifyUnhandledAsyncException unhandled = item as INotifyUnhandledAsyncException; if (unhandled != null) unhandled.UnhandledAsyncException -= new EventHandler<ErrorEventArgs>(unhandled_UnhandledAsyncException); INotifyPropertyChanged c = item as INotifyPropertyChanged; if (c != null) c.PropertyChanged -= new PropertyChangedEventHandler(Child_PropertyChanged); INotifyChildChanged child = item as INotifyChildChanged; if (child != null) child.ChildChanged -= new EventHandler<ChildChangedEventArgs>(Child_Changed); } /// <summary> /// This method is called on a newly deserialized object /// after deserialization is complete. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnDeserialized() { // do nothing - this is here so a subclass // could override if needed } void ISerializationNotification.Deserialized() { // don't rehook events here, because the MobileFormatter has // created new objects and so the lists will auto-subscribe // the events OnDeserialized(); } [System.Runtime.Serialization.OnDeserialized] private void OnDeserializedHandler(System.Runtime.Serialization.StreamingContext context) { foreach (T item in this) OnAddEventHooks(item); OnDeserialized(); } [NonSerialized] [NotUndoable] private EventHandler<Csla.Core.ChildChangedEventArgs> _childChangedHandlers; /// <summary> /// Event raised when a child object has been changed. /// </summary> public event EventHandler<Csla.Core.ChildChangedEventArgs> ChildChanged { add { _childChangedHandlers = (EventHandler<Csla.Core.ChildChangedEventArgs>) System.Delegate.Combine(_childChangedHandlers, value); } remove { _childChangedHandlers = (EventHandler<Csla.Core.ChildChangedEventArgs>) System.Delegate.Remove(_childChangedHandlers, value); } } /// <summary> /// Raises the ChildChanged event, indicating that a child /// object has been changed. /// </summary> /// <param name="e"> /// ChildChangedEventArgs object. /// </param> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnChildChanged(ChildChangedEventArgs e) { if (_childChangedHandlers != null) _childChangedHandlers.Invoke(this, e); } #if NETFX_CORE || (ANDROID || IOS) /// <summary> /// Creates a ChildChangedEventArgs and raises the event. /// </summary> private void RaiseChildChanged( object childObject, PropertyChangedEventArgs propertyArgs, NotifyCollectionChangedEventArgs listArgs) { ChildChangedEventArgs args = new ChildChangedEventArgs(childObject, propertyArgs, listArgs); OnChildChanged(args); } /// <summary> /// Handles any PropertyChanged event from /// a child object and echoes it up as /// a ChildChanged event. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { RaiseChildChanged(sender, e, null); } /// <summary> /// Handles any ChildChanged event from /// a child object and echoes it up as /// a ChildChanged event. /// </summary> private void Child_Changed(object sender, ChildChangedEventArgs e) { RaiseChildChanged(e.ChildObject, e.PropertyChangedArgs, e.CollectionChangedArgs); } #else /// <summary> /// Creates a ChildChangedEventArgs and raises the event. /// </summary> private void RaiseChildChanged( object childObject, PropertyChangedEventArgs propertyArgs, ListChangedEventArgs listArgs) { ChildChangedEventArgs args = new ChildChangedEventArgs(childObject, propertyArgs, listArgs); OnChildChanged(args); } /// <summary> /// Handles any PropertyChanged event from /// a child object and echoes it up as /// a ChildChanged event. /// </summary> /// <param name="sender">Object that raised the event.</param> /// <param name="e">Property changed args.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { RaiseChildChanged(sender, e, null); } /// <summary> /// Handles any ChildChanged event from /// a child object and echoes it up as /// a ChildChanged event. /// </summary> private void Child_Changed(object sender, ChildChangedEventArgs e) { RaiseChildChanged(e.ChildObject, e.PropertyChangedArgs, e.ListChangedArgs); } #endif /// <summary> /// Use this object to suppress ListChangedEvents for an entire code block. /// May be nested in multiple levels for the same object. /// </summary> public IDisposable SuppressListChangedEvents { get { return new SuppressListChangedEventsClass<T>(this); } } /// <summary> /// Handles the suppressing of raising ChangedEvents when altering the content of an ObservableBindingList. /// Will be instanciated by a factory property on the ObservableBindingList implementation. /// </summary> /// <typeparam name="TC">The type of the C.</typeparam> class SuppressListChangedEventsClass<TC> : IDisposable { private readonly BindingList<TC> _businessObject; private readonly bool _initialRaiseListChangedEvents; public SuppressListChangedEventsClass(BindingList<TC> businessObject) { this._businessObject = businessObject; _initialRaiseListChangedEvents = businessObject.RaiseListChangedEvents; businessObject.RaiseListChangedEvents = false; } public void Dispose() { _businessObject.RaiseListChangedEvents = _initialRaiseListChangedEvents; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="PluginManager.cs" company=""> // // </copyright> // <summary> // Summary description for PluginServices. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace MineAPI.Editor.Plugin { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Windows.Forms; using EditorBase; using EditorBase.Logging; using EditorBase.Mod; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// Contains host methods which plugins can interface with along with actual loader for plugins based on directory. /// </summary> public class PluginManager : IPluginHost { #region Fields /// <summary> /// The collection available plugins which will work against the loaded mod data. /// </summary> private EditorPluginCollection _pluginCollection; #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="PluginManager"/> class. /// Searches the Application's Startup Directory for Plugins /// </summary> public PluginManager() { // Create a new collection to hold all of our plugin instances. _pluginCollection = new EditorPluginCollection(); // Find and load all available plugins into that collection. FindPlugins(ModData.GetPluginDirectory()); } #endregion #region Public Properties /// <summary> /// A Collection of all Plugins Found and Loaded by the FindPlugins() Method /// </summary> public EditorPluginCollection PluginCollection { get { return _pluginCollection; } set { _pluginCollection = value; } } #endregion #region Public Methods and Operators /// <summary> /// Loops through every plugin and destroys any loaded control data that might currently be loaded. /// </summary> public void CloseOpenPluginControls() { foreach (EditorPlugin loadedPlugin in _pluginCollection) { if (loadedPlugin.Instance != null) { // Calls the standard interface method all plugins should be following, if not we are going to complain about it. loadedPlugin.Instance.CloseControl(); // Check if the content (user control) was properly destroyed. if (loadedPlugin.Instance.PluginContent != null) { Logger.Log( Logger.Level.Warning, "Plugin control instance was not cleared after calling close control!"); } } else { Logger.Log( Logger.Level.Warning, "Found plugin with dead instance! Possible plugin crash for: " + loadedPlugin.AssemblyPath); } } } /// <summary> /// Displays a feedback dialog from the plugin /// </summary> /// <param name="feedback"> /// String message for feedback /// </param> /// <param name="plugin"> /// The plugin that called the feedback /// </param> public void Feedback(string feedback, IPlugin plugin) { if (Program.ShellForm != null) { string pluginTitle = plugin.PluginName + " - " + plugin.PluginVersion; MessageBox.Show( Program.ShellForm, feedback, pluginTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } } /// <summary> /// Returns the currently loaded mod project if one has been loaded. /// </summary> /// <returns>Loaded mod project, null if no project loaded.</returns> public ModData LoadedMod() { return Program.LoadedMod; } /// <summary> /// Initializes a new instance of the <see cref="ModData"/> class. /// Reads a JSON file from disk and parses it to MineAPI object which is then loaded into main instance for editing. /// </summary> /// <param name="filePath"> /// </param> public void ProjectOpen(string filePath) { // Throw error if previous mod data is loaded. if (((IPluginHost)this).LoadedMod() != null) { return; } // Check the path to the file that was given to us by open file dialog. if (string.IsNullOrEmpty(filePath)) { return; } // Read JSON directly from a file. using (var file = new StreamReader(filePath)) { using (var reader = new JsonTextReader(file)) { // Read the JSON from stream reader into generic JSON object. var o2 = (JObject)JToken.ReadFrom(reader); // Convert the JSON object into our default factory object for Minecraft/Forge modding. if (o2 != null) { // Pass the RootObject along... Program.LoadedMod = new ModData(o2.ToObject<ModData>()); } } } } /// <summary> /// Unloads the current mod project from the editor and returns it to same state as when it was loaded before a project was loaded to edit. /// </summary> public void ProjectUnload() { ((IPluginHost)this).LoadedMod().UnloadMod(); } /// <summary> /// Saves the given JSON for a mod in the proper location for it based on loaded mod instance, also saves metadata java /// class file. /// </summary> public void ProjectSave() { ((IPluginHost)this).LoadedMod().SaveMod(); } public List<string> GetLoadedPlugins() { throw new NotImplementedException(); } public EditorBase.EditorPlugin GetPluginByName(string selectedPluginName) { throw new NotImplementedException(); } /// <summary> /// Searches the passed path for Plugins /// </summary> /// <param name="path"> /// Directory to search for Plugins in /// </param> public void FindPlugins(string path) { // First empty the collection, we're reloading them all _pluginCollection.Clear(); Logger.Log("Checking for existing plugins directory."); if (!Directory.Exists(path)) { Logger.Log("Creating plugins directory: " + path); try { Directory.CreateDirectory(path); } catch (Exception err) { Logger.Log(err); throw; } } // Go through all the files in the plugin directory string[] possiblePluginFiles = Directory.GetFiles(path, "*.dll"); Logger.Log("Found total of " + possiblePluginFiles.Length + " potential plugins to load."); foreach (string possiblePlugin in possiblePluginFiles) { FileInfo file = new FileInfo(possiblePlugin); // Preliminary check, must be .dll (we force it to be all lowercase just to make extra sure). if (file.Extension.ToLower().Equals(".dll")) { // Add the 'plugin' Logger.Log("Adding plugin " + Path.GetFileNameWithoutExtension(file.FullName)); AddPlugin(possiblePlugin); } } } /// <summary> /// Unloads and Closes all PluginCollection /// </summary> public void UnloadPlugins() { foreach (EditorPlugin pluginOn in _pluginCollection) { // Close all plugin instances if (pluginOn.Instance != null) { // We call the plugins UnloadPlugin sub first in case it has to do its own cleanup stuff. Logger.Log("Unloading plugin: " + pluginOn.Instance.PluginName); pluginOn.Instance.UnloadPlugin(); } // After we give the plugin a chance to tidy up, get rid of it pluginOn.Instance = null; } // Finally, clear our collection of available plugins _pluginCollection.Clear(); } #endregion #region Methods /// <summary> /// The add plugin. /// </summary> /// <param name="fileName"> /// The file name. /// </param> private void AddPlugin(string fileName) { // Create a new assembly from the plugin file we're adding.. Assembly pluginAssembly = Assembly.LoadFrom(fileName); // Next we'll loop through all the Types found in the assembly foreach (Type pluginType in pluginAssembly.GetTypes()) { if (pluginType.IsPublic) { // Only look at public types if (!pluginType.IsAbstract) { // Only look at non-abstract types // Gets a type object of the interface we need the plugins to match Type typeInterface = pluginType.GetInterface("MineAPI.EditorBase.IPlugin", true); // Make sure the interface we want to use actually exists if (typeInterface == null) { // Skip to the next public non-abstract type we locate in the plugin... continue; } // Create a new available plugin since the type implements the IPlugin interface EditorPlugin newPlugin = new EditorPlugin(); // Set the filename where we found it newPlugin.AssemblyPath = fileName; // Create a new instance and store the instance in the collection for later use // We could change this later on to not load an instance.. we have 2 options // 1- Make one instance, and use it whenever we need it.. it's always there // 2- Don't make an instance, and instead make an instance whenever we use it, then close it // For now we'll just make an instance of all the plugins newPlugin.Instance = (IPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); // Set the plugin's host to this class which inherited IPluginHost newPlugin.Instance.PluginHost = this; // Call the initialization sub of the plugin newPlugin.Instance.LoadPlugin(); // Add the new plugin to our collection here _pluginCollection.Add(newPlugin); } } } } #endregion } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Codex.Storage.Utilities; using Nest; namespace Codex.Storage.ElasticProviders { /// <summary> /// Helper class with custom analyzers. /// </summary> internal static class CustomAnalyzers { /// <summary> /// Project name analyzer which lowercases project name /// </summary> public static CustomAnalyzer LowerCaseKeywordAnalyzer { get; } = new CustomAnalyzer { Filter = new List<string> { // (built in) normalize to lowercase "lowercase", }, Tokenizer = "keyword", }; /// <summary> /// Project name analyzer which lowercases project name /// </summary> public static CustomNormalizer LowerCaseKeywordNormalizer { get; } = new CustomNormalizer { Filter = new List<string> { // (built in) normalize to lowercase "lowercase", // (built in) normalize to ascii equivalents "asciifolding", }, }; /// <summary> /// NGramAnalyzer is useful for "partial name search". /// </summary> public static CustomAnalyzer PrefixFilterIdentifierNGramAnalyzer { get; } = new CustomAnalyzer { Filter = new List<string> { "name_gram_boundary_inserter", "lower_to_upper_delimiter_inserter", "number_to_letter_delimiter_inserter", "delimited_name_prefix_generator", "lowercase", // (built in) normalize to ascii equivalents "asciifolding", "name_gram_delimiter_remover" }, Tokenizer = "keyword", }; public static CustomAnalyzer PrefixFilterFullNameNGramAnalyzer { get; } = new CustomAnalyzer { Filter = new List<string> { "container_name_prefix_generator", // TODO: All the filters above here could be replaced with path_hierarchy tokenizer with delimiter '.' and reverse=true. // (built in) normalize to lowercase "lowercase", // (built in) normalize to ascii equivalents "asciifolding", }, Tokenizer = "keyword", }; public static CustomAnalyzer EncodedFullTextAnalyzer { get; } = new CustomAnalyzer { Filter = new List<string> { "standard", "lowercase", }, Tokenizer = "standard", CharFilter = new List<string> { "punctuation_to_space_replacement", } }; public static readonly IDictionary<string, ICharFilter> CharFiltersMap = new Dictionary<string, ICharFilter>() { { // Replace punctuation (i.e. '.' or ',') characters with a space // $ ^ +=`~ <> "punctuation_to_space_replacement", new PatternReplaceCharFilter() { Pattern = "[$^+=`~<>!\"#%&'()*,-./:;?@\\[\\]\\\\_{}]", //Pattern = $"[{Regex.Escape("!\"#%&'()*,-./:;?@[\\]_{}")}]", Replacement = " " } } }; public static readonly IDictionary<string, ITokenFilter> FiltersMap = new Dictionary<string, ITokenFilter>() { { // Add '@^' symbols at the beginning of string "name_gram_boundary_inserter", new PatternReplaceTokenFilter() { Pattern = "^(.*)", Replacement = "\\^$1^" } }, { // Add @ symbol before upper to lower case transition "lower_to_upper_delimiter_inserter", new PatternReplaceTokenFilter() { Pattern = "(?:(?<leading>\\p{Ll})(?<trailing>\\p{Lu}))", Replacement = "${leading}@${trailing}" } }, { // Add @ symbol before number to letter transition "number_to_letter_delimiter_inserter", new PatternReplaceTokenFilter() { Pattern = "(?:(?<leading>\\d+)(?<trailing>\\w))", Replacement = "${leading}@${trailing}" } }, { "delimited_name_prefix_generator", new PathHierarchyTokenFilter() { Delimiter = '@', Reverse = true } }, { "container_name_prefix_generator", new PathHierarchyTokenFilter() { Delimiter = '.', Reverse = true } }, { // Remove @ symbol marker in preparation for // generating final name grams "name_gram_delimiter_remover", new PatternReplaceTokenFilter() { Pattern = "\\@", Replacement = "" } } }; public static TokenFiltersDescriptor AddTokenFilters(this TokenFiltersDescriptor descriptor) { foreach (var tokenFilterEntry in FiltersMap) { descriptor = descriptor.UserDefined(tokenFilterEntry.Key, tokenFilterEntry.Value); } return descriptor; } public static CharFiltersDescriptor AddCharFilters(this CharFiltersDescriptor descriptor) { foreach (var charFilterEntry in CharFiltersMap) { descriptor = descriptor.UserDefined(charFilterEntry.Key, charFilterEntry.Value); } return descriptor; } public const string LowerCaseKeywordNormalizerName = "lowercase_keyword_norm"; public const string LowerCaseKeywordAnalyzerName = "lowercase_keyword"; public const string PrefixFilterFullNameNGramAnalyzerName = "full_name"; public const string PrefixFilterPartialNameNGramAnalyzerName = "partial_name"; public const string EncodedFullTextAnalyzerName = "encoded_full_text"; /// <summary> /// Capture filter splits incoming sequence into the tokens that would be used by the following analysis. /// This means that uploading the "StringBuilder" we'll get following set of indices: "str", "stri", ... "stringbuilder", "bui", "build", ... "builder. /// To test tokenizer, you can use following query in sense: /// <code> /// GET testsources/_analyze?tokenizer=keyword&analyzer=partial_name { "StringBuilder"} /// </code> /// where 'testsources' is an index with an uploaded source. /// </summary> public static TokenFilterBase CamelCaseFilter => new PatternCaptureTokenFilter() { PreserveOriginal = true, Patterns = new[] { // Lowercase sequence with at least three lower case characters "(\\p{Lu}\\p{Lu}\\p{Lu}+)", // Uppercase followed by lowercase then rest of word characters (NOTE: word characters include underscore '_') "(\\p{Lu}\\p{Ll}\\w+)", // Non-alphanumeric char (not captured) followed by series of word characters (NOTE: word characters include underscore '_') "[^\\p{L}\\d]+(\\w+)", // Alphanumeric char (not captured) followed by series of at least one alpha-number then series of word characters // (NOTE: word characters include underscore '_') "[\\p{L}\\d]([^\\p{L}\\d]+\\w+)", // Sequence of digits "(\\d\\d+)" }, }; public const int MinGram = 2; public const int MaxGram = 70; /// <summary> /// Func that can be used with <see cref="CreateIndexExtensions.CreateIndexAsync"/>. /// </summary> public static Func<CreateIndexDescriptor, CreateIndexDescriptor> AddNGramAnalyzerFunc { get; } = c => c.Settings(AddAnalyzerSettings); public static IndexSettingsDescriptor AddAnalyzerSettings(this IndexSettingsDescriptor isd) { return isd.Analysis(descriptor => descriptor .TokenFilters(tfd => AddTokenFilters(tfd)) .CharFilters(cfd => AddCharFilters(cfd)) .Normalizers(bases => bases .UserDefined(LowerCaseKeywordNormalizerName, LowerCaseKeywordNormalizer)) .Analyzers(bases => bases .UserDefined(PrefixFilterPartialNameNGramAnalyzerName, PrefixFilterIdentifierNGramAnalyzer) .UserDefined(PrefixFilterFullNameNGramAnalyzerName, PrefixFilterFullNameNGramAnalyzer) .UserDefined(LowerCaseKeywordAnalyzerName, LowerCaseKeywordAnalyzer) .UserDefined(EncodedFullTextAnalyzerName, EncodedFullTextAnalyzer))); } private class PathHierarchyTokenFilter : PathHierarchyTokenizer, ITokenFilter { public PathHierarchyTokenFilter() { Type = "edge_ngram_delimited"; Delimiter = '\\'; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Dns.Fluent { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; internal partial class DnsZoneImpl { /// <summary> /// Gets entry point to manage record sets in this zone containing AAAA (IPv6 address) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.IAaaaRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.AaaaRecordSets { get { return this.AaaaRecordSets(); } } /// <summary> /// Gets the access type of this zone (Private or Public). /// </summary> Models.ZoneType Microsoft.Azure.Management.Dns.Fluent.IDnsZone.AccessType { get { return this.AccessType(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing A (IPv4 address) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.IARecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ARecordSets { get { return this.ARecordSets(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing Caa (canonical name) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.ICaaRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.CaaRecordSets { get { return this.CaaRecordSets(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing CNAME (canonical name) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.ICNameRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.CNameRecordSets { get { return this.CNameRecordSets(); } } /// <summary> /// Gets the etag associated with this zone. /// </summary> string Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ETag { get { return this.ETag(); } } /// <summary> /// Gets the maximum number of record sets that can be created in this zone. /// </summary> long Microsoft.Azure.Management.Dns.Fluent.IDnsZone.MaxNumberOfRecordSets { get { return this.MaxNumberOfRecordSets(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing MX (mail exchange) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.IMXRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.MXRecordSets { get { return this.MXRecordSets(); } } /// <summary> /// Gets name servers assigned for this zone. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.NameServers { get { return this.NameServers(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing NS (name server) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.INSRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.NSRecordSets { get { return this.NSRecordSets(); } } /// <summary> /// Gets the current number of record sets in this zone. /// </summary> long Microsoft.Azure.Management.Dns.Fluent.IDnsZone.NumberOfRecordSets { get { return this.NumberOfRecordSets(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing PTR (pointer) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.IPtrRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.PtrRecordSets { get { return this.PtrRecordSets(); } } /// <summary> /// Gets a list of references to virtual networks that register hostnames in this DNS zone for Private DNS zone. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.RegistrationVirtualNetworkIds { get { return this.RegistrationVirtualNetworkIds(); } } /// <summary> /// Gets a list of references to virtual networks that resolve records in this DNS zone for Private DNS zone. /// </summary> System.Collections.Generic.IReadOnlyList<string> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ResolutionVirtualNetworkIds { get { return this.ResolutionVirtualNetworkIds(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing SRV (service) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.ISrvRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.SrvRecordSets { get { return this.SrvRecordSets(); } } /// <summary> /// Gets entry point to manage record sets in this zone containing TXT (text) records. /// </summary> Microsoft.Azure.Management.Dns.Fluent.ITxtRecordSets Microsoft.Azure.Management.Dns.Fluent.IDnsZone.TxtRecordSets { get { return this.TxtRecordSets(); } } /// <summary> /// Specifies definition of an AAAA record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the AAAA record set.</param> /// <return>The stage representing configuration for the AAAA record set.</return> DnsRecordSet.UpdateDefinition.IAaaaRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineAaaaRecordSet(string name) { return this.DefineAaaaRecordSet(name); } /// <summary> /// Specifies definition of an AAAA record set. /// </summary> /// <param name="name">Name of the AAAA record set.</param> /// <return>The stage representing configuration for the AAAA record set.</return> DnsRecordSet.Definition.IAaaaRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineAaaaRecordSet(string name) { return this.DefineAaaaRecordSet(name); } /// <summary> /// Specifies definition of an A record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the A record set.</param> /// <return>The stage representing configuration for the A record set.</return> DnsRecordSet.UpdateDefinition.IARecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineARecordSet(string name) { return this.DefineARecordSet(name); } /// <summary> /// Specifies definition of an A record set. /// </summary> /// <param name="name">Name of the A record set.</param> /// <return>The stage representing configuration for the A record set.</return> DnsRecordSet.Definition.IARecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineARecordSet(string name) { return this.DefineARecordSet(name); } /// <summary> /// Specifies definition of a Caa record set to be attached to the DNS zone. /// </summary> /// <param name="name">The name of the Caa record set.</param> /// <return>The stage representing configuration for the Caa record set.</return> DnsRecordSet.UpdateDefinition.ICaaRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineCaaRecordSet(string name) { return this.DefineCaaRecordSet(name); } /// <summary> /// Specifies definition of a Caa record set. /// </summary> /// <param name="name">The name of the Caa record set.</param> /// <return>The stage representing configuration for the Caa record set.</return> DnsRecordSet.Definition.ICaaRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineCaaRecordSet(string name) { return this.DefineCaaRecordSet(name); } /// <summary> /// Specifies definition of a CNAME record set. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <return>The next stage of DNS zone definition.</return> DnsRecordSet.UpdateDefinition.ICNameRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineCNameRecordSet(string name) { return this.DefineCNameRecordSet(name); } /// <summary> /// Specifies definition of a CNAME record set. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <return>The next stage of DNS zone definition.</return> DnsRecordSet.Definition.ICNameRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineCNameRecordSet(string name) { return this.DefineCNameRecordSet(name); } /// <summary> /// Specifies definition of a MX record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the MX record set.</param> /// <return>The stage representing configuration for the MX record set.</return> DnsRecordSet.UpdateDefinition.IMXRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineMXRecordSet(string name) { return this.DefineMXRecordSet(name); } /// <summary> /// Specifies definition of a MX record set. /// </summary> /// <param name="name">Name of the MX record set.</param> /// <return>The stage representing configuration for the MX record set.</return> DnsRecordSet.Definition.IMXRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineMXRecordSet(string name) { return this.DefineMXRecordSet(name); } /// <summary> /// Specifies definition of an NS record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the NS record set.</param> /// <return>The stage representing configuration for the NS record set.</return> DnsRecordSet.UpdateDefinition.INSRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineNSRecordSet(string name) { return this.DefineNSRecordSet(name); } /// <summary> /// Specifies definition of an NS record set. /// </summary> /// <param name="name">Name of the NS record set.</param> /// <return>The stage representing configuration for the NS record set.</return> DnsRecordSet.Definition.INSRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineNSRecordSet(string name) { return this.DefineNSRecordSet(name); } /// <summary> /// Specifies definition of a PTR record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the PTR record set.</param> /// <return>The stage representing configuration for the PTR record set.</return> DnsRecordSet.UpdateDefinition.IPtrRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefinePtrRecordSet(string name) { return this.DefinePtrRecordSet(name); } /// <summary> /// Specifies definition of a PTR record set. /// </summary> /// <param name="name">Name of the PTR record set.</param> /// <return>The stage representing configuration for the PTR record set.</return> DnsRecordSet.Definition.IPtrRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefinePtrRecordSet(string name) { return this.DefinePtrRecordSet(name); } /// <summary> /// Specifies definition of a SRV record set to be attached to the DNS zone. /// </summary> /// <param name="name">The name of the SRV record set.</param> /// <return>The stage representing configuration for the SRV record set.</return> DnsRecordSet.UpdateDefinition.ISrvRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineSrvRecordSet(string name) { return this.DefineSrvRecordSet(name); } /// <summary> /// Specifies definition of a SRV record set. /// </summary> /// <param name="name">The name of the SRV record set.</param> /// <return>The stage representing configuration for the SRV record set.</return> DnsRecordSet.Definition.ISrvRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineSrvRecordSet(string name) { return this.DefineSrvRecordSet(name); } /// <summary> /// Specifies definition of a TXT record set to be attached to the DNS zone. /// </summary> /// <param name="name">The name of the TXT record set.</param> /// <return>The stage representing configuration for the TXT record set.</return> DnsRecordSet.UpdateDefinition.ITxtRecordSetBlank<DnsZone.Update.IUpdate> DnsZone.Update.IWithRecordSet.DefineTxtRecordSet(string name) { return this.DefineTxtRecordSet(name); } /// <summary> /// Specifies definition of a TXT record set. /// </summary> /// <param name="name">The name of the TXT record set.</param> /// <return>The stage representing configuration for the TXT record set.</return> DnsRecordSet.Definition.ITxtRecordSetBlank<DnsZone.Definition.IWithCreate> DnsZone.Definition.IWithRecordSet.DefineTxtRecordSet(string name) { return this.DefineTxtRecordSet(name); } /// <return>The record set containing SOA (start of authority) record associated with this DNS zone.</return> Microsoft.Azure.Management.Dns.Fluent.ISoaRecordSet Microsoft.Azure.Management.Dns.Fluent.IDnsZone.GetSoaRecordSet() { return this.GetSoaRecordSet(); } /// <return>The record sets in this zone.</return> System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Dns.Fluent.IDnsRecordSet> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ListRecordSets() { return this.ListRecordSets(); } /// <summary> /// Lists all the record sets in this zone with the given suffix. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <return>The record sets.</return> System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Dns.Fluent.IDnsRecordSet> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ListRecordSets(string recordSetNameSuffix) { return this.ListRecordSets(recordSetNameSuffix); } /// <summary> /// Lists all the record sets in this zone with each entries in each page /// limited to the given size. /// </summary> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>The record sets.</return> System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Dns.Fluent.IDnsRecordSet> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ListRecordSets(int pageSize) { return this.ListRecordSets(pageSize); } /// <summary> /// Lists all the record sets in this zone with the given suffix, also limits /// the number of entries per page to the given page size. /// </summary> /// <param name="recordSetNameSuffix">The record set name suffix.</param> /// <param name="pageSize">The maximum number of record sets in a page.</param> /// <return>The record sets.</return> System.Collections.Generic.IEnumerable<Microsoft.Azure.Management.Dns.Fluent.IDnsRecordSet> Microsoft.Azure.Management.Dns.Fluent.IDnsZone.ListRecordSets(string recordSetNameSuffix, int pageSize) { return this.ListRecordSets(recordSetNameSuffix, pageSize); } /// <summary> /// Refreshes the resource to sync with Azure. /// </summary> /// <return>The Observable to refreshed resource.</return> async Task<Microsoft.Azure.Management.Dns.Fluent.IDnsZone> Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IRefreshable<Microsoft.Azure.Management.Dns.Fluent.IDnsZone>.RefreshAsync(CancellationToken cancellationToken) { return await this.RefreshAsync(cancellationToken); } /// <summary> /// Begins the description of an update of an existing AAAA record set in this DNS zone. /// </summary> /// <param name="name">Name of the AAAA record set.</param> /// <return>The stage representing configuration for the AAAA record set.</return> DnsRecordSet.UpdateAaaaRecordSet.IUpdateAaaaRecordSet DnsZone.Update.IWithRecordSet.UpdateAaaaRecordSet(string name) { return this.UpdateAaaaRecordSet(name); } /// <summary> /// Begins the description of an update of an existing A record set in this DNS zone. /// </summary> /// <param name="name">Name of the A record set.</param> /// <return>The stage representing configuration for the A record set.</return> DnsRecordSet.UpdateARecordSet.IUpdateARecordSet DnsZone.Update.IWithRecordSet.UpdateARecordSet(string name) { return this.UpdateARecordSet(name); } /// <summary> /// Begins the description of an update of an existing Caa record set in this DNS zone. /// </summary> /// <param name="name">The name of the Caa record set.</param> /// <return>The stage representing configuration for the Caa record set.</return> DnsRecordSet.UpdateCaaRecordSet.IUpdateCaaRecordSet DnsZone.Update.IWithRecordSet.UpdateCaaRecordSet(string name) { return this.UpdateCaaRecordSet(name); } /// <summary> /// Specifies definition of a CNAME record set. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <return>The stage representing configuration for the CNAME record set.</return> DnsRecordSet.UpdateCNameRecordSet.IUpdateCNameRecordSet DnsZone.Update.IWithRecordSet.UpdateCNameRecordSet(string name) { return this.UpdateCNameRecordSet(name); } /// <summary> /// Begins the description of an update of an existing MX record set in this DNS zone. /// </summary> /// <param name="name">Name of the MX record set.</param> /// <return>The stage representing configuration for the MX record set.</return> DnsRecordSet.UpdateMXRecordSet.IUpdateMXRecordSet DnsZone.Update.IWithRecordSet.UpdateMXRecordSet(string name) { return this.UpdateMXRecordSet(name); } /// <summary> /// Begins the description of an update of an existing NS record set in this DNS zone. /// </summary> /// <param name="name">Name of the NS record set.</param> /// <return>The stage representing configuration for the NS record set.</return> DnsRecordSet.UpdateNSRecordSet.IUpdateNSRecordSet DnsZone.Update.IWithRecordSet.UpdateNSRecordSet(string name) { return this.UpdateNSRecordSet(name); } /// <summary> /// Begins the description of an update of an existing PTR record set in this DNS zone. /// </summary> /// <param name="name">Name of the PTR record set.</param> /// <return>The stage representing configuration for the PTR record set.</return> DnsRecordSet.UpdatePtrRecordSet.IUpdatePtrRecordSet DnsZone.Update.IWithRecordSet.UpdatePtrRecordSet(string name) { return this.UpdatePtrRecordSet(name); } /// <summary> /// Begins the description of an update of the SOA record in this DNS zone. /// </summary> /// <return>The stage representing configuration for the TXT record set.</return> DnsRecordSet.UpdateSoaRecord.IUpdateSoaRecord DnsZone.Update.IWithRecordSet.UpdateSoaRecord() { return this.UpdateSoaRecord(); } /// <summary> /// Begins the description of an update of an existing SRV record set in this DNS zone. /// </summary> /// <param name="name">The name of the SRV record set.</param> /// <return>The stage representing configuration for the SRV record set.</return> DnsRecordSet.UpdateSrvRecordSet.IUpdateSrvRecordSet DnsZone.Update.IWithRecordSet.UpdateSrvRecordSet(string name) { return this.UpdateSrvRecordSet(name); } /// <summary> /// Begins the description of an update of an existing TXT record set in this DNS zone. /// </summary> /// <param name="name">The name of the TXT record set.</param> /// <return>The stage representing configuration for the TXT record set.</return> DnsRecordSet.UpdateTxtRecordSet.IUpdateTxtRecordSet DnsZone.Update.IWithRecordSet.UpdateTxtRecordSet(string name) { return this.UpdateTxtRecordSet(name); } /// <summary> /// Specifies definition of a CNAME record set to be attached to the DNS zone. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <param name="alias">The CNAME record alias.</param> /// <return>The next stage of DNS zone definition.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithCNameRecordSet(string name, string alias) { return this.WithCNameRecordSet(name, alias); } /// <summary> /// Specifies definition of a CNAME record set. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <param name="alias">The CNAME record alias.</param> /// <return>The next stage of DNS zone definition.</return> DnsZone.Definition.IWithCreate DnsZone.Definition.IWithRecordSet.WithCNameRecordSet(string name, string alias) { return this.WithCNameRecordSet(name, alias); } /// <summary> /// Specifies that If-Match header needs to set to the current eTag value associated /// with the DNS Zone. /// </summary> /// <return>The next stage of the update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithETagCheck.WithETagCheck() { return this.WithETagCheck(); } /// <summary> /// Specifies that if-Match header needs to set to the given eTag value. /// </summary> /// <param name="eTagValue">The eTag value.</param> /// <return>The next stage of the update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithETagCheck.WithETagCheck(string eTagValue) { return this.WithETagCheck(eTagValue); } /// <summary> /// Specifies that If-None-Match header needs to set to to prevent updating an existing DNS zone. /// </summary> /// <return>The next stage of the definition.</return> DnsZone.Definition.IWithCreate DnsZone.Definition.IWithETagCheck.WithETagCheck() { return this.WithETagCheck(); } /// <summary> /// Removes a AAAA record set in the DNS zone. /// </summary> /// <param name="name">Name of the AAAA record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutAaaaRecordSet(string name) { return this.WithoutAaaaRecordSet(name); } /// <summary> /// Removes a AAAA record set in the DNS zone. /// </summary> /// <param name="name">Name of the AAAA record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutAaaaRecordSet(string name, string eTagValue) { return this.WithoutAaaaRecordSet(name, eTagValue); } /// <summary> /// Removes a A record set in the DNS zone. /// </summary> /// <param name="name">Name of the A record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutARecordSet(string name) { return this.WithoutARecordSet(name); } /// <summary> /// Removes a A record set in the DNS zone. /// </summary> /// <param name="name">Name of the A record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutARecordSet(string name, string eTagValue) { return this.WithoutARecordSet(name, eTagValue); } /// <summary> /// Removes a Caa record set in the DNS zone. /// </summary> /// <param name="name">Name of the Caa record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutCaaRecordSet(string name) { return this.WithoutCaaRecordSet(name); } /// <summary> /// Removes a Caa record set in the DNS zone. /// </summary> /// <param name="name">Name of the Caa record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutCaaRecordSet(string name, string eTagValue) { return this.WithoutCaaRecordSet(name, eTagValue); } /// <summary> /// Removes a CNAME record set in the DNS zone. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutCNameRecordSet(string name) { return this.WithoutCNameRecordSet(name); } /// <summary> /// Removes a CNAME record set in the DNS zone. /// </summary> /// <param name="name">Name of the CNAME record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutCNameRecordSet(string name, string eTagValue) { return this.WithoutCNameRecordSet(name, eTagValue); } /// <summary> /// Removes a MX record set in the DNS zone. /// </summary> /// <param name="name">Name of the MX record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutMXRecordSet(string name) { return this.WithoutMXRecordSet(name); } /// <summary> /// Removes a MX record set in the DNS zone. /// </summary> /// <param name="name">Name of the MX record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutMXRecordSet(string name, string eTagValue) { return this.WithoutMXRecordSet(name, eTagValue); } /// <summary> /// Removes a NS record set in the DNS zone. /// </summary> /// <param name="name">Name of the NS record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutNSRecordSet(string name) { return this.WithoutNSRecordSet(name); } /// <summary> /// Removes a NS record set in the DNS zone. /// </summary> /// <param name="name">Name of the NS record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutNSRecordSet(string name, string eTagValue) { return this.WithoutNSRecordSet(name, eTagValue); } /// <summary> /// Removes a PTR record set in the DNS zone. /// </summary> /// <param name="name">Name of the PTR record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutPtrRecordSet(string name) { return this.WithoutPtrRecordSet(name); } /// <summary> /// Removes a PTR record set in the DNS zone. /// </summary> /// <param name="name">Name of the PTR record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutPtrRecordSet(string name, string eTagValue) { return this.WithoutPtrRecordSet(name, eTagValue); } /// <summary> /// Removes a SRV record set in the DNS zone. /// </summary> /// <param name="name">Name of the SRV record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutSrvRecordSet(string name) { return this.WithoutSrvRecordSet(name); } /// <summary> /// Removes a SRV record set in the DNS zone. /// </summary> /// <param name="name">Name of the SRV record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutSrvRecordSet(string name, string eTagValue) { return this.WithoutSrvRecordSet(name, eTagValue); } /// <summary> /// Removes a TXT record set in the DNS zone. /// </summary> /// <param name="name">Name of the TXT record set.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutTxtRecordSet(string name) { return this.WithoutTxtRecordSet(name); } /// <summary> /// Removes a TXT record set in the DNS zone. /// </summary> /// <param name="name">Name of the TXT record set.</param> /// <param name="eTagValue">The etag to use for concurrent protection.</param> /// <return>The next stage of DNS zone update.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithRecordSet.WithoutTxtRecordSet(string name, string eTagValue) { return this.WithoutTxtRecordSet(name, eTagValue); } /// <summary> /// Sets the type of this zone to Private. /// </summary> /// <return>The next stage of the definition.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithZoneType.WithPrivateAccess() { return this.WithPrivateAccess(); } /// <summary> /// Sets the type of this zone to Private. /// </summary> /// <param name="registrationVirtualNetworkIds">A list of references to virtual networks that register hostnames in this DNS zone.</param> /// <param name="resolutionVirtualNetworkIds">A list of references to virtual networks that resolve records in this DNS zone.</param> /// <return>The next stage of the definition.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithZoneType.WithPrivateAccess(IList<string> registrationVirtualNetworkIds, IList<string> resolutionVirtualNetworkIds) { return this.WithPrivateAccess(registrationVirtualNetworkIds, resolutionVirtualNetworkIds); } /// <summary> /// Sets the type of this zone to Private. /// </summary> /// <return>The next stage of the definition.</return> DnsZone.Definition.IWithCreate DnsZone.Definition.IWithZoneType.WithPrivateAccess() { return this.WithPrivateAccess(); } /// <summary> /// Sets the type of this zone to Private. /// </summary> /// <param name="registrationVirtualNetworkIds">A list of references to virtual networks that register hostnames in this DNS zone.</param> /// <param name="resolutionVirtualNetworkIds">A list of references to virtual networks that resolve records in this DNS zone.</param> /// <return>The next stage of the definition.</return> DnsZone.Definition.IWithCreate DnsZone.Definition.IWithZoneType.WithPrivateAccess(IList<string> registrationVirtualNetworkIds, IList<string> resolutionVirtualNetworkIds) { return this.WithPrivateAccess(registrationVirtualNetworkIds, resolutionVirtualNetworkIds); } /// <summary> /// Sets the type of this zone to Public (default behavior). /// </summary> /// <return>The next stage of the definition.</return> DnsZone.Update.IUpdate DnsZone.Update.IWithZoneType.WithPublicAccess() { return this.WithPublicAccess(); } /// <summary> /// Sets the type of this zone to Public (default behavior). /// </summary> /// <return>The next stage of the definition.</return> DnsZone.Definition.IWithCreate DnsZone.Definition.IWithZoneType.WithPublicAccess() { return this.WithPublicAccess(); } } }
namespace DataTanker.AccessMethods.BPlusTree { using System; using System.Diagnostics; using BinaryFormat.Page; using MemoryManagement; using PageManagement; using Settings; /// <summary> /// Key-value storage based on B+Tree /// </summary> /// <typeparam name="TKey">The type of keys</typeparam> /// <typeparam name="TValue">The type of values</typeparam> internal class BPlusTreeKeyValueStorage<TKey, TValue> : TransactionalStorage, IBPlusTreeKeyValueStorage<TKey, TValue> where TKey : IComparableKey where TValue : IValue { private readonly int _maxKeySize; private readonly IBPlusTree<TKey, TValue> _tree; private TReturnValue WrapWithReadLock<TReturnValue>(Func<TKey, TReturnValue> method, TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); EnterReadWrap(); try { return method(key); } finally { ExitReadWrap(); } } private TReturnValue WrapWithReadLock<TReturnValue>(Func<TReturnValue> method) { EnterReadWrap(); try { return method(); } finally { ExitReadWrap(); } } private TKey WrapWithReadLock(Func<TKey> method) { EnterReadWrap(); try { return method(); } finally { ExitReadWrap(); } } protected override void Init() { base.Init(); //add access-method page IPage amPage = PageManager.CreatePage(); Debug.Assert(amPage.Index == 2, "The first access method page should have index 2"); var tnph = new BPlusTreeNodePageHeader { ParentPageIndex = -1, PreviousPageIndex = -1, NextPageIndex = -1, IsLeaf = true, SizeRange = DbItem.GetSizeRange(_maxKeySize + sizeof(Int64) + sizeof(Int16)) }; PageFormatter.InitPage(amPage, tnph); PageManager.UpdatePage(amPage); } protected override void CheckInfo() { base.CheckInfo(); if (Info.KeyClrTypeName != typeof(TKey).FullName) throw new DataTankerException("Mismatch storage key type"); if (Info.ValueClrTypeName != typeof(TValue).FullName) throw new DataTankerException("Mismatch storage value type"); if (Info.MaxKeyLength != _maxKeySize) throw new DataTankerException("Mismatch key size"); } protected override void FillInfo() { base.FillInfo(); Info.KeyClrTypeName = typeof(TKey).FullName; Info.ValueClrTypeName = typeof(TValue).FullName; Info.MaxKeyLength = _maxKeySize; } public Type KeyType { get; } public Type ValueType { get; } /// <summary> /// Gets the access method implemented by this storage /// </summary> public override AccessMethod AccessMethod => AccessMethod.BPlusTree; /// <summary> /// Gets the minimal key. /// </summary> /// <returns>The minimal key</returns> public TKey Min() { return WrapWithReadLock(_tree.Min); } /// <summary> /// Gets the maximal key. /// </summary> /// <returns>The maximal key</returns> public TKey Max() { return WrapWithReadLock(_tree.Max); } /// <summary> /// Gets a value corresponing to the minimal key. /// </summary> /// <returns>The value corresponding to the minimal key</returns> public TValue MinValue() { return WrapWithReadLock<TValue>(_tree.MinValue); } /// <summary> /// Gets the value corresponing to the maximal key. /// </summary> /// <returns>The value corresponding to the maximal key</returns> public TValue MaxValue() { return WrapWithReadLock<TValue>(_tree.MaxValue); } /// <summary> /// Gets the key previous to the specified key. /// The existence of the specified key is not required. /// </summary> /// <returns>The key previous to specified key</returns> public TKey PreviousTo(TKey key) { return WrapWithReadLock(_tree.PreviousTo, key); } /// <summary> /// Gets the key next to the specified key. /// The existence of the specified key is not required. /// </summary> /// <returns>The key next to specified key</returns> public TKey NextTo(TKey key) { return WrapWithReadLock(_tree.NextTo, key); } /// <summary> /// Gets a value from storage. /// </summary> /// <param name="key">The key</param> /// <returns>Requested value</returns> public TValue Get(TKey key) { return WrapWithReadLock(_tree.Get, key); } /// <summary> /// Inserts a new value to storage or updates an existing one. /// </summary> /// <param name="key">The key</param> /// <param name="value">The value :)</param> public void Set(TKey key, TValue value) { if(key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); EnterWriteWrap(); try { _tree.Set(key, value); } finally { EditOperationFinished(); ExitWriteWrap(); } } /// <summary> /// Removes a value from storage by its key /// </summary> /// <param name="key">The key of value to remove</param> public void Remove(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); EnterWriteWrap(); try { _tree.Remove(key); } finally { EditOperationFinished(); ExitWriteWrap(); } } /// <summary> /// Cheks if key-value pair exists in storage. /// </summary> /// <param name="key">The key</param> /// <returns>True if key-value pair exists, false otherwise</returns> public bool Exists(TKey key) { return WrapWithReadLock(_tree.Exists, key); } /// <summary> /// Computes the count of key-value pairs in tree. /// </summary> /// <returns>the count of key-value pairs</returns> public long Count() { EnterReadWrap(); try { return _tree.Count(); } finally { ExitReadWrap(); } } /// <summary> /// Retrieves the length (in bytes) of binary representation /// of the value referenced by the specified key. /// </summary> /// <param name="key">The key</param> /// <returns>The length of binary representation</returns> public long GetRawDataLength(TKey key) { return WrapWithReadLock(_tree.GetRawDataLength, key); } /// <summary> /// Retrieves a segment of binary representation /// of the value referenced by the specified key. /// </summary> /// <param name="key">The key</param> /// <param name="startIndex">The index in binary representation where the specified segment starts</param> /// <param name="endIndex">The index in binary representation where the specified segment ends</param> /// <returns></returns> public byte[] GetRawDataSegment(TKey key, long startIndex, long endIndex) { EnterReadWrap(); try { return _tree.GetRawDataSegment(key, startIndex, endIndex); } finally { ExitReadWrap(); } } internal BPlusTreeKeyValueStorage(IPageManager pageManager, IBPlusTree<TKey, TValue> tree, int maxKeySize) : this(pageManager, tree, maxKeySize, 10000, TimeSpan.Zero) { } internal BPlusTreeKeyValueStorage(IPageManager pageManager, IBPlusTree<TKey, TValue> tree, int maxKeySize, int autoFlushInterval, TimeSpan autoFlushTimeout) : base(pageManager, autoFlushInterval, autoFlushTimeout) { _maxKeySize = maxKeySize; _tree = tree ?? throw new ArgumentNullException(nameof(tree)); ValueType = typeof(TKey); KeyType = typeof(TValue); } } }
/* * 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.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Mono.Addins; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ObjectAdd")] public class ObjectAdd : INonSharedRegionModule { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; #region INonSharedRegionModule Members public void Initialise(IConfigSource pSource) { } public void AddRegion(Scene scene) { m_scene = scene; m_scene.EventManager.OnRegisterCaps += RegisterCaps; } public void RemoveRegion(Scene scene) { if (m_scene == scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } } public void RegionLoaded(Scene scene) { } public void Close() { } public string Name { get { return "ObjectAddModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion public void RegisterCaps(UUID agentID, Caps caps) { UUID capuuid = UUID.Random(); // m_log.InfoFormat("[OBJECTADD]: {0}", "/CAPS/OA/" + capuuid + "/"); caps.RegisterHandler( "ObjectAdd", new RestHTTPHandler( "POST", "/CAPS/OA/" + capuuid + "/", httpMethod => ProcessAdd(httpMethod, agentID, caps), "ObjectAdd", agentID.ToString())); ; } public Hashtable ProcessAdd(Hashtable request, UUID AgentId, Caps cap) { Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 400; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = "Request wasn't what was expected"; ScenePresence avatar; if (!m_scene.TryGetScenePresence(AgentId, out avatar)) return responsedata; OSD r = OSDParser.DeserializeLLSDXml((string)request["requestbody"]); if (r.Type != OSDType.Map) // not a proper req return responsedata; //UUID session_id = UUID.Zero; bool bypass_raycast = false; uint everyone_mask = 0; uint group_mask = 0; uint next_owner_mask = 0; uint flags = 0; UUID group_id = UUID.Zero; int hollow = 0; int material = 0; int p_code = 0; int path_begin = 0; int path_curve = 0; int path_end = 0; int path_radius_offset = 0; int path_revolutions = 0; int path_scale_x = 0; int path_scale_y = 0; int path_shear_x = 0; int path_shear_y = 0; int path_skew = 0; int path_taper_x = 0; int path_taper_y = 0; int path_twist = 0; int path_twist_begin = 0; int profile_begin = 0; int profile_curve = 0; int profile_end = 0; Vector3 ray_end = Vector3.Zero; bool ray_end_is_intersection = false; Vector3 ray_start = Vector3.Zero; UUID ray_target_id = UUID.Zero; Quaternion rotation = Quaternion.Identity; Vector3 scale = Vector3.Zero; int state = 0; int lastattach = 0; OSDMap rm = (OSDMap)r; if (rm.ContainsKey("ObjectData")) //v2 { if (rm["ObjectData"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has ObjectData key, but data not in expected format"; return responsedata; } OSDMap ObjMap = (OSDMap)rm["ObjectData"]; bypass_raycast = ObjMap["BypassRaycast"].AsBoolean(); everyone_mask = readuintval(ObjMap["EveryoneMask"]); flags = readuintval(ObjMap["Flags"]); group_mask = readuintval(ObjMap["GroupMask"]); material = ObjMap["Material"].AsInteger(); next_owner_mask = readuintval(ObjMap["NextOwnerMask"]); p_code = ObjMap["PCode"].AsInteger(); if (ObjMap.ContainsKey("Path")) { if (ObjMap["Path"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has Path key, but data not in expected format"; return responsedata; } OSDMap PathMap = (OSDMap)ObjMap["Path"]; path_begin = PathMap["Begin"].AsInteger(); path_curve = PathMap["Curve"].AsInteger(); path_end = PathMap["End"].AsInteger(); path_radius_offset = PathMap["RadiusOffset"].AsInteger(); path_revolutions = PathMap["Revolutions"].AsInteger(); path_scale_x = PathMap["ScaleX"].AsInteger(); path_scale_y = PathMap["ScaleY"].AsInteger(); path_shear_x = PathMap["ShearX"].AsInteger(); path_shear_y = PathMap["ShearY"].AsInteger(); path_skew = PathMap["Skew"].AsInteger(); path_taper_x = PathMap["TaperX"].AsInteger(); path_taper_y = PathMap["TaperY"].AsInteger(); path_twist = PathMap["Twist"].AsInteger(); path_twist_begin = PathMap["TwistBegin"].AsInteger(); } if (ObjMap.ContainsKey("Profile")) { if (ObjMap["Profile"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has Profile key, but data not in expected format"; return responsedata; } OSDMap ProfileMap = (OSDMap)ObjMap["Profile"]; profile_begin = ProfileMap["Begin"].AsInteger(); profile_curve = ProfileMap["Curve"].AsInteger(); profile_end = ProfileMap["End"].AsInteger(); hollow = ProfileMap["Hollow"].AsInteger(); } ray_end_is_intersection = ObjMap["RayEndIsIntersection"].AsBoolean(); ray_target_id = ObjMap["RayTargetId"].AsUUID(); state = ObjMap["State"].AsInteger(); lastattach = ObjMap["LastAttachPoint"].AsInteger(); try { ray_end = ((OSDArray)ObjMap["RayEnd"]).AsVector3(); ray_start = ((OSDArray)ObjMap["RayStart"]).AsVector3(); scale = ((OSDArray)ObjMap["Scale"]).AsVector3(); rotation = ((OSDArray)ObjMap["Rotation"]).AsQuaternion(); } catch (Exception) { responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; return responsedata; } if (rm.ContainsKey("AgentData")) { if (rm["AgentData"].Type != OSDType.Map) { responsedata["str_response_string"] = "Has AgentData key, but data not in expected format"; return responsedata; } OSDMap AgentDataMap = (OSDMap)rm["AgentData"]; //session_id = AgentDataMap["SessionId"].AsUUID(); group_id = AgentDataMap["GroupId"].AsUUID(); } } else { //v1 bypass_raycast = rm["bypass_raycast"].AsBoolean(); everyone_mask = readuintval(rm["everyone_mask"]); flags = readuintval(rm["flags"]); group_id = rm["group_id"].AsUUID(); group_mask = readuintval(rm["group_mask"]); hollow = rm["hollow"].AsInteger(); material = rm["material"].AsInteger(); next_owner_mask = readuintval(rm["next_owner_mask"]); hollow = rm["hollow"].AsInteger(); p_code = rm["p_code"].AsInteger(); path_begin = rm["path_begin"].AsInteger(); path_curve = rm["path_curve"].AsInteger(); path_end = rm["path_end"].AsInteger(); path_radius_offset = rm["path_radius_offset"].AsInteger(); path_revolutions = rm["path_revolutions"].AsInteger(); path_scale_x = rm["path_scale_x"].AsInteger(); path_scale_y = rm["path_scale_y"].AsInteger(); path_shear_x = rm["path_shear_x"].AsInteger(); path_shear_y = rm["path_shear_y"].AsInteger(); path_skew = rm["path_skew"].AsInteger(); path_taper_x = rm["path_taper_x"].AsInteger(); path_taper_y = rm["path_taper_y"].AsInteger(); path_twist = rm["path_twist"].AsInteger(); path_twist_begin = rm["path_twist_begin"].AsInteger(); profile_begin = rm["profile_begin"].AsInteger(); profile_curve = rm["profile_curve"].AsInteger(); profile_end = rm["profile_end"].AsInteger(); ray_end_is_intersection = rm["ray_end_is_intersection"].AsBoolean(); ray_target_id = rm["ray_target_id"].AsUUID(); //session_id = rm["session_id"].AsUUID(); state = rm["state"].AsInteger(); lastattach = rm["last_attach_point"].AsInteger(); try { ray_end = ((OSDArray)rm["ray_end"]).AsVector3(); ray_start = ((OSDArray)rm["ray_start"]).AsVector3(); rotation = ((OSDArray)rm["rotation"]).AsQuaternion(); scale = ((OSDArray)rm["scale"]).AsVector3(); } catch (Exception) { responsedata["str_response_string"] = "RayEnd, RayStart, Scale or Rotation wasn't in the expected format"; return responsedata; } } Vector3 pos = m_scene.GetNewRezLocation(ray_start, ray_end, ray_target_id, rotation, (bypass_raycast) ? (byte)1 : (byte)0, (ray_end_is_intersection) ? (byte)1 : (byte)0, true, scale, false); PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox(); pbs.PathBegin = (ushort)path_begin; pbs.PathCurve = (byte)path_curve; pbs.PathEnd = (ushort)path_end; pbs.PathRadiusOffset = (sbyte)path_radius_offset; pbs.PathRevolutions = (byte)path_revolutions; pbs.PathScaleX = (byte)path_scale_x; pbs.PathScaleY = (byte)path_scale_y; pbs.PathShearX = (byte)path_shear_x; pbs.PathShearY = (byte)path_shear_y; pbs.PathSkew = (sbyte)path_skew; pbs.PathTaperX = (sbyte)path_taper_x; pbs.PathTaperY = (sbyte)path_taper_y; pbs.PathTwist = (sbyte)path_twist; pbs.PathTwistBegin = (sbyte)path_twist_begin; pbs.HollowShape = (HollowShape)hollow; pbs.PCode = (byte)p_code; pbs.ProfileBegin = (ushort)profile_begin; pbs.ProfileCurve = (byte)profile_curve; pbs.ProfileEnd = (ushort)profile_end; pbs.Scale = scale; pbs.State = (byte)state; pbs.LastAttachPoint = (byte)lastattach; SceneObjectGroup obj = null; ; if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos)) { // rez ON the ground, not IN the ground // pos.Z += 0.25F; obj = m_scene.AddNewPrim(avatar.UUID, group_id, pos, rotation, pbs); } if (obj == null) return responsedata; SceneObjectPart rootpart = obj.RootPart; rootpart.Shape = pbs; rootpart.Flags |= (PrimFlags)flags; rootpart.EveryoneMask = everyone_mask; rootpart.GroupID = group_id; rootpart.GroupMask = group_mask; rootpart.NextOwnerMask = next_owner_mask; rootpart.Material = (byte)material; obj.AggregatePerms(); m_scene.PhysicsScene.AddPhysicsActorTaint(rootpart.PhysActor); responsedata["int_response_code"] = 200; //501; //410; //404; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>", ConvertUintToBytes(obj.LocalId)); return responsedata; } private uint readuintval(OSD obj) { byte[] tmp = obj.AsBinary(); if (BitConverter.IsLittleEndian) Array.Reverse(tmp); return Utils.BytesToUInt(tmp); } private string ConvertUintToBytes(uint val) { byte[] resultbytes = Utils.UIntToBytes(val); if (BitConverter.IsLittleEndian) Array.Reverse(resultbytes); return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Messaging; using Orleans.Providers; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Orleans.Streams; namespace Orleans { internal class OutsideRuntimeClient : IRuntimeClient, IDisposable { internal static bool TestOnlyThrowExceptionDuringInit { get; set; } private readonly Logger logger; private readonly Logger appLogger; private readonly ClientConfiguration config; private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks; private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects; private readonly ProxiedMessageCenter transport; private bool listenForMessages; private CancellationTokenSource listeningCts; private bool firstMessageReceived; private readonly ClientProviderRuntime clientProviderRuntime; private readonly StatisticsProviderManager statisticsProviderManager; internal ClientStatisticsManager ClientStatistics; private GrainId clientId; private readonly GrainId handshakeClientId; private IGrainTypeResolver grainInterfaceMap; private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking; private readonly Func<Message, bool> tryResendMessage; private readonly Action<Message> unregisterCallback; // initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1); private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1); private const string BARS = "----------"; private readonly GrainFactory grainFactory; public IInternalGrainFactory InternalGrainFactory { get { return grainFactory; } } /// <summary> /// Response timeout. /// </summary> private TimeSpan responseTimeout; private static readonly Object staticLock = new Object(); private TypeMetadataCache typeCache; private readonly AssemblyProcessor assemblyProcessor; Logger IRuntimeClient.AppLogger { get { return appLogger; } } public ActivationAddress CurrentActivationAddress { get; private set; } public string CurrentActivationIdentity { get { return CurrentActivationAddress.ToString(); } } internal IList<Uri> Gateways { get { return transport.GatewayManager.ListProvider.GetGateways().GetResult(); } } public IStreamProviderManager CurrentStreamProviderManager { get; private set; } public IStreamProviderRuntime CurrentStreamProviderRuntime { get { return clientProviderRuntime; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")] public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false) { this.typeCache = new TypeMetadataCache(); this.assemblyProcessor = new AssemblyProcessor(this.typeCache); this.grainFactory = new GrainFactory(this, this.typeCache); if (cfg == null) { Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object."); throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg"); } this.config = cfg; if (!LogManager.IsInitialized) LogManager.Initialize(config); StatisticsCollector.Initialize(config); SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider); this.assemblyProcessor.Initialize(); logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime); appLogger = LogManager.GetLogger("Application", LoggerType.Application); BufferPool.InitGlobalBufferPool(config); this.handshakeClientId = GrainId.NewClientId(); tryResendMessage = TryResendMessage; unregisterCallback = msg => UnRegisterCallback(msg.Id); try { LoadAdditionalAssemblies(); callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>(); localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>(); if (!secondary) { UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked SerializationManager.GetDeserializer(typeof(String)); clientProviderRuntime = new ClientProviderRuntime(grainFactory, null); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, handshakeClientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } config.CheckGatewayProviderSettings(); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config) .WithTimeout(initTimeout).Result; transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); ConstructorReset(); throw; } } private void StreamingInitialize() { var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result; clientProviderRuntime.StreamingInitialize(implicitSubscriberTable); var streamProviderManager = new Streams.StreamProviderManager(); streamProviderManager .LoadStreamProviders( this.config.ProviderConfigurations, clientProviderRuntime) .Wait(); CurrentStreamProviderManager = streamProviderManager; } private void LoadAdditionalAssemblies() { #if !NETSTANDARD_TODO var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime); var directories = new Dictionary<string, SearchOption> { { Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location), SearchOption.AllDirectories } }; var excludeCriteria = new AssemblyLoaderPathNameCriterion[] { AssemblyLoaderCriteria.ExcludeResourceAssemblies, AssemblyLoaderCriteria.ExcludeSystemBinaries() }; var loadProvidersCriteria = new AssemblyLoaderReflectionCriterion[] { AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider)) }; this.assemblyProcessor.Initialize(); AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger); #endif } private void UnhandledException(ISchedulingContext context, Exception exception) { logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception); logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client."); } public void Start() { lock (staticLock) { if (RuntimeClient.Current != null) throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain"); RuntimeClient.Current = this; } StartInternal(); logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + handshakeClientId); } // used for testing to (carefully!) allow two clients in the same process internal void StartInternal() { transport.Start(); LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started. CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId); ClientStatistics = new ClientStatisticsManager(config); listeningCts = new CancellationTokenSource(); var ct = listeningCts.Token; listenForMessages = true; // Keeping this thread handling it very simple for now. Just queue task on thread pool. Task.Factory.StartNew(() => { try { RunClientMessagePump(ct); } catch (Exception exc) { logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc); } } ); grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result; ClientStatistics.Start(statisticsProviderManager, transport, clientId) .WaitWithThrow(initTimeout); StreamingInitialize(); } private void RunClientMessagePump(CancellationToken ct) { if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStartExecution(); } while (listenForMessages) { var message = transport.WaitMessage(Message.Categories.Application, ct); if (message == null) // if wait was cancelled break; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStartProcessing(); } #endif // when we receive the first message, we update the // clientId for this client because it may have been modified to // include the cluster name if (!firstMessageReceived) { firstMessageReceived = true; if (!handshakeClientId.Equals(message.TargetGrain)) { clientId = message.TargetGrain; transport.UpdateClientId(clientId); CurrentActivationAddress = ActivationAddress.GetAddress(transport.MyAddress, clientId, CurrentActivationAddress.Activation); } else { clientId = handshakeClientId; } } switch (message.Direction) { case Message.Directions.Response: { ReceiveResponse(message); break; } case Message.Directions.OneWay: case Message.Directions.Request: { this.DispatchToLocalObject(message); break; } default: logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message)); break; } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopProcessing(); incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed(); } #endif } if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopExecution(); } } private void DispatchToLocalObject(Message message) { LocalObjectData objectData; GuidId observerId = message.TargetObserverId; if (observerId == null) { logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound_2, String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message)); return; } if (localObjects.TryGetValue(observerId, out objectData)) this.InvokeLocalObjectAsync(objectData, message); else { logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound, String.Format( "Unexpected target grain in request: {0}. Message={1}", message.TargetGrain, message)); } } private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message) { var obj = (IAddressable)objectData.LocalObject.Target; if (obj == null) { //// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore. logger.Warn(ErrorCode.Runtime_Error_100162, String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message)); LocalObjectData ignore; // Try to remove. If it's not there, we don't care. localObjects.TryRemove(objectData.ObserverId, out ignore); return; } bool start; lock (objectData.Messages) { objectData.Messages.Enqueue(message); start = !objectData.Running; objectData.Running = true; } if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start); if (start) { // we use Task.Run() to ensure that the message pump operates asynchronously // with respect to the current thread. see // http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74 // at position 54:45. // // according to the information posted at: // http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr // this idiom is dependent upon the a TaskScheduler not implementing the // override QueueTask as task inlining (as opposed to queueing). this seems // implausible to the author, since none of the .NET schedulers do this and // it is considered bad form (the OrleansTaskScheduler does not do this). // // if, for some reason this doesn't hold true, we can guarantee what we // want by passing a placeholder continuation token into Task.StartNew() // instead. i.e.: // // return Task.StartNew(() => ..., new CancellationToken()); Func<Task> asyncFunc = async () => await this.LocalObjectMessagePumpAsync(objectData); Task.Run(asyncFunc).Ignore(); } } private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData) { while (true) { try { Message message; lock (objectData.Messages) { if (objectData.Messages.Count == 0) { objectData.Running = false; break; } message = objectData.Messages.Dequeue(); } if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke)) continue; RequestContext.Import(message.RequestContextData); var request = (InvokeMethodRequest)message.BodyObject; var targetOb = (IAddressable)objectData.LocalObject.Target; object resultObject = null; Exception caught = null; try { // exceptions thrown within this scope are not considered to be thrown from user code // and not from runtime code. var resultPromise = objectData.Invoker.Invoke(targetOb, request); if (resultPromise != null) // it will be null for one way messages { resultObject = await resultPromise; } } catch (Exception exc) { // the exception needs to be reported in the log or propagated back to the caller. caught = exc; } if (caught != null) this.ReportException(message, caught); else if (message.Direction != Message.Directions.OneWay) await this.SendResponseAsync(message, resultObject); } catch (Exception) { // ignore, keep looping. } } } private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase) { if (message.IsExpired) { message.DropExpiredMessage(phase); return true; } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Task SendResponseAsync( Message message, object resultObject) { if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond)) return TaskDone.Done; object deepCopy = null; try { // we're expected to notify the caller if the deep copy failed. deepCopy = SerializationManager.DeepCopy(resultObject); } catch (Exception exc2) { SendResponse(message, Response.ExceptionResponse(exc2)); logger.Warn( ErrorCode.ProxyClient_OGC_SendResponseFailed, "Exception trying to send a response.", exc2); return TaskDone.Done; } // the deep-copy succeeded. SendResponse(message, new Response(deepCopy)); return TaskDone.Done; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ReportException(Message message, Exception exception) { var request = (InvokeMethodRequest)message.BodyObject; switch (message.Direction) { default: throw new InvalidOperationException(); case Message.Directions.OneWay: { logger.Error( ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke, String.Format( "Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.", request.MethodId, request.InterfaceId), exception); break; } case Message.Directions.Request: { Exception deepCopy = null; try { // we're expected to notify the caller if the deep copy failed. deepCopy = (Exception)SerializationManager.DeepCopy(exception); } catch (Exception ex2) { SendResponse(message, Response.ExceptionResponse(ex2)); logger.Warn( ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed, "Exception trying to send an exception response", ex2); return; } // the deep-copy succeeded. var response = Response.ExceptionResponse(deepCopy); SendResponse(message, response); break; } } } private void SendResponse(Message request, Response response) { var message = request.CreateResponseMessage(); message.BodyObject = response; transport.SendMessage(message); } /// <summary> /// For testing only. /// </summary> public void Disconnect() { transport.Disconnect(); } /// <summary> /// For testing only. /// </summary> public void Reconnect() { transport.Reconnect(); } #region Implementation of IRuntimeClient [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")] public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = Message.CreateMessage(request, options); SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments); } private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (!String.IsNullOrEmpty(genericArguments)) message.GenericGrainType = genericArguments; if (targetGrainId.IsSystemTarget) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = target.SystemTargetSilo; if (target.SystemTargetSilo != null) { message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo); } } // Client sending messages to another client (observer). Yes, we support that. if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } if (message.IsExpirableMessage(config)) { // don't set expiration for system target messages. message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW; } if (!oneWay) { var callbackData = new CallbackData( callback, tryResendMessage, context, message, unregisterCallback, config); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(responseTimeout); } if (logger.IsVerbose2) logger.Verbose2("Send {0}", message); transport.SendMessage(message); } private bool TryResendMessage(Message message) { if (!message.MayResend(config)) { return false; } if (logger.IsVerbose) logger.Verbose("Resend {0}", message); message.ResendCount = message.ResendCount + 1; message.TargetHistory = message.GetTargetHistory(); if (!message.TargetGrain.IsSystemTarget) { message.TargetActivation = null; message.TargetSilo = null; message.ClearTargetAddress(); } transport.SendMessage(message); return true; } public void ReceiveResponse(Message response) { if (logger.IsVerbose2) logger.Verbose2("Received {0}", response); // ignore duplicate requests if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest) return; CallbackData callbackData; var found = callbacks.TryGetValue(response.Id, out callbackData); if (found) { // We need to import the RequestContext here as well. // Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task. // RequestContext.Import(response.RequestContextData); callbackData.DoCallback(response); } else { logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response); } } private void UnRegisterCallback(CorrelationId id) { CallbackData ignore; callbacks.TryRemove(id, out ignore); } public void Reset(bool cleanup) { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId); } }); Utils.SafeExecute(() => { if (clientProviderRuntime != null) { clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout); } }, logger, "Client.clientProviderRuntime.Reset"); Utils.SafeExecute(() => { if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking.OnStopExecution(); } }, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution"); Utils.SafeExecute(() => { if (transport != null) { transport.PrepareToStop(); } }, logger, "Client.PrepareToStop-Transport"); listenForMessages = false; Utils.SafeExecute(() => { if (listeningCts != null) { listeningCts.Cancel(); } }, logger, "Client.Stop-ListeningCTS"); Utils.SafeExecute(() => { if (transport != null) { transport.Stop(); } }, logger, "Client.Stop-Transport"); Utils.SafeExecute(() => { if (ClientStatistics != null) { ClientStatistics.Stop(); } }, logger, "Client.Stop-ClientStatistics"); ConstructorReset(); } private void ConstructorReset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId); } }); try { UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler(); } catch (Exception) { } try { AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload; } catch (Exception) { } try { if (clientProviderRuntime != null) { clientProviderRuntime.Reset().WaitWithThrow(resetTimeout); } } catch (Exception) { } try { LogManager.UnInitialize(); } catch (Exception) { } } public void SetResponseTimeout(TimeSpan timeout) { responseTimeout = timeout; } public TimeSpan GetResponseTimeout() { return responseTimeout; } public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName) { await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool } public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker) { if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference."); GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId()); if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker))) { throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr"); } return gr; } public void DeleteObjectReference(IAddressable obj) { if (!(obj is GrainReference)) throw new ArgumentException("Argument reference is not a grain reference."); var reference = (GrainReference)obj; LocalObjectData ignore; if (!localObjects.TryRemove(reference.ObserverId, out ignore)) throw new ArgumentException("Reference is not associated with a local object.", "reference"); } #endregion Implementation of IRuntimeClient private void CurrentDomain_DomainUnload(object sender, EventArgs e) { try { logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload, String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails())); LogManager.Flush(); } catch (Exception) { // just ignore, make sure not to throw from here. } } private string PrintAppDomainDetails() { #if NETSTANDARD_TODO return "N/A"; #else return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName); #endif } private class LocalObjectData { internal WeakReference LocalObject { get; private set; } internal IGrainMethodInvoker Invoker { get; private set; } internal GuidId ObserverId { get; private set; } internal Queue<Message> Messages { get; private set; } internal bool Running { get; set; } internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker) { LocalObject = new WeakReference(obj); ObserverId = observerId; Invoker = invoker; Messages = new Queue<Message>(); Running = false; } } public void Dispose() { if (listeningCts != null) { listeningCts.Dispose(); listeningCts = null; this.assemblyProcessor.Dispose(); } transport.Dispose(); if (ClientStatistics != null) { ClientStatistics.Dispose(); ClientStatistics = null; } GC.SuppressFinalize(this); } public IGrainTypeResolver GrainTypeResolver { get { return grainInterfaceMap; } } public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo) { foreach (var callback in callbacks) { if (deadSilo.Equals(callback.Value.Message.TargetSilo)) { callback.Value.OnTargetSiloFail(); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Portable { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Portable.IO; /// <summary> /// Write delegate. /// </summary> /// <param name="writer">Write context.</param> /// <param name="obj">Object to write.</param> internal delegate void PortableSystemWriteDelegate(PortableWriterImpl writer, object obj); /// <summary> /// Typed write delegate. /// </summary> /// <param name="stream">Stream.</param> /// <param name="obj">Object to write.</param> // ReSharper disable once TypeParameterCanBeVariant // Generic variance in a delegate causes performance hit internal delegate void PortableSystemTypedWriteDelegate<T>(IPortableStream stream, T obj); /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class PortableSystemHandlers { /** Write handlers. */ private static readonly Dictionary<Type, PortableSystemWriteDelegate> WriteHandlers = new Dictionary<Type, PortableSystemWriteDelegate>(); /** Read handlers. */ private static readonly IPortableSystemReader[] ReadHandlers = new IPortableSystemReader[255]; /** Typed write handler: boolean. */ public static readonly PortableSystemTypedWriteDelegate<bool> WriteHndBoolTyped = WriteBoolTyped; /** Typed write handler: byte. */ public static readonly PortableSystemTypedWriteDelegate<byte> WriteHndByteTyped = WriteByteTyped; /** Typed write handler: short. */ public static readonly PortableSystemTypedWriteDelegate<short> WriteHndShortTyped = WriteShortTyped; /** Typed write handler: char. */ public static readonly PortableSystemTypedWriteDelegate<char> WriteHndCharTyped = WriteCharTyped; /** Typed write handler: int. */ public static readonly PortableSystemTypedWriteDelegate<int> WriteHndIntTyped = WriteIntTyped; /** Typed write handler: long. */ public static readonly PortableSystemTypedWriteDelegate<long> WriteHndLongTyped = WriteLongTyped; /** Typed write handler: float. */ public static readonly PortableSystemTypedWriteDelegate<float> WriteHndFloatTyped = WriteFloatTyped; /** Typed write handler: double. */ public static readonly PortableSystemTypedWriteDelegate<double> WriteHndDoubleTyped = WriteDoubleTyped; /** Typed write handler: decimal. */ public static readonly PortableSystemTypedWriteDelegate<decimal> WriteHndDecimalTyped = WriteDecimalTyped; /** Typed write handler: Date. */ public static readonly PortableSystemTypedWriteDelegate<DateTime?> WriteHndDateTyped = WriteDateTyped; /** Typed write handler: string. */ public static readonly PortableSystemTypedWriteDelegate<string> WriteHndStringTyped = WriteStringTyped; /** Typed write handler: Guid. */ public static readonly PortableSystemTypedWriteDelegate<Guid?> WriteHndGuidTyped = WriteGuidTyped; /** Typed write handler: Portable. */ public static readonly PortableSystemTypedWriteDelegate<PortableUserObject> WriteHndPortableTyped = WritePortableTyped; /** Typed write handler: boolean array. */ public static readonly PortableSystemTypedWriteDelegate<bool[]> WriteHndBoolArrayTyped = WriteBoolArrayTyped; /** Typed write handler: byte array. */ public static readonly PortableSystemTypedWriteDelegate<byte[]> WriteHndByteArrayTyped = WriteByteArrayTyped; /** Typed write handler: short array. */ public static readonly PortableSystemTypedWriteDelegate<short[]> WriteHndShortArrayTyped = WriteShortArrayTyped; /** Typed write handler: char array. */ public static readonly PortableSystemTypedWriteDelegate<char[]> WriteHndCharArrayTyped = WriteCharArrayTyped; /** Typed write handler: int array. */ public static readonly PortableSystemTypedWriteDelegate<int[]> WriteHndIntArrayTyped = WriteIntArrayTyped; /** Typed write handler: long array. */ public static readonly PortableSystemTypedWriteDelegate<long[]> WriteHndLongArrayTyped = WriteLongArrayTyped; /** Typed write handler: float array. */ public static readonly PortableSystemTypedWriteDelegate<float[]> WriteHndFloatArrayTyped = WriteFloatArrayTyped; /** Typed write handler: double array. */ public static readonly PortableSystemTypedWriteDelegate<double[]> WriteHndDoubleArrayTyped = WriteDoubleArrayTyped; /** Typed write handler: decimal array. */ public static readonly PortableSystemTypedWriteDelegate<decimal[]> WriteHndDecimalArrayTyped = WriteDecimalArrayTyped; /** Typed write handler: Date array. */ public static readonly PortableSystemTypedWriteDelegate<DateTime?[]> WriteHndDateArrayTyped = WriteDateArrayTyped; /** Typed write handler: string array. */ public static readonly PortableSystemTypedWriteDelegate<string[]> WriteHndStringArrayTyped = WriteStringArrayTyped; /** Typed write handler: Guid array. */ public static readonly PortableSystemTypedWriteDelegate<Guid?[]> WriteHndGuidArrayTyped = WriteGuidArrayTyped; /** Write handler: boolean. */ public static readonly PortableSystemWriteDelegate WriteHndBool = WriteBool; /** Write handler: sbyte. */ public static readonly PortableSystemWriteDelegate WriteHndSbyte = WriteSbyte; /** Write handler: byte. */ public static readonly PortableSystemWriteDelegate WriteHndByte = WriteByte; /** Write handler: short. */ public static readonly PortableSystemWriteDelegate WriteHndShort = WriteShort; /** Write handler: ushort. */ public static readonly PortableSystemWriteDelegate WriteHndUshort = WriteUshort; /** Write handler: char. */ public static readonly PortableSystemWriteDelegate WriteHndChar = WriteChar; /** Write handler: int. */ public static readonly PortableSystemWriteDelegate WriteHndInt = WriteInt; /** Write handler: uint. */ public static readonly PortableSystemWriteDelegate WriteHndUint = WriteUint; /** Write handler: long. */ public static readonly PortableSystemWriteDelegate WriteHndLong = WriteLong; /** Write handler: ulong. */ public static readonly PortableSystemWriteDelegate WriteHndUlong = WriteUlong; /** Write handler: float. */ public static readonly PortableSystemWriteDelegate WriteHndFloat = WriteFloat; /** Write handler: double. */ public static readonly PortableSystemWriteDelegate WriteHndDouble = WriteDouble; /** Write handler: decimal. */ public static readonly PortableSystemWriteDelegate WriteHndDecimal = WriteDecimal; /** Write handler: Date. */ public static readonly PortableSystemWriteDelegate WriteHndDate = WriteDate; /** Write handler: string. */ public static readonly PortableSystemWriteDelegate WriteHndString = WriteString; /** Write handler: Guid. */ public static readonly PortableSystemWriteDelegate WriteHndGuid = WriteGuid; /** Write handler: Portable. */ public static readonly PortableSystemWriteDelegate WriteHndPortable = WritePortable; /** Write handler: Enum. */ public static readonly PortableSystemWriteDelegate WriteHndEnum = WriteEnum; /** Write handler: boolean array. */ public static readonly PortableSystemWriteDelegate WriteHndBoolArray = WriteBoolArray; /** Write handler: sbyte array. */ public static readonly PortableSystemWriteDelegate WriteHndSbyteArray = WriteSbyteArray; /** Write handler: byte array. */ public static readonly PortableSystemWriteDelegate WriteHndByteArray = WriteByteArray; /** Write handler: short array. */ public static readonly PortableSystemWriteDelegate WriteHndShortArray = WriteShortArray; /** Write handler: ushort array. */ public static readonly PortableSystemWriteDelegate WriteHndUshortArray = WriteUshortArray; /** Write handler: char array. */ public static readonly PortableSystemWriteDelegate WriteHndCharArray = WriteCharArray; /** Write handler: int array. */ public static readonly PortableSystemWriteDelegate WriteHndIntArray = WriteIntArray; /** Write handler: uint array. */ public static readonly PortableSystemWriteDelegate WriteHndUintArray = WriteUintArray; /** Write handler: long array. */ public static readonly PortableSystemWriteDelegate WriteHndLongArray = WriteLongArray; /** Write handler: ulong array. */ public static readonly PortableSystemWriteDelegate WriteHndUlongArray = WriteUlongArray; /** Write handler: float array. */ public static readonly PortableSystemWriteDelegate WriteHndFloatArray = WriteFloatArray; /** Write handler: double array. */ public static readonly PortableSystemWriteDelegate WriteHndDoubleArray = WriteDoubleArray; /** Write handler: decimal array. */ public static readonly PortableSystemWriteDelegate WriteHndDecimalArray = WriteDecimalArray; /** Write handler: date array. */ public static readonly PortableSystemWriteDelegate WriteHndDateArray = WriteDateArray; /** Write handler: string array. */ public static readonly PortableSystemWriteDelegate WriteHndStringArray = WriteStringArray; /** Write handler: Guid array. */ public static readonly PortableSystemWriteDelegate WriteHndGuidArray = WriteGuidArray; /** Write handler: Enum array. */ public static readonly PortableSystemWriteDelegate WriteHndEnumArray = WriteEnumArray; /** Write handler: object array. */ public static readonly PortableSystemWriteDelegate WriteHndArray = WriteArray; /** Write handler: collection. */ public static readonly PortableSystemWriteDelegate WriteHndCollection = WriteCollection; /** Write handler: dictionary. */ public static readonly PortableSystemWriteDelegate WriteHndDictionary = WriteDictionary; /** Write handler: generic collection. */ public static readonly PortableSystemWriteDelegate WriteHndGenericCollection = WriteGenericCollection; /** Write handler: generic dictionary. */ public static readonly PortableSystemWriteDelegate WriteHndGenericDictionary = WriteGenericDictionary; /** * <summary>Static initializer.</summary> */ static PortableSystemHandlers() { // 1. Primitives. ReadHandlers[PortableUtils.TypeBool] = new PortableSystemReader<bool>(s => s.ReadBool()); WriteHandlers[typeof(sbyte)] = WriteHndSbyte; ReadHandlers[PortableUtils.TypeByte] = new PortableSystemReader<byte>(s => s.ReadByte()); WriteHandlers[typeof(ushort)] = WriteHndUshort; ReadHandlers[PortableUtils.TypeShort] = new PortableSystemReader<short>(s => s.ReadShort()); ReadHandlers[PortableUtils.TypeChar] = new PortableSystemReader<char>(s => s.ReadChar()); WriteHandlers[typeof(uint)] = WriteHndUint; ReadHandlers[PortableUtils.TypeInt] = new PortableSystemReader<int>(s => s.ReadInt()); WriteHandlers[typeof(ulong)] = WriteHndUlong; ReadHandlers[PortableUtils.TypeLong] = new PortableSystemReader<long>(s => s.ReadLong()); ReadHandlers[PortableUtils.TypeFloat] = new PortableSystemReader<float>(s => s.ReadFloat()); ReadHandlers[PortableUtils.TypeDouble] = new PortableSystemReader<double>(s => s.ReadDouble()); ReadHandlers[PortableUtils.TypeDecimal] = new PortableSystemReader<decimal>(PortableUtils.ReadDecimal); // 2. Date. ReadHandlers[PortableUtils.TypeDate] = new PortableSystemReader<DateTime?>(s => PortableUtils.ReadDate(s, false)); // 3. String. ReadHandlers[PortableUtils.TypeString] = new PortableSystemReader<string>(PortableUtils.ReadString); // 4. Guid. ReadHandlers[PortableUtils.TypeGuid] = new PortableSystemReader<Guid?>(PortableUtils.ReadGuid); // 5. Primitive arrays. ReadHandlers[PortableUtils.TypeArrayBool] = new PortableSystemReader<bool[]>(PortableUtils.ReadBooleanArray); WriteHandlers[typeof(sbyte[])] = WriteHndSbyteArray; ReadHandlers[PortableUtils.TypeArrayByte] = new PortableSystemDualReader<byte[], sbyte[]>(PortableUtils.ReadByteArray, PortableUtils.ReadSbyteArray); WriteHandlers[typeof(ushort[])] = WriteHndUshortArray; ReadHandlers[PortableUtils.TypeArrayShort] = new PortableSystemDualReader<short[], ushort[]>(PortableUtils.ReadShortArray, PortableUtils.ReadUshortArray); ReadHandlers[PortableUtils.TypeArrayChar] = new PortableSystemReader<char[]>(PortableUtils.ReadCharArray); WriteHandlers[typeof(uint[])] = WriteHndUintArray; ReadHandlers[PortableUtils.TypeArrayInt] = new PortableSystemDualReader<int[], uint[]>(PortableUtils.ReadIntArray, PortableUtils.ReadUintArray); WriteHandlers[typeof(ulong[])] = WriteHndUlongArray; ReadHandlers[PortableUtils.TypeArrayLong] = new PortableSystemDualReader<long[], ulong[]>(PortableUtils.ReadLongArray, PortableUtils.ReadUlongArray); ReadHandlers[PortableUtils.TypeArrayFloat] = new PortableSystemReader<float[]>(PortableUtils.ReadFloatArray); ReadHandlers[PortableUtils.TypeArrayDouble] = new PortableSystemReader<double[]>(PortableUtils.ReadDoubleArray); ReadHandlers[PortableUtils.TypeArrayDecimal] = new PortableSystemReader<decimal[]>(PortableUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[PortableUtils.TypeArrayDate] = new PortableSystemReader<DateTime?[]>(s => PortableUtils.ReadDateArray(s, false)); // 7. String array. ReadHandlers[PortableUtils.TypeArrayString] = new PortableSystemGenericArrayReader<string>(); // 8. Guid array. ReadHandlers[PortableUtils.TypeArrayGuid] = new PortableSystemGenericArrayReader<Guid?>(); // 9. Array. ReadHandlers[PortableUtils.TypeArray] = new PortableSystemReader(ReadArray); // 10. Predefined collections. WriteHandlers[typeof(ArrayList)] = WriteArrayList; // 11. Predefined dictionaries. WriteHandlers[typeof(Hashtable)] = WriteHashtable; // 12. Arbitrary collection. ReadHandlers[PortableUtils.TypeCollection] = new PortableSystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[PortableUtils.TypeDictionary] = new PortableSystemReader(ReadDictionary); // 14. Map entry. WriteHandlers[typeof(DictionaryEntry)] = WriteMapEntry; ReadHandlers[PortableUtils.TypeMapEntry] = new PortableSystemReader(ReadMapEntry); // 15. Portable. WriteHandlers[typeof(PortableUserObject)] = WritePortable; // 16. Enum. ReadHandlers[PortableUtils.TypeEnum] = new PortableSystemReader<int>(PortableUtils.ReadEnum<int>); ReadHandlers[PortableUtils.TypeArrayEnum] = new PortableSystemReader(ReadEnumArray); } /** * <summary>Get write handler for type.</summary> * <param name="type">Type.</param> * <returns>Handler or null if cannot be hanled in special way.</returns> */ public static PortableSystemWriteDelegate WriteHandler(Type type) { PortableSystemWriteDelegate handler; if (WriteHandlers.TryGetValue(type, out handler)) return handler; // 1. Array? if (type.IsArray) { if (type.GetElementType().IsEnum) return WriteEnumArray; return WriteArray; } // 2. Enum? if (type.IsEnum) return WriteEnum; // 3. Collection? PortableCollectionInfo info = PortableCollectionInfo.Info(type); if (info.IsAny) return info.WriteHandler; // No special handler found. return null; } /// <summary> /// Reads an object of predefined type. /// </summary> public static T ReadSystemType<T>(byte typeId, PortableReaderImpl ctx) { var handler = ReadHandlers[typeId]; Debug.Assert(handler != null, "Cannot find predefined read handler: " + typeId); return handler.Read<T>(ctx); } /** * <summary>Write boolean.</summary> */ private static void WriteBool(PortableWriterImpl ctx, object obj) { WriteBoolTyped(ctx.Stream, (bool)obj); } /** * <summary>Write boolean.</summary> */ private static void WriteBoolTyped(IPortableStream stream, bool obj) { stream.WriteByte(PortableUtils.TypeBool); stream.WriteBool(obj); } /** * <summary>Write sbyte.</summary> */ private static unsafe void WriteSbyte(PortableWriterImpl ctx, object obj) { sbyte val = (sbyte)obj; ctx.Stream.WriteByte(PortableUtils.TypeByte); ctx.Stream.WriteByte(*(byte*)&val); } /** * <summary>Write byte.</summary> */ private static void WriteByte(PortableWriterImpl ctx, object obj) { WriteByteTyped(ctx.Stream, (byte)obj); } /** * <summary>Write byte.</summary> */ private static void WriteByteTyped(IPortableStream stream, byte obj) { stream.WriteByte(PortableUtils.TypeByte); stream.WriteByte(obj); } /** * <summary>Write short.</summary> */ private static void WriteShort(PortableWriterImpl ctx, object obj) { WriteShortTyped(ctx.Stream, (short)obj); } /** * <summary>Write short.</summary> */ private static void WriteShortTyped(IPortableStream stream, short obj) { stream.WriteByte(PortableUtils.TypeShort); stream.WriteShort(obj); } /** * <summary>Write ushort.</summary> */ private static unsafe void WriteUshort(PortableWriterImpl ctx, object obj) { ushort val = (ushort)obj; ctx.Stream.WriteByte(PortableUtils.TypeShort); ctx.Stream.WriteShort(*(short*)&val); } /** * <summary>Write char.</summary> */ private static void WriteChar(PortableWriterImpl ctx, object obj) { WriteCharTyped(ctx.Stream, (char)obj); } /** * <summary>Write char.</summary> */ private static void WriteCharTyped(IPortableStream stream, char obj) { stream.WriteByte(PortableUtils.TypeChar); stream.WriteChar(obj); } /** * <summary>Write int.</summary> */ private static void WriteInt(PortableWriterImpl ctx, object obj) { WriteIntTyped(ctx.Stream, (int)obj); } /** * <summary>Write int.</summary> */ private static void WriteIntTyped(IPortableStream stream, int obj) { stream.WriteByte(PortableUtils.TypeInt); stream.WriteInt(obj); } /** * <summary>Write uint.</summary> */ private static unsafe void WriteUint(PortableWriterImpl ctx, object obj) { uint val = (uint)obj; ctx.Stream.WriteByte(PortableUtils.TypeInt); ctx.Stream.WriteInt(*(int*)&val); } /** * <summary>Write long.</summary> */ private static void WriteLong(PortableWriterImpl ctx, object obj) { WriteLongTyped(ctx.Stream, (long)obj); } /** * <summary>Write long.</summary> */ private static void WriteLongTyped(IPortableStream stream, long obj) { stream.WriteByte(PortableUtils.TypeLong); stream.WriteLong(obj); } /** * <summary>Write ulong.</summary> */ private static unsafe void WriteUlong(PortableWriterImpl ctx, object obj) { ulong val = (ulong)obj; ctx.Stream.WriteByte(PortableUtils.TypeLong); ctx.Stream.WriteLong(*(long*)&val); } /** * <summary>Write float.</summary> */ private static void WriteFloat(PortableWriterImpl ctx, object obj) { WriteFloatTyped(ctx.Stream, (float)obj); } /** * <summary>Write float.</summary> */ private static void WriteFloatTyped(IPortableStream stream, float obj) { stream.WriteByte(PortableUtils.TypeFloat); stream.WriteFloat(obj); } /** * <summary>Write double.</summary> */ private static void WriteDouble(PortableWriterImpl ctx, object obj) { WriteDoubleTyped(ctx.Stream, (double)obj); } /** * <summary>Write double.</summary> */ private static void WriteDoubleTyped(IPortableStream stream, double obj) { stream.WriteByte(PortableUtils.TypeDouble); stream.WriteDouble(obj); } /** * <summary>Write decimal.</summary> */ private static void WriteDecimal(PortableWriterImpl ctx, object obj) { WriteDecimalTyped(ctx.Stream, (decimal)obj); } /** * <summary>Write double.</summary> */ private static void WriteDecimalTyped(IPortableStream stream, decimal obj) { stream.WriteByte(PortableUtils.TypeDecimal); PortableUtils.WriteDecimal(obj, stream); } /** * <summary>Write date.</summary> */ private static void WriteDate(PortableWriterImpl ctx, object obj) { WriteDateTyped(ctx.Stream, (DateTime?)obj); } /** * <summary>Write double.</summary> */ private static void WriteDateTyped(IPortableStream stream, DateTime? obj) { stream.WriteByte(PortableUtils.TypeDate); PortableUtils.WriteDate(obj, stream); } /** * <summary>Write string.</summary> */ private static void WriteString(PortableWriterImpl ctx, object obj) { WriteStringTyped(ctx.Stream, (string)obj); } /** * <summary>Write string.</summary> */ private static void WriteStringTyped(IPortableStream stream, string obj) { stream.WriteByte(PortableUtils.TypeString); PortableUtils.WriteString(obj, stream); } /** * <summary>Write Guid.</summary> */ private static void WriteGuid(PortableWriterImpl ctx, object obj) { WriteGuidTyped(ctx.Stream, (Guid?)obj); } /** * <summary>Write Guid.</summary> */ private static void WriteGuidTyped(IPortableStream stream, Guid? obj) { stream.WriteByte(PortableUtils.TypeGuid); PortableUtils.WriteGuid(obj, stream); } /** * <summary>Write bool array.</summary> */ private static void WriteBoolArray(PortableWriterImpl ctx, object obj) { WriteBoolArrayTyped(ctx.Stream, (bool[])obj); } /** * <summary>Write bool array.</summary> */ private static void WriteBoolArrayTyped(IPortableStream stream, bool[] obj) { stream.WriteByte(PortableUtils.TypeArrayBool); PortableUtils.WriteBooleanArray(obj, stream); } /** * <summary>Write byte array.</summary> */ private static void WriteByteArray(PortableWriterImpl ctx, object obj) { WriteByteArrayTyped(ctx.Stream, (byte[])obj); } /** * <summary>Write byte array.</summary> */ private static void WriteByteArrayTyped(IPortableStream stream, byte[] obj) { stream.WriteByte(PortableUtils.TypeArrayByte); PortableUtils.WriteByteArray(obj, stream); } /** * <summary>Write sbyte array.</summary> */ private static void WriteSbyteArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArrayByte); PortableUtils.WriteByteArray((byte[])(Array)obj, ctx.Stream); } /** * <summary>Write short array.</summary> */ private static void WriteShortArray(PortableWriterImpl ctx, object obj) { WriteShortArrayTyped(ctx.Stream, (short[])obj); } /** * <summary>Write short array.</summary> */ private static void WriteShortArrayTyped(IPortableStream stream, short[] obj) { stream.WriteByte(PortableUtils.TypeArrayShort); PortableUtils.WriteShortArray(obj, stream); } /** * <summary>Write ushort array.</summary> */ private static void WriteUshortArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArrayShort); PortableUtils.WriteShortArray((short[])(Array)obj, ctx.Stream); } /** * <summary>Write char array.</summary> */ private static void WriteCharArray(PortableWriterImpl ctx, object obj) { WriteCharArrayTyped(ctx.Stream, (char[])obj); } /** * <summary>Write char array.</summary> */ private static void WriteCharArrayTyped(IPortableStream stream, char[] obj) { stream.WriteByte(PortableUtils.TypeArrayChar); PortableUtils.WriteCharArray(obj, stream); } /** * <summary>Write int array.</summary> */ private static void WriteIntArray(PortableWriterImpl ctx, object obj) { WriteIntArrayTyped(ctx.Stream, (int[])obj); } /** * <summary>Write int array.</summary> */ private static void WriteIntArrayTyped(IPortableStream stream, int[] obj) { stream.WriteByte(PortableUtils.TypeArrayInt); PortableUtils.WriteIntArray(obj, stream); } /** * <summary>Write uint array.</summary> */ private static void WriteUintArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArrayInt); PortableUtils.WriteIntArray((int[])(Array)obj, ctx.Stream); } /** * <summary>Write long array.</summary> */ private static void WriteLongArray(PortableWriterImpl ctx, object obj) { WriteLongArrayTyped(ctx.Stream, (long[])obj); } /** * <summary>Write long array.</summary> */ private static void WriteLongArrayTyped(IPortableStream stream, long[] obj) { stream.WriteByte(PortableUtils.TypeArrayLong); PortableUtils.WriteLongArray(obj, stream); } /** * <summary>Write ulong array.</summary> */ private static void WriteUlongArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArrayLong); PortableUtils.WriteLongArray((long[])(Array)obj, ctx.Stream); } /** * <summary>Write float array.</summary> */ private static void WriteFloatArray(PortableWriterImpl ctx, object obj) { WriteFloatArrayTyped(ctx.Stream, (float[])obj); } /** * <summary>Write float array.</summary> */ private static void WriteFloatArrayTyped(IPortableStream stream, float[] obj) { stream.WriteByte(PortableUtils.TypeArrayFloat); PortableUtils.WriteFloatArray(obj, stream); } /** * <summary>Write double array.</summary> */ private static void WriteDoubleArray(PortableWriterImpl ctx, object obj) { WriteDoubleArrayTyped(ctx.Stream, (double[])obj); } /** * <summary>Write double array.</summary> */ private static void WriteDoubleArrayTyped(IPortableStream stream, double[] obj) { stream.WriteByte(PortableUtils.TypeArrayDouble); PortableUtils.WriteDoubleArray(obj, stream); } /** * <summary>Write decimal array.</summary> */ private static void WriteDecimalArray(PortableWriterImpl ctx, object obj) { WriteDecimalArrayTyped(ctx.Stream, (decimal[])obj); } /** * <summary>Write double array.</summary> */ private static void WriteDecimalArrayTyped(IPortableStream stream, decimal[] obj) { stream.WriteByte(PortableUtils.TypeArrayDecimal); PortableUtils.WriteDecimalArray(obj, stream); } /** * <summary>Write date array.</summary> */ private static void WriteDateArray(PortableWriterImpl ctx, object obj) { WriteDateArrayTyped(ctx.Stream, (DateTime?[])obj); } /** * <summary>Write date array.</summary> */ private static void WriteDateArrayTyped(IPortableStream stream, DateTime?[] obj) { stream.WriteByte(PortableUtils.TypeArrayDate); PortableUtils.WriteDateArray(obj, stream); } /** * <summary>Write string array.</summary> */ private static void WriteStringArray(PortableWriterImpl ctx, object obj) { WriteStringArrayTyped(ctx.Stream, (string[])obj); } /** * <summary>Write string array.</summary> */ private static void WriteStringArrayTyped(IPortableStream stream, string[] obj) { stream.WriteByte(PortableUtils.TypeArrayString); PortableUtils.WriteStringArray(obj, stream); } /** * <summary>Write Guid array.</summary> */ private static void WriteGuidArray(PortableWriterImpl ctx, object obj) { WriteGuidArrayTyped(ctx.Stream, (Guid?[])obj); } /** * <summary>Write Guid array.</summary> */ private static void WriteGuidArrayTyped(IPortableStream stream, Guid?[] obj) { stream.WriteByte(PortableUtils.TypeArrayGuid); PortableUtils.WriteGuidArray(obj, stream); } /** * <summary>Write enum array.</summary> */ private static void WriteEnumArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArrayEnum); PortableUtils.WriteArray((Array)obj, ctx, true); } /** * <summary>Write array.</summary> */ private static void WriteArray(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeArray); PortableUtils.WriteArray((Array)obj, ctx, true); } /** * <summary>Write collection.</summary> */ private static void WriteCollection(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeCollection); PortableUtils.WriteCollection((ICollection)obj, ctx); } /** * <summary>Write generic collection.</summary> */ private static void WriteGenericCollection(PortableWriterImpl ctx, object obj) { PortableCollectionInfo info = PortableCollectionInfo.Info(obj.GetType()); Debug.Assert(info.IsGenericCollection, "Not generic collection: " + obj.GetType().FullName); ctx.Stream.WriteByte(PortableUtils.TypeCollection); info.WriteGeneric(ctx, obj); } /** * <summary>Write dictionary.</summary> */ private static void WriteDictionary(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeDictionary); PortableUtils.WriteDictionary((IDictionary)obj, ctx); } /** * <summary>Write generic dictionary.</summary> */ private static void WriteGenericDictionary(PortableWriterImpl ctx, object obj) { PortableCollectionInfo info = PortableCollectionInfo.Info(obj.GetType()); Debug.Assert(info.IsGenericDictionary, "Not generic dictionary: " + obj.GetType().FullName); ctx.Stream.WriteByte(PortableUtils.TypeDictionary); info.WriteGeneric(ctx, obj); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeCollection); PortableUtils.WriteTypedCollection((ICollection)obj, ctx, PortableUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeDictionary); PortableUtils.WriteTypedDictionary((IDictionary)obj, ctx, PortableUtils.MapHashMap); } /** * <summary>Write map entry.</summary> */ private static void WriteMapEntry(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeMapEntry); PortableUtils.WriteMapEntry(ctx, (DictionaryEntry)obj); } /** * <summary>Write portable object.</summary> */ private static void WritePortable(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypePortable); PortableUtils.WritePortable(ctx.Stream, (PortableUserObject)obj); } /** * <summary>Write portable object.</summary> */ private static void WritePortableTyped(IPortableStream stream, PortableUserObject obj) { stream.WriteByte(PortableUtils.TypePortable); PortableUtils.WritePortable(stream, obj); } /// <summary> /// Write enum. /// </summary> private static void WriteEnum(PortableWriterImpl ctx, object obj) { ctx.Stream.WriteByte(PortableUtils.TypeEnum); PortableUtils.WriteEnum(ctx.Stream, (Enum)obj); } /** * <summary>Read enum array.</summary> */ private static object ReadEnumArray(PortableReaderImpl ctx, Type type) { return PortableUtils.ReadArray(ctx, true, type.GetElementType()); } /** * <summary>Read array.</summary> */ private static object ReadArray(PortableReaderImpl ctx, Type type) { var elemType = type.IsArray ? type.GetElementType() : typeof(object); return PortableUtils.ReadArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(PortableReaderImpl ctx, Type type) { PortableCollectionInfo info = PortableCollectionInfo.Info(type); return info.IsGenericCollection ? info.ReadGeneric(ctx) : PortableUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(PortableReaderImpl ctx, Type type) { PortableCollectionInfo info = PortableCollectionInfo.Info(type); return info.IsGenericDictionary ? info.ReadGeneric(ctx) : PortableUtils.ReadDictionary(ctx, null); } /** * <summary>Read map entry.</summary> */ private static object ReadMapEntry(PortableReaderImpl ctx, Type type) { return PortableUtils.ReadMapEntry(ctx); } /** * <summary>Create new ArrayList.</summary> * <param name="len">Length.</param> * <returns>ArrayList.</returns> */ public static ICollection CreateArrayList(int len) { return new ArrayList(len); } /** * <summary>Add element to array list.</summary> * <param name="col">Array list.</param> * <param name="elem">Element.</param> */ public static void AddToArrayList(ICollection col, object elem) { ((ArrayList) col).Add(elem); } /** * <summary>Create new List.</summary> * <param name="len">Length.</param> * <returns>List.</returns> */ public static ICollection<T> CreateList<T>(int len) { return new List<T>(len); } /** * <summary>Create new LinkedList.</summary> * <param name="len">Length.</param> * <returns>LinkedList.</returns> */ public static ICollection<T> CreateLinkedList<T>(int len) { return new LinkedList<T>(); } /** * <summary>Create new HashSet.</summary> * <param name="len">Length.</param> * <returns>HashSet.</returns> */ public static ICollection<T> CreateHashSet<T>(int len) { return new HashSet<T>(); } /** * <summary>Create new SortedSet.</summary> * <param name="len">Length.</param> * <returns>SortedSet.</returns> */ public static ICollection<T> CreateSortedSet<T>(int len) { return new SortedSet<T>(); } /** * <summary>Create new Hashtable.</summary> * <param name="len">Length.</param> * <returns>Hashtable.</returns> */ public static IDictionary CreateHashtable(int len) { return new Hashtable(len); } /** * <summary>Create new Dictionary.</summary> * <param name="len">Length.</param> * <returns>Dictionary.</returns> */ public static IDictionary<TK, TV> CreateDictionary<TK, TV>(int len) { return new Dictionary<TK, TV>(len); } /** * <summary>Create new SortedDictionary.</summary> * <param name="len">Length.</param> * <returns>SortedDictionary.</returns> */ public static IDictionary<TK, TV> CreateSortedDictionary<TK, TV>(int len) { return new SortedDictionary<TK, TV>(); } /** * <summary>Create new ConcurrentDictionary.</summary> * <param name="len">Length.</param> * <returns>ConcurrentDictionary.</returns> */ public static IDictionary<TK, TV> CreateConcurrentDictionary<TK, TV>(int len) { return new ConcurrentDictionary<TK, TV>(Environment.ProcessorCount, len); } /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object PortableSystemReadDelegate(PortableReaderImpl ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IPortableSystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(PortableReaderImpl ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IPortableSystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(PortableReaderImpl ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class PortableSystemReader : IPortableSystemReader { /** */ private readonly PortableSystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="PortableSystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public PortableSystemReader(PortableSystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(PortableReaderImpl ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class PortableSystemReader<T> : IPortableSystemReader { /** */ private readonly Func<IPortableStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="PortableSystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public PortableSystemReader(Func<IPortableStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(PortableReaderImpl ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class PortableSystemGenericArrayReader<T> : IPortableSystemReader { public TResult Read<TResult>(PortableReaderImpl ctx) { return TypeCaster<TResult>.Cast(PortableUtils.ReadGenericArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class PortableSystemDualReader<T1, T2> : IPortableSystemReader, IPortableSystemReader<T2> { /** */ private readonly Func<IPortableStream, T1> _readDelegate1; /** */ private readonly Func<IPortableStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="PortableSystemDualReader{T1, T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public PortableSystemDualReader(Func<IPortableStream, T1> readDelegate1, Func<IPortableStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ T2 IPortableSystemReader<T2>.Read(PortableReaderImpl ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(PortableReaderImpl ctx) { // Can't use "as" because of variance. // For example, IPortableSystemReader<byte[]> can be cast to IPortableSystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IPortableSystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Chutzpah.Exceptions; using Chutzpah.Models; using Chutzpah.Wrappers; using Chutzpah.FileProcessors; namespace Chutzpah.BatchProcessor { public class BatchCompilerService : IBatchCompilerService { private readonly IProcessHelper processHelper; private readonly IFileSystemWrapper fileSystem; private readonly ISourceMapDiscoverer sourceMapDiscoverer; public BatchCompilerService(IProcessHelper processHelper, IFileSystemWrapper fileSystem, ISourceMapDiscoverer sourceMapDiscoverer) { this.processHelper = processHelper; this.fileSystem = fileSystem; this.sourceMapDiscoverer = sourceMapDiscoverer; } public void Compile(IEnumerable<TestContext> testContexts, ITestMethodRunnerCallback callback = null) { // Group the test contexts by test settings to run batch aware settings like compile // For each test settings file that defines a compile step we will run it and update // testContexts reference files accordingly. var groupedTestContexts = testContexts.GroupBy(x => x.TestFileSettings); foreach (var contextGroup in groupedTestContexts) { var testSettings = contextGroup.Key; // If there is no compile setting then nothing to do here if (testSettings.Compile == null) continue; // Build the mapping from source to output files and gather properties about them var filePropeties = ( from file in contextGroup.SelectMany(x => x.ReferencedFiles).Where(x => !x.IsBuiltInDependency).Distinct() where testSettings.Compile.Extensions.Any(x => file.Path.EndsWith(x, StringComparison.OrdinalIgnoreCase)) let sourceProperties = GetFileProperties(file.Path) let sourceHasOutput = !testSettings.Compile.ExtensionsWithNoOutput.Any(x => file.Path.EndsWith(x, StringComparison.OrdinalIgnoreCase)) let outputPath = GetOutputPath(file.Path, testSettings.Compile) let outputProperties = sourceHasOutput ? GetFileProperties(outputPath) : null select new SourceCompileInfo { SourceProperties = sourceProperties, OutputProperties = outputProperties, SourceHasOutput = sourceHasOutput }).ToList(); var outputPathMap = filePropeties .Where(x => x.SourceHasOutput) .ToDictionary(x => x.SourceProperties.Path, x => x.OutputProperties.Path, StringComparer.OrdinalIgnoreCase); // Check if the batch compile is needed var shouldCompile = CheckIfCompileIsNeeded(testSettings, filePropeties); // Run the batch compile if necessary if (shouldCompile) { if (testSettings.Compile.Mode == BatchCompileMode.Executable) { RunBatchCompile(testSettings); } else { ChutzpahTracer.TraceWarning("Chutzpah determined generated .js files are missing but the compile mode is External so Chutzpah can't compile them. Test results may be wrong."); } } else { ChutzpahTracer.TraceInformation("Skipping batch compile since all files are update to date for {0}", testSettings.SettingsFileName); } // Now that compile finished set generated path on all files who match the compiled extensions var filesToUpdate = contextGroup.SelectMany(x => x.ReferencedFiles) .Where(x => outputPathMap.ContainsKey(x.Path)); foreach (var file in filesToUpdate) { var outputPath = outputPathMap[file.Path]; if (outputPath != null && fileSystem.FileExists(outputPath)) { file.GeneratedFilePath = outputPath; ChutzpahTracer.TraceInformation("Found generated path for {0} at {1}", file.Path, outputPath); } else { // If we could not find the file at the configured path attempt to see if it co-located ChutzpahTracer.TraceInformation("Unable to find generated path at configured location so attempting to see if generated file is co-located."); var coLocatedOutputPath = Path.ChangeExtension(file.Path, ".js"); if (fileSystem.FileExists(coLocatedOutputPath)) { file.GeneratedFilePath = coLocatedOutputPath; ChutzpahTracer.TraceInformation("Found generated path for {0} at {1}", file.Path, coLocatedOutputPath); } else { var error = string.Format("Couldn't find generated path for {0} at {1} or at {2}", file.Path, outputPath, coLocatedOutputPath); ChutzpahTracer.TraceError(error); if (!testSettings.Compile.IgnoreMissingFiles.GetValueOrDefault()) { // Throw and fail here since if we cant find the file we cannot be sure anything will run var exception = new FileNotFoundException(error, outputPath); callback.ExceptionThrown(exception, outputPath); } } } if (!string.IsNullOrWhiteSpace(file.GeneratedFilePath)) { file.SourceMapFilePath = testSettings.Compile.UseSourceMaps.GetValueOrDefault() ? sourceMapDiscoverer.FindSourceMap(file.GeneratedFilePath) : null; } } } } private void RunBatchCompile(ChutzpahTestSettingsFile testSettings) { try { var result = processHelper.RunBatchCompileProcess(testSettings.Compile); if (result.ExitCode > 0) { throw new ChutzpahCompilationFailedException(result.StandardOutput + Environment.NewLine + result.StandardError, testSettings.SettingsFileName); } } catch (Exception e) { ChutzpahTracer.TraceError(e, "Error during batch compile of {0}", testSettings.SettingsFileName); throw new ChutzpahCompilationFailedException(e.Message, testSettings.SettingsFileName, e); } } /// <summary> /// Determines if a compile is needed. To figure this out we check the following things: /// 1. Check if any source file which produces output is missing its output /// 2. Check if any source file which produces output is newer than its output /// 3. Check if any source file which does not produce output is newer than the oldest output file /// </summary> /// <param name="testSettings"></param> /// <param name="filePropeties"></param> /// <returns></returns> private static bool CheckIfCompileIsNeeded(ChutzpahTestSettingsFile testSettings, List<SourceCompileInfo> filePropeties) { if (!filePropeties.Any(x => x.SourceHasOutput)) { return false; } // If SkipIfUnchanged is true then we check if all the output files are newer than the input files // we will only run the compile if this fails if (testSettings.Compile.SkipIfUnchanged.GetValueOrDefault()) { var hasMissingOutput = filePropeties .Where(x => x.SourceHasOutput) .Any(x => !x.OutputProperties.Exists); if (!hasMissingOutput) { var pairFileHasChanged = filePropeties.Any(x => x.SourceHasOutput && x.SourceProperties.Exists && x.OutputProperties.Exists && x.SourceProperties.LastModifiedDate > x.OutputProperties.LastModifiedDate); var fileWithNoOutputHasChanged = false; var sourcesWithNoOutput = filePropeties.Where(x => x.SourceProperties.Exists && !x.SourceHasOutput).ToList(); if (sourcesWithNoOutput.Any()) { // Get the time of the newest file change of a file which has no output (like a .d.ts) var newestSourceWithNoOutputFileTime = sourcesWithNoOutput.Max(x => x.SourceProperties.LastModifiedDate); var oldestOutputFileTime = filePropeties .Where(x => x.SourceHasOutput && x.OutputProperties.Exists) .Min(x => x.OutputProperties.LastModifiedDate); fileWithNoOutputHasChanged = newestSourceWithNoOutputFileTime >= oldestOutputFileTime; } return pairFileHasChanged || fileWithNoOutputHasChanged; } } return true; } private string GetOutputPath(string filePath, BatchCompileConfiguration compileConfiguration) { foreach (var pathMap in compileConfiguration.Paths) { if (filePath.IndexOf(pathMap.SourcePath, StringComparison.OrdinalIgnoreCase) >= 0) { // If the configured sourcePath is a full file path we just assume the fileName is the relative name // Otherwise we calculate the relative path from the configured sourcePath to the current file var relativePath = pathMap.SourcePathIsFile ? Path.GetFileName(pathMap.SourcePath) : UrlBuilder.GetRelativePath(pathMap.SourcePath, filePath); string outputPath = pathMap.OutputPath; if (!pathMap.OutputPathIsFile) { // If output path is not a file we calculate the file path using the input filePath's relative location compared // to the output directory outputPath = Path.Combine(outputPath, relativePath); outputPath = Path.ChangeExtension(outputPath, ".js"); } return outputPath; } } ChutzpahTracer.TraceError("Can't find location for generated path on {0}",filePath); return null; } private FileProperties GetFileProperties(string path) { var fileProperties = new FileProperties(); if (string.IsNullOrEmpty(path)) { return fileProperties; } fileProperties.Path = path; fileProperties.Exists = fileSystem.FileExists(path); fileProperties.LastModifiedDate = fileSystem.GetLastWriteTime(path); return fileProperties; } private class FileProperties { public DateTime LastModifiedDate { get; set; } public string Path { get; set; } public bool Exists { get; set; } } private class SourceCompileInfo { public SourceCompileInfo() { SourceHasOutput = true; } public bool SourceHasOutput { get; set; } public FileProperties SourceProperties { get; set; } public FileProperties OutputProperties { get; set; } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { /// <summary> /// Allows setting up a mock service in the client-server tests easily. /// </summary> public class MockServiceHelper { public const string ServiceName = "tests.Test"; readonly string host; readonly ServerServiceDefinition serviceDefinition; readonly IEnumerable<ChannelOption> channelOptions; readonly Method<string, string> unaryMethod; readonly Method<string, string> clientStreamingMethod; readonly Method<string, string> serverStreamingMethod; readonly Method<string, string> duplexStreamingMethod; UnaryServerMethod<string, string> unaryHandler; ClientStreamingServerMethod<string, string> clientStreamingHandler; ServerStreamingServerMethod<string, string> serverStreamingHandler; DuplexStreamingServerMethod<string, string> duplexStreamingHandler; Server server; Channel channel; public MockServiceHelper(string host = null, Marshaller<string> marshaller = null, IEnumerable<ChannelOption> channelOptions = null) { this.host = host ?? "localhost"; this.channelOptions = channelOptions; marshaller = marshaller ?? Marshallers.StringMarshaller; unaryMethod = new Method<string, string>( MethodType.Unary, ServiceName, "Unary", marshaller, marshaller); clientStreamingMethod = new Method<string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", marshaller, marshaller); serverStreamingMethod = new Method<string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", marshaller, marshaller); duplexStreamingMethod = new Method<string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", marshaller, marshaller); serviceDefinition = ServerServiceDefinition.CreateBuilder(ServiceName) .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); } /// <summary> /// Returns the default server for this service and creates one if not yet created. /// </summary> public Server GetServer() { if (server == null) { server = new Server { Services = { serviceDefinition }, Ports = { { Host, ServerPort.PickUnused, ServerCredentials.Insecure } } }; } return server; } /// <summary> /// Returns the default channel for this service and creates one if not yet created. /// </summary> public Channel GetChannel() { if (channel == null) { channel = new Channel(Host, GetServer().Ports.Single().BoundPort, ChannelCredentials.Insecure, channelOptions); } return channel; } public CallInvocationDetails<string, string> CreateUnaryCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, unaryMethod, options); } public CallInvocationDetails<string, string> CreateClientStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, clientStreamingMethod, options); } public CallInvocationDetails<string, string> CreateServerStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, serverStreamingMethod, options); } public CallInvocationDetails<string, string> CreateDuplexStreamingCall(CallOptions options = default(CallOptions)) { return new CallInvocationDetails<string, string>(channel, duplexStreamingMethod, options); } public string Host { get { return this.host; } } public ServerServiceDefinition ServiceDefinition { get { return this.serviceDefinition; } } public UnaryServerMethod<string, string> UnaryHandler { get { return this.unaryHandler; } set { unaryHandler = value; } } public ClientStreamingServerMethod<string, string> ClientStreamingHandler { get { return this.clientStreamingHandler; } set { clientStreamingHandler = value; } } public ServerStreamingServerMethod<string, string> ServerStreamingHandler { get { return this.serverStreamingHandler; } set { serverStreamingHandler = value; } } public DuplexStreamingServerMethod<string, string> DuplexStreamingHandler { get { return this.duplexStreamingHandler; } set { duplexStreamingHandler = value; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Ruzzie.Common.Numerics.Statistics; #if !NETSTANDARD1_1 using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; #endif namespace Ruzzie.Common.Numerics.Distributions { /// <summary> /// Methods for ChiSquared calculation /// </summary> public static class ChiSquared { #region adapted from entlib chisq.c /* Module: chisq.c Purpose: compute approximations to chisquare distribution probabilities Contents: pochisq() Uses: poz() in z.c (Algorithm 209) Programmer: Gary Perlman Organization: Wang Institute, Tyngsboro, MA 01879 Copyright: none */ /// <summary> /// log (sqrt (pi)) /// </summary> private const double LogSqrtPi = 0.5723649429247000870717135; /// <summary> /// 1 / sqrt (pi) /// </summary> private const double SqrtPi = 0.5641895835477562869480795; /// <summary> /// max value to represent exp (x) /// </summary> private const double BigX = 20.0; private static double Ex(in double x) { return (((x) < -BigX) ? 0.0 : Math.Exp(x)); } /// <summary> /// probability of chi square value /// </summary> /// <param name="ax">obtained chi-square value</param> /// <param name="degreesOfFreedom">degrees of freedom</param> /// <returns> probability of chi square value</returns> /// <remarks> /// Adapted from: /// Hill, I.D.and Pike, M. C.Algorithm 299 /// Collected Algorithms for the CACM 1967 p. 243 /// Updated for rounding errors based on remark in /// ACM TOMS June 1985, page 185 /// </remarks> public static double ProbabilityOfChiSquared(in double ax, in int degreesOfFreedom) { double x = ax; double y = 0; double a, s; double e, c, z; bool even; /* true if df is an even number */ if (x <= 0.0 || degreesOfFreedom < 1) { return 1.0; } a = 0.5 * x; even = (2 * (degreesOfFreedom / 2)) == degreesOfFreedom; if (degreesOfFreedom > 1) { y = Ex(-a); } s = (even ? y : (2.0*ZProbability.ProbabilityOfZ(-Math.Sqrt(x)))); if (degreesOfFreedom > 2) { x = 0.5 * (degreesOfFreedom - 1.0); z = (even ? 1.0 : 0.5); if (a > BigX) { e = (even ? 0.0 : LogSqrtPi); c = Math.Log(a); while (z <= x) { e = Math.Log(z) + e; s += Ex(c * z - a - e); z += 1.0; } return (s); } else { e = (even ? 1.0 : (SqrtPi / Math.Sqrt(a))); c = 0.0; while (z <= x) { e = e * (a / z); c = c + e; z += 1.0; } return (c * y + s); } } else { return s; } } #endregion /// <summary> /// Chi squared P of samples. /// </summary> /// <param name="sampleSize">Size of the sample.</param> /// <param name="samples">The samples.</param> /// <returns></returns> /// <exception cref="ArgumentException">The <paramref name="samples"/> is an empty collection.</exception> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="sampleSize"/> argument is less than or equal to 0..</exception> /// <exception cref="ArgumentNullException"><paramref name="samples"/> is <see langword="null" />.</exception> [SuppressMessage("ReSharper", "RedundantCast")] public static double ChiSquaredP(in int sampleSize, in byte[] samples) { if (sampleSize <= 0) { throw new ArgumentOutOfRangeException(nameof(sampleSize)); } if (samples == null) { throw new ArgumentNullException(nameof(samples)); } if (samples.Length == 0) { throw new ArgumentException("Argument is an empty collection", nameof(samples)); } const int byteMaxValuePlusOne = byte.MaxValue + 1; double expectedCount = (double) sampleSize/ byteMaxValuePlusOne; var histogram = samples.ToHistogramDictionary(); double chisq = 0; for (int i = 0; i < byteMaxValuePlusOne; i++) { if (histogram.TryGetValue((byte) i, out var intValue) == false) { intValue = 0; } double a = intValue - expectedCount; chisq += (a*a)/expectedCount; } return chisq; } /// <summary> /// Chi squared P of samples. /// </summary> /// <param name="maxValue">The maximum value.</param> /// <param name="sampleSize">Size of the sample.</param> /// <param name="histogram">The histogram of samples</param> /// <exception cref="ArgumentNullException">Throws when the <paramref name="histogram"/> value is null.</exception> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="maxValue"/> argument is less than or equal to 0.</exception> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="sampleSize"/> argument is less than or equal to 0.</exception> [SuppressMessage("ReSharper", "RedundantCast")] public static double ChiSquaredP(int maxValue, int sampleSize, IDictionary<int, int> histogram) { if (histogram == null) { throw new ArgumentNullException(nameof(histogram)); } if (maxValue <= 0) { throw new ArgumentOutOfRangeException(nameof(maxValue),"Must be greater than 0."); } if (sampleSize <= 0) { throw new ArgumentOutOfRangeException(nameof(sampleSize), "Must be greater than 0."); } double expectedCount = (double)sampleSize / (double)(maxValue); #if NETSTANDARD1_1 double chisq = ChiSquaredP(new Tuple<int, int>(0,maxValue), histogram, expectedCount); return chisq; #else var partitioner = Partitioner.Create(0, maxValue); ConcurrentBag<double> sums = new ConcurrentBag<double>(); Parallel.ForEach(partitioner, range => { double partialChisq = ChiSquaredP(range, histogram, expectedCount); sums.Add(partialChisq); }); return sums.Sum(); #endif } private static double ChiSquaredP(in Tuple<int, int> range, in IDictionary<int, int> histogram, in double expectedCount) { double partialChisq = 0; for (int i = range.Item1; i < range.Item2; i++) { if (histogram.TryGetValue(i, out var intValue) == false) { intValue = 0; } double a = intValue - expectedCount; partialChisq += (a*a)/expectedCount; } return partialChisq; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; namespace DotSpatial.Data { /// <summary> /// The buffered binary reader was originally designed by Ted Dunsford to make shapefile reading more /// efficient, but ostensibly could be used for other binary reading exercises. To use this class, /// simply specify the BufferSize in bytes that you would like to use and begin reading values. /// </summary> public class BufferedBinaryWriter { #region Private Variables private readonly long _fileLength; private BinaryWriter _binaryWriter; private Stream _fileStream; private bool _isBufferLoaded; private int _maxBufferSize; private IProgressHandler _progressHandler; private ProgressMeter _progressMeter; private int _writeOffset; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BufferedBinaryWriter"/> class. /// </summary> /// <param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param> public BufferedBinaryWriter(string fileName) : this(fileName, null, 100000) { // This is just an overload that sends the default null value in for the progressHandler _progressHandler = DataManager.DefaultDataManager.ProgressHandler; _progressMeter = new ProgressMeter(_progressHandler); } /// <summary> /// Initializes a new instance of the <see cref="BufferedBinaryWriter"/> class on an arbitrary stream. /// </summary> /// <param name="s">Stream used for writing.</param> public BufferedBinaryWriter(Stream s) { long expectedByteCount = 100000; _fileStream = s; _fileLength = 0; FileOffset = 0; Buffer = new byte[expectedByteCount]; BufferSize = Convert.ToInt32(expectedByteCount); _maxBufferSize = BufferSize; _writeOffset = -1; // There is no buffer loaded. BufferOffset = -1; // -1 means no buffer is loaded. } /// <summary> /// Initializes a new instance of the <see cref="BufferedBinaryWriter"/> class and specifies where to send progress messages. /// </summary> /// <param name="fileName">The string path of a file to open using this BufferedBinaryReader.</param> /// <param name="progressHandler">Any implementation of IProgressHandler for receiving progress messages.</param> /// <param name="expectedByteCount">A long specifying the number of bytes that will be written for the purposes of tracking progress</param> public BufferedBinaryWriter(string fileName, IProgressHandler progressHandler, long expectedByteCount) { if (File.Exists(fileName)) { // Imagine we have written a header and want to add more stuff _fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write); FileInfo fi = new FileInfo(fileName); _fileLength = fi.Length; FileOffset = 0; } else { // In this case, we just create the new file from scratch _fileStream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write); _fileLength = 0; FileOffset = 0; } _binaryWriter = new BinaryWriter(_fileStream); Buffer = new byte[expectedByteCount]; BufferSize = Convert.ToInt32(expectedByteCount); _maxBufferSize = BufferSize; _writeOffset = -1; // There is no buffer loaded. BufferOffset = -1; // -1 means no buffer is loaded. // report progress if (progressHandler != null) { _progressHandler = progressHandler; _progressMeter.Key = "Writing to " + Path.GetFileName(fileName); _progressMeter.EndValue = expectedByteCount; } } #endregion #region Properties /// <summary> /// Gets or sets the actual array of bytes currently in the buffer /// </summary> public byte[] Buffer { get; set; } /// <summary> /// Gets or sets a long integer specifying the starting position of the currently loaded buffer /// relative to the start of the file. A value of -1 indicates that no buffer is /// currently loaded. /// </summary> public long BufferOffset { get; protected set; } /// <summary> /// Gets or sets an integer value specifying the size of the buffer currently loaded into memory. /// This will either be the MaxBufferSize, or a smaller buffer representing a smaller /// remainder existing in the file. /// </summary> public int BufferSize { get; protected set; } /// <summary> /// Gets or sets a value indicating whether there is currently any information loaded into the buffer. /// </summary> public virtual bool IsBufferLoaded { get { return _isBufferLoaded; } protected set { _isBufferLoaded = value; } } /// <summary> /// Gets or sets the current read position in the file in bytes. /// </summary> public long FileOffset { get; protected set; } /// <summary> /// Gets or sets the buffer size to read in chunks. This does not /// describe the size of the actual /// </summary> public virtual int MaxBufferSize { get { return _maxBufferSize; } set { if (value < 0) { throw new ArgumentException(DataStrings.ArgumentCannotBeNegative_S.Replace("%S", "BufferSize")); } _maxBufferSize = value; } } /// <summary> /// Gets or sets the progress handler for this binary writer. /// </summary> public virtual IProgressHandler ProgressHandler { get { return _progressHandler; } set { _progressHandler = value; _progressMeter = new ProgressMeter(_progressHandler); } } /// <summary> /// Gets or sets where reading will begin (relative to the start of the buffer). /// </summary> public virtual int WriteOffset { get { return _writeOffset; } protected set { _writeOffset = value; } } /// <summary> /// Gets or sets the progress meter that is directly linked to the progress handler. /// </summary> protected virtual ProgressMeter ProgressMeter { get { return _progressMeter; } set { _progressMeter = value; } } #endregion #region Methods /// <summary> /// Finishes writing whatever is in memory to the file, closes the internal binary writer, the underlying file, clears the memory /// and disposes the filestream. /// </summary> public void Close() { if (_binaryWriter != null) { // Finish pasting any residual data to the file PasteBuffer(); // Close the binary writer and underlying filestream _binaryWriter.Close(); } _binaryWriter = null; Buffer = null; _progressMeter = null; // the IProgressHandler could be an undesired handle to a whole form or something _fileStream?.Dispose(); _fileStream = null; } /// <summary> /// This seeks both in the file AND in the buffer. This is used to write only the desired portions of a buffer that is in memory to a file. /// </summary> /// <param name="offset">A 64 bit integer specifying where to skip to in the file.</param> /// <param name="origin">A System.IO.SeekOrigin enumeration specifying how to estimate the location.</param> /// <returns>The position.</returns> public virtual long Seek(long offset, SeekOrigin origin) { long startPosition = 0; switch (origin) { case SeekOrigin.Begin: startPosition = offset; break; case SeekOrigin.Current: startPosition = _writeOffset + offset; break; case SeekOrigin.End: startPosition = _fileLength - offset; break; } if (startPosition >= _fileLength || startPosition < 0) { // regardless of what direction, we need a start position inside the file throw new EndOfStreamException(DataStrings.EndOfFile); } // Only worry about resetting the buffer or repositioning the position // inside the buffer if a buffer is actually loaded. if (_isBufferLoaded) { long delta = startPosition - FileOffset; if (delta > BufferSize - _writeOffset) { // The new position is beyond our current buffer Buffer = null; _writeOffset = -1; BufferOffset = -1; _isBufferLoaded = false; } else { // The new position is still inside the buffer _writeOffset += Convert.ToInt32(delta); FileOffset = startPosition; // we don't want to actually seek in the internal reader return startPosition; } } // If no buffer is loaded, the file may not be open and may cause an exception when trying to seek. // probably better for tracking than not throwing one. FileOffset = startPosition; if (_fileStream.CanSeek) _fileStream.Seek(offset, origin); return startPosition; } #region Write Methods /// <summary> /// Writes a boolean to the buffer. /// </summary> /// <param name="value">Value that gets written.</param> public void Write(bool value) { byte[] data = BitConverter.GetBytes(value); Write(data); } /// <summary> /// Writes a character to the buffer. /// </summary> /// <param name="value">A character to write to the buffer, and eventually the file.</param> public void Write(char value) { byte[] data = BitConverter.GetBytes(value); Write(data); } /// <summary> /// Writes an array of character to the buffer. /// </summary> /// <param name="values">Values that get written.</param> public void Write(char[] values) { List<byte> lstData = new List<byte>(); foreach (var b in values) { lstData.AddRange(BitConverter.GetBytes(b)); } byte[] data = lstData.ToArray(); Write(data); } /// <summary> /// Writes a double to the buffer. /// </summary> /// <param name="value">Value that gets written.</param> public void Write(double value) { Write(value, true); } /// <summary> /// Writes a double-precision floating point to the buffer. /// </summary> /// <param name="value">A double-precision floating point decimal value to write as 8 bytes.</param> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> public void Write(double value, bool isLittleEndian) { // Integers are 8 Bytes long. byte[] data = BitConverter.GetBytes(value); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } Write(data); } /// <summary> /// Writes the specified array of doubles to the file. /// </summary> /// <param name="values">The values to write.</param> public void Write(double[] values) { byte[] rawbytes = new byte[values.Length * 8]; System.Buffer.BlockCopy(values, 0, rawbytes, 0, rawbytes.Length); Write(rawbytes); } /// <summary> /// Writes the specified array of integers to the file. /// </summary> /// <param name="values">The values to write.</param> public void Write(int[] values) { byte[] rawbytes = new byte[values.Length * 4]; System.Buffer.BlockCopy(values, 0, rawbytes, 0, rawbytes.Length); Write(rawbytes); } /// <summary> /// By default, this will use little Endian ordering. /// </summary> /// <param name="value">Value that gets written.</param> public void Write(int value) { Write(value, true); } /// <summary> /// Reads an integer from the file, using the isLittleEndian argument /// to decide whether to flip the bits or not. /// </summary> /// <param name="value">A 32-bit integer to write as 4 bytes in the buffer.</param> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> public virtual void Write(int value, bool isLittleEndian) { // Integers are 4 Bytes long. byte[] data = BitConverter.GetBytes(value); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } Write(data); } /// <summary> /// Writes an Int16 to the buffer. /// </summary> /// <param name="value">An Int16 to convert into 2 bytes to write to the buffer.</param> public virtual void Write(short value) { byte[] data = BitConverter.GetBytes(value); Write(data); } /// <summary> /// Writes a single-precision floading point to 4 bytes in the buffer, automatically loading the next buffer if necessary. /// This assumes the value should be little endian. /// </summary> /// <param name="value">A Single to convert to 4 bytes to write to the buffer.</param> public virtual void Write(float value) { Write(value, true); } /// <summary> /// Reads a single-precision floading point from 4 bytes in the buffer, automatically loading the next buffer if necessary. /// </summary> /// <param name="value">A single-precision floating point converted from four bytes</param> /// <param name="isLittleEndian">Boolean, true if the value should be returned with little endian byte ordering.</param> public virtual void Write(float value, bool isLittleEndian) { // Integers are 4 Bytes long. byte[] data = BitConverter.GetBytes(value); if (isLittleEndian != BitConverter.IsLittleEndian) { // The IsLittleEndian property on the BitConverter tells us what the system is using by default. // The isLittleEndian argument tells us what bit order the output should be in. Array.Reverse(data); } Write(data); } /// <summary> /// Writes the specified bytes to the buffer, advancing the buffer automatically if necessary. /// </summary> /// <param name="value">An array of byte values to write to the buffer.</param> public virtual void Write(byte[] value) { bool finished = false; int bytesPasted = 0; int index = 0; int count = value.Length; if (_isBufferLoaded == false) AdvanceBuffer(); do { int bytesInBuffer = BufferSize - _writeOffset; if (count < bytesInBuffer) { Array.Copy(value, index, Buffer, _writeOffset, count - bytesPasted); _writeOffset += count - bytesPasted; FileOffset += count - bytesPasted; finished = true; } else { int sourceLeft = count - index; if (sourceLeft > bytesInBuffer) { Array.Copy(value, index, Buffer, _writeOffset, bytesInBuffer); index += bytesInBuffer; bytesPasted += bytesInBuffer; FileOffset += bytesInBuffer; _writeOffset += bytesInBuffer; if (bytesPasted >= count) { finished = true; } else { AdvanceBuffer(); } } else { Array.Copy(value, index, Buffer, _writeOffset, sourceLeft); index += sourceLeft; bytesPasted += sourceLeft; FileOffset += sourceLeft; _writeOffset += sourceLeft; finished = true; } } } while (finished == false); } #endregion // This internal method attempts to advance the buffer. private void AdvanceBuffer() { if (_isBufferLoaded) { // write the contents of the buffer _binaryWriter.Write(Buffer); // reposition the buffer after the last paste BufferOffset = 0; // file offset is tracked at the time of an individual write event } else { _isBufferLoaded = true; } // either way, dimension the next chunk Buffer = new byte[_maxBufferSize]; // indicate where to start writing in the buffer _writeOffset = 0; } /// <summary> /// Forces the buffer to paste all its existing values into the file, but does not /// advance the buffer, or in fact do anything to the buffer. It does advance /// the position of the file index. /// </summary> private void PasteBuffer() { if (_writeOffset > -1) { _binaryWriter.Write(Buffer, 0, _writeOffset); FileOffset += _writeOffset; } } #endregion } }
#if !NETFX_CORE using System; using System.ComponentModel; using System.Reflection; using Should; using Xunit; namespace MicroMapper.UnitTests { namespace CustomMapping { public class When_specifying_type_converters : AutoMapperSpecBase { private Destination _result; public class Source { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public class Destination { public int Value1 { get; set; } public DateTime Value2 { get; set; } public Type Value3 { get; set; } } public class DateTimeTypeConverter : TypeConverter<string, DateTime> { protected override DateTime ConvertCore(string source) { return System.Convert.ToDateTime(source); } } public class TypeTypeConverter : TypeConverter<string, Type> { protected override Type ConvertCore(string source) { Type type = Assembly.GetExecutingAssembly().GetType(source); return type; } } protected override void Establish_context() { Mapper.Initialize(cfg => { cfg.CreateMap<string, int>().ConvertUsing((string arg) => Convert.ToInt32(arg)); cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); cfg.CreateMap<Source, Destination>(); }); var source = new Source { Value1 = "5", Value2 = "01/01/2000", Value3 = "MicroMapper.UnitTests.CustomMapping.When_specifying_type_converters+Destination" }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value1.ShouldEqual(5); } [Fact] public void Should_convert_type_using_instance() { _result.Value2.ShouldEqual(new DateTime(2000, 1, 1)); } [Fact] public void Should_convert_type_using_Func_that_returns_instance() { _result.Value3.ShouldEqual(typeof(Destination)); } } public class When_specifying_type_converters_on_types_with_incompatible_members : AutoMapperSpecBase { private ParentDestination _result; public class Source { public string Foo { get; set; } } public class Destination { public int Type { get; set; } } public class ParentSource { public Source Value { get; set; } } public class ParentDestination { public Destination Value { get; set; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>().ConvertUsing(arg => new Destination {Type = Convert.ToInt32(arg.Foo)}); Mapper.CreateMap<ParentSource, ParentDestination>(); var source = new ParentSource { Value = new Source { Foo = "5",} }; _result = Mapper.Map<ParentSource, ParentDestination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value.Type.ShouldEqual(5); } } public class When_specifying_mapping_with_the_BCL_type_converter_class : AutoMapperSpecBase { [TypeConverter(typeof(CustomTypeConverter))] public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomTypeConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof (Destination); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { return new Destination { OtherValue = ((Source) value).Value + 10 }; } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(Destination); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return new Source {Value = ((Destination) value).OtherValue - 10}; } } [Fact] public void Should_convert_from_type_using_the_custom_type_converter() { var source = new Source { Value = 5 }; var destination = Mapper.Map<Source, Destination>(source); destination.OtherValue.ShouldEqual(15); } [Fact] public void Should_convert_to_type_using_the_custom_type_converter() { var source = new Destination() { OtherValue = 15 }; var destination = Mapper.Map<Destination, Source>(source); destination.Value.ShouldEqual(5); } } public class When_specifying_a_type_converter_for_a_non_generic_configuration : SpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { return new Destination { OtherValue = source.Value + 10 }; } } protected override void Establish_context() { Mapper.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing<CustomConverter>(); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldEqual(15); } [Fact] public void Should_pass_configuration_validation() { Mapper.AssertConfigurationIsValid(); } } public class When_specifying_a_non_generic_type_converter_for_a_non_generic_configuration : SpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : TypeConverter<Source, Destination> { protected override Destination ConvertCore(Source source) { return new Destination { OtherValue = source.Value + 10 }; } } protected override void Establish_context() { Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source), typeof(Destination)).ConvertUsing(typeof(CustomConverter))); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldEqual(15); } [Fact] public void Should_pass_configuration_validation() { Mapper.AssertConfigurationIsValid(); } } } } #endif
using System.Collections; using System.Collections.Generic; using UnityEngine; using SimpleJSON; using System.IO; public class GameController : MonoBehaviour { public DGame dGame; public GameObject UICanvas; public GameObject CountryViewUIPrefab; public GameObject CityViewUIPrefab; private GameObject countryView; private CountryMap countryMap; private GameObject cityView; private bool buildingToggle = false; // Initialization void Start() { dGame = new DGame(this); // Re-enable the cursor Cursor.lockState = CursorLockMode.None; Cursor.visible = true; // Start off at the country view countryView = Instantiate(CountryViewUIPrefab, UICanvas.transform); countryMap = countryView.GetComponent<CountryMap>(); // Get all cities foreach (string file in System.IO.Directory.GetFiles(Constants.CITY_JSON_PATH)) { if (Path.GetExtension(file) == ".json") { var cityJSON = JSON.Parse(File.ReadAllText(file)); // Add city to list of available cities for the game dGame.availableCities.Add(cityJSON["name"]); List<string> edges = new List<string>(); for(int i=0; i< cityJSON["linked_cities"].AsArray.Count; i++) { edges.Add((cityJSON["linked_cities"].AsArray[i])); } countryMap.SpawnCityNode( cityJSON["name"], new Vector3(cityJSON["position"]["x"],cityJSON["position"]["y"], -1), edges); } } countryMap.SpawnEdges(); } void Update() { if (Input.GetKeyUp(KeyCode.Space)) { ToggleBuildingModals(!buildingToggle); buildingToggle = !buildingToggle; } } public void LoadGame(string savedGameFile, string pathToSavedGames=Constants.SAVE_JSON_PATH) { pathToSavedGames = Application.dataPath + pathToSavedGames; destroyCityAndBuildings(); Destroy(cityView); var json = File.ReadAllText(pathToSavedGames + @"/" + savedGameFile); dGame = DGame.LoadFromJSON(JSON.Parse(json), this); if (dGame.currentCity != null) { // Spawn City UI cityView = Instantiate(CityViewUIPrefab, UICanvas.transform); // Disable Country View countryView.SetActive(false); } else { ReturnToMap(true); } } public void SaveGame(string savedGameFile, string pathToSavedGames = Constants.SAVE_JSON_PATH) { pathToSavedGames = Application.dataPath + pathToSavedGames; // Add the .json extension if not present if (!savedGameFile.EndsWith(".json")) { savedGameFile += ".json"; } var json = dGame.SaveToJSON(); File.WriteAllText(pathToSavedGames + @"/" + savedGameFile, json.ToString()); } public void DeleteGame(string deleteGameFile, string pathToSavedGames = Constants.SAVE_JSON_PATH) { pathToSavedGames = Application.dataPath + pathToSavedGames; // Add the .json extension if not present if (!deleteGameFile.EndsWith(".json")) { deleteGameFile += ".json"; } File.Delete(pathToSavedGames + Path.DirectorySeparatorChar + deleteGameFile); File.Delete(pathToSavedGames + Path.DirectorySeparatorChar + deleteGameFile.Replace(".json",".meta")); } public void SelectCity(string cityName) { //CreateCity(Constants.CITY_JSON_PATH, File.ReadAllText(Constants.CITY_JSON_PATH + @"/" + cityName.ToLower() + ".json")); var json = File.ReadAllText(Constants.CITY_JSON_PATH + @"/" + cityName.ToLower() + ".json"); cityView = Instantiate(CityViewUIPrefab, UICanvas.transform); DCity newCity = DCity.LoadFromJSON(JSON.Parse(json), dGame, false); dGame.AddCity(newCity); dGame.SelectCity(cityName); // Spawn City UI // Disable Country View countryView.SetActive(false); } public List<string> listSavedGames(string pathToSavedGames = Constants.SAVE_JSON_PATH) { pathToSavedGames = Application.dataPath + pathToSavedGames; List<string> listSavedGames = new List<string>(); // Debug.Log(); foreach(string s in Directory.GetFiles(pathToSavedGames, "*.json")) { string[] newS = s.Split(Path.DirectorySeparatorChar); string name = newS[newS.Length-1]; listSavedGames.Add(name.Split('.')[0]); } return listSavedGames; } public void ReturnToMap(bool destroyCityView=false) { if (destroyCityView) { Destroy(cityView); // Destroy game objects var children = new List<GameObject>(); foreach (Transform child in transform) children.Add(child.gameObject); children.ForEach(child => Destroy(child)); // Disable all cities countryMap.DisableAllNodes(); if (dGame.currentCity != null) { // Enable cities connected to completed city List<string> linkedCities = new List<string>(); foreach (var cityName in dGame.currentCity.LinkedCityKeys) { // If we haven't previously completed this city if (!dGame.Cities.ContainsKey(cityName)) linkedCities.Add(cityName); } countryMap.SetCitiesEnabled(linkedCities, true); } else { // Only show available cities countryMap.SetCitiesEnabled(dGame.availableCities, true); } // Reset the turn counter dGame.TurnNumber = 0; } countryView.SetActive(true); } public void EndTurnButtonCallback() { if (dGame.GameState == DGame._gameState.PLAY) { dGame.EndTurnUpdate(); GetComponentInChildren<CityController>().UpdateSprite(); GameObject.Find("SfxLibrary").GetComponents<AudioSource>()[2].Play(); } } public void NewGame() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (cityView != null) { destroyCityAndBuildings(); Destroy(cityView); dGame.Reset(); } countryView.SetActive(true); foreach (string file in System.IO.Directory.GetFiles(Constants.CITY_JSON_PATH)) { if (Path.GetExtension(file) == ".json") { var cityJSON = JSON.Parse(File.ReadAllText(file)); List<string> edges = new List<string>(); for (int i = 0; i < cityJSON["linked_cities"].AsArray.Count; i++) { edges.Add((cityJSON["linked_cities"].AsArray[i])); } countryMap.SpawnCityNode( cityJSON["name"], new Vector3(cityJSON["position"]["x"], cityJSON["position"]["y"], -1), edges); } } countryMap.SpawnEdges(); } public void destroyCityAndBuildings() { foreach (Transform t in this.transform) { Destroy(t.gameObject); } Destroy(cityView); } public void ToggleBuildingModals(bool toggle) { // Toggle all building controllers var children = new List<BuildingController>(); foreach (Transform child in transform) { BuildingController bc = child.gameObject.GetComponent<BuildingController>(); if (bc != null) children.Add(bc); } children.ForEach(child => child.ToggleBuildingModal(toggle)); } #region Controller Spawners public CityController CreateCityController(DCity city) { CityController cityController = InstantiatePrefab<CityController>(Constants.CITY_PREFAB_PATH, this.transform); cityController.ConnectToDataEngine(dGame, city); return cityController; } public BuildingController CreateBuildingController(DBuilding building, Vector3 position) { string prefab_path = DBuilding.RandomBuildingPrefabPath(building.BuildType); BuildingController buildingController = InstantiatePrefab<BuildingController>(prefab_path, this.transform); buildingController.ConnectToDataEngine(building); // Set position buildingController.transform.position = position; // Generate all predefined tasks foreach (var kvp in buildingController.dBuilding.Tasks) { TaskController newTaskController = AttachTaskController(kvp.Value, buildingController); } return buildingController; } public MeepleController CreateMeepleController(TaskTraySingle taskTray, DPerson person) { MeepleController meepleController = InstantiatePrefab<MeepleController>(Constants.MEEPLE_PREFAB_PATH, taskTray.transform); meepleController.ConnectToDataEngine(taskTray, person); return meepleController; } public TaskController AttachTaskController(DTask dTask, BuildingController buildingController) { TaskController taskController = InstantiatePrefab<TaskController>(Constants.TASK_TRAY_PREFAB_PATH, buildingController.transform); taskController.ConnectToDataEngine(dTask); // Give BuildingController a reference to it and vice versa buildingController.AddTaskController(taskController); taskController.buildingController = buildingController; return taskController; } #endregion private T InstantiatePrefab<T>(string prefabPath) { return (Instantiate(Resources.Load(prefabPath)) as GameObject).GetComponent<T>(); } private T InstantiatePrefab<T>(string prefabPath, Transform parent) { return (Instantiate(Resources.Load(prefabPath), parent) as GameObject).GetComponent<T>(); } }
// SF API version v50.0 // Custom fields included: False // Relationship objects included: True using System; using NetCoreForce.Client.Models; using NetCoreForce.Client.Attributes; using Newtonsoft.Json; namespace NetCoreForce.Models { ///<summary> /// Refund ///<para>SObject Name: Refund</para> ///<para>Custom Object: False</para> ///</summary> public class SfRefund : SObject { [JsonIgnore] public static string SObjectTypeName { get { return "Refund"; } } ///<summary> /// Refund ID /// <para>Name: Id</para> /// <para>SF Type: id</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "id")] [Updateable(false), Createable(false)] public string Id { get; set; } ///<summary> /// Deleted /// <para>Name: IsDeleted</para> /// <para>SF Type: boolean</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "isDeleted")] [Updateable(false), Createable(false)] public bool? IsDeleted { get; set; } ///<summary> /// Refund Number /// <para>Name: RefundNumber</para> /// <para>SF Type: string</para> /// <para>AutoNumber field</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "refundNumber")] [Updateable(false), Createable(false)] public string RefundNumber { get; set; } ///<summary> /// Created Date /// <para>Name: CreatedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdDate")] [Updateable(false), Createable(false)] public DateTimeOffset? CreatedDate { get; set; } ///<summary> /// Created By ID /// <para>Name: CreatedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "createdById")] [Updateable(false), Createable(false)] public string CreatedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: CreatedBy</para> ///</summary> [JsonProperty(PropertyName = "createdBy")] [Updateable(false), Createable(false)] public SfUser CreatedBy { get; set; } ///<summary> /// Last Modified Date /// <para>Name: LastModifiedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastModifiedDate { get; set; } ///<summary> /// Last Modified By ID /// <para>Name: LastModifiedById</para> /// <para>SF Type: reference</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedById")] [Updateable(false), Createable(false)] public string LastModifiedById { get; set; } ///<summary> /// ReferenceTo: User /// <para>RelationshipName: LastModifiedBy</para> ///</summary> [JsonProperty(PropertyName = "lastModifiedBy")] [Updateable(false), Createable(false)] public SfUser LastModifiedBy { get; set; } ///<summary> /// System Modstamp /// <para>Name: SystemModstamp</para> /// <para>SF Type: datetime</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "systemModstamp")] [Updateable(false), Createable(false)] public DateTimeOffset? SystemModstamp { get; set; } ///<summary> /// Last Viewed Date /// <para>Name: LastViewedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastViewedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastViewedDate { get; set; } ///<summary> /// Last Referenced Date /// <para>Name: LastReferencedDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "lastReferencedDate")] [Updateable(false), Createable(false)] public DateTimeOffset? LastReferencedDate { get; set; } ///<summary> /// Type /// <para>Name: Type</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "type")] public string Type { get; set; } ///<summary> /// Payment Group ID /// <para>Name: PaymentGroupId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentGroupId")] public string PaymentGroupId { get; set; } ///<summary> /// ReferenceTo: PaymentGroup /// <para>RelationshipName: PaymentGroup</para> ///</summary> [JsonProperty(PropertyName = "paymentGroup")] [Updateable(false), Createable(false)] public SfPaymentGroup PaymentGroup { get; set; } ///<summary> /// Impact Amount /// <para>Name: ImpactAmount</para> /// <para>SF Type: currency</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "impactAmount")] [Updateable(false), Createable(false)] public decimal? ImpactAmount { get; set; } ///<summary> /// Processing Mode /// <para>Name: ProcessingMode</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "processingMode")] [Updateable(false), Createable(true)] public string ProcessingMode { get; set; } ///<summary> /// Amount /// <para>Name: Amount</para> /// <para>SF Type: currency</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "amount")] public decimal? Amount { get; set; } ///<summary> /// Account ID /// <para>Name: AccountId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "accountId")] public string AccountId { get; set; } ///<summary> /// ReferenceTo: Account /// <para>RelationshipName: Account</para> ///</summary> [JsonProperty(PropertyName = "account")] [Updateable(false), Createable(false)] public SfAccount Account { get; set; } ///<summary> /// Payment Method ID /// <para>Name: PaymentMethodId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentMethodId")] public string PaymentMethodId { get; set; } ///<summary> /// ReferenceTo: PaymentMethod /// <para>RelationshipName: PaymentMethod</para> ///</summary> [JsonProperty(PropertyName = "paymentMethod")] [Updateable(false), Createable(false)] public SfPaymentMethod PaymentMethod { get; set; } ///<summary> /// Comments /// <para>Name: Comments</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "comments")] public string Comments { get; set; } ///<summary> /// Status /// <para>Name: Status</para> /// <para>SF Type: picklist</para> /// <para>Nillable: False</para> ///</summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } ///<summary> /// Gateway Reference Number /// <para>Name: GatewayRefNumber</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "gatewayRefNumber")] public string GatewayRefNumber { get; set; } ///<summary> /// Client Context /// <para>Name: ClientContext</para> /// <para>SF Type: textarea</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "clientContext")] [Updateable(false), Createable(false)] public string ClientContext { get; set; } ///<summary> /// Gateway ResultCode /// <para>Name: GatewayResultCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "gatewayResultCode")] public string GatewayResultCode { get; set; } ///<summary> /// Gateway ResultCode Description /// <para>Name: GatewayResultCodeDescription</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "gatewayResultCodeDescription")] public string GatewayResultCodeDescription { get; set; } ///<summary> /// Salesforce ResultCode /// <para>Name: SfResultCode</para> /// <para>SF Type: picklist</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "sfResultCode")] public string SfResultCode { get; set; } ///<summary> /// Gateway Date /// <para>Name: GatewayDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "gatewayDate")] public DateTimeOffset? GatewayDate { get; set; } ///<summary> /// IP Address /// <para>Name: IpAddress</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "ipAddress")] public string IpAddress { get; set; } ///<summary> /// MAC Address /// <para>Name: MacAddress</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "macAddress")] public string MacAddress { get; set; } ///<summary> /// Phone /// <para>Name: Phone</para> /// <para>SF Type: phone</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "phone")] public string Phone { get; set; } ///<summary> /// Audit Email /// <para>Name: Email</para> /// <para>SF Type: email</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "email")] public string Email { get; set; } ///<summary> /// Effective Date /// <para>Name: EffectiveDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "effectiveDate")] public DateTimeOffset? EffectiveDate { get; set; } ///<summary> /// Date /// <para>Name: Date</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "date")] public DateTimeOffset? Date { get; set; } ///<summary> /// Cancellation Effective Date /// <para>Name: CancellationEffectiveDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationEffectiveDate")] public DateTimeOffset? CancellationEffectiveDate { get; set; } ///<summary> /// Cancellation Date /// <para>Name: CancellationDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationDate")] public DateTimeOffset? CancellationDate { get; set; } ///<summary> /// Cancellation Gateway Reference Number /// <para>Name: CancellationGatewayRefNumber</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationGatewayRefNumber")] public string CancellationGatewayRefNumber { get; set; } ///<summary> /// Cancellation Gateway ResultCode /// <para>Name: CancellationGatewayResultCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationGatewayResultCode")] public string CancellationGatewayResultCode { get; set; } ///<summary> /// Cancellation Salesforce ResultCode /// <para>Name: CancellationSfResultCode</para> /// <para>SF Type: string</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationSfResultCode")] public string CancellationSfResultCode { get; set; } ///<summary> /// Cancellation Gateway Date /// <para>Name: CancellationGatewayDate</para> /// <para>SF Type: datetime</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "cancellationGatewayDate")] public DateTimeOffset? CancellationGatewayDate { get; set; } ///<summary> /// Payment Gateway ID /// <para>Name: PaymentGatewayId</para> /// <para>SF Type: reference</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "paymentGatewayId")] public string PaymentGatewayId { get; set; } ///<summary> /// ReferenceTo: PaymentGateway /// <para>RelationshipName: PaymentGateway</para> ///</summary> [JsonProperty(PropertyName = "paymentGateway")] [Updateable(false), Createable(false)] public SfPaymentGateway PaymentGateway { get; set; } ///<summary> /// Total Applied /// <para>Name: TotalApplied</para> /// <para>SF Type: currency</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "totalApplied")] [Updateable(false), Createable(false)] public decimal? TotalApplied { get; set; } ///<summary> /// Total Unapplied /// <para>Name: TotalUnapplied</para> /// <para>SF Type: currency</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "totalUnapplied")] [Updateable(false), Createable(false)] public decimal? TotalUnapplied { get; set; } ///<summary> /// Net Applied /// <para>Name: NetApplied</para> /// <para>SF Type: currency</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "netApplied")] [Updateable(false), Createable(false)] public decimal? NetApplied { get; set; } ///<summary> /// Balance /// <para>Name: Balance</para> /// <para>SF Type: currency</para> /// <para>Nillable: True</para> ///</summary> [JsonProperty(PropertyName = "balance")] [Updateable(false), Createable(false)] public decimal? Balance { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01a.named01a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01a.named01a; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(x: 2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01b.named01b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01b.named01b; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d = 2; return tf.Foo(x: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01c.named01c { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named01c.named01c; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 2; return tf.Foo(x: d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02a.named02a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02a.named02a; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(y: 1, x: 2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02b.named02b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02b.named02b; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d1 = 1; dynamic d2 = 2; return tf.Foo(y: d1, x: d2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02c.named02c { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named02c.named02c; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with named parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x, int y) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d1 = 1; dynamic d2 = 2; return tf.Foo(y: d1, x: d2); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03a.named03a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03a.named03a; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with and incorrect parameter</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); try { tf.Foo(Invalid: 2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadNamedArgument, e.Message, "Foo", "Invalid"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03c.named03c { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.named03c.named03c; // <Area>Named Parameters</Area> // <Title> Basic Named Parameter</Title> // <Description>Basic testing of a simple function with and incorrect parameter</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 2; try { tf.Foo(Invalid: d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadNamedArgument, e.Message, "Foo", "Invalid"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional03.optional03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional03.optional03; // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with non-optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); try { tf.Foo(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { bool ret = ErrorVerifier.Verify(ErrorMessageId.BadArgCount, e.Message, "Foo", "0"); if (ret) return 0; } return 1; } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02a.optional02a { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02a.optional02a; // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(1); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02b.optional02b { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02b.optional02b; // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { Derived tf = new Derived(); dynamic d = 1; return tf.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02c.optional02c { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional02c.optional02c; // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 1; else return 0; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); dynamic d = 1; return tf.Foo(d); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional01.optional01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.basic.optional01.optional01; // <Area>Optional Parameters</Area> // <Title> Basic Optional Parameter</Title> // <Description>Basic testing of a simple function with optional parameters</Description> // <Expects status=success></Expects> // <Code> public class Derived { public int Foo(int x = 2) { if (x == 2) return 0; else return 1; } } public class TestFunction { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic tf = new Derived(); return tf.Foo(); } } //</Code> }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Glass.Mapper.Sc.Configuration; using Sitecore.Data; using Sitecore.SecurityModel; namespace Glass.Mapper.Sc.Integration.DataMappers { [TestFixture] public class AbstractSitecoreFieldMapperFixture : AbstractMapperFixture { #region Constructors [Test] public void Constructor_TypesPassed_TypesHandledSet() { //Assign var type1 = typeof (int); var type2 = typeof (string); //Act var mapper = new StubMapper(type1, type2); //Assert Assert.IsTrue(mapper.TypesHandled.Any(x => x == type1)); Assert.IsTrue(mapper.TypesHandled.Any(x => x == type2)); } #endregion #region Method - CanHandle [Test] public void CanHandle_TypeIsHandledWithConfig_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); var type1 = typeof (string); var mapper = new StubMapper(type1); config.PropertyInfo = typeof (Stub).GetProperty("Property"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_TwoTypesAreHandledWithConfig_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); var type2 = typeof(string); var type1 = typeof(int); var mapper = new StubMapper(type1, type2); config.PropertyInfo = typeof(Stub).GetProperty("Property"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_IncorrectConfigType_ReturnsFalse() { //Assign var config = new SitecoreIdConfiguration(); var type2 = typeof(string); var type1 = typeof(int); var mapper = new StubMapper(type1, type2); config.PropertyInfo = typeof(Stub).GetProperty("Property"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsFalse(result); } [Test] public void CanHandle_IncorrectPropertType_ReturnsFalse() { //Assign var config = new SitecoreIdConfiguration(); var type1 = typeof(int); var mapper = new StubMapper(type1); config.PropertyInfo = typeof(Stub).GetProperty("Property"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsFalse(result); } #endregion #region Method - MapToProperty [Test] public void MapToProperty_GetsValueByFieldName_ReturnsFieldValue() { //Assign var fieldValue = "test value"; var fieldName = "Field"; var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToProperty"); var config = new SitecoreFieldConfiguration(); config.FieldName = fieldName; var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null,config)); mapper.Value = fieldValue; var context = new SitecoreDataMappingContext(null, item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldName] = fieldValue; item.Editing.EndEdit(); } //Act var result = mapper.MapToProperty(context); //Assert Assert.AreEqual(fieldValue, result); } [Test] public void MapToProperty_GetsValueByFieldId_ReturnsFieldValue() { //Assign var fieldValue = "test value"; var fieldId = new ID("{6B43481F-F129-4F53-BEEE-EA84F9B1A6D4}"); var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToProperty"); var config = new SitecoreFieldConfiguration(); config.FieldId = fieldId; var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null,config)); mapper.Value = fieldValue; var context = new SitecoreDataMappingContext(null, item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldId] = fieldValue; item.Editing.EndEdit(); } //Act var result = mapper.MapToProperty(context); //Assert Assert.AreEqual(fieldValue, result); } #endregion #region Method - MapToCms [Test] public void MapToCms_SetsValueByFieldId_FieldValueUpdated() { //Assign var fieldValue = "test value set"; var fieldId = new ID("{6B43481F-F129-4F53-BEEE-EA84F9B1A6D4}"); var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); var config = new SitecoreFieldConfiguration(); config.FieldId = fieldId; config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null,config)); mapper.Value = fieldValue; var context = new SitecoreDataMappingContext(new Stub(), item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldId] = string.Empty; item.Editing.EndEdit(); } //Act using (new SecurityDisabler()) { item.Editing.BeginEdit(); mapper.MapToCms(context); item.Editing.EndEdit(); } //Assert var itemAfter = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); Assert.AreEqual(mapper.Value, itemAfter[fieldId]); } [Test] public void MapToCms_SetsValueByFieldName_FieldValueUpdated() { //Assign var fieldValue = "test value set"; var fieldName = "Field"; var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); var config = new SitecoreFieldConfiguration(); config.FieldName = fieldName; config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null,config)); mapper.Value = fieldValue; var context = new SitecoreDataMappingContext(new Stub(), item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldName] = string.Empty; item.Editing.EndEdit(); } //Act using (new SecurityDisabler()) { item.Editing.BeginEdit(); mapper.MapToCms(context); item.Editing.EndEdit(); } //Assert var itemAfter = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); Assert.AreEqual( mapper.Value, itemAfter[fieldName]); } #endregion #region Method - MapPropertyToCms [Test] public void MapPropertyToCms_FieldReadOnly_FieldNotUpdated() { //Assign var fieldValue = "test value set"; var fieldName = "Field"; var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); var config = new SitecoreFieldConfiguration(); config.FieldName = fieldName; config.PropertyInfo = typeof(Stub).GetProperty("Property"); config.ReadOnly = true; var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null, config)); mapper.Value = fieldValue; Assert.IsTrue(mapper.ReadOnly); var context = new SitecoreDataMappingContext(new Stub(), item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldName] = string.Empty; item.Editing.EndEdit(); } //Act using (new SecurityDisabler()) { item.Editing.BeginEdit(); mapper.MapPropertyToCms(context); item.Editing.EndEdit(); } //Assert var itemAfter = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); Assert.AreNotEqual(mapper.Value, itemAfter[fieldName]); Assert.AreEqual(item[fieldName], itemAfter[fieldName]); } [Test] public void MapPropertyToCms_PageEditorOnly_FieldNotUpdated() { //Assign var fieldValue = "test value set"; var fieldName = "Field"; var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); var config = new SitecoreFieldConfiguration(); config.FieldName = fieldName; config.PropertyInfo = typeof(Stub).GetProperty("Property"); config.ReadOnly = false; config.Setting = SitecoreFieldSettings.PageEditorOnly; var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null, config)); mapper.Value = fieldValue; Assert.IsFalse(mapper.ReadOnly); var context = new SitecoreDataMappingContext(new Stub(), item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldName] = string.Empty; item.Editing.EndEdit(); } //Act using (new SecurityDisabler()) { item.Editing.BeginEdit(); mapper.MapPropertyToCms(context); item.Editing.EndEdit(); } //Assert var itemAfter = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); Assert.AreNotEqual(mapper.Value, itemAfter[fieldName]); Assert.AreEqual(item[fieldName], itemAfter[fieldName]); } #endregion #region Method - MapCmsToProperty [Test] public void MapCmsToProperty_PageEditorOnly_FieldNotUpdated() { //Assign var fieldValue = "test value set"; var preValue = "some other value"; var fieldName = "Field"; var database = Sitecore.Configuration.Factory.GetDatabase("master"); var item = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); var config = new SitecoreFieldConfiguration(); config.FieldName = fieldName; config.PropertyInfo = typeof(Stub).GetProperty("Property"); config.ReadOnly = false; config.Setting = SitecoreFieldSettings.PageEditorOnly; var mapper = new StubMapper(null); mapper.Setup(new DataMapperResolverArgs(null, config)); mapper.Value = preValue; Assert.IsFalse(mapper.ReadOnly); var context = new SitecoreDataMappingContext(new Stub(), item, null); using (new SecurityDisabler()) { item.Editing.BeginEdit(); item[fieldName] = fieldValue; item.Editing.EndEdit(); } //Act using (new SecurityDisabler()) { item.Editing.BeginEdit(); mapper.MapCmsToProperty(context); item.Editing.EndEdit(); } //Assert var itemAfter = database.GetItem("/sitecore/content/Tests/DataMappers/AbstractSitecoreFieldMapper/MapToCms"); Assert.AreEqual(mapper.Value, preValue); Assert.AreEqual(fieldValue, itemAfter[fieldName]); } #endregion #region Stubs public class StubMapper : AbstractSitecoreFieldMapper { public string Value { get; set; } public StubMapper(params Type[] typeHandlers) : base(typeHandlers) { } public override object GetFieldValue(string fieldValue, Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { return Value; } public override void SetField(Sitecore.Data.Fields.Field field, object value, Configuration.SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { field.Value = Value; } public override string SetFieldValue(object value, SitecoreFieldConfiguration config, SitecoreDataMappingContext context) { throw new NotImplementedException(); } } public class Stub { public string Property { get; set; } } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="ScaleTransform3D.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { sealed partial class ScaleTransform3D : AffineTransform3D { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new ScaleTransform3D Clone() { return (ScaleTransform3D)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new ScaleTransform3D CloneCurrentValue() { return (ScaleTransform3D)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void ScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedScaleXValue = (double)e.NewValue; target.PropertyChanged(ScaleXProperty); } private static void ScaleYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedScaleYValue = (double)e.NewValue; target.PropertyChanged(ScaleYProperty); } private static void ScaleZPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedScaleZValue = (double)e.NewValue; target.PropertyChanged(ScaleZProperty); } private static void CenterXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedCenterXValue = (double)e.NewValue; target.PropertyChanged(CenterXProperty); } private static void CenterYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedCenterYValue = (double)e.NewValue; target.PropertyChanged(CenterYProperty); } private static void CenterZPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ScaleTransform3D target = ((ScaleTransform3D) d); target._cachedCenterZValue = (double)e.NewValue; target.PropertyChanged(CenterZProperty); } #region Public Properties /// <summary> /// ScaleX - double. Default value is 1.0. /// </summary> public double ScaleX { get { ReadPreamble(); return _cachedScaleXValue; } set { SetValueInternal(ScaleXProperty, value); } } /// <summary> /// ScaleY - double. Default value is 1.0. /// </summary> public double ScaleY { get { ReadPreamble(); return _cachedScaleYValue; } set { SetValueInternal(ScaleYProperty, value); } } /// <summary> /// ScaleZ - double. Default value is 1.0. /// </summary> public double ScaleZ { get { ReadPreamble(); return _cachedScaleZValue; } set { SetValueInternal(ScaleZProperty, value); } } /// <summary> /// CenterX - double. Default value is 0.0. /// </summary> public double CenterX { get { ReadPreamble(); return _cachedCenterXValue; } set { SetValueInternal(CenterXProperty, value); } } /// <summary> /// CenterY - double. Default value is 0.0. /// </summary> public double CenterY { get { ReadPreamble(); return _cachedCenterYValue; } set { SetValueInternal(CenterYProperty, value); } } /// <summary> /// CenterZ - double. Default value is 0.0. /// </summary> public double CenterZ { get { ReadPreamble(); return _cachedCenterZValue; } set { SetValueInternal(CenterZProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new ScaleTransform3D(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { base.UpdateResource(channel, skipOnChannelCheck); // Obtain handles for animated properties DUCE.ResourceHandle hScaleXAnimations = GetAnimationResourceHandle(ScaleXProperty, channel); DUCE.ResourceHandle hScaleYAnimations = GetAnimationResourceHandle(ScaleYProperty, channel); DUCE.ResourceHandle hScaleZAnimations = GetAnimationResourceHandle(ScaleZProperty, channel); DUCE.ResourceHandle hCenterXAnimations = GetAnimationResourceHandle(CenterXProperty, channel); DUCE.ResourceHandle hCenterYAnimations = GetAnimationResourceHandle(CenterYProperty, channel); DUCE.ResourceHandle hCenterZAnimations = GetAnimationResourceHandle(CenterZProperty, channel); // Pack & send command packet DUCE.MILCMD_SCALETRANSFORM3D data; unsafe { data.Type = MILCMD.MilCmdScaleTransform3D; data.Handle = _duceResource.GetHandle(channel); if (hScaleXAnimations.IsNull) { data.scaleX = ScaleX; } data.hScaleXAnimations = hScaleXAnimations; if (hScaleYAnimations.IsNull) { data.scaleY = ScaleY; } data.hScaleYAnimations = hScaleYAnimations; if (hScaleZAnimations.IsNull) { data.scaleZ = ScaleZ; } data.hScaleZAnimations = hScaleZAnimations; if (hCenterXAnimations.IsNull) { data.centerX = CenterX; } data.hCenterXAnimations = hCenterXAnimations; if (hCenterYAnimations.IsNull) { data.centerY = CenterY; } data.hCenterYAnimations = hCenterYAnimations; if (hCenterZAnimations.IsNull) { data.centerZ = CenterZ; } data.hCenterZAnimations = hCenterZAnimations; // Send packed command structure channel.SendCommand( (byte*)&data, sizeof(DUCE.MILCMD_SCALETRANSFORM3D)); } } } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_SCALETRANSFORM3D)) { AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the ScaleTransform3D.ScaleX property. /// </summary> public static readonly DependencyProperty ScaleXProperty; /// <summary> /// The DependencyProperty for the ScaleTransform3D.ScaleY property. /// </summary> public static readonly DependencyProperty ScaleYProperty; /// <summary> /// The DependencyProperty for the ScaleTransform3D.ScaleZ property. /// </summary> public static readonly DependencyProperty ScaleZProperty; /// <summary> /// The DependencyProperty for the ScaleTransform3D.CenterX property. /// </summary> public static readonly DependencyProperty CenterXProperty; /// <summary> /// The DependencyProperty for the ScaleTransform3D.CenterY property. /// </summary> public static readonly DependencyProperty CenterYProperty; /// <summary> /// The DependencyProperty for the ScaleTransform3D.CenterZ property. /// </summary> public static readonly DependencyProperty CenterZProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields private double _cachedScaleXValue = 1.0; private double _cachedScaleYValue = 1.0; private double _cachedScaleZValue = 1.0; private double _cachedCenterXValue = 0.0; private double _cachedCenterYValue = 0.0; private double _cachedCenterZValue = 0.0; internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal const double c_ScaleX = 1.0; internal const double c_ScaleY = 1.0; internal const double c_ScaleZ = 1.0; internal const double c_CenterX = 0.0; internal const double c_CenterY = 0.0; internal const double c_CenterZ = 0.0; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static ScaleTransform3D() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(ScaleTransform3D); ScaleXProperty = RegisterProperty("ScaleX", typeof(double), typeofThis, 1.0, new PropertyChangedCallback(ScaleXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); ScaleYProperty = RegisterProperty("ScaleY", typeof(double), typeofThis, 1.0, new PropertyChangedCallback(ScaleYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); ScaleZProperty = RegisterProperty("ScaleZ", typeof(double), typeofThis, 1.0, new PropertyChangedCallback(ScaleZPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterXProperty = RegisterProperty("CenterX", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterYProperty = RegisterProperty("CenterY", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); CenterZProperty = RegisterProperty("CenterZ", typeof(double), typeofThis, 0.0, new PropertyChangedCallback(CenterZPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
using System; using System.Collections.Generic; using System.Linq; using InvisibleCollectorLib.Utils; namespace InvisibleCollectorLib.Model { public class Payment : ItemsModel<PaymentLine> { internal const string NumberName = "number"; internal const string CurrencyName = "currency"; internal const string GrossTotalName = "grossTotal"; internal const string TypeName = "type"; internal const string TaxName = "tax"; internal const string NetTotalName = "netTotal"; internal const string DateName = "date"; internal const string StatusName = "status"; internal const string LinesName = "lines"; internal const string ExternalIdName = "externalId"; /// <summary> /// The currency. Must be an ISO 4217 currency code. /// </summary> public string Currency { get => GetField<string>(CurrencyName); set => this[CurrencyName] = value; } /// <summary> /// The payment date. Only the years, month and days are considered. /// </summary> public DateTime? Date { get => GetField<DateTime?>(DateName); set => this[DateName] = value; } public double? GrossTotal { get => GetField<double?>(GrossTotalName); set => this[GrossTotalName] = value; } public double? NetTotal { get => GetField<double?>(NetTotalName); set => this[NetTotalName] = value; } /// <summary> /// The payment status. Can be one of: "FINAL" - default; "CANCELLED" /// </summary> public string Status { get => GetField<string>(StatusName); set => this[StatusName] = value; } /// <summary> /// The payment type. /// </summary> public string Type { get => GetField<string>(TypeName); set => this[TypeName] = value; } public string Number { get => GetField<string>(NumberName); set => this[NumberName] = value; } /// <summary> /// The 'id' of the payment, which will be used to identify this payment on future requests. /// </summary> public string ExternalId { get => GetField<string>(ExternalIdName); set => this[ExternalIdName] = value; } /// <summary> /// The total amount being paid in tax. /// </summary> public double? Tax { get => GetField<double?>(TaxName); set => this[TaxName] = value; } protected override IList<PaymentLine> InternalItems { get => GetField<IList<PaymentLine>>(LinesName); set => this[LinesName] = value; } protected override string ItemName => LinesName; /// <summary> /// A list of debts being paid. /// </summary> public IList<PaymentLine> Lines { get => InternalItems?.Clone(); set => InternalItems = value?.Clone(); } public void AddLine(PaymentLine line) { AddItem(line); } public void UnsetExternalId() { UnsetField(ExternalId); } public void UnsetCurrency() { UnsetField(CurrencyName); } public void UnsetDate() { UnsetField(DateName); } public void UnsetGrossTotal() { UnsetField(GrossTotalName); } public void UnsetNetTotal() { UnsetField(NetTotalName); } public void UnsetNumber() { UnsetField(NumberName); } public void UnsetStatus() { UnsetField(StatusName); } public void UnsetTax() { UnsetField(TaxName); } public void UnsetType() { UnsetField(TypeName); } public void UnsetLines() { UnsetField(LinesName); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object other) { return other is Payment payment && this == payment; } public static bool operator ==(Payment left, Payment right) { return AreEqual(left, right, LinesName); } public static bool operator !=(Payment left, Payment right) { return !(left == right); } public override string ToString() { var fields = FieldsShallow; fields[LinesName] = InternalItems?.StringifyList(); return fields.StringifyDictionary(); } } }
// *********************************************************************** // Copyright (c) 2010 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework.Attributes { [TestFixture] public class ApplyToTestTests { Test test; [SetUp] public void SetUp() { test = new TestDummy(); test.RunState = RunState.Runnable; } #region CategoryAttribute [Test] public void CategoryAttributeSetsCategory() { new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsCategoryOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsMultipleCategories() { new CategoryAttribute("group1").ApplyToTest(test); new CategoryAttribute("group2").ApplyToTest(test); Assert.That(test.Properties[PropertyNames.Category], Is.EquivalentTo( new string[] { "group1", "group2" } )); } #endregion #region DescriptionAttribute [Test] public void DescriptionAttributeSetsDescription() { new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } [Test] public void DescriptionAttributeSetsDescriptionOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } #endregion #region IgnoreAttribute [Test] public void IgnoreAttributeIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeSetsIgnoreReason() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void IgnoreAttributeDoesNotAffectNonRunnableTest() { test.MakeInvalid("UNCHANGED"); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void IgnoreAttributeIgnoresTestUntilDateSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeIgnoresTestUntilDateTimeSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01 12:00:00Z"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeMarksTestAsRunnableAfterUntilDatePasses() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1492-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [TestCase("4242-01-01")] [TestCase("4242-01-01 00:00:00Z")] [TestCase("4242-01-01 00:00:00")] public void IgnoreAttributeUntilSetsTheReason(string date) { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = date; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Ignoring until 4242-01-01 00:00:00Z. BECAUSE")); } [Test] public void IgnoreAttributeWithInvalidDateThrowsException() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); Assert.Throws<FormatException>(() => ignoreAttribute.Until = "Thursday the twenty fifth of December"); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDateProperty() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("4242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDatePropertyPastUntilDate() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("1242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithExplicitIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region ExplicitAttribute [Test] public void ExplicitAttributeMakesTestExplicit() { new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); } [Test] public void ExplicitAttributeSetsIgnoreReason() { new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void ExplicitAttributeDoesNotAffectNonRunnableTest() { test.MakeInvalid("UNCHANGED"); new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void ExplicitAttributeWithIgnoreIgnoresTest() { new ExplicitAttribute().ApplyToTest(test); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttributeSetsJoinType() { new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } [Test] public void CombinatorialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } #endregion #region CultureAttribute [Test] public void CultureAttributeIncludingCurrentCultureRunsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void CultureAttributeExcludingCurrentCultureSkipsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; CultureAttribute attr = new CultureAttribute(name); attr.Exclude = name; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Not supported under culture " + name)); } [Test] public void CultureAttributeIncludingOtherCultureSkipsTest() { string name = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == name) name = "en-US"; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Only supported under culture " + name)); } [Test] public void CultureAttributeExcludingOtherCultureRunsTest() { string other = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == other) other = "en-US"; CultureAttribute attr = new CultureAttribute(); attr.Exclude = other; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeWithMultipleCulturesIncluded() { string current = System.Globalization.CultureInfo.CurrentCulture.Name; string other = current == "fr-FR" ? "en-US" : "fr-FR"; string cultures = current + "," + other; new CultureAttribute(cultures).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region MaxTimeAttribute [Test] public void MaxTimeAttributeSetsMaxTime() { new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } [Test] public void MaxTimeAttributeSetsMaxTimeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttributeSetsJoinType() { new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } [Test] public void PairwiseAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } #endregion #region PlatformAttribute #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void PlatformAttributeRunsTest() { string myPlatform = GetMyPlatform(); new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void PlatformAttributeSkipsTest() { string notMyPlatform = System.IO.Path.DirectorySeparatorChar == '/' ? "Win" : "Linux"; new PlatformAttribute(notMyPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); } [Test] public void PlatformAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string myPlatform = GetMyPlatform(); new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void InvalidPlatformAttributeIsNotRunnable() { var invalidPlatform = "FakePlatform"; new PlatformAttribute(invalidPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Invalid platform name")); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Does.Contain(invalidPlatform)); } string GetMyPlatform() { if (System.IO.Path.DirectorySeparatorChar == '/') { return OSPlatform.CurrentPlatform.IsMacOSX ? "MacOSX" : "Linux"; } return "Win"; } #endif #endregion #region RepeatAttribute [Test] public void RepeatAttributeSetsRepeatCount() { new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } [Test] public void RepeatAttributeSetsRepeatCountOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } #endregion #if !NETSTANDARD1_3 && !NETSTANDARD1_6 #region RequiresMTAAttribute [Test] public void RequiresMTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } [Test] public void RequiresMTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } #endregion #region RequiresSTAAttribute [Test] public void RequiresSTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } [Test] public void RequiresSTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endregion #endif #region RequiresThreadAttribute #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void RequiresThreadAttributeSetsRequiresThread() { new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } [Test] public void RequiresThreadAttributeSetsRequiresThreadOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } #endif #if !NETSTANDARD1_3 && !NETSTANDARD1_6 [Test] public void RequiresThreadAttributeMaySetApartmentState() { new RequiresThreadAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endif #endregion #region SequentialAttribute [Test] public void SequentialAttributeSetsJoinType() { new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } [Test] public void SequentialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } #endregion #if !NETSTANDARD1_3 && !NETSTANDARD1_6 #region SetCultureAttribute public void SetCultureAttributeSetsSetCultureProperty() { new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } public void SetCultureAttributeSetsSetCulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } #endregion #region SetUICultureAttribute public void SetUICultureAttributeSetsSetUICultureProperty() { new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } public void SetUICultureAttributeSetsSetUICulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } #endregion #endif } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace org.pescuma.sharpdecorators { public class FuncDecorator<TResult> { private readonly ConcurrentQueue<Func<Func<TResult>, TResult>> decorators = new ConcurrentQueue<Func<Func<TResult>, TResult>>(); public void Add(Func<Func<TResult>, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(Func<TResult> code) { var blocks = decorators.ToList(); blocks.Add(n => code()); return ExecuteNext(blocks, 0); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<TResult>, TResult>> blocks, int current) { return blocks[current](() => ExecuteNext(blocks, current + 1)); } } public class FuncDecorator<T1, TResult> { private readonly ConcurrentQueue<Func<Func<T1, TResult>, T1, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, TResult>, T1, TResult>>(); public void Add(Func<Func<T1, TResult>, T1, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, Func<T1, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1) => code(a1)); return ExecuteNext(blocks, 0, arg1); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, TResult>, T1, TResult>> blocks, int current, T1 arg1) { return blocks[current]((a1) => ExecuteNext(blocks, current + 1, a1), arg1); } } public class FuncDecorator<T1, T2, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, TResult>, T1, T2, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, TResult>, T1, T2, TResult>>(); public void Add(Func<Func<T1, T2, TResult>, T1, T2, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, Func<T1, T2, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2) => code(a1, a2)); return ExecuteNext(blocks, 0, arg1, arg2); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, TResult>, T1, T2, TResult>> blocks, int current, T1 arg1, T2 arg2) { return blocks[current]((a1, a2) => ExecuteNext(blocks, current + 1, a1, a2), arg1, arg2); } } public class FuncDecorator<T1, T2, T3, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, TResult>, T1, T2, T3, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, TResult>, T1, T2, T3, TResult>>(); public void Add(Func<Func<T1, T2, T3, TResult>, T1, T2, T3, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, Func<T1, T2, T3, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3) => code(a1, a2, a3)); return ExecuteNext(blocks, 0, arg1, arg2, arg3); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, TResult>, T1, T2, T3, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3) { return blocks[current]((a1, a2, a3) => ExecuteNext(blocks, current + 1, a1, a2, a3), arg1, arg2, arg3); } } public class FuncDecorator<T1, T2, T3, T4, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, Func<T1, T2, T3, T4, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4) => code(a1, a2, a3, a4)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, TResult>, T1, T2, T3, T4, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { return blocks[current]((a1, a2, a3, a4) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4), arg1, arg2, arg3, arg4); } } public class FuncDecorator<T1, T2, T3, T4, T5, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Func<T1, T2, T3, T4, T5, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4, a5) => code(a1, a2, a3, a4, a5)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4, arg5); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, T5, TResult>, T1, T2, T3, T4, T5, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) { return blocks[current]((a1, a2, a3, a4, a5) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4, a5), arg1, arg2, arg3, arg4, arg5); } } public class FuncDecorator<T1, T2, T3, T4, T5, T6, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Func<T1, T2, T3, T4, T5, T6, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4, a5, a6) => code(a1, a2, a3, a4, a5, a6)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4, arg5, arg6); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, T5, T6, TResult>, T1, T2, T3, T4, T5, T6, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) { return blocks[current]((a1, a2, a3, a4, a5, a6) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4, a5, a6), arg1, arg2, arg3, arg4, arg5, arg6); } } public class FuncDecorator<T1, T2, T3, T4, T5, T6, T7, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, TResult>, T1, T2, T3, T4, T5, T6, T7, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, TResult>, T1, T2, T3, T4, T5, T6, T7, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, T5, T6, T7, TResult>, T1, T2, T3, T4, T5, T6, T7, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, Func<T1, T2, T3, T4, T5, T6, T7, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4, a5, a6, a7) => code(a1, a2, a3, a4, a5, a6, a7)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, T5, T6, T7, TResult>, T1, T2, T3, T4, T5, T6, T7, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7) { return blocks[current]((a1, a2, a3, a4, a5, a6, a7) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4, a5, a6, a7), arg1, arg2, arg3, arg4, arg5, arg6, arg7); } } public class FuncDecorator<T1, T2, T3, T4, T5, T6, T7, T8, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4, a5, a6, a7, a8) => code(a1, a2, a3, a4, a5, a6, a7, a8)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8) { return blocks[current]((a1, a2, a3, a4, a5, a6, a7, a8) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4, a5, a6, a7, a8), arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } } public class FuncDecorator<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> { private readonly ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> decorators = new ConcurrentQueue<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>>(); public void Add(Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> decorator) { decorators.Enqueue(decorator); } [DebuggerStepThrough] public TResult Call(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> code) { var blocks = decorators.ToList(); blocks.Add((n, a1, a2, a3, a4, a5, a6, a7, a8, a9) => code(a1, a2, a3, a4, a5, a6, a7, a8, a9)); return ExecuteNext(blocks, 0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } [DebuggerStepThrough] private TResult ExecuteNext(List<Func<Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> blocks, int current, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9) { return blocks[current]((a1, a2, a3, a4, a5, a6, a7, a8, a9) => ExecuteNext(blocks, current + 1, a1, a2, a3, a4, a5, a6, a7, a8, a9), arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ProjectTracker.AppServerHost.Areas.HelpPage.ModelDescriptions; using ProjectTracker.AppServerHost.Areas.HelpPage.Models; namespace ProjectTracker.AppServerHost.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Player Audio Profiles //---------------------------------------------------------------------------- datablock SFXProfile(DeathCrySound) { fileName = "art/sound/orc_death"; description = AudioClose3d; preload = true; }; datablock SFXProfile(PainCrySound) { fileName = "art/sound/orc_pain"; description = AudioClose3d; preload = true; }; //---------------------------------------------------------------------------- datablock SFXProfile(FootLightSoftSound) { filename = "art/sound/lgtStep_mono_01"; description = AudioClosest3d; preload = true; }; datablock SFXProfile(FootLightHardSound) { filename = "art/sound/hvystep_ mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightMetalSound) { filename = "art/sound/metalstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightSnowSound) { filename = "art/sound/snowstep_mono_01"; description = AudioClosest3d; preload = true; }; datablock SFXProfile(FootLightShallowSplashSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightWadingSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClose3d; preload = true; }; datablock SFXProfile(FootLightUnderwaterSound) { filename = "art/sound/waterstep_mono_01"; description = AudioClosest3d; preload = true; }; //---------------------------------------------------------------------------- // Splash //---------------------------------------------------------------------------- datablock ParticleData(PlayerSplashMist) { dragCoefficient = 2.0; gravityCoefficient = -0.05; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 400; lifetimeVarianceMS = 100; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 500.0; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 0.8; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerSplashMistEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 3.0; velocityVariance = 2.0; ejectionOffset = 0.0; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; lifetimeMS = 250; particles = "PlayerSplashMist"; }; datablock ParticleData(PlayerBubbleParticle) { dragCoefficient = 0.0; gravityCoefficient = -0.50; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 400; lifetimeVarianceMS = 100; useInvAlpha = false; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 0.4"; colors[1] = "0.7 0.8 1.0 0.4"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.1; sizes[1] = 0.3; sizes[2] = 0.3; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerBubbleEmitter) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 2.0; ejectionOffset = 0.5; velocityVariance = 0.5; thetaMin = 0; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; particles = "PlayerBubbleParticle"; }; datablock ParticleData(PlayerFoamParticle) { dragCoefficient = 2.0; gravityCoefficient = -0.05; inheritedVelFactor = 0.1; constantAcceleration = 0.0; lifetimeMS = 600; lifetimeVarianceMS = 100; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 500.0; textureName = "art/shapes/particles/millsplash01"; colors[0] = "0.7 0.8 1.0 0.20"; colors[1] = "0.7 0.8 1.0 0.20"; colors[2] = "0.7 0.8 1.0 0.00"; sizes[0] = 0.2; sizes[1] = 0.4; sizes[2] = 1.6; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(PlayerFoamEmitter) { ejectionPeriodMS = 10; periodVarianceMS = 0; ejectionVelocity = 3.0; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 85; thetaMax = 85; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; particles = "PlayerFoamParticle"; }; datablock ParticleData( PlayerFoamDropletsParticle ) { dragCoefficient = 1; gravityCoefficient = 0.2; inheritedVelFactor = 0.2; constantAcceleration = -0.0; lifetimeMS = 600; lifetimeVarianceMS = 0; textureName = "art/shapes/actors/common/splash"; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.8; sizes[1] = 0.3; sizes[2] = 0.0; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData( PlayerFoamDropletsEmitter ) { ejectionPeriodMS = 7; periodVarianceMS = 0; ejectionVelocity = 2; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 60; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; orientParticles = true; particles = "PlayerFoamDropletsParticle"; }; datablock ParticleData( PlayerWakeParticle ) { textureName = "art/shapes/particles/wake"; dragCoefficient = "0.0"; gravityCoefficient = "0.0"; inheritedVelFactor = "0.0"; lifetimeMS = "2500"; lifetimeVarianceMS = "200"; windCoefficient = "0.0"; useInvAlpha = "1"; spinRandomMin = "30.0"; spinRandomMax = "30.0"; animateTexture = true; framesPerSec = 1; animTexTiling = "2 1"; animTexFrames = "0 1"; colors[0] = "1 1 1 0.1"; colors[1] = "1 1 1 0.7"; colors[2] = "1 1 1 0.3"; colors[3] = "0.5 0.5 0.5 0"; sizes[0] = "1.0"; sizes[1] = "2.0"; sizes[2] = "3.0"; sizes[3] = "3.5"; times[0] = "0.0"; times[1] = "0.25"; times[2] = "0.5"; times[3] = "1.0"; }; datablock ParticleEmitterData( PlayerWakeEmitter ) { ejectionPeriodMS = "200"; periodVarianceMS = "10"; ejectionVelocity = "0"; velocityVariance = "0"; ejectionOffset = "0"; thetaMin = "89"; thetaMax = "90"; phiReferenceVel = "0"; phiVariance = "1"; alignParticles = "1"; alignDirection = "0 0 1"; particles = "PlayerWakeParticle"; }; datablock ParticleData( PlayerSplashParticle ) { dragCoefficient = 1; gravityCoefficient = 0.2; inheritedVelFactor = 0.2; constantAcceleration = -0.0; lifetimeMS = 600; lifetimeVarianceMS = 0; colors[0] = "0.7 0.8 1.0 1.0"; colors[1] = "0.7 0.8 1.0 0.5"; colors[2] = "0.7 0.8 1.0 0.0"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 0.5; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData( PlayerSplashEmitter ) { ejectionPeriodMS = 1; periodVarianceMS = 0; ejectionVelocity = 3; velocityVariance = 1.0; ejectionOffset = 0.0; thetaMin = 60; thetaMax = 80; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; orientParticles = true; lifetimeMS = 100; particles = "PlayerSplashParticle"; }; datablock SplashData(PlayerSplash) { numSegments = 15; ejectionFreq = 15; ejectionAngle = 40; ringLifetime = 0.5; lifetimeMS = 300; velocity = 4.0; startRadius = 0.0; acceleration = -3.0; texWrap = 5.0; texture = "art/shapes/particles/millsplash01"; emitter[0] = PlayerSplashEmitter; emitter[1] = PlayerSplashMistEmitter; colors[0] = "0.7 0.8 1.0 0.0"; colors[1] = "0.7 0.8 1.0 0.3"; colors[2] = "0.7 0.8 1.0 0.7"; colors[3] = "0.7 0.8 1.0 0.0"; times[0] = 0.0; times[1] = 0.4; times[2] = 0.8; times[3] = 1.0; }; //---------------------------------------------------------------------------- // Foot puffs //---------------------------------------------------------------------------- datablock ParticleData(LightPuff) { dragCoefficient = 2.0; gravityCoefficient = -0.01; inheritedVelFactor = 0.6; constantAcceleration = 0.0; lifetimeMS = 800; lifetimeVarianceMS = 100; useInvAlpha = true; spinRandomMin = -35.0; spinRandomMax = 35.0; colors[0] = "1.0 1.0 1.0 1.0"; colors[1] = "1.0 1.0 1.0 0.0"; sizes[0] = 0.1; sizes[1] = 0.8; times[0] = 0.3; times[1] = 1.0; }; datablock ParticleEmitterData(LightPuffEmitter) { ejectionPeriodMS = 35; periodVarianceMS = 10; ejectionVelocity = 0.2; velocityVariance = 0.1; ejectionOffset = 0.0; thetaMin = 20; thetaMax = 60; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; useEmitterColors = true; particles = "LightPuff"; }; //---------------------------------------------------------------------------- // Liftoff dust //---------------------------------------------------------------------------- datablock ParticleData(LiftoffDust) { dragCoefficient = 1.0; gravityCoefficient = -0.01; inheritedVelFactor = 0.0; constantAcceleration = 0.0; lifetimeMS = 1000; lifetimeVarianceMS = 100; useInvAlpha = true; spinRandomMin = -90.0; spinRandomMax = 500.0; colors[0] = "1.0 1.0 1.0 1.0"; sizes[0] = 1.0; times[0] = 1.0; textureName = "art/shapes/particles/dustParticle"; }; datablock ParticleEmitterData(LiftoffDustEmitter) { ejectionPeriodMS = 5; periodVarianceMS = 0; ejectionVelocity = 2.0; velocityVariance = 0.0; ejectionOffset = 0.0; thetaMin = 90; thetaMax = 90; phiReferenceVel = 0; phiVariance = 360; overrideAdvance = false; useEmitterColors = true; particles = "LiftoffDust"; }; //---------------------------------------------------------------------------- datablock DecalData(PlayerFootprint) { size = 0.4; material = CommonPlayerFootprint; }; datablock DebrisData( PlayerDebris ) { explodeOnMaxBounce = false; elasticity = 0.15; friction = 0.5; lifetime = 4.0; lifetimeVariance = 0.0; minSpinSpeed = 40; maxSpinSpeed = 600; numBounces = 5; bounceVariance = 0; staticOnMaxBounce = true; gravModifier = 1.0; useRadiusMass = true; baseRadius = 1; velocity = 20.0; velocityVariance = 12.0; }; // ---------------------------------------------------------------------------- // This is our default player datablock that all others will derive from. // ---------------------------------------------------------------------------- datablock PlayerData(DefaultPlayerData) { renderFirstPerson = true; className = Armor; shapeFile = "art/shapes/actors/Soldier/soldier_rigged.dae"; cameraMaxDist = 3; computeCRC = false; canObserve = 1; cmdCategory = "Clients"; cameraDefaultFov = 45.0; cameraMinFov = 5.0; cameraMaxFov = 45.0; debrisShapeName = "art/shapes/actors/common/debris_player.dts"; debris = playerDebris; aiAvoidThis = 1; minLookAngle = -1.4; maxLookAngle = 0.9; maxFreelookAngle = 3.0; mass = 120; drag = 1.3; maxdrag = 0.4; density = 1.1; maxDamage = 100; maxEnergy = 60; repairRate = 0.33; energyPerDamagePoint = 75; rechargeRate = 0.256; runForce = 4320; runEnergyDrain = 0; minRunEnergy = 0; maxForwardSpeed = 8; maxBackwardSpeed = 6; maxSideSpeed = 6; crouchForce = 405; maxCrouchForwardSpeed = 4.0; maxCrouchBackwardSpeed = 2.0; maxCrouchSideSpeed = 2.0; maxUnderwaterForwardSpeed = 8.4; maxUnderwaterBackwardSpeed = 7.8; maxUnderwaterSideSpeed = 7.8; jumpForce = "747"; jumpEnergyDrain = 0; minJumpEnergy = 0; jumpDelay = "15"; airControl = 0.3; recoverDelay = 15; recoverRunForceScale = 1.2; minImpactSpeed = "10"; speedDamageScale = 0.4; boundingBox = "1 1 2"; swimBoundingBox = "1 2 2"; pickupRadius = 1; // Damage location details boxNormalHeadPercentage = 0.83; boxNormalTorsoPercentage = 0.49; boxHeadLeftPercentage = 0; boxHeadRightPercentage = 1; boxHeadBackPercentage = 0; boxHeadFrontPercentage = 1; // Foot Prints decalOffset = 0.25; footPuffEmitter = "LightPuffEmitter"; footPuffNumParts = 10; footPuffRadius = "0.25"; dustEmitter = "LightPuffEmitter"; splash = PlayerSplash; splashVelocity = 4.0; splashAngle = 67.0; splashFreqMod = 300.0; splashVelEpsilon = 0.60; bubbleEmitTime = 0.4; splashEmitter[0] = PlayerWakeEmitter; splashEmitter[1] = PlayerFoamEmitter; splashEmitter[2] = PlayerBubbleEmitter; mediumSplashSoundVelocity = 10.0; hardSplashSoundVelocity = 20.0; exitSplashSoundVelocity = 5.0; // Controls over slope of runnable/jumpable surfaces runSurfaceAngle = 38; jumpSurfaceAngle = 80; maxStepHeight = 1.5; //two meters minJumpSpeed = 20; maxJumpSpeed = 30; horizMaxSpeed = 68; horizResistSpeed = 33; horizResistFactor = 0.35; upMaxSpeed = 80; upResistSpeed = 25; upResistFactor = 0.3; footstepSplashHeight = 0.35; //NOTE: some sounds commented out until wav's are available // Footstep Sounds FootSoftSound = FootLightSoftSound; FootHardSound = FootLightHardSound; FootMetalSound = FootLightMetalSound; FootSnowSound = FootLightSnowSound; FootShallowSound = FootLightShallowSplashSound; FootWadingSound = FootLightWadingSound; FootUnderwaterSound = FootLightUnderwaterSound; //FootBubblesSound = FootLightBubblesSound; //movingBubblesSound = ArmorMoveBubblesSound; //waterBreathSound = WaterBreathMaleSound; //impactSoftSound = ImpactLightSoftSound; //impactHardSound = ImpactLightHardSound; //impactMetalSound = ImpactLightMetalSound; //impactSnowSound = ImpactLightSnowSound; //impactWaterEasy = ImpactLightWaterEasySound; //impactWaterMedium = ImpactLightWaterMediumSound; //impactWaterHard = ImpactLightWaterHardSound; groundImpactMinSpeed = "45"; groundImpactShakeFreq = "4.0 4.0 4.0"; groundImpactShakeAmp = "1.0 1.0 1.0"; groundImpactShakeDuration = 0.8; groundImpactShakeFalloff = 10.0; //exitingWater = ExitingWaterLightSound; observeParameters = "0.5 4.5 4.5"; class = "armor"; // Allowable Inventory Items mainWeapon = Rifle; maxInv[Rifle] = 1; maxInv[BulletAmmo] = 1000; maxInv[RocketLauncher] = 0; maxInv[RocketLauncherAmmo] = 0; maxInv[GrenadeLauncher] = 0; maxInv[GrenadeLauncherAmmo] = 0; maxInvRifle = "1"; maxInvBulletAmmo = "1000"; maxInvGrenadeLauncher = "0"; maxInvGrenadeLauncherAmmo = "0"; maxInvRocketLauncher = "0"; maxInvRocketLauncherAmmo = "0"; class = "armor"; cameraMinDist = "0"; DecalData = "PlayerFootprint"; }; datablock PlayerData(SoldierData) { renderFirstPerson = true; className = Armor; shapeFile = "art/shapes/actors/Soldier/soldier_rigged.dae"; cameraMaxDist = 3; computeCRC = false; canObserve = 1; cmdCategory = "Clients"; cameraDefaultFov = 45.0; cameraMinFov = 5.0; cameraMaxFov = 45.0; debrisShapeName = "art/shapes/actors/common/debris_player.dts"; debris = playerDebris; aiAvoidThis = 1; minLookAngle = -1.4; maxLookAngle = 0.9; maxFreelookAngle = 3.0; mass = 120; drag = 1.3; maxdrag = 0.4; density = 1.1; maxDamage = 100; maxEnergy = 60; repairRate = 0.33; energyPerDamagePoint = 75; rechargeRate = 0.256; runForce = 4320; runEnergyDrain = 0; minRunEnergy = 0; maxForwardSpeed = 8; maxBackwardSpeed = 6; maxSideSpeed = 6; crouchForce = 405; maxCrouchForwardSpeed = 4.0; maxCrouchBackwardSpeed = 2.0; maxCrouchSideSpeed = 2.0; maxUnderwaterForwardSpeed = 8.4; maxUnderwaterBackwardSpeed = 7.8; maxUnderwaterSideSpeed = 7.8; jumpForce = "747"; jumpEnergyDrain = 0; minJumpEnergy = 0; jumpDelay = "15"; airControl = 0.3; recoverDelay = 15; recoverRunForceScale = 1.2; minImpactSpeed = "10"; speedDamageScale = 0.4; boundingBox = "1 1 2"; swimBoundingBox = "1 2 2"; pickupRadius = 1; // Damage location details boxNormalHeadPercentage = 0.83; boxNormalTorsoPercentage = 0.49; boxHeadLeftPercentage = 0; boxHeadRightPercentage = 1; boxHeadBackPercentage = 0; boxHeadFrontPercentage = 1; // Foot Prints decalOffset = 0.25; footPuffEmitter = "LightPuffEmitter"; footPuffNumParts = 10; footPuffRadius = "0.25"; dustEmitter = "LightPuffEmitter"; splash = PlayerSplash; splashVelocity = 4.0; splashAngle = 67.0; splashFreqMod = 300.0; splashVelEpsilon = 0.60; bubbleEmitTime = 0.4; splashEmitter[0] = PlayerWakeEmitter; splashEmitter[1] = PlayerFoamEmitter; splashEmitter[2] = PlayerBubbleEmitter; mediumSplashSoundVelocity = 10.0; hardSplashSoundVelocity = 20.0; exitSplashSoundVelocity = 5.0; // Controls over slope of runnable/jumpable surfaces runSurfaceAngle = 38; jumpSurfaceAngle = 80; maxStepHeight = 1.5; //two meters minJumpSpeed = 20; maxJumpSpeed = 30; horizMaxSpeed = 68; horizResistSpeed = 33; horizResistFactor = 0.35; upMaxSpeed = 80; upResistSpeed = 25; upResistFactor = 0.3; footstepSplashHeight = 0.35; //NOTE: some sounds commented out until wav's are available // Footstep Sounds FootSoftSound = FootLightSoftSound; FootHardSound = FootLightHardSound; FootMetalSound = FootLightMetalSound; FootSnowSound = FootLightSnowSound; FootShallowSound = FootLightShallowSplashSound; FootWadingSound = FootLightWadingSound; FootUnderwaterSound = FootLightUnderwaterSound; //FootBubblesSound = FootLightBubblesSound; //movingBubblesSound = ArmorMoveBubblesSound; //waterBreathSound = WaterBreathMaleSound; //impactSoftSound = ImpactLightSoftSound; //impactHardSound = ImpactLightHardSound; //impactMetalSound = ImpactLightMetalSound; //impactSnowSound = ImpactLightSnowSound; //impactWaterEasy = ImpactLightWaterEasySound; //impactWaterMedium = ImpactLightWaterMediumSound; //impactWaterHard = ImpactLightWaterHardSound; groundImpactMinSpeed = "45"; groundImpactShakeFreq = "4.0 4.0 4.0"; groundImpactShakeAmp = "1.0 1.0 1.0"; groundImpactShakeDuration = 0.8; groundImpactShakeFalloff = 10.0; //exitingWater = ExitingWaterLightSound; observeParameters = "0.5 4.5 4.5"; class = "armor"; // Allowable Inventory Items mainWeapon = Rifle; maxInv[Rifle] = 1; maxInv[BulletAmmo] = 1000; maxInv[RocketLauncher] = 0; maxInv[RocketLauncherAmmo] = 0; maxInv[GrenadeLauncher] = 0; maxInv[GrenadeLauncherAmmo] = 0; maxInvRifle = "1"; maxInvBulletAmmo = "1000"; maxInvGrenadeLauncher = "0"; maxInvGrenadeLauncherAmmo = "0"; maxInvRocketLauncher = "0"; maxInvRocketLauncherAmmo = "0"; class = "armor"; cameraMinDist = "0"; DecalData = "PlayerFootprint"; }; datablock PlayerData(GideonData) { renderFirstPerson = true; className = Armor; shapeFile = "art/shapes/actors/Gideon/gideon.dts"; cameraMaxDist = 3; computeCRC = false; canObserve = 1; cmdCategory = "Clients"; cameraDefaultFov = 45.0; cameraMinFov = 5.0; cameraMaxFov = 45.0; debrisShapeName = "art/shapes/actors/common/debris_player.dts"; debris = playerDebris; aiAvoidThis = true; minLookAngle = -1.4; maxLookAngle = 1.4; maxFreelookAngle = 3.0; mass = 100; drag = 1.3; maxdrag = 0.4; density = 1.1; maxDamage = 100; maxEnergy = 60; repairRate = 0.33; energyPerDamagePoint = 75; rechargeRate = 0.256; runForce = 4320; runEnergyDrain = 0; minRunEnergy = 0; maxForwardSpeed = 8; maxBackwardSpeed = 6; maxSideSpeed = 6; crouchForce = 405; maxCrouchForwardSpeed = 4.0; maxCrouchBackwardSpeed = 2.0; maxCrouchSideSpeed = 2.0; maxUnderwaterForwardSpeed = 8.4; maxUnderwaterBackwardSpeed = 7.8; maxUnderwaterSideSpeed = 7.8; jumpForce = 747; jumpEnergyDrain = 0; minJumpEnergy = 0; jumpDelay = 15; airControl = 0.3; recoverDelay = 9; recoverRunForceScale = 1.2; minImpactSpeed = 45; speedDamageScale = 0.4; boundingBox = "1 1 2"; swimBoundingBox = "1 2 2"; pickupRadius = 1; // Damage location details boxNormalHeadPercentage = 0.83; boxNormalTorsoPercentage = 0.49; boxHeadLeftPercentage = 0; boxHeadRightPercentage = 1; boxHeadBackPercentage = 0; boxHeadFrontPercentage = 1; // Foot Prints decalOffset = 0.25; footPuffEmitter = LightPuffEmitter; footPuffNumParts = 10; footPuffRadius = 0.25; dustEmitter = LiftoffDustEmitter; splash = PlayerSplash; splashVelocity = 4.0; splashAngle = 67.0; splashFreqMod = 300.0; splashVelEpsilon = 0.60; bubbleEmitTime = 0.4; splashEmitter[0] = PlayerWakeEmitter; splashEmitter[1] = PlayerFoamEmitter; splashEmitter[2] = PlayerBubbleEmitter; mediumSplashSoundVelocity = 10.0; hardSplashSoundVelocity = 20.0; exitSplashSoundVelocity = 5.0; // Controls over slope of runnable/jumpable surfaces runSurfaceAngle = 38; jumpSurfaceAngle = 80; maxStepHeight = 1.5; //two meters minJumpSpeed = 20; maxJumpSpeed = 30; horizMaxSpeed = 68; horizResistSpeed = 33; horizResistFactor = 0.35; upMaxSpeed = 80; upResistSpeed = 25; upResistFactor = 0.3; footstepSplashHeight = 0.35; //NOTE: some sounds commented out until wav's are available // Footstep Sounds FootSoftSound = FootLightSoftSound; FootHardSound = FootLightHardSound; FootMetalSound = FootLightMetalSound; FootSnowSound = FootLightSnowSound; FootShallowSound = FootLightShallowSplashSound; FootWadingSound = FootLightWadingSound; FootUnderwaterSound = FootLightUnderwaterSound; //FootBubblesSound = FootLightBubblesSound; //movingBubblesSound = ArmorMoveBubblesSound; //waterBreathSound = WaterBreathMaleSound; //impactSoftSound = ImpactLightSoftSound; //impactHardSound = ImpactLightHardSound; //impactMetalSound = ImpactLightMetalSound; //impactSnowSound = ImpactLightSnowSound; //impactWaterEasy = ImpactLightWaterEasySound; //impactWaterMedium = ImpactLightWaterMediumSound; //impactWaterHard = ImpactLightWaterHardSound; groundImpactMinSpeed = 10.0; groundImpactShakeFreq = "4.0 4.0 4.0"; groundImpactShakeAmp = "1.0 1.0 1.0"; groundImpactShakeDuration = 0.8; groundImpactShakeFalloff = 10.0; //exitingWater = ExitingWaterLightSound; observeParameters = "0.5 4.5 4.5"; // Allowable Inventory Items mainWeapon = GrenadeLauncher; maxInv[Rifle] = 0; maxInv[BulletAmmo] = 0; maxInv[RocketLauncher] = 0; maxInv[RocketLauncherAmmo] = 0; maxInv[GrenadeLauncher] = 1; maxInv[GrenadeLauncherAmmo] = 20; maxInvRifle = "0"; maxInvBulletAmmo = "0"; maxInvGrenadeLauncher = "1"; maxInvGrenadeLauncherAmmo = "20"; maxInvRocketLauncher = "0"; maxInvRocketLauncherAmmo = "0"; class = "armor"; };
namespace System.Globalization { /// <summary> /// Provides culture-specific information about the format of date and time values. /// </summary> [Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)] [Bridge.External] [Bridge.Reflectable] public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable, Bridge.IBridgeClass { /// <summary> /// Initializes a new writable instance of the DateTimeFormatInfo class that is culture-independent (invariant). /// </summary> public extern DateTimeFormatInfo(); /// <summary> /// Gets the default read-only DateTimeFormatInfo object that is culture-independent (invariant). /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public static extern DateTimeFormatInfo InvariantInfo { get; } /// <summary> /// Gets or sets the string designator for hours that are "ante meridiem" (before noon). /// </summary> [Bridge.Name("amDesignator")] public extern string AMDesignator { get; set; } /// <summary> /// Gets or sets the string designator for hours that are "post meridiem" (after noon). /// </summary> [Bridge.Name("pmDesignator")] public extern string PMDesignator { get; set; } /// <summary> /// Gets or sets the string that separates the components of a date, that is, the year, month, and day. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string DateSeparator { get; set; } /// <summary> /// Gets or sets the string that separates the components of time, that is, the hour, minutes, and seconds. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string TimeSeparator { get; set; } /// <summary> /// Gets the custom format string for a universal, sortable date and time string. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string UniversalSortableDateTimePattern { get; set; } /// <summary> /// Gets the custom format string for a sortable date and time value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string SortableDateTimePattern { get; set; } /// <summary> /// Gets or sets the custom format string for a long date and long time value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string FullDateTimePattern { get; set; } /// <summary> /// Gets or sets the custom format string for a long date value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string LongDatePattern { get; set; } /// <summary> /// Gets or sets the custom format string for a short date value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string ShortDatePattern { get; set; } /// <summary> /// Gets or sets the custom format string for a long time value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string LongTimePattern { get; set; } /// <summary> /// Gets or sets the custom format string for a short time value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string ShortTimePattern { get; set; } [Bridge.Convention(Bridge.Notation.CamelCase)] public extern DayOfWeek FirstDayOfWeek { get; set; } /// <summary> /// Gets or sets a one-dimensional string array that contains the culture-specific full names of the days of the week. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] DayNames { get; set; } /// <summary> /// Gets or sets a one-dimensional array of type String containing the culture-specific abbreviated names of the days of the week. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] AbbreviatedDayNames { get; set; } /// <summary> /// Gets or sets a string array of the shortest unique abbreviated day names associated with the current DateTimeFormatInfo object. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] ShortestDayNames { get; set; } /// <summary> /// Gets or sets a one-dimensional array of type String containing the culture-specific full names of the months. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] MonthNames { get; set; } [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] MonthGenitiveNames { get; set; } /// <summary> /// Gets or sets a one-dimensional string array that contains the culture-specific abbreviated names of the months. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] AbbreviatedMonthNames { get; set; } /// <summary> /// Gets or sets a string array of abbreviated month names associated with the current DateTimeFormatInfo object. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string[] AbbreviatedMonthGenitiveNames { get; set; } /// <summary> /// Gets or sets the custom format string for a month and day value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string MonthDayPattern { get; set; } /// <summary> /// Gets the custom format string for a time value that is based on the Internet Engineering Task Force (IETF) Request for Comments (RFC) 1123 specification. /// </summary> [Bridge.Name("rfc1123Pattern")] public extern string RFC1123Pattern { get; set; } /// <summary> /// Gets or sets the custom format string for a year and month value. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string YearMonthPattern { get; set; } [Bridge.Convention(Bridge.Notation.CamelCase)] public extern string RoundtripFormat { get; set; } /// <summary> /// Returns an object of the specified type that provides a date and time formatting service. /// </summary> /// <param name="formatType">The type of the required formatting service.</param> /// <returns>The current object, if formatType is the same as the type of the current DateTimeFormatInfo; otherwise, null.</returns> public extern object GetFormat(Type formatType); /// <summary> /// Creates a shallow copy of the DateTimeFormatInfo. /// </summary> /// <returns>A new DateTimeFormatInfo object copied from the original DateTimeFormatInfo.</returns> public extern object Clone(); /// <summary> /// Gets a read-only DateTimeFormatInfo object that formats values based on the current culture. /// </summary> [Bridge.Convention(Bridge.Notation.CamelCase)] public static extern DateTimeFormatInfo CurrentInfo { get; } /// <summary> /// Returns the culture-specific abbreviated name of the specified day of the week based on the culture associated with the current DateTimeFormatInfo object. /// </summary> /// <param name="dayofweek">A System.DayOfWeek value.</param> /// <returns>The culture-specific abbreviated name of the day of the week represented by dayofweek.</returns> public extern string GetAbbreviatedDayName(DayOfWeek dayofweek); /// <summary> /// Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object. /// </summary> /// <param name="month">An integer from 1 through 13 representing the name of the month to retrieve.</param> /// <returns>The culture-specific abbreviated name of the month represented by month.</returns> public extern string GetAbbreviatedMonthName(int month); /// <summary> /// Returns all the standard patterns in which date and time values can be formatted. /// </summary> /// <returns>An array that contains the standard patterns in which date and time values can be formatted.</returns> public extern string[] GetAllDateTimePatterns(); /// <summary> /// Returns all the patterns in which date and time values can be formatted using the specified standard format string. /// </summary> /// <param name="format">A standard format string.</param> /// <returns>An array containing the standard patterns in which date and time values can be formatted using the specified format string.</returns> public extern string[] GetAllDateTimePatterns(char format); /// <summary> /// Returns the culture-specific full name of the specified day of the week based on the culture associated with the current DateTimeFormatInfo object. /// </summary> /// <param name="dayofweek">A System.DayOfWeek value.</param> /// <returns>The culture-specific full name of the day of the week represented by dayofweek.</returns> public extern string GetDayName(DayOfWeek dayofweek); /// <summary> /// Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object. /// </summary> /// <param name="month">An integer from 1 through 13 representing the name of the month to retrieve.</param> /// <returns>The culture-specific full name of the month represented by month.</returns> public extern string GetMonthName(int month); /// <summary> /// Obtains the shortest abbreviated day name for a specified day of the week associated with the current DateTimeFormatInfo object. /// </summary> /// <param name="dayOfWeek">One of the DayOfWeek values.</param> /// <returns>The abbreviated name of the week that corresponds to the dayOfWeek parameter.</returns> public extern string GetShortestDayName(DayOfWeek dayOfWeek); } }
// 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.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal sealed class CachedSystemStoreProvider : IStorePal { // These intervals are mostly arbitrary. // Prior to this refreshing cache the system collections were read just once per process, on the // assumption that system trust changes would happen before the process start (or would come // followed by a reboot for a kernel update, etc). // Customers requested something more often than "never" and 5 minutes seems like a reasonable // balance. // // Note that on Ubuntu the LastWrite test always fails, because the system default for SSL_CERT_DIR // is a symlink, so the LastWrite value is always just when the symlink was created (and Ubuntu does // not provide the single-file version at SSL_CERT_FILE, so the file update does not trigger) -- // meaning the "assume invalid" interval is Ubuntu's only refresh. private static readonly TimeSpan s_lastWriteRecheckInterval = TimeSpan.FromSeconds(5); private static readonly TimeSpan s_assumeInvalidInterval = TimeSpan.FromMinutes(5); private static readonly Stopwatch s_recheckStopwatch = new Stopwatch(); private static readonly DirectoryInfo s_rootStoreDirectoryInfo = SafeOpenRootDirectoryInfo(); private static readonly FileInfo s_rootStoreFileInfo = SafeOpenRootFileInfo(); // Use non-Value-Tuple so that it's an atomic update. private static Tuple<SafeX509StackHandle, SafeX509StackHandle> s_nativeCollections; private static DateTime s_directoryCertsLastWrite; private static DateTime s_fileCertsLastWrite; private readonly bool _isRoot; private CachedSystemStoreProvider(bool isRoot) { _isRoot = isRoot; } internal static CachedSystemStoreProvider MachineRoot { get; } = new CachedSystemStoreProvider(true); internal static CachedSystemStoreProvider MachineIntermediate { get; } = new CachedSystemStoreProvider(false); public void Dispose() { // No-op } public void CloneTo(X509Certificate2Collection collection) { Tuple<SafeX509StackHandle, SafeX509StackHandle> nativeColls = GetCollections(); SafeX509StackHandle nativeColl = _isRoot ? nativeColls.Item1 : nativeColls.Item2; int count = Interop.Crypto.GetX509StackFieldCount(nativeColl); for (int i = 0; i < count; i++) { X509Certificate2 clone = new X509Certificate2(Interop.Crypto.GetX509StackField(nativeColl, i)); collection.Add(clone); } } internal static void GetNativeCollections(out SafeX509StackHandle root, out SafeX509StackHandle intermediate) { Tuple<SafeX509StackHandle, SafeX509StackHandle> nativeColls = GetCollections(); root = nativeColls.Item1; intermediate = nativeColls.Item2; } public void Add(ICertificatePal cert) { // These stores can only be opened in ReadOnly mode. throw new InvalidOperationException(); } public void Remove(ICertificatePal cert) { // These stores can only be opened in ReadOnly mode. throw new InvalidOperationException(); } public SafeHandle SafeHandle => null; private static Tuple<SafeX509StackHandle, SafeX509StackHandle> GetCollections() { TimeSpan elapsed = s_recheckStopwatch.Elapsed; Tuple<SafeX509StackHandle, SafeX509StackHandle> ret = s_nativeCollections; if (ret == null || elapsed > s_lastWriteRecheckInterval) { lock (s_recheckStopwatch) { FileInfo fileInfo = s_rootStoreFileInfo; DirectoryInfo dirInfo = s_rootStoreDirectoryInfo; fileInfo?.Refresh(); dirInfo?.Refresh(); if (ret == null || elapsed > s_assumeInvalidInterval || (fileInfo != null && fileInfo.Exists && fileInfo.LastWriteTimeUtc != s_fileCertsLastWrite) || (dirInfo != null && dirInfo.Exists && dirInfo.LastWriteTimeUtc != s_directoryCertsLastWrite)) { ret = LoadMachineStores(dirInfo, fileInfo); } } } Debug.Assert(ret != null); return ret; } private static Tuple<SafeX509StackHandle, SafeX509StackHandle> LoadMachineStores( DirectoryInfo rootStorePath, FileInfo rootStoreFile) { Debug.Assert( Monitor.IsEntered(s_recheckStopwatch), "LoadMachineStores assumes a lock(s_recheckStopwatch)"); SafeX509StackHandle rootStore = Interop.Crypto.NewX509Stack(); Interop.Crypto.CheckValidOpenSslHandle(rootStore); SafeX509StackHandle intermedStore = Interop.Crypto.NewX509Stack(); Interop.Crypto.CheckValidOpenSslHandle(intermedStore); DateTime newFileTime = default; DateTime newDirTime = default; var uniqueRootCerts = new HashSet<X509Certificate2>(); var uniqueIntermediateCerts = new HashSet<X509Certificate2>(); if (rootStoreFile != null && rootStoreFile.Exists) { newFileTime = rootStoreFile.LastWriteTimeUtc; ProcessFile(rootStoreFile); } if (rootStorePath != null && rootStorePath.Exists) { newDirTime = rootStorePath.LastWriteTimeUtc; foreach (FileInfo file in rootStorePath.EnumerateFiles()) { ProcessFile(file); } } void ProcessFile(FileInfo file) { using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb")) { // The handle may be invalid, for example when we don't have read permission for the file. if (fileBio.IsInvalid) { Interop.Crypto.ErrClearError(); return; } // Some distros ship with two variants of the same certificate. // One is the regular format ('BEGIN CERTIFICATE') and the other // contains additional AUX-data ('BEGIN TRUSTED CERTIFICATE'). // The additional data contains the appropriate usage (e.g. emailProtection, serverAuth, ...). // Because corefx doesn't validate for a specific usage, derived certificates are rejected. // For now, we skip the certificates with AUX data and use the regular certificates. ICertificatePal pal; while (OpenSslX509CertificateReader.TryReadX509PemNoAux(fileBio, out pal) || OpenSslX509CertificateReader.TryReadX509Der(fileBio, out pal)) { X509Certificate2 cert = new X509Certificate2(pal); // The HashSets are just used for uniqueness filters, they do not survive this method. if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer)) { if (uniqueRootCerts.Add(cert)) { using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(pal.Handle)) { if (!Interop.Crypto.PushX509StackField(rootStore, tmp)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // The ownership has been transferred to the stack tmp.SetHandleAsInvalid(); } continue; } } else { if (uniqueIntermediateCerts.Add(cert)) { using (SafeX509Handle tmp = Interop.Crypto.X509UpRef(pal.Handle)) { if (!Interop.Crypto.PushX509StackField(intermedStore, tmp)) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } // The ownership has been transferred to the stack tmp.SetHandleAsInvalid(); } continue; } } // There's a good chance we'll encounter duplicates on systems that have both one-cert-per-file // and one-big-file trusted certificate stores. Anything that wasn't unique will end up here. cert.Dispose(); } } } foreach (X509Certificate2 cert in uniqueRootCerts) { cert.Dispose(); } foreach (X509Certificate2 cert in uniqueIntermediateCerts) { cert.Dispose(); } Tuple<SafeX509StackHandle, SafeX509StackHandle> newCollections = Tuple.Create(rootStore, intermedStore); Debug.Assert( Monitor.IsEntered(s_recheckStopwatch), "LoadMachineStores assumes a lock(s_recheckStopwatch)"); // The existing collections are not Disposed here, intentionally. // They could be in the gap between when they are returned from this method and not yet used // in a P/Invoke, which would result in exceptions being thrown. // In order to maintain "finalization-free" the GetNativeCollections method would need to // DangerousAddRef, and the callers would need to DangerousRelease, adding more interlocked operations // on every call. Volatile.Write(ref s_nativeCollections, newCollections); s_directoryCertsLastWrite = newDirTime; s_fileCertsLastWrite = newFileTime; s_recheckStopwatch.Restart(); return newCollections; } private static FileInfo SafeOpenRootFileInfo() { string rootFile = Interop.Crypto.GetX509RootStoreFile(); if (!string.IsNullOrEmpty(rootFile)) { try { return new FileInfo(rootFile); } catch (ArgumentException) { // If SSL_CERT_FILE is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } } return null; } private static DirectoryInfo SafeOpenRootDirectoryInfo() { string rootDirectory = Interop.Crypto.GetX509RootStorePath(); if (!string.IsNullOrEmpty(rootDirectory)) { try { return new DirectoryInfo(rootDirectory); } catch (ArgumentException) { // If SSL_CERT_DIR is set to the empty string, or anything else which gives // "The path is not of a legal form", then the GetX509RootStoreFile value is ignored. } } return null; } } }
// TODO: // DispatcherObject returned by BeginInvoke must allow: // * Waiting until delegate is invoked. // See: BeginInvoke documentation for details // // Implement the "Invoke" methods, they are currently not working. // // Add support for disabling the dispatcher and resuming it. // Add support for Waiting for new tasks to be pushed, so that we dont busy loop. // Add support for aborting an operation (emit the hook.operationaborted too) // // Very confusing information about Shutdown: it states that shutdown is // not over, until all events are unwinded, and also states that all events // are aborted at that point. See 'Dispatcher.InvokeShutdown' docs, // // Testing reveals that // -> InvokeShutdown() stops processing, even if events are available, // there is no "unwinding" of events, even of higher priority events, // they are just ignored. // // The documentation for the Dispatcher family is poorly written, complete // sections are cut-and-pasted that add no value and the important pieces // like (what is a frame) is not on the APIs, but scattered everywhere else // // ----------------------------------------------------------------------- // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2006 Novell, Inc. (http://www.novell.com) // // Authors: // Miguel de Icaza (miguel@novell.com) // using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Security; using System.Threading; namespace System.Windows.Threading { [Flags] internal enum Flags { ShutdownStarted = 1, Shutdown = 2, Disabled = 4 } public sealed class Dispatcher { static Dictionary<Thread, Dispatcher> dispatchers = new Dictionary<Thread, Dispatcher> (); static object olock = new object (); static DispatcherFrame main_execution_frame = new DispatcherFrame (); const int TOP_PRIO = (int)DispatcherPriority.Send; Thread base_thread; PokableQueue [] priority_queues = new PokableQueue [TOP_PRIO+1]; Flags flags; int queue_bits; // // Used to notify the dispatcher thread that new data is available // EventWaitHandle wait; // // The hooks for this Dispatcher // DispatcherHooks hooks; // // The current DispatcherFrame active in a given Dispatcher, we use this to // keep a linked list of all active frames, so we can "ExitAll" frames when // requested DispatcherFrame current_frame; Dispatcher (Thread t) { base_thread = t; for (int i = 1; i <= (int) DispatcherPriority.Send; i++) priority_queues [i] = new PokableQueue (); wait = new EventWaitHandle (false, EventResetMode.AutoReset); hooks = new DispatcherHooks (this); } [EditorBrowsable (EditorBrowsableState.Never)] public bool CheckAccess () { return Thread.CurrentThread == base_thread; } [EditorBrowsable (EditorBrowsableState.Never)] public void VerifyAccess () { if (Thread.CurrentThread != base_thread) throw new InvalidOperationException ("Invoked from a different thread"); } public static void ValidatePriority (DispatcherPriority priority, string parameterName) { if (priority < DispatcherPriority.Inactive || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException (parameterName); } public DispatcherOperation BeginInvoke (Delegate method, object[] args) { throw new NotImplementedException (); } public DispatcherOperation BeginInvoke (Delegate method, DispatcherPriority priority, object[] args) { throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public DispatcherOperation BeginInvoke (DispatcherPriority priority, Delegate method) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); DispatcherOperation op = new DispatcherOperation (this, priority, method); Queue (priority, op); return op; } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public DispatcherOperation BeginInvoke (DispatcherPriority priority, Delegate method, object arg) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); DispatcherOperation op = new DispatcherOperation (this, priority, method, arg); Queue (priority, op); return op; } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public DispatcherOperation BeginInvoke (DispatcherPriority priority, Delegate method, object arg, params object [] args) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); DispatcherOperation op = new DispatcherOperation (this, priority, method, arg, args); Queue (priority, op); return op; } public object Invoke (Delegate method, object[] args) { throw new NotImplementedException (); } public object Invoke (Delegate method, TimeSpan timeout, object[] args) { throw new NotImplementedException (); } public object Invoke (Delegate method, TimeSpan timeout, DispatcherPriority priority, object[] args) { throw new NotImplementedException (); } public object Invoke (Delegate method, DispatcherPriority priority, object[] args) { throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, Delegate method) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); DispatcherOperation op = new DispatcherOperation (this, priority, method); Queue (priority, op); PushFrame (new DispatcherFrame ()); throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, Delegate method, object arg) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); Queue (priority, new DispatcherOperation (this, priority, method, arg)); throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, Delegate method, object arg, params object [] args) { if (priority < 0 || priority > DispatcherPriority.Send) throw new InvalidEnumArgumentException ("priority"); if (priority == DispatcherPriority.Inactive) throw new ArgumentException ("priority can not be inactive", "priority"); if (method == null) throw new ArgumentNullException ("method"); Queue (priority, new DispatcherOperation (this, priority, method, arg, args)); throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, TimeSpan timeout, Delegate method) { throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, TimeSpan timeout, Delegate method, object arg) { throw new NotImplementedException (); } [Browsable (false)] [EditorBrowsable (EditorBrowsableState.Never)] public object Invoke (DispatcherPriority priority, TimeSpan timeout, Delegate method, object arg, params object [] args) { throw new NotImplementedException (); } void Queue (DispatcherPriority priority, DispatcherOperation x) { int p = ((int) priority); PokableQueue q = priority_queues [p]; lock (q){ int flag = 1 << p; q.Enqueue (x); queue_bits |= flag; } hooks.EmitOperationPosted (x); if (Thread.CurrentThread != base_thread) wait.Set (); } internal void Reprioritize (DispatcherOperation op, DispatcherPriority oldpriority) { int oldp = (int) oldpriority; PokableQueue q = priority_queues [oldp]; lock (q){ q.Remove (op); } Queue (op.Priority, op); hooks.EmitOperationPriorityChanged (op); } public static Dispatcher CurrentDispatcher { get { lock (olock){ Thread t = Thread.CurrentThread; Dispatcher dis = FromThread (t); if (dis != null) return dis; dis = new Dispatcher (t); dispatchers [t] = dis; return dis; } } } public static Dispatcher FromThread (Thread thread) { Dispatcher dis; if (dispatchers.TryGetValue (thread, out dis)) return dis; return null; } public Thread Thread { get { return base_thread; } } [SecurityCritical] public static void Run () { PushFrame (main_execution_frame); } [SecurityCritical] public static void PushFrame (DispatcherFrame frame) { if (frame == null) throw new ArgumentNullException ("frame"); Dispatcher dis = CurrentDispatcher; if (dis.HasShutdownFinished) throw new InvalidOperationException ("The Dispatcher has shut down"); if (frame.dispatcher != null) throw new InvalidOperationException ("Frame is already running on a different dispatcher"); if ((dis.flags & Flags.Disabled) != 0) throw new InvalidOperationException ("Dispatcher processing has been disabled"); frame.ParentFrame = dis.current_frame; dis.current_frame = frame; frame.dispatcher = dis; dis.RunFrame (frame); } void PerformShutdown () { EventHandler h; h = ShutdownStarted; if (h != null) h (this, new EventArgs ()); flags |= Flags.Shutdown; h = ShutdownFinished; if (h != null) h (this, new EventArgs ()); priority_queues = null; wait = null; } void RunFrame (DispatcherFrame frame) { do { while (queue_bits != 0){ for (int i = TOP_PRIO; i > 0 && queue_bits != 0; i--){ int current_bit = queue_bits & (1 << i); if (current_bit != 0){ PokableQueue q = priority_queues [i]; do { DispatcherOperation task; lock (q){ task = (DispatcherOperation) q.Dequeue (); } task.Invoke (); // // call hooks. // if (task.Status == DispatcherOperationStatus.Aborted) hooks.EmitOperationAborted (task); else hooks.EmitOperationCompleted (task); if (!frame.Continue) return; if (HasShutdownStarted){ PerformShutdown (); return; } // if we are done with this queue, leave. lock (q){ if (q.Count == 0){ queue_bits &= ~(1 << i); break; } } // // If a higher-priority task comes in, go do that // if (current_bit < (queue_bits & ~current_bit)) break; } while (true); } } } hooks.EmitInactive (); wait.WaitOne (); wait.Reset (); } while (frame.Continue); } [EditorBrowsable (EditorBrowsableState.Advanced)] public DispatcherHooks Hooks { [SecurityCritical] get { throw new NotImplementedException (); } } public bool HasShutdownStarted { get { return (flags & Flags.ShutdownStarted) != 0; } } public bool HasShutdownFinished { get { return (flags & Flags.Shutdown) != 0; } } // // Do no work here, so that any events are thrown on the owning thread // [SecurityCritical] public void InvokeShutdown () { flags |= Flags.ShutdownStarted; } [SecurityCritical] public void BeginInvokeShutdown (DispatcherPriority priority) { throw new NotImplementedException (); } [SecurityCritical] public static void ExitAllFrames () { Dispatcher dis = CurrentDispatcher; for (DispatcherFrame frame = dis.current_frame; frame != null; frame = frame.ParentFrame){ if (frame.exit_on_request) frame.Continue = false; else { // // Stop unwinding the frames at the first frame that is // long running break; } } } public DispatcherProcessingDisabled DisableProcessing () { throw new NotImplementedException (); } public event EventHandler ShutdownStarted; public event EventHandler ShutdownFinished; public event DispatcherUnhandledExceptionEventHandler UnhandledException; public event DispatcherUnhandledExceptionFilterEventHandler UnhandledExceptionFilter; } internal class PokableQueue { const int initial_capacity = 32; int size, head, tail; object [] array; internal PokableQueue (int capacity) { array = new object [capacity]; } internal PokableQueue () : this (initial_capacity) { } public void Enqueue (object obj) { if (size == array.Length) Grow (); array[tail] = obj; tail = (tail+1) % array.Length; size++; } public object Dequeue () { if (size < 1) throw new InvalidOperationException (); object result = array[head]; array [head] = null; head = (head + 1) % array.Length; size--; return result; } void Grow () { int newc = array.Length * 2; object[] new_contents = new object[newc]; array.CopyTo (new_contents, 0); array = new_contents; head = 0; tail = head + size; } public int Count { get { return size; } } public void Remove (object obj) { for (int i = 0; i < size; i++){ if (array [(head+i) % array.Length] == obj){ for (int j = i; j < size-i; j++) array [(head +j) % array.Length] = array [(head+j+1) % array.Length]; size--; if (size < 0) size = array.Length-1; tail--; } } } } }
// // CryptoConvert.cs - Crypto Convertion Routines // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Security.Cryptography; #if !(SILVERLIGHT || READ_ONLY) namespace Mono.Security.Cryptography { static class CryptoConvert { static private int ToInt32LE (byte [] bytes, int offset) { return (bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]; } static private uint ToUInt32LE (byte [] bytes, int offset) { return (uint)((bytes [offset+3] << 24) | (bytes [offset+2] << 16) | (bytes [offset+1] << 8) | bytes [offset]); } static private byte[] Trim (byte[] array) { for (int i=0; i < array.Length; i++) { if (array [i] != 0x00) { byte[] result = new byte [array.Length - i]; Buffer.BlockCopy (array, i, result, 0, result.Length); return result; } } return null; } static RSA FromCapiPrivateKeyBlob (byte[] blob, int offset) { RSAParameters rsap = new RSAParameters (); try { if ((blob [offset] != 0x07) || // PRIVATEKEYBLOB (0x07) (blob [offset+1] != 0x02) || // Version (0x02) (blob [offset+2] != 0x00) || // Reserved (word) (blob [offset+3] != 0x00) || (ToUInt32LE (blob, offset+8) != 0x32415352)) // DWORD magic = RSA2 throw new CryptographicException ("Invalid blob header"); // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE (blob, offset+12); // DWORD public exponent byte[] exp = new byte [4]; Buffer.BlockCopy (blob, offset+16, exp, 0, 4); Array.Reverse (exp); rsap.Exponent = Trim (exp); int pos = offset+20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte [byteLen]; Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse (rsap.Modulus); pos += byteLen; // BYTE prime1[rsapubkey.bitlen/16]; int byteHalfLen = (byteLen >> 1); rsap.P = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.P, 0, byteHalfLen); Array.Reverse (rsap.P); pos += byteHalfLen; // BYTE prime2[rsapubkey.bitlen/16]; rsap.Q = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.Q, 0, byteHalfLen); Array.Reverse (rsap.Q); pos += byteHalfLen; // BYTE exponent1[rsapubkey.bitlen/16]; rsap.DP = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.DP, 0, byteHalfLen); Array.Reverse (rsap.DP); pos += byteHalfLen; // BYTE exponent2[rsapubkey.bitlen/16]; rsap.DQ = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.DQ, 0, byteHalfLen); Array.Reverse (rsap.DQ); pos += byteHalfLen; // BYTE coefficient[rsapubkey.bitlen/16]; rsap.InverseQ = new byte [byteHalfLen]; Buffer.BlockCopy (blob, pos, rsap.InverseQ, 0, byteHalfLen); Array.Reverse (rsap.InverseQ); pos += byteHalfLen; // ok, this is hackish but CryptoAPI support it so... // note: only works because CRT is used by default // http://bugzilla.ximian.com/show_bug.cgi?id=57941 rsap.D = new byte [byteLen]; // must be allocated if (pos + byteLen + offset <= blob.Length) { // BYTE privateExponent[rsapubkey.bitlen/8]; Buffer.BlockCopy (blob, pos, rsap.D, 0, byteLen); Array.Reverse (rsap.D); } } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } RSA rsa = null; try { rsa = RSA.Create (); rsa.ImportParameters (rsap); } catch (CryptographicException) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 bool throws = false; try { CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider (csp); rsa.ImportParameters (rsap); } catch { throws = true; } if (throws) { // rethrow original, not the latter, exception if this fails throw; } } return rsa; } static RSA FromCapiPublicKeyBlob (byte[] blob, int offset) { try { if ((blob [offset] != 0x06) || // PUBLICKEYBLOB (0x06) (blob [offset+1] != 0x02) || // Version (0x02) (blob [offset+2] != 0x00) || // Reserved (word) (blob [offset+3] != 0x00) || (ToUInt32LE (blob, offset+8) != 0x31415352)) // DWORD magic = RSA1 throw new CryptographicException ("Invalid blob header"); // ALGID (CALG_RSA_SIGN, CALG_RSA_KEYX, ...) // int algId = ToInt32LE (blob, offset+4); // DWORD bitlen int bitLen = ToInt32LE (blob, offset+12); // DWORD public exponent RSAParameters rsap = new RSAParameters (); rsap.Exponent = new byte [3]; rsap.Exponent [0] = blob [offset+18]; rsap.Exponent [1] = blob [offset+17]; rsap.Exponent [2] = blob [offset+16]; int pos = offset+20; // BYTE modulus[rsapubkey.bitlen/8]; int byteLen = (bitLen >> 3); rsap.Modulus = new byte [byteLen]; Buffer.BlockCopy (blob, pos, rsap.Modulus, 0, byteLen); Array.Reverse (rsap.Modulus); RSA rsa = null; try { rsa = RSA.Create (); rsa.ImportParameters (rsap); } catch (CryptographicException) { // this may cause problem when this code is run under // the SYSTEM identity on Windows (e.g. ASP.NET). See // http://bugzilla.ximian.com/show_bug.cgi?id=77559 CspParameters csp = new CspParameters (); csp.Flags = CspProviderFlags.UseMachineKeyStore; rsa = new RSACryptoServiceProvider (csp); rsa.ImportParameters (rsap); } return rsa; } catch (Exception e) { throw new CryptographicException ("Invalid blob.", e); } } // PRIVATEKEYBLOB // PUBLICKEYBLOB static public RSA FromCapiKeyBlob (byte[] blob) { return FromCapiKeyBlob (blob, 0); } static public RSA FromCapiKeyBlob (byte[] blob, int offset) { if (blob == null) throw new ArgumentNullException ("blob"); if (offset >= blob.Length) throw new ArgumentException ("blob is too small."); switch (blob [offset]) { case 0x00: // this could be a public key inside an header // like "sn -e" would produce if (blob [offset + 12] == 0x06) { return FromCapiPublicKeyBlob (blob, offset + 12); } break; case 0x06: return FromCapiPublicKeyBlob (blob, offset); case 0x07: return FromCapiPrivateKeyBlob (blob, offset); } throw new CryptographicException ("Unknown blob format."); } } } #endif
#region Copyright notice and license // Copyright 2015 gRPC authors. // // 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 using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers. /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking /// a remote call so in general you should reuse a single channel for as many calls as possible. /// </summary> public class Channel { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>(); readonly object myLock = new object(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource(); readonly string target; readonly GrpcEnvironment environment; readonly CompletionQueueSafeHandle completionQueue; readonly ChannelSafeHandle handle; readonly Dictionary<string, ChannelOption> options; readonly Task connectivityWatcherTask; bool shutdownRequested; /// <summary> /// Creates a channel that connects to a specific host. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel. /// </summary> /// <param name="target">Target of the channel.</param> /// <param name="credentials">Credentials to secure the channel.</param> public Channel(string target, ChannelCredentials credentials) : this(target, credentials, null) { } /// <summary> /// Creates a channel that connects to a specific host. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel. /// </summary> /// <param name="target">Target of the channel.</param> /// <param name="credentials">Credentials to secure the channel.</param> /// <param name="options">Channel options.</param> public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options) { this.target = GrpcPreconditions.CheckNotNull(target, "target"); this.options = CreateOptionsDictionary(options); EnsureUserAgentChannelOption(this.options); this.environment = GrpcEnvironment.AddRef(); this.completionQueue = this.environment.PickCompletionQueue(); using (var nativeCredentials = credentials.ToNativeCredentials()) using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values)) { if (nativeCredentials != null) { this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs); } else { this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs); } } // TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822. // Remove once retries are supported in C core this.connectivityWatcherTask = RunConnectivityWatcherAsync(); GrpcEnvironment.RegisterChannel(this); } /// <summary> /// Creates a channel that connects to a specific host and port. /// </summary> /// <param name="host">The name or IP address of the host.</param> /// <param name="port">The port.</param> /// <param name="credentials">Credentials to secure the channel.</param> public Channel(string host, int port, ChannelCredentials credentials) : this(host, port, credentials, null) { } /// <summary> /// Creates a channel that connects to a specific host and port. /// </summary> /// <param name="host">The name or IP address of the host.</param> /// <param name="port">The port.</param> /// <param name="credentials">Credentials to secure the channel.</param> /// <param name="options">Channel options.</param> public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) : this(string.Format("{0}:{1}", host, port), credentials, options) { } /// <summary> /// Gets current connectivity state of this channel. /// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned. /// </summary> public ChannelState State { get { return GetConnectivityState(false); } } // cached handler for watch connectivity state static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) => { var tcs = (TaskCompletionSource<object>) state; if (success) { tcs.SetResult(null); } else { tcs.SetCanceled(); } }; /// <summary> /// Returned tasks completes once channel state has become different from /// given lastObservedState. /// If deadline is reached or and error occurs, returned task is cancelled. /// </summary> public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null) { GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown, "Shutdown is a terminal state. No further state changes can occur."); var tcs = new TaskCompletionSource<object>(); var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture; lock (myLock) { // pass "tcs" as "state" for WatchConnectivityStateHandler. handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs); } return tcs.Task; } /// <summary>Resolved address of the remote endpoint in URI format.</summary> public string ResolvedTarget { get { return handle.GetTarget(); } } /// <summary>The original target used to create the channel.</summary> public string Target { get { return this.target; } } /// <summary> /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked. /// </summary> public CancellationToken ShutdownToken { get { return this.shutdownTokenSource.Token; } } /// <summary> /// Allows explicitly requesting channel to connect without starting an RPC. /// Returned task completes once state Ready was seen. If the deadline is reached, /// or channel enters the Shutdown state, the task is cancelled. /// There is no need to call this explicitly unless your use case requires that. /// Starting an RPC on a new channel will request connection implicitly. /// </summary> /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param> public async Task ConnectAsync(DateTime? deadline = null) { var currentState = GetConnectivityState(true); while (currentState != ChannelState.Ready) { if (currentState == ChannelState.Shutdown) { throw new OperationCanceledException("Channel has reached Shutdown state."); } await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false); currentState = GetConnectivityState(false); } } /// <summary> /// Shuts down the channel cleanly. It is strongly recommended to shutdown /// all previously created channels before exiting from the process. /// </summary> /// <remarks> /// This method doesn't wait for all calls on this channel to finish (nor does /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure /// all the calls on this channel have finished (successfully or with an error) /// before shutting down the channel to ensure channel shutdown won't impact /// the outcome of those remote calls. /// </remarks> public async Task ShutdownAsync() { lock (myLock) { GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } GrpcEnvironment.UnregisterChannel(this); shutdownTokenSource.Cancel(); var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount); } lock (myLock) { handle.Dispose(); } await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false); } internal ChannelSafeHandle Handle { get { return this.handle; } } internal GrpcEnvironment Environment { get { return this.environment; } } internal CompletionQueueSafeHandle CompletionQueue { get { return this.completionQueue; } } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } private ChannelState GetConnectivityState(bool tryToConnect) { try { lock (myLock) { return handle.CheckConnectivityState(tryToConnect); } } catch (ObjectDisposedException) { return ChannelState.Shutdown; } } /// <summary> /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822 /// </summary> private async Task RunConnectivityWatcherAsync() { try { var lastState = State; while (lastState != ChannelState.Shutdown) { lock (myLock) { if (shutdownRequested) { break; } } try { await WaitForStateChangedAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false); } catch (TaskCanceledException) { // ignore timeout } lastState = State; } } catch (ObjectDisposedException) { // during shutdown, channel is going to be disposed. } } private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options) { var key = ChannelOptions.PrimaryUserAgentString; var userAgentString = ""; ChannelOption option; if (options.TryGetValue(key, out option)) { // user-provided userAgentString needs to be at the beginning userAgentString = option.StringValue + " "; }; // TODO(jtattermusch): it would be useful to also provide .NET/mono version. userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion); options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString); } private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options) { var dict = new Dictionary<string, ChannelOption>(); if (options == null) { return dict; } foreach (var option in options) { dict.Add(option.Name, option); } return dict; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// Convert.ToString(System.Double) /// </summary> public class ConvertToString11 { public static int Main() { ConvertToString11 testObj = new ConvertToString11(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Double)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verify value is a random Double... "; string c_TEST_ID = "P001"; Double doubleValue = TestLibrary.Generator.GetDouble(-55); String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verify value is a random negative Double... "; string c_TEST_ID = "P002"; Double doubleValue = TestLibrary.Generator.GetDouble(-55); doubleValue = -doubleValue; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verify value is Double.MaxValue... "; string c_TEST_ID = "P003"; Double doubleValue = Double.MaxValue; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verify value is Double.MinValue... "; string c_TEST_ID = "P004"; Double doubleValue = Double.MinValue; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string c_TEST_DESC = "PosTest5: Verify value is Double.Epsilon... "; string c_TEST_ID = "P005"; Double doubleValue = Double.Epsilon; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string c_TEST_DESC = "PosTest6: Verify value is 0... "; string c_TEST_ID = "P006"; Double doubleValue = 0; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string c_TEST_DESC = "PosTest7: Verify value is Double.NaN... "; string c_TEST_ID = "P007"; Double doubleValue = Double.NaN; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string c_TEST_DESC = "PosTest8: Verify value is Double.NaN... "; string c_TEST_ID = "P008"; Double doubleValue = Double.NegativeInfinity; String actualValue = doubleValue.ToString(); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { String resValue = Convert.ToString(doubleValue); if (actualValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); errorDesc += "\n double value is " + doubleValue; TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #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.Diagnostics; namespace System.Net.Http.Headers { public class AuthenticationHeaderValue : ICloneable { private string _scheme; private string _parameter; public string Scheme { get { return _scheme; } } // We simplify parameters by just considering them one string. The caller is responsible for correctly parsing // the string. // The reason is that we can't determine the format of parameters. According to Errata 1959 in RFC 2617 // parameters can be "token", "quoted-string", or "#auth-param" where "auth-param" is defined as // "token "=" ( token | quoted-string )". E.g. take the following BASIC example: // Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // Due to Base64 encoding we have two final "=". The value is neither a token nor a quoted-string, so it must // be an auth-param according to the RFC definition. But that's also incorrect: auth-param means that we // consider the value before the first "=" as "name" and the final "=" as "value". public string Parameter { get { return _parameter; } } public AuthenticationHeaderValue(string scheme) : this(scheme, null) { } public AuthenticationHeaderValue(string scheme, string parameter) { HeaderUtilities.CheckValidToken(scheme, "scheme"); _scheme = scheme; _parameter = parameter; } private AuthenticationHeaderValue(AuthenticationHeaderValue source) { Debug.Assert(source != null); _scheme = source._scheme; _parameter = source._parameter; } private AuthenticationHeaderValue() { } public override string ToString() { if (string.IsNullOrEmpty(_parameter)) { return _scheme; } return _scheme + " " + _parameter; } public override bool Equals(object obj) { AuthenticationHeaderValue other = obj as AuthenticationHeaderValue; if (other == null) { return false; } if (string.IsNullOrEmpty(_parameter) && string.IsNullOrEmpty(other._parameter)) { return (string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase)); } else { // Since we can't parse the parameter, we use case-sensitive comparison. return string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase) && string.Equals(_parameter, other._parameter, StringComparison.Ordinal); } } public override int GetHashCode() { int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_scheme); if (!string.IsNullOrEmpty(_parameter)) { result = result ^ _parameter.GetHashCode(); } return result; } public static AuthenticationHeaderValue Parse(string input) { int index = 0; return (AuthenticationHeaderValue)GenericHeaderParser.SingleValueAuthenticationParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out AuthenticationHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueAuthenticationParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (AuthenticationHeaderValue)output; return true; } return false; } internal static int GetAuthenticationLength(string input, int startIndex, out object parsedValue) { Debug.Assert(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Parse the scheme string: <scheme> in '<scheme> <parameter>' int schemeLength = HttpRuleParser.GetTokenLength(input, startIndex); if (schemeLength == 0) { return 0; } AuthenticationHeaderValue result = new AuthenticationHeaderValue(); result._scheme = input.Substring(startIndex, schemeLength); int current = startIndex + schemeLength; int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; if ((current == input.Length) || (input[current] == ',')) { // If we only have a scheme followed by whitespace, we're done. parsedValue = result; return current - startIndex; } // We need at least one space between the scheme and parameters. If there are no whitespace, then we must // have reached the end of the string (i.e. scheme-only string). if (whitespaceLength == 0) { return 0; } // If we get here, we have a <scheme> followed by a whitespace. Now we expect the following: // '<scheme> <blob>[,<name>=<value>]*[, <otherscheme>...]*': <blob> potentially contains one // or more '=' characters, optionally followed by additional name/value pairs, optionally followed by // other schemes. <blob> may be a quoted string. // We look at the value after ',': if it is <token>=<value> then we have a parameter for <scheme>. // If we have either a <token>-only or <token><whitespace><blob> then we have another scheme. int parameterStartIndex = current; int parameterEndIndex = current; if (!TrySkipFirstBlob(input, ref current, ref parameterEndIndex)) { return 0; } if (current < input.Length) { if (!TryGetParametersEndIndex(input, ref current, ref parameterEndIndex)) { return 0; } } result._parameter = input.Substring(parameterStartIndex, parameterEndIndex - parameterStartIndex + 1); parsedValue = result; return current - startIndex; } private static bool TrySkipFirstBlob(string input, ref int current, ref int parameterEndIndex) { // Find the delimiter: Note that <blob> in "<scheme> <blob>" may be a token, quoted string, name/value // pair or a Base64 encoded string. So make sure that we don't consider ',' characters within a quoted // string as delimiter. while ((current < input.Length) && (input[current] != ',')) { if (input[current] == '"') { int quotedStringLength = 0; if (HttpRuleParser.GetQuotedStringLength(input, current, out quotedStringLength) != HttpParseResult.Parsed) { // We have a quote but an invalid quoted-string. return false; } current = current + quotedStringLength; parameterEndIndex = current - 1; // -1 because 'current' points to the char after the final '"' } else { int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); // We don't want trailing whitespace to be considered part of the parameter blob. Increment // 'parameterEndIndex' only if we don't have a whitespace. E.g. "Basic AbC= , NTLM" should return // "AbC=" as parameter ignoring the spaces before ','. if (whitespaceLength == 0) { parameterEndIndex = current; current++; } else { current = current + whitespaceLength; } } } return true; } private static bool TryGetParametersEndIndex(string input, ref int parseEndIndex, ref int parameterEndIndex) { Debug.Assert(parseEndIndex < input.Length, "Expected string to have at least 1 char"); Debug.Assert(input[parseEndIndex] == ','); int current = parseEndIndex; do { current++; // skip ',' delimiter bool separatorFound = false; // ignore value returned by GetNextNonEmptyOrWhitespaceIndex() current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(input, current, true, out separatorFound); if (current == input.Length) { return true; } // Now we have to determine if after ',' we have a list of <name>=<value> pairs that are part of // the auth scheme parameters OR if we have another auth scheme. Either way, after ',' we expect a // valid token that is either the <name> in a <name>=<value> pair OR <scheme> of another scheme. int tokenLength = HttpRuleParser.GetTokenLength(input, current); if (tokenLength == 0) { return false; } current = current + tokenLength; current = current + HttpRuleParser.GetWhitespaceLength(input, current); // If we reached the end of the string or the token is followed by anything but '=', then the parsed // token is another scheme name. The string representing parameters ends before the token (e.g. // "Digest a=b, c=d, NTLM": return scheme "Digest" with parameters string "a=b, c=d"). if ((current == input.Length) || (input[current] != '=')) { return true; } current++; // skip '=' delimiter current = current + HttpRuleParser.GetWhitespaceLength(input, current); int valueLength = NameValueHeaderValue.GetValueLength(input, current); // After '<name>=' we expect a valid <value> (either token or quoted string) if (valueLength == 0) { return false; } // Update parameter end index, since we just parsed a valid <name>=<value> pair that is part of the // parameters string. current = current + valueLength; parameterEndIndex = current - 1; // -1 because 'current' already points to the char after <value> current = current + HttpRuleParser.GetWhitespaceLength(input, current); parseEndIndex = current; // this essentially points to parameterEndIndex + whitespace + next char } while ((current < input.Length) && (input[current] == ',')); return true; } object ICloneable.Clone() { return new AuthenticationHeaderValue(this); } } }
namespace Trionic5Controls { partial class ctrlCompressorMapEx { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ctrlCompressorMapEx)); this.panel1 = new System.Windows.Forms.Panel(); this.scalablePictureBox1 = new Trionic5Controls.ScalablePictureBox(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.toolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.t25ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0415GToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0418TToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tD0419TToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT28RSToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT3071r86ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT30RToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gT40RToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.hX40wToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.s400SX371ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox2 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripDropDownButton2 = new System.Windows.Forms.ToolStripDropDownButton(); this.toolStripTextBox3 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox4 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox5 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox6 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox7 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox8 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox9 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox10 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox11 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox12 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox13 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox14 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox15 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox16 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox17 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripTextBox18 = new System.Windows.Forms.ToolStripTextBox(); this.panel1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.scalablePictureBox1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 25); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(682, 435); this.panel1.TabIndex = 1; // // scalablePictureBox1 // this.scalablePictureBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.scalablePictureBox1.Location = new System.Drawing.Point(0, 0); this.scalablePictureBox1.Name = "scalablePictureBox1"; this.scalablePictureBox1.Size = new System.Drawing.Size(682, 435); this.scalablePictureBox1.TabIndex = 1; this.scalablePictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.scalablePictureBox1_Paint); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripComboBox1, this.toolStripButton1, this.toolStripButton2, this.toolStripDropDownButton1, this.toolStripLabel2, this.toolStripTextBox1, this.toolStripLabel3, this.toolStripTextBox2, this.toolStripDropDownButton2}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(682, 25); this.toolStrip1.TabIndex = 2; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(90, 22); this.toolStripLabel1.Text = "Select your turbo"; // // toolStripComboBox1 // this.toolStripComboBox1.Items.AddRange(new object[] { "Garrett T25 trim 55", "Garrett T25 trim 60", "Mitsubishi TD04-15G", "Mitsubishi TD04-16T", "Mitsubishi TD04-18T", "Mitsubishi TD04-19T", "Mitsubishi TD06-20G", "Garrett GT2871R", "Garrett GT28RS", "Garrett GT3071R", "Garrett GT3076R", "Garrett GT40R", "Holset HX40w", "S400SX3-71", "GT17", "Garrett T25 54mm trim 60 (NG900, 9-3)"}); this.toolStripComboBox1.Name = "toolStripComboBox1"; this.toolStripComboBox1.Size = new System.Drawing.Size(250, 25); this.toolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox1_SelectedIndexChanged); // // toolStripButton1 // this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image"))); this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton1.Name = "toolStripButton1"; this.toolStripButton1.Size = new System.Drawing.Size(23, 22); this.toolStripButton1.Text = "Refresh"; this.toolStripButton1.Click += new System.EventHandler(this.toolStripButton1_Click); // // toolStripButton2 // this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image"))); this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton2.Name = "toolStripButton2"; this.toolStripButton2.Size = new System.Drawing.Size(23, 22); this.toolStripButton2.Text = "Save image"; this.toolStripButton2.Visible = false; this.toolStripButton2.Click += new System.EventHandler(this.toolStripButton2_Click); // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.t25ToolStripMenuItem, this.tD0415GToolStripMenuItem, this.tD0418TToolStripMenuItem, this.tD0419TToolStripMenuItem, this.gT28RSToolStripMenuItem, this.gT3071r86ToolStripMenuItem, this.gT30RToolStripMenuItem, this.gT40RToolStripMenuItem, this.hX40wToolStripMenuItem, this.s400SX371ToolStripMenuItem}); this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image"))); this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; this.toolStripDropDownButton1.Size = new System.Drawing.Size(29, 22); this.toolStripDropDownButton1.Text = "Select compressor map"; this.toolStripDropDownButton1.Visible = false; // // t25ToolStripMenuItem // this.t25ToolStripMenuItem.Name = "t25ToolStripMenuItem"; this.t25ToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.t25ToolStripMenuItem.Text = "T25"; this.t25ToolStripMenuItem.Click += new System.EventHandler(this.t25ToolStripMenuItem_Click); // // tD0415GToolStripMenuItem // this.tD0415GToolStripMenuItem.Name = "tD0415GToolStripMenuItem"; this.tD0415GToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.tD0415GToolStripMenuItem.Text = "TD04-15G"; this.tD0415GToolStripMenuItem.Click += new System.EventHandler(this.tD0415GToolStripMenuItem_Click); // // tD0418TToolStripMenuItem // this.tD0418TToolStripMenuItem.Name = "tD0418TToolStripMenuItem"; this.tD0418TToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.tD0418TToolStripMenuItem.Text = "TD04-18T"; this.tD0418TToolStripMenuItem.Click += new System.EventHandler(this.tD0418TToolStripMenuItem_Click); // // tD0419TToolStripMenuItem // this.tD0419TToolStripMenuItem.Name = "tD0419TToolStripMenuItem"; this.tD0419TToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.tD0419TToolStripMenuItem.Text = "TD04-19T"; this.tD0419TToolStripMenuItem.Click += new System.EventHandler(this.tD0419TToolStripMenuItem_Click); // // gT28RSToolStripMenuItem // this.gT28RSToolStripMenuItem.Name = "gT28RSToolStripMenuItem"; this.gT28RSToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.gT28RSToolStripMenuItem.Text = "GT28RS"; this.gT28RSToolStripMenuItem.Click += new System.EventHandler(this.gT28RSToolStripMenuItem_Click); // // gT3071r86ToolStripMenuItem // this.gT3071r86ToolStripMenuItem.Name = "gT3071r86ToolStripMenuItem"; this.gT3071r86ToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.gT3071r86ToolStripMenuItem.Text = "GT3071R"; this.gT3071r86ToolStripMenuItem.Click += new System.EventHandler(this.gT3071r86ToolStripMenuItem_Click); // // gT30RToolStripMenuItem // this.gT30RToolStripMenuItem.Name = "gT30RToolStripMenuItem"; this.gT30RToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.gT30RToolStripMenuItem.Text = "GT30R"; this.gT30RToolStripMenuItem.Click += new System.EventHandler(this.gT30RToolStripMenuItem_Click); // // gT40RToolStripMenuItem // this.gT40RToolStripMenuItem.Name = "gT40RToolStripMenuItem"; this.gT40RToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.gT40RToolStripMenuItem.Text = "GT40R"; this.gT40RToolStripMenuItem.Click += new System.EventHandler(this.gT40RToolStripMenuItem_Click); // // hX40wToolStripMenuItem // this.hX40wToolStripMenuItem.Name = "hX40wToolStripMenuItem"; this.hX40wToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.hX40wToolStripMenuItem.Text = "HX40w"; this.hX40wToolStripMenuItem.Click += new System.EventHandler(this.hX40wToolStripMenuItem_Click); // // s400SX371ToolStripMenuItem // this.s400SX371ToolStripMenuItem.Name = "s400SX371ToolStripMenuItem"; this.s400SX371ToolStripMenuItem.Size = new System.Drawing.Size(143, 22); this.s400SX371ToolStripMenuItem.Text = "S400SX3-71"; this.s400SX371ToolStripMenuItem.Click += new System.EventHandler(this.s400SX371ToolStripMenuItem_Click); // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(51, 22); this.toolStripLabel2.Text = "Temp (C)"; // // toolStripTextBox1 // this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(30, 25); this.toolStripTextBox1.Text = "20"; this.toolStripTextBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripTextBox1_KeyDown); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(19, 22); this.toolStripLabel3.Text = "VE"; // // toolStripTextBox2 // this.toolStripTextBox2.Name = "toolStripTextBox2"; this.toolStripTextBox2.Size = new System.Drawing.Size(30, 25); this.toolStripTextBox2.Text = "85"; this.toolStripTextBox2.Visible = false; this.toolStripTextBox2.KeyDown += new System.Windows.Forms.KeyEventHandler(this.toolStripTextBox1_KeyDown); // // toolStripDropDownButton2 // this.toolStripDropDownButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.toolStripDropDownButton2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripTextBox3, this.toolStripTextBox4, this.toolStripTextBox5, this.toolStripTextBox6, this.toolStripTextBox7, this.toolStripTextBox8, this.toolStripTextBox9, this.toolStripTextBox10, this.toolStripTextBox11, this.toolStripTextBox12, this.toolStripTextBox13, this.toolStripTextBox14, this.toolStripTextBox15, this.toolStripTextBox16, this.toolStripTextBox17, this.toolStripTextBox18}); this.toolStripDropDownButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton2.Image"))); this.toolStripDropDownButton2.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton2.Name = "toolStripDropDownButton2"; this.toolStripDropDownButton2.Size = new System.Drawing.Size(29, 22); this.toolStripDropDownButton2.Text = "Specific efficiency per RPM range"; this.toolStripDropDownButton2.DropDownClosed += new System.EventHandler(this.toolStripDropDownButton2_DropDownClosed); // // toolStripTextBox3 // this.toolStripTextBox3.Name = "toolStripTextBox3"; this.toolStripTextBox3.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox3.Text = "90"; // // toolStripTextBox4 // this.toolStripTextBox4.Name = "toolStripTextBox4"; this.toolStripTextBox4.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox4.Text = "90"; // // toolStripTextBox5 // this.toolStripTextBox5.Name = "toolStripTextBox5"; this.toolStripTextBox5.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox5.Text = "90"; // // toolStripTextBox6 // this.toolStripTextBox6.Name = "toolStripTextBox6"; this.toolStripTextBox6.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox6.Text = "90"; // // toolStripTextBox7 // this.toolStripTextBox7.Name = "toolStripTextBox7"; this.toolStripTextBox7.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox7.Text = "90"; // // toolStripTextBox8 // this.toolStripTextBox8.Name = "toolStripTextBox8"; this.toolStripTextBox8.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox8.Text = "90"; // // toolStripTextBox9 // this.toolStripTextBox9.Name = "toolStripTextBox9"; this.toolStripTextBox9.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox9.Text = "90"; // // toolStripTextBox10 // this.toolStripTextBox10.Name = "toolStripTextBox10"; this.toolStripTextBox10.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox10.Text = "90"; // // toolStripTextBox11 // this.toolStripTextBox11.Name = "toolStripTextBox11"; this.toolStripTextBox11.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox11.Text = "90"; // // toolStripTextBox12 // this.toolStripTextBox12.Name = "toolStripTextBox12"; this.toolStripTextBox12.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox12.Text = "90"; // // toolStripTextBox13 // this.toolStripTextBox13.Name = "toolStripTextBox13"; this.toolStripTextBox13.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox13.Text = "90"; // // toolStripTextBox14 // this.toolStripTextBox14.Name = "toolStripTextBox14"; this.toolStripTextBox14.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox14.Text = "90"; // // toolStripTextBox15 // this.toolStripTextBox15.Name = "toolStripTextBox15"; this.toolStripTextBox15.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox15.Text = "90"; // // toolStripTextBox16 // this.toolStripTextBox16.Name = "toolStripTextBox16"; this.toolStripTextBox16.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox16.Text = "90"; // // toolStripTextBox17 // this.toolStripTextBox17.Name = "toolStripTextBox17"; this.toolStripTextBox17.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox17.Text = "90"; // // toolStripTextBox18 // this.toolStripTextBox18.Name = "toolStripTextBox18"; this.toolStripTextBox18.Size = new System.Drawing.Size(100, 21); this.toolStripTextBox18.Text = "90"; // // ctrlCompressorMapEx // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.panel1); this.Controls.Add(this.toolStrip1); this.Name = "ctrlCompressorMapEx"; this.Size = new System.Drawing.Size(682, 460); this.panel1.ResumeLayout(false); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem t25ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0415GToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT28RSToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT30RToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0418TToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tD0419TToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT3071r86ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gT40RToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem hX40wToolStripMenuItem; private System.Windows.Forms.ToolStripComboBox toolStripComboBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripButton toolStripButton1; private System.Windows.Forms.ToolStripButton toolStripButton2; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripTextBox toolStripTextBox2; private Trionic5Controls.ScalablePictureBox scalablePictureBox1; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton2; private System.Windows.Forms.ToolStripTextBox toolStripTextBox3; private System.Windows.Forms.ToolStripTextBox toolStripTextBox4; private System.Windows.Forms.ToolStripTextBox toolStripTextBox5; private System.Windows.Forms.ToolStripTextBox toolStripTextBox6; private System.Windows.Forms.ToolStripTextBox toolStripTextBox7; private System.Windows.Forms.ToolStripTextBox toolStripTextBox8; private System.Windows.Forms.ToolStripTextBox toolStripTextBox9; private System.Windows.Forms.ToolStripTextBox toolStripTextBox10; private System.Windows.Forms.ToolStripTextBox toolStripTextBox11; private System.Windows.Forms.ToolStripTextBox toolStripTextBox12; private System.Windows.Forms.ToolStripTextBox toolStripTextBox13; private System.Windows.Forms.ToolStripTextBox toolStripTextBox14; private System.Windows.Forms.ToolStripTextBox toolStripTextBox15; private System.Windows.Forms.ToolStripTextBox toolStripTextBox16; private System.Windows.Forms.ToolStripTextBox toolStripTextBox17; private System.Windows.Forms.ToolStripTextBox toolStripTextBox18; private System.Windows.Forms.ToolStripMenuItem s400SX371ToolStripMenuItem; } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NuGet.Common; namespace Sleet { public static class InitCommand { public static Task<bool> RunAsync(LocalSettings settings, ISleetFileSystem source, ILogger log) { var token = CancellationToken.None; return RunAsync(settings, source, enableCatalog: false, enableSymbols: false, log: log, token: token); } public static async Task<bool> RunAsync(LocalSettings settings, ISleetFileSystem source, bool enableCatalog, bool enableSymbols, ILogger log, CancellationToken token) { var feedSettings = await FeedSettingsUtility.GetSettingsOrDefault(source, log, token); feedSettings.CatalogEnabled = enableCatalog; feedSettings.SymbolsEnabled = enableSymbols; return await InitAsync(settings, source, feedSettings, log, token); } public static Task<bool> InitAsync(SleetContext context) { return InitAsync(context.LocalSettings, context.Source, context.SourceSettings, context.Log, context.Token); } public static Task<bool> InitAsync(LocalSettings settings, ISleetFileSystem source, FeedSettings feedSettings, ILogger log, CancellationToken token) { return InitAsync(settings, source, feedSettings, autoCreateBucket: true, log: log, token: token); } public static async Task<bool> InitAsync(LocalSettings settings, ISleetFileSystem source, FeedSettings feedSettings, bool autoCreateBucket, ILogger log, CancellationToken token) { SourceUtility.ValidateFileSystem(source); await SourceUtility.EnsureBucketOrThrow(source, autoCreateBucket, log, token); var exitCode = true; var noChanges = true; var now = DateTimeOffset.UtcNow; var context = new SleetContext() { LocalSettings = settings, Source = source, SourceSettings = feedSettings, Log = log, Token = token, OperationStart = now }; log.LogMinimal($"Initializing {source.BaseURI.AbsoluteUri}"); // Validate source var exists = await source.Validate(log, token); if (!exists) { return false; } // Create service index.json noChanges &= !await CreateServiceIndexAsync(source, log, token, now); var serviceIndexFile = source.Get("index.json"); var serviceIndexJson = await serviceIndexFile.GetJson(log, token); var serviceIndexJsonBefore = serviceIndexJson.DeepClone(); serviceIndexJson["resources"] = new JArray(); // Create sleet.settings.json noChanges &= !await CreateSettingsAsync(source, feedSettings, log, token, now, serviceIndexJson); // Create catalog/index.json if (feedSettings.CatalogEnabled) { noChanges &= !await CreateCatalogAsync(source, log, token, now, serviceIndexJson); } // Create autocomplete noChanges &= !await CreateAutoCompleteAsync(source, log, token, now, serviceIndexJson); // Create search noChanges &= !await CreateSearchAsync(source, log, token, now, serviceIndexJson); // Create package index noChanges &= !await CreatePackageIndexAsync(context, serviceIndexJson); // Additional entries AddServiceIndexEntry(source.BaseURI, "registration/", "RegistrationsBaseUrl/3.4.0", "Package registrations used for search and packages.config.", serviceIndexJson); AddServiceIndexEntry(source.BaseURI, "", "ReportAbuseUriTemplate/3.0.0", "Report abuse template.", serviceIndexJson); AddServiceIndexEntry(source.BaseURI, "flatcontainer/", "PackageBaseAddress/3.0.0", "Packages used by project.json", serviceIndexJson); // Add symbols feed if enabled if (feedSettings.SymbolsEnabled) { await AddSymbolsFeedAsync(source, serviceIndexJson, context); } // Check if services changed noChanges &= serviceIndexJsonBefore.Equals(serviceIndexJson); if (noChanges) { throw new InvalidOperationException("Source is already initialized. No actions taken."); } // Write the service index out await serviceIndexFile.Write(serviceIndexJson, log, token); // Save all exitCode &= await source.Commit(log, token); if (exitCode) { log.LogMinimal($"Successfully initialized {source.BaseURI.AbsoluteUri}"); } else { log.LogError($"Failed to initialize {source.BaseURI.AbsoluteUri}"); } return exitCode; } private static async Task AddSymbolsFeedAsync(ISleetFileSystem source, JObject serviceIndexJson, SleetContext context) { AddServiceIndexEntry(source.BaseURI, "symbols/packages/index.json", "http://schema.emgarten.com/sleet#SymbolsPackageIndex/1.0.0", "Packages indexed in the symbols feed.", serviceIndexJson); AddServiceIndexEntry(source.BaseURI, "symbols/", "http://schema.emgarten.com/sleet#SymbolsServer/1.0.0", "Symbols server containing dll and pdb files.", serviceIndexJson); var symbols = new Symbols(context); await symbols.PackageIndex.InitAsync(); } private static void AddServiceIndexEntry(Uri baseUri, string relativeFilePath, string type, string comment, JObject json) { var id = UriUtility.GetPath(baseUri, relativeFilePath); RemoveServiceIndexEntry(id, json); var array = (JArray)json["resources"]; array.Add(GetServiceIndexEntry(baseUri, relativeFilePath, type, comment)); } private static JObject GetServiceIndexEntry(Uri baseUri, string relativeFilePath, string type, string comment) { var id = UriUtility.GetPath(baseUri, relativeFilePath); var json = new JObject { ["@id"] = id.AbsoluteUri, ["@type"] = type, ["comment"] = comment }; return json; } private static void RemoveServiceIndexEntry(Uri id, JObject json) { var array = (JArray)json["resources"]; foreach (var item in array.Where(e => id.Equals(((JObject)e).GetIdUri()))) { array.Remove(item); } } private static async Task<bool> CreateFromTemplateAsync( ISleetFileSystem source, ILogger log, DateTimeOffset now, string templatePath, string sourcePath, CancellationToken token) { var remoteFile = source.Get(sourcePath); if (!await remoteFile.Exists(log, token)) { var json = await TemplateUtility.LoadTemplate(templatePath, now, source.BaseURI); await remoteFile.Write(JObject.Parse(json), log, token); return true; } return false; } private static async Task<bool> CreateCatalogAsync(ISleetFileSystem source, ILogger log, CancellationToken token, DateTimeOffset now, JObject serviceIndexJson) { AddServiceIndexEntry(source.BaseURI, "catalog/index.json", "Catalog/3.0.0", "Catalog service.", serviceIndexJson); return await CreateFromTemplateAsync(source, log, now, "CatalogIndex", "catalog/index.json", token); } private static async Task<bool> CreateAutoCompleteAsync(ISleetFileSystem source, ILogger log, CancellationToken token, DateTimeOffset now, JObject serviceIndexJson) { AddServiceIndexEntry(source.BaseURI, "autocomplete/query", "SearchAutocompleteService/3.0.0-beta", "Powershell autocomplete.", serviceIndexJson); return await CreateFromTemplateAsync(source, log, now, "AutoComplete", "autocomplete/query", token); } private static async Task<bool> CreateSearchAsync(ISleetFileSystem source, ILogger log, CancellationToken token, DateTimeOffset now, JObject serviceIndexJson) { AddServiceIndexEntry(source.BaseURI, "search/query", "SearchQueryService/3.0.0-beta", "Static package list in search result form.", serviceIndexJson); return await CreateFromTemplateAsync(source, log, now, "Search", "search/query", token); } private static async Task<bool> CreateServiceIndexAsync(ISleetFileSystem source, ILogger log, CancellationToken token, DateTimeOffset now) { return await CreateFromTemplateAsync(source, log, now, "ServiceIndex", "index.json", token); } private static async Task<bool> CreateSettingsAsync(ISleetFileSystem source, FeedSettings feedSettings, ILogger log, CancellationToken token, DateTimeOffset now, JObject serviceIndexJson) { AddServiceIndexEntry(source.BaseURI, "sleet.settings.json", "http://schema.emgarten.com/sleet#SettingsFile/1.0.0", "Sleet feed settings.", serviceIndexJson); // Create new file. var result = await CreateFromTemplateAsync(source, log, now, "Settings", "sleet.settings.json", token); // Write out the current settings. await FeedSettingsUtility.SaveSettings(source, feedSettings, log, token); return result; } private static async Task<bool> CreatePackageIndexAsync(SleetContext context, JObject serviceIndexJson) { var packageIndex = context.Source.Get("sleet.packageindex.json"); AddServiceIndexEntry(context.Source.BaseURI, "sleet.packageindex.json", "http://schema.emgarten.com/sleet#PackageIndex/1.0.0", "Sleet package index.", serviceIndexJson); if (!await packageIndex.Exists(context.Log, context.Token)) { var index = new PackageIndex(context); await index.InitAsync(); return true; } return false; } } }
using System; using System.Collections.Generic; using System.Globalization; using Xunit; using SimMetrics.Net.Metric; using SimMetrics.Net.Utilities; namespace SimMetrics.Net.Tests.SimilarityClasses.EditDistance { // [TestFixture] public sealed class SmithWatermanUnitTests { #region Test Data Setup struct SwTestRecord { public string NameOne; public string NameTwo; public double SwDefault; public double SwCost; public double SwCostFunction; public double SwCostAndCostFunction; } struct SwgTestRecord { public string NameOne; public string NameTwo; public double SwgDefault; public double SwgGapCostFunction; public double SwgCostFunction; public double SwgGapCostAndCostFunctions; } struct SwgaTestRecord { public string NameOne; public string NameTwo; public double SwgaDefault; public double SwgaWindowSize; public double SwgaGapCostFunction; public double SwgaGapCostFunctionAndWindowSize; public double SwgaGapCostAndCostFunctions; public double SwgaGapCostAndCostFunctionsAndWindowSize; public double SwgaCostFunction; public double SwgaCostFunctionAndWindowSize; } readonly Settings _addressSettings = Settings.Default; readonly List<SwTestRecord> _swTestNames = new List<SwTestRecord>(26); readonly List<SwgTestRecord> _swgTestNames = new List<SwgTestRecord>(26); readonly List<SwgaTestRecord> _swgaTestNames = new List<SwgaTestRecord>(26); void SwAddNames(string addChars) { if (addChars != null) { string[] letters = addChars.Split(','); SwTestRecord testName; testName.NameOne = letters[0]; testName.NameTwo = letters[1]; testName.SwDefault = Convert.ToDouble(letters[2], CultureInfo.InvariantCulture); testName.SwCost = Convert.ToDouble(letters[3], CultureInfo.InvariantCulture); testName.SwCostFunction = Convert.ToDouble(letters[4], CultureInfo.InvariantCulture); testName.SwCostAndCostFunction = Convert.ToDouble(letters[5], CultureInfo.InvariantCulture); _swTestNames.Add(testName); } } void SwgAddNames(string addChars) { if (addChars != null) { string[] letters = addChars.Split(','); SwgTestRecord testName; testName.NameOne = letters[0]; testName.NameTwo = letters[1]; testName.SwgDefault = Convert.ToDouble(letters[2], CultureInfo.InvariantCulture); testName.SwgGapCostFunction = Convert.ToDouble(letters[3], CultureInfo.InvariantCulture); testName.SwgCostFunction = Convert.ToDouble(letters[4], CultureInfo.InvariantCulture); testName.SwgGapCostAndCostFunctions = Convert.ToDouble(letters[5], CultureInfo.InvariantCulture); _swgTestNames.Add(testName); } } void SwgaAddNames(string addChars) { if (addChars != null) { string[] letters = addChars.Split(','); SwgaTestRecord testName; testName.NameOne = letters[0]; testName.NameTwo = letters[1]; testName.SwgaDefault = Convert.ToDouble(letters[2], CultureInfo.InvariantCulture); testName.SwgaWindowSize = Convert.ToDouble(letters[3], CultureInfo.InvariantCulture); testName.SwgaGapCostFunction = Convert.ToDouble(letters[4], CultureInfo.InvariantCulture); testName.SwgaGapCostFunctionAndWindowSize = Convert.ToDouble(letters[5], CultureInfo.InvariantCulture); testName.SwgaGapCostAndCostFunctions = Convert.ToDouble(letters[6], CultureInfo.InvariantCulture); testName.SwgaGapCostAndCostFunctionsAndWindowSize = Convert.ToDouble(letters[7], CultureInfo.InvariantCulture); testName.SwgaCostFunction = Convert.ToDouble(letters[8], CultureInfo.InvariantCulture); testName.SwgaCostFunctionAndWindowSize = Convert.ToDouble(letters[9], CultureInfo.InvariantCulture); _swgaTestNames.Add(testName); } } void LoadData() { SwAddNames(_addressSettings.swName1); SwAddNames(_addressSettings.swName2); SwAddNames(_addressSettings.swName3); SwAddNames(_addressSettings.swName4); SwAddNames(_addressSettings.swName5); SwAddNames(_addressSettings.swName6); SwAddNames(_addressSettings.swName7); SwgAddNames(_addressSettings.swgName1); SwgAddNames(_addressSettings.swgName2); SwgAddNames(_addressSettings.swgName3); SwgAddNames(_addressSettings.swgName4); SwgAddNames(_addressSettings.swgName5); SwgAddNames(_addressSettings.swgName6); SwgAddNames(_addressSettings.swgName7); SwgaAddNames(_addressSettings.swgaName1); SwgaAddNames(_addressSettings.swgaName2); SwgaAddNames(_addressSettings.swgaName3); SwgaAddNames(_addressSettings.swgaName4); SwgaAddNames(_addressSettings.swgaName5); SwgaAddNames(_addressSettings.swgaName6); SwgaAddNames(_addressSettings.swgaName7); SwgaAddNames(_addressSettings.swgaName8); } #endregion #region SmithWaterman Tests [Fact] // [Category("SmithWaterman")] public void SmithWatermanShortDescription() { AssertUtil.Equal(_mySmithWatermanDefault.ShortDescriptionString, "SmithWaterman", "Problem with SmithWaterman test ShortDescription"); } [Fact] // [Category("SmithWaterman")] public void SmithWatermanDefaultTestData() { foreach (SwTestRecord testRecord in _swTestNames) { AssertUtil.Equal(testRecord.SwDefault.ToString("F3"), _mySmithWatermanDefault.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SmithWaterman test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWaterman")] public void SmithWatermanCostTestData() { foreach (SwTestRecord testRecord in _swTestNames) { AssertUtil.Equal(testRecord.SwDefault.ToString("F3"), _mySmithWatermanCost.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SmithWaterman test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWaterman")] public void SmithWatermanCostFunctionTestData() { foreach (SwTestRecord testRecord in _swTestNames) { AssertUtil.Equal(testRecord.SwDefault.ToString("F3"), _mySmithWatermanCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SmithWaterman test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWaterman")] public void SmithWatermanCostAndCostFunctionTestData() { foreach (SwTestRecord testRecord in _swTestNames) { AssertUtil.Equal(testRecord.SwDefault.ToString("F3"), _mySmithWatermanCostAndCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo). ToString("F3"), "Problem with SmithWaterman test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } #endregion #region SmithWatermanGotoh tests [Fact] // [Category("SmithWatermanGotoh")] public void SmithWatermanGotohShortDescription() { AssertUtil.Equal(_mySmithWatermanGotohDefault.ShortDescriptionString, "SmithWatermanGotoh", "Problem with SmithWaterman test ShortDescription"); } [Fact] // [Category("SmithWatermanGotoh")] public void SmithWatermanGotohDefaultTestData() { foreach (SwgTestRecord testRecord in _swgTestNames) { AssertUtil.Equal(testRecord.SwgDefault.ToString("F3"), _mySmithWatermanGotohDefault.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SmithWatermanGotoh test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWatermanGotoh")] public void SmithWatermanGotoGapCostFunctionTestData() { foreach (SwgTestRecord testRecord in _swgTestNames) { AssertUtil.Equal(testRecord.SwgGapCostFunction.ToString("F3"), _mySmithWatermanGotohGapCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo). ToString("F3"), "Problem with SmithWatermanGotoh test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWatermanGotoh")] public void SmithWatermanGotoCostFunctionTestData() { foreach (SwgTestRecord testRecord in _swgTestNames) { AssertUtil.Equal(testRecord.SwgCostFunction.ToString("F3"), _mySmithWatermanGotohCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString( "F3"), "Problem with SmithWatermanGotoh test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SmithWatermanGotoh")] public void SmithWatermanGotoGapCostAndCostFunctionsTestData() { foreach (SwgTestRecord testRecord in _swgTestNames) { AssertUtil.Equal(testRecord.SwgGapCostAndCostFunctions.ToString("F3"), _mySmithWatermanGotohGapCostAndCostFunctions.GetSimilarity(testRecord.NameOne, testRecord.NameTwo) .ToString("F3"), "Problem with SmithWatermanGotoh test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } #endregion #region SmithWatermanGotohWindowedAffine tests [Fact] // [Category("SWGWA")] public void SwgwaShortDescription() { AssertUtil.Equal(_mySwgwaDefault.ShortDescriptionString, "SmithWatermanGotohWindowedAffine", "Problem with SmithWaterman test ShortDescription"); } [Fact] // [Category("SWGWA")] public void SwgwaDefaultTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaDefault.ToString("F3"), _mySwgwaDefault.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaWindowSizeTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaWindowSize.ToString("F3"), _mySwgwaWindowSize.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaGapCostFunctionTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaGapCostFunction.ToString("F3"), _mySwgwaGapCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaGapCostFunctionAndWindowSizeTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaGapCostFunctionAndWindowSize.ToString("F3"), _mySwgwaGapCostFunctionAndWindowSize.GetSimilarity(testRecord.NameOne, testRecord.NameTwo). ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaGapCostAndCostFunctionsTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaGapCostAndCostFunctions.ToString("F3"), _mySwgwaGapCostAndCostFunctions.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString( "F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaGapCostAndCostFunctionsAndWindowSizeTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaGapCostAndCostFunctionsAndWindowSize.ToString("F3"), _mySwgwaGapCostAndCostFunctionsAndWindowSize.GetSimilarity(testRecord.NameOne, testRecord.NameTwo) .ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaCostFunctionTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaCostFunction.ToString("F3"), _mySwgwaCostFunction.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString("F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } [Fact] // [Category("SWGWA")] public void SwgwaCostFunctionAndWindowSizeTestData() { foreach (SwgaTestRecord testRecord in _swgaTestNames) { AssertUtil.Equal(testRecord.SwgaCostFunctionAndWindowSize.ToString("F3"), _mySwgwaCostFunctionAndWindowSize.GetSimilarity(testRecord.NameOne, testRecord.NameTwo).ToString( "F3"), "Problem with SWGWA test - " + testRecord.NameOne + ' ' + testRecord.NameTwo); } } #endregion #region private fields SmithWaterman _mySmithWatermanDefault; SmithWaterman _mySmithWatermanCost; SmithWaterman _mySmithWatermanCostFunction; SmithWaterman _mySmithWatermanCostAndCostFunction; SmithWatermanGotoh _mySmithWatermanGotohDefault; SmithWatermanGotoh _mySmithWatermanGotohGapCostFunction; SmithWatermanGotoh _mySmithWatermanGotohCostFunction; SmithWatermanGotoh _mySmithWatermanGotohGapCostAndCostFunctions; SmithWatermanGotohWindowedAffine _mySwgwaDefault; SmithWatermanGotohWindowedAffine _mySwgwaWindowSize; SmithWatermanGotohWindowedAffine _mySwgwaGapCostFunction; SmithWatermanGotohWindowedAffine _mySwgwaGapCostFunctionAndWindowSize; SmithWatermanGotohWindowedAffine _mySwgwaGapCostAndCostFunctions; SmithWatermanGotohWindowedAffine _mySwgwaGapCostAndCostFunctionsAndWindowSize; SmithWatermanGotohWindowedAffine _mySwgwaCostFunction; SmithWatermanGotohWindowedAffine _mySwgwaCostFunctionAndWindowSize; #endregion // [SetUp] public SmithWatermanUnitTests() { LoadData(); # region SmithWaterman classes // 0.5F and SubCostRange1ToMinus2 are the values used for the default constructor _mySmithWatermanDefault = new SmithWaterman(); _mySmithWatermanCost = new SmithWaterman(0.5D); _mySmithWatermanCostFunction = new SmithWaterman(new SubCostRange1ToMinus2()); _mySmithWatermanCostAndCostFunction = new SmithWaterman(0.5D, new SubCostRange1ToMinus2()); #endregion // we also need to check running a different set of tests #region SmithWatermanGotoh classes _mySmithWatermanGotohDefault = new SmithWatermanGotoh(); _mySmithWatermanGotohGapCostFunction = new SmithWatermanGotoh(new AffineGapRange5To0Multiplier1()); _mySmithWatermanGotohCostFunction = new SmithWatermanGotoh(new SubCostRange5ToMinus3()); _mySmithWatermanGotohGapCostAndCostFunctions = new SmithWatermanGotoh(new AffineGapRange5To0Multiplier1(), new SubCostRange5ToMinus3()); #endregion #region SmithWatermanGotohWindowedAffine classes _mySwgwaDefault = new SmithWatermanGotohWindowedAffine(); _mySwgwaWindowSize = new SmithWatermanGotohWindowedAffine(100); _mySwgwaGapCostFunction = new SmithWatermanGotohWindowedAffine(new AffineGapRange5To0Multiplier1()); _mySwgwaGapCostFunctionAndWindowSize = new SmithWatermanGotohWindowedAffine(new AffineGapRange5To0Multiplier1(), 100); _mySwgwaGapCostAndCostFunctions = new SmithWatermanGotohWindowedAffine(new AffineGapRange5To0Multiplier1(), new SubCostRange5ToMinus3()); _mySwgwaGapCostAndCostFunctionsAndWindowSize = new SmithWatermanGotohWindowedAffine(new AffineGapRange5To0Multiplier1(), new SubCostRange5ToMinus3(), 100); _mySwgwaCostFunction = new SmithWatermanGotohWindowedAffine(new SubCostRange5ToMinus3()); _mySwgwaCostFunctionAndWindowSize = new SmithWatermanGotohWindowedAffine(new SubCostRange5ToMinus3(), 100); #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A simple coordination data structure that we use for fork/join style parallelism. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { /// <summary> /// Represents a synchronization primitive that is signaled when its count reaches zero. /// </summary> /// <remarks> /// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="CountdownEvent"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [ComVisible(false)] [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] public class CountdownEvent : IDisposable { // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a // latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can // wait on the latch at any point; when the latch count reaches 0, all threads are woken and // subsequent waiters return without waiting. The implementation internally lazily creates a true // Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a // wait. private int m_initialCount; // The original # of signals the latch was instantiated with. private volatile int m_currentCount; // The # of outstanding signals before the latch transitions to a signaled state. private ManualResetEventSlim m_event; // An event used to manage blocking and signaling. private volatile bool m_disposed; // Whether the latch has been disposed. /// <summary> /// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the /// specified count. /// </summary> /// <param name="initialCount">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less /// than 0.</exception> public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException(nameof(initialCount)); } m_initialCount = initialCount; m_currentCount = initialCount; // Allocate a thin event, which internally defers creation of an actual Win32 event. m_event = new ManualResetEventSlim(); // If the latch was created with a count of 0, then it's already in the signaled state. if (initialCount == 0) { m_event.Set(); } } /// <summary> /// Gets the number of remaining signals required to set the event. /// </summary> /// <value> /// The number of remaining signals required to set the event. /// </value> public int CurrentCount { get { int observedCount = m_currentCount; return observedCount < 0 ? 0 : observedCount; } } /// <summary> /// Gets the numbers of signals initially required to set the event. /// </summary> /// <value> /// The number of signals initially required to set the event. /// </value> public int InitialCount { get { return m_initialCount; } } /// <summary> /// Determines whether the event is set. /// </summary> /// <value>true if the event is set; otherwise, false.</value> public bool IsSet { get { // The latch is "completed" if its current count has reached 0. Note that this is NOT // the same thing is checking the event's IsCompleted property. There is a tiny window // of time, after the final decrement of the current count to 0 and before setting the // event, where the two values are out of sync. return (m_currentCount <= 0); } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set. /// </summary> /// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception> /// <remarks> /// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases /// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/> /// to be set, the <see cref="Wait()"/> method should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); return m_event.WaitHandle; } } /// <summary> /// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { // Gets rid of this latch's associated resources. This can consist of a Win32 event // which is (lazily) allocated by the underlying thin event. This method is not safe to // call concurrently -- i.e. a caller must coordinate to ensure only one thread is using // the latch at the time of the call to Dispose. Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="T:System.Threading.CountdownEvent"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release /// only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (disposing) { m_event.Dispose(); m_disposed = true; } } /// <summary> /// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its /// count. /// </summary> /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException">The current instance is already set. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal() { ThrowIfDisposed(); Debug.Assert(m_event != null); if (m_currentCount <= 0) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } #pragma warning disable 0420 int newCount = Interlocked.Decrement(ref m_currentCount); #pragma warning restore 0420 if (newCount == 0) { m_event.Set(); return true; } else if (newCount < 0) { //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here //because there was a thread already which decremented it to zero and set the event throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } return false; } /// <summary> /// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>, /// decrementing its count by the specified amount. /// </summary> /// <param name="signalCount">The number of signals to register.</param> /// <returns>true if the signals caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException"> /// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see /// cref="CurrentCount"/>. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 1.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException(nameof(signalCount)); } ThrowIfDisposed(); Debug.Assert(m_event != null); int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; // If the latch is already signaled, we will fail. if (observedCount < signalCount) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount - signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } // If we were the last to signal, set the event. if (observedCount == signalCount) { m_event.Set(); return true; } Debug.Assert(m_currentCount >= 0, "latch was decremented below zero"); return false; } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException"> /// The current instance has already been disposed. /// </exception> public void AddCount() { AddCount(1); } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero. this will return false.</returns> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount() { return TryAddCount(1); } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified /// value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyZero")); } } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a /// specified value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero this will return false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException(nameof(signalCount)); } ThrowIfDisposed(); // Loop around until we successfully increment the count. int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; if (observedCount <= 0) { return false; } else if (observedCount > (Int32.MaxValue - signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyMax")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount + signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } return true; } /// <summary> /// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed..</exception> public void Reset() { Reset(m_initialCount); } /// <summary> /// Resets the <see cref="CurrentCount"/> to a specified value. /// </summary> /// <param name="count">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is /// less than 0.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception> public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } m_currentCount = count; m_initialCount = count; if (count == 0) { m_event.Set(); } else { m_event.Reset(); } } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set. /// </summary> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while /// observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. If the /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed /// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/> /// will be thrown. /// </remarks> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using /// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool returnValue = IsSet; // If not completed yet, wait on the event. if (!returnValue) { // ** the actual wait returnValue = m_event.Wait(millisecondsTimeout, cancellationToken); //the Wait will throw OCE itself if the token is canceled. } return returnValue; } // -------------------------------------- // Private methods /// <summary> /// Throws an exception if the latch has been disposed. /// </summary> private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } }
using System; using System.Windows.Forms; using System.Drawing; namespace WeifenLuo.WinFormsUI.Docking { partial class DockPanel { private class AutoHideWindowControl : Panel, ISplitterDragSource { private class SplitterControl : SplitterBase { public SplitterControl(AutoHideWindowControl autoHideWindow) { m_autoHideWindow = autoHideWindow; } private AutoHideWindowControl m_autoHideWindow; private AutoHideWindowControl AutoHideWindow { get { return m_autoHideWindow; } } protected override int SplitterSize { get { return Measures.SplitterSize; } } protected override void StartDrag() { AutoHideWindow.DockPanel.BeginDrag(AutoHideWindow, AutoHideWindow.RectangleToScreen(Bounds)); } } #region consts private const int ANIMATE_TIME = 100; // in mini-seconds #endregion private Timer m_timerMouseTrack; private SplitterControl m_splitter; public AutoHideWindowControl(DockPanel dockPanel) { m_dockPanel = dockPanel; m_timerMouseTrack = new Timer(); m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick); Visible = false; m_splitter = new SplitterControl(this); Controls.Add(m_splitter); } protected override void Dispose(bool disposing) { if (disposing) { m_timerMouseTrack.Dispose(); } base.Dispose(disposing); } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } } private DockPane m_activePane = null; public DockPane ActivePane { get { return m_activePane; } } private void SetActivePane() { DockPane value = (ActiveContent == null ? null : ActiveContent.DockHandler.Pane); if (value == m_activePane) return; m_activePane = value; } private static readonly object ActiveContentChangedEvent = new object(); public event EventHandler ActiveContentChanged { add { Events.AddHandler(ActiveContentChangedEvent, value); } remove { Events.RemoveHandler(ActiveContentChangedEvent, value); } } protected virtual void OnActiveContentChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[ActiveContentChangedEvent]; if (handler != null) handler(this, e); } private IDockContent m_activeContent = null; public IDockContent ActiveContent { get { return m_activeContent; } set { if (value == m_activeContent) return; if (value != null) { if (!DockHelper.IsDockStateAutoHide(value.DockHandler.DockState) || value.DockHandler.DockPanel != DockPanel) throw (new InvalidOperationException(Strings.DockPanel_ActiveAutoHideContent_InvalidValue)); } DockPanel.SuspendLayout(); if (m_activeContent != null) { if (m_activeContent.DockHandler.Form.ContainsFocus) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(m_activeContent); } } AnimateWindow(false); } m_activeContent = value; SetActivePane(); if (ActivePane != null) ActivePane.ActiveContent = m_activeContent; if (m_activeContent != null) AnimateWindow(true); DockPanel.ResumeLayout(); DockPanel.RefreshAutoHideStrip(); SetTimerMouseTrack(); OnActiveContentChanged(EventArgs.Empty); } } public DockState DockState { get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockHandler.DockState; } } private bool m_flagAnimate = true; private bool FlagAnimate { get { return m_flagAnimate; } set { m_flagAnimate = value; } } private bool m_flagDragging = false; internal bool FlagDragging { get { return m_flagDragging; } set { if (m_flagDragging == value) return; m_flagDragging = value; SetTimerMouseTrack(); } } private void AnimateWindow(bool show) { if (!FlagAnimate && Visible != show) { Visible = show; return; } Parent.SuspendLayout(); Rectangle rectSource = GetRectangle(!show); Rectangle rectTarget = GetRectangle(show); int dxLoc, dyLoc; int dWidth, dHeight; dxLoc = dyLoc = dWidth = dHeight = 0; if (DockState == DockState.DockTopAutoHide) dHeight = show ? 1 : -1; else if (DockState == DockState.DockLeftAutoHide) dWidth = show ? 1 : -1; else if (DockState == DockState.DockRightAutoHide) { dxLoc = show ? -1 : 1; dWidth = show ? 1 : -1; } else if (DockState == DockState.DockBottomAutoHide) { dyLoc = (show ? -1 : 1); dHeight = (show ? 1 : -1); } if (show) { Bounds = DockPanel.GetAutoHideWindowBounds(new Rectangle(-rectTarget.Width, -rectTarget.Height, rectTarget.Width, rectTarget.Height)); if (Visible == false) Visible = true; PerformLayout(); } SuspendLayout(); LayoutAnimateWindow(rectSource); if (Visible == false) Visible = true; int speedFactor = 1; int totalPixels = (rectSource.Width != rectTarget.Width) ? Math.Abs(rectSource.Width - rectTarget.Width) : Math.Abs(rectSource.Height - rectTarget.Height); int remainPixels = totalPixels; DateTime startingTime = DateTime.Now; while (rectSource != rectTarget) { DateTime startPerMove = DateTime.Now; rectSource.X += dxLoc * speedFactor; rectSource.Y += dyLoc * speedFactor; rectSource.Width += dWidth * speedFactor; rectSource.Height += dHeight * speedFactor; if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc)) rectSource.X = rectTarget.X; if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc)) rectSource.Y = rectTarget.Y; if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth)) rectSource.Width = rectTarget.Width; if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight)) rectSource.Height = rectTarget.Height; LayoutAnimateWindow(rectSource); if (Parent != null) Parent.Update(); remainPixels -= speedFactor; while (true) { TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME); TimeSpan elapsedPerMove = DateTime.Now - startPerMove; TimeSpan elapsedTime = DateTime.Now - startingTime; if (((int)((time - elapsedTime).TotalMilliseconds)) <= 0) { speedFactor = remainPixels; break; } else speedFactor = remainPixels * (int)elapsedPerMove.TotalMilliseconds / (int)((time - elapsedTime).TotalMilliseconds); if (speedFactor >= 1) break; } } ResumeLayout(); Parent.ResumeLayout(); } private void LayoutAnimateWindow(Rectangle rect) { Bounds = DockPanel.GetAutoHideWindowBounds(rect); Rectangle rectClient = ClientRectangle; if (DockState == DockState.DockLeftAutoHide) ActivePane.Location = new Point(rectClient.Right - 2 - Measures.SplitterSize - ActivePane.Width, ActivePane.Location.Y); else if (DockState == DockState.DockTopAutoHide) ActivePane.Location = new Point(ActivePane.Location.X, rectClient.Bottom - 2 - Measures.SplitterSize - ActivePane.Height); } private Rectangle GetRectangle(bool show) { if (DockState == DockState.Unknown) return Rectangle.Empty; Rectangle rect = DockPanel.AutoHideWindowRectangle; if (show) return rect; if (DockState == DockState.DockLeftAutoHide) rect.Width = 0; else if (DockState == DockState.DockRightAutoHide) { rect.X += rect.Width; rect.Width = 0; } else if (DockState == DockState.DockTopAutoHide) rect.Height = 0; else { rect.Y += rect.Height; rect.Height = 0; } return rect; } private void SetTimerMouseTrack() { if (ActivePane == null || ActivePane.IsActivated || FlagDragging) { m_timerMouseTrack.Enabled = false; return; } // start the timer int hovertime = SystemInformation.MouseHoverTime ; // assign a default value 400 in case of setting Timer.Interval invalid value exception if (hovertime <= 0) hovertime = 400; m_timerMouseTrack.Interval = 2 * (int)hovertime; m_timerMouseTrack.Enabled = true; } protected virtual Rectangle DisplayingRectangle { get { Rectangle rect = ClientRectangle; // exclude the border and the splitter if (DockState == DockState.DockBottomAutoHide) { rect.Y += 2 + Measures.SplitterSize; rect.Height -= 2 + Measures.SplitterSize; } else if (DockState == DockState.DockRightAutoHide) { rect.X += 2 + Measures.SplitterSize; rect.Width -= 2 + Measures.SplitterSize; } else if (DockState == DockState.DockTopAutoHide) rect.Height -= 2 + Measures.SplitterSize; else if (DockState == DockState.DockLeftAutoHide) rect.Width -= 2 + Measures.SplitterSize; return rect; } } protected override void OnLayout(LayoutEventArgs levent) { DockPadding.All = 0; if (DockState == DockState.DockLeftAutoHide) { DockPadding.Right = 2; m_splitter.Dock = DockStyle.Right; } else if (DockState == DockState.DockRightAutoHide) { DockPadding.Left = 2; m_splitter.Dock = DockStyle.Left; } else if (DockState == DockState.DockTopAutoHide) { DockPadding.Bottom = 2; m_splitter.Dock = DockStyle.Bottom; } else if (DockState == DockState.DockBottomAutoHide) { DockPadding.Top = 2; m_splitter.Dock = DockStyle.Top; } Rectangle rectDisplaying = DisplayingRectangle; Rectangle rectHidden = new Rectangle(-rectDisplaying.Width, rectDisplaying.Y, rectDisplaying.Width, rectDisplaying.Height); foreach (Control c in Controls) { DockPane pane = c as DockPane; if (pane == null) continue; if (pane == ActivePane) pane.Bounds = rectDisplaying; else pane.Bounds = rectHidden; } base.OnLayout(levent); } protected override void OnPaint(PaintEventArgs e) { // Draw the border Graphics g = e.Graphics; if (DockState == DockState.DockBottomAutoHide) g.DrawLine(SystemPens.ControlLightLight, 0, 1, ClientRectangle.Right, 1); else if (DockState == DockState.DockRightAutoHide) g.DrawLine(SystemPens.ControlLightLight, 1, 0, 1, ClientRectangle.Bottom); else if (DockState == DockState.DockTopAutoHide) { g.DrawLine(SystemPens.ControlDark, 0, ClientRectangle.Height - 2, ClientRectangle.Right, ClientRectangle.Height - 2); g.DrawLine(SystemPens.ControlDarkDark, 0, ClientRectangle.Height - 1, ClientRectangle.Right, ClientRectangle.Height - 1); } else if (DockState == DockState.DockLeftAutoHide) { g.DrawLine(SystemPens.ControlDark, ClientRectangle.Width - 2, 0, ClientRectangle.Width - 2, ClientRectangle.Bottom); g.DrawLine(SystemPens.ControlDarkDark, ClientRectangle.Width - 1, 0, ClientRectangle.Width - 1, ClientRectangle.Bottom); } base.OnPaint(e); } public void RefreshActiveContent() { if (ActiveContent == null) return; if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState)) { FlagAnimate = false; ActiveContent = null; FlagAnimate = true; } } public void RefreshActivePane() { SetTimerMouseTrack(); } private void TimerMouseTrack_Tick(object sender, EventArgs e) { if (IsDisposed) return; if (ActivePane == null || ActivePane.IsActivated) { m_timerMouseTrack.Enabled = false; return; } DockPane pane = ActivePane; Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition); Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition); Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState); if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel)) { ActiveContent = null; m_timerMouseTrack.Enabled = false; } } #region ISplitterDragSource Members void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) { FlagDragging = true; } void ISplitterDragSource.EndDrag() { FlagDragging = false; } bool ISplitterDragSource.IsVertical { get { return (DockState == DockState.DockLeftAutoHide || DockState == DockState.DockRightAutoHide); } } Rectangle ISplitterDragSource.DragLimitBounds { get { Rectangle rectLimit = DockPanel.DockArea; if ((this as ISplitterDragSource).IsVertical) { rectLimit.X += MeasurePane.MinSize; rectLimit.Width -= 2 * MeasurePane.MinSize; } else { rectLimit.Y += MeasurePane.MinSize; rectLimit.Height -= 2 * MeasurePane.MinSize; } return DockPanel.RectangleToScreen(rectLimit); } } void ISplitterDragSource.MoveSplitter(int offset) { Rectangle rectDockArea = DockPanel.DockArea; IDockContent content = ActiveContent; if (DockState == DockState.DockLeftAutoHide && rectDockArea.Width > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Width; else content.DockHandler.AutoHidePortion = Width + offset; } else if (DockState == DockState.DockRightAutoHide && rectDockArea.Width > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Width; else content.DockHandler.AutoHidePortion = Width - offset; } else if (DockState == DockState.DockBottomAutoHide && rectDockArea.Height > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion -= ((double)offset) / (double)rectDockArea.Height; else content.DockHandler.AutoHidePortion = Height - offset; } else if (DockState == DockState.DockTopAutoHide && rectDockArea.Height > 0) { if (content.DockHandler.AutoHidePortion < 1) content.DockHandler.AutoHidePortion += ((double)offset) / (double)rectDockArea.Height; else content.DockHandler.AutoHidePortion = Height + offset; } } #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion #endregion } private AutoHideWindowControl AutoHideWindow { get { return m_autoHideWindow; } } internal Control AutoHideControl { get { return m_autoHideWindow; } } internal void RefreshActiveAutoHideContent() { AutoHideWindow.RefreshActiveContent(); } internal Rectangle AutoHideWindowRectangle { get { DockState state = AutoHideWindow.DockState; Rectangle rectDockArea = DockArea; if (ActiveAutoHideContent == null) return Rectangle.Empty; if (Parent == null) return Rectangle.Empty; Rectangle rect = Rectangle.Empty; double autoHideSize = ActiveAutoHideContent.DockHandler.AutoHidePortion; if (state == DockState.DockLeftAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Width * autoHideSize; if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) autoHideSize = rectDockArea.Width - MeasurePane.MinSize; rect.X = rectDockArea.X; rect.Y = rectDockArea.Y; rect.Width = (int)autoHideSize; rect.Height = rectDockArea.Height; } else if (state == DockState.DockRightAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Width * autoHideSize; if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) autoHideSize = rectDockArea.Width - MeasurePane.MinSize; rect.X = rectDockArea.X + rectDockArea.Width - (int)autoHideSize; rect.Y = rectDockArea.Y; rect.Width = (int)autoHideSize; rect.Height = rectDockArea.Height; } else if (state == DockState.DockTopAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Height * autoHideSize; if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) autoHideSize = rectDockArea.Height - MeasurePane.MinSize; rect.X = rectDockArea.X; rect.Y = rectDockArea.Y; rect.Width = rectDockArea.Width; rect.Height = (int)autoHideSize; } else if (state == DockState.DockBottomAutoHide) { if (autoHideSize < 1) autoHideSize = rectDockArea.Height * autoHideSize; if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) autoHideSize = rectDockArea.Height - MeasurePane.MinSize; rect.X = rectDockArea.X; rect.Y = rectDockArea.Y + rectDockArea.Height - (int)autoHideSize; rect.Width = rectDockArea.Width; rect.Height = (int)autoHideSize; } return rect; } } internal Rectangle GetAutoHideWindowBounds(Rectangle rectAutoHideWindow) { if (DocumentStyle == DocumentStyle.SystemMdi || DocumentStyle == DocumentStyle.DockingMdi) return (Parent == null) ? Rectangle.Empty : Parent.RectangleToClient(RectangleToScreen(rectAutoHideWindow)); else return rectAutoHideWindow; } internal void RefreshAutoHideStrip() { AutoHideStripControl.RefreshChanges(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Drawing; using Edge = Microsoft.Msagl.Drawing.Edge; using Ellipse = Microsoft.Msagl.Core.Geometry.Curves.Ellipse; using LineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment; using Node = Microsoft.Msagl.Drawing.Node; using Point = Microsoft.Msagl.Core.Geometry.Point; using Polyline = Microsoft.Msagl.Core.Geometry.Curves.Polyline; using Shape = Microsoft.Msagl.Drawing.Shape; using Size = System.Windows.Size; namespace Microsoft.Msagl.WpfGraphControl { public class VNode : IViewerNode, IInvalidatable { internal Path BoundaryPath; internal FrameworkElement FrameworkElementOfNodeForLabel; readonly Func<Edge, VEdge> _funcFromDrawingEdgeToVEdge; Subgraph _subgraph; Node _node; Border _collapseButtonBorder; Rectangle _topMarginRect; Path _collapseSymbolPath; readonly Brush _collapseSymbolPathInactive = Brushes.Silver; internal int ZIndex { get { var geomNode = Node.GeometryNode; if (geomNode == null) return 0; int ret = 0; do { if (geomNode.ClusterParents == null) return ret; geomNode = geomNode.ClusterParents.FirstOrDefault(); if (geomNode != null) ret++; else return ret; } while (true); } } public Node Node { get { return _node; } private set { _node = value; _subgraph = _node as Subgraph; } } internal VNode(Node node, FrameworkElement frameworkElementOfNodeForLabelOfLabel, Func<Edge, VEdge> funcFromDrawingEdgeToVEdge, Func<double> pathStrokeThicknessFunc) { PathStrokeThicknessFunc = pathStrokeThicknessFunc; Node = node; FrameworkElementOfNodeForLabel = frameworkElementOfNodeForLabelOfLabel; _funcFromDrawingEdgeToVEdge = funcFromDrawingEdgeToVEdge; CreateNodeBoundaryPath(); if (FrameworkElementOfNodeForLabel != null) { FrameworkElementOfNodeForLabel.Tag = this; //get a backpointer to the VNode Common.PositionFrameworkElement(FrameworkElementOfNodeForLabel, node.GeometryNode.Center, 1); Panel.SetZIndex(FrameworkElementOfNodeForLabel, Panel.GetZIndex(BoundaryPath) + 1); } SetupSubgraphDrawing(); Node.Attr.VisualsChanged += (a, b) => Invalidate(); Node.IsVisibleChanged += obj => { foreach (var frameworkElement in FrameworkElements) { frameworkElement.Visibility = Node.IsVisible ? Visibility.Visible : Visibility.Hidden; } }; } internal IEnumerable<FrameworkElement> FrameworkElements { get { if (FrameworkElementOfNodeForLabel != null) yield return FrameworkElementOfNodeForLabel; if (BoundaryPath != null) yield return BoundaryPath; if (_collapseButtonBorder != null) { yield return _collapseButtonBorder; yield return _topMarginRect; yield return _collapseSymbolPath; } } } void SetupSubgraphDrawing() { if (_subgraph == null) return; SetupTopMarginBorder(); SetupCollapseSymbol(); } void SetupTopMarginBorder() { var cluster = (Cluster) _subgraph.GeometryObject; _topMarginRect = new Rectangle { Fill = Brushes.Transparent, Width = Node.Width, Height = cluster.RectangularBoundary.TopMargin }; PositionTopMarginBorder(cluster); SetZIndexAndMouseInteractionsForTopMarginRect(); } void PositionTopMarginBorder(Cluster cluster) { var box = cluster.BoundaryCurve.BoundingBox; Common.PositionFrameworkElement(_topMarginRect, box.LeftTop + new Point(_topMarginRect.Width/2, -_topMarginRect.Height/2), 1); } void SetZIndexAndMouseInteractionsForTopMarginRect() { _topMarginRect.MouseEnter += ( (a, b) => { _collapseButtonBorder.Background = Common.BrushFromMsaglColor(_subgraph.CollapseButtonColorActive); _collapseSymbolPath.Stroke = Brushes.Black; } ); _topMarginRect.MouseLeave += (a, b) => { _collapseButtonBorder.Background = Common.BrushFromMsaglColor(_subgraph.CollapseButtonColorInactive); _collapseSymbolPath.Stroke = Brushes.Silver; }; Panel.SetZIndex(_topMarginRect, int.MaxValue); } void SetupCollapseSymbol() { var collapseBorderSize = GetCollapseBorderSymbolSize(); Debug.Assert(collapseBorderSize > 0); _collapseButtonBorder = new Border { Background = Common.BrushFromMsaglColor(_subgraph.CollapseButtonColorInactive), Width = collapseBorderSize, Height = collapseBorderSize, CornerRadius = new CornerRadius(collapseBorderSize/2) }; Panel.SetZIndex(_collapseButtonBorder, Panel.GetZIndex(BoundaryPath) + 1); var collapseButtonCenter = GetCollapseButtonCenter(collapseBorderSize); Common.PositionFrameworkElement(_collapseButtonBorder, collapseButtonCenter, 1); double w = collapseBorderSize*0.4; _collapseSymbolPath = new Path { Data = CreateCollapseSymbolPath(collapseButtonCenter + new Point(0, -w/2), w), Stroke = _collapseSymbolPathInactive, StrokeThickness = 1 }; Panel.SetZIndex(_collapseSymbolPath, Panel.GetZIndex(_collapseButtonBorder) + 1); _topMarginRect.MouseLeftButtonDown += TopMarginRectMouseLeftButtonDown; } /// <summary> /// </summary> public event Action<IViewerNode> IsCollapsedChanged; void InvokeIsCollapsedChanged() { if (IsCollapsedChanged != null) IsCollapsedChanged(this); } void TopMarginRectMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { var pos = e.GetPosition(_collapseButtonBorder); if (pos.X <= _collapseButtonBorder.Width && pos.Y <= _collapseButtonBorder.Height && pos.X >= 0 && pos.Y >= 0) { e.Handled = true; var cluster = (Cluster) _subgraph.GeometryNode; cluster.IsCollapsed = !cluster.IsCollapsed; InvokeIsCollapsedChanged(); } } double GetCollapseBorderSymbolSize() { return ((Cluster) _subgraph.GeometryNode).RectangularBoundary.TopMargin - PathStrokeThickness/2 - 0.5; } Point GetCollapseButtonCenter(double collapseBorderSize) { var box = _subgraph.GeometryNode.BoundaryCurve.BoundingBox; //cannot trust subgraph.GeometryNode.BoundingBox for a cluster double offsetFromBoundaryPath = PathStrokeThickness/2 + 0.5; var collapseButtonCenter = box.LeftTop + new Point(collapseBorderSize/2 + offsetFromBoundaryPath, -collapseBorderSize/2 - offsetFromBoundaryPath); return collapseButtonCenter; } /* void FlipCollapsePath() { var size = GetCollapseBorderSymbolSize(); var center = GetCollapseButtonCenter(size); if (collapsePathFlipped) { collapsePathFlipped = false; collapseSymbolPath.RenderTransform = null; } else { collapsePathFlipped = true; collapseSymbolPath.RenderTransform = new RotateTransform(180, center.X, center.Y); } } */ Geometry CreateCollapseSymbolPath(Point center, double width) { var pathGeometry = new PathGeometry(); var pathFigure = new PathFigure {StartPoint = Common.WpfPoint(center + new Point(-width, width))}; pathFigure.Segments.Add(new System.Windows.Media.LineSegment(Common.WpfPoint(center), true)); pathFigure.Segments.Add( new System.Windows.Media.LineSegment(Common.WpfPoint(center + new Point(width, width)), true)); pathGeometry.Figures.Add(pathFigure); return pathGeometry; } internal void CreateNodeBoundaryPath() { if (FrameworkElementOfNodeForLabel != null) { // FrameworkElementOfNode.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); var center = Node.GeometryNode.Center; var margin = 2*Node.Attr.LabelMargin; var bc = NodeBoundaryCurves.GetNodeBoundaryCurve(Node, FrameworkElementOfNodeForLabel .Width + margin, FrameworkElementOfNodeForLabel .Height + margin); bc.Translate(center); // if (LgNodeInfo != null) { // //LgNodeInfo.OriginalCurveOfGeomNode = bc; // Node.GeometryNode.BoundaryCurve = // bc.Transform(PlaneTransformation.ScaleAroundCenterTransformation(LgNodeInfo.Scale, // Node.GeometryNode.Center)) // .Clone(); // } } BoundaryPath = new Path {Data = CreatePathFromNodeBoundary(), Tag = this}; Panel.SetZIndex(BoundaryPath, ZIndex); SetFillAndStroke(); if (Node.Label != null) { BoundaryPath.ToolTip = Node.LabelText; if (FrameworkElementOfNodeForLabel != null) FrameworkElementOfNodeForLabel.ToolTip = Node.LabelText; } } internal Func<double> PathStrokeThicknessFunc; double PathStrokeThickness { get { return PathStrokeThicknessFunc != null ? PathStrokeThicknessFunc() : Node.Attr.LineWidth; } } byte GetTransparency(byte t) { return t; } void SetFillAndStroke() { byte trasparency = GetTransparency(Node.Attr.Color.A); BoundaryPath.Stroke = Common.BrushFromMsaglColor(new Drawing.Color(trasparency, Node.Attr.Color.R, Node.Attr.Color.G, Node.Attr.Color.B)); SetBoundaryFill(); BoundaryPath.StrokeThickness = PathStrokeThickness; var textBlock = FrameworkElementOfNodeForLabel as TextBlock; if (textBlock != null) { var col = Node.Label.FontColor; textBlock.Foreground = Common.BrushFromMsaglColor(new Drawing.Color(GetTransparency(col.A), col.R, col.G, col.B)); } } void SetBoundaryFill() { BoundaryPath.Fill = Common.BrushFromMsaglColor(Node.Attr.FillColor); } Geometry DoubleCircle() { var box = Node.BoundingBox; double w = box.Width; double h = box.Height; var pathGeometry = new PathGeometry(); var r = new Rect(box.Left, box.Bottom, w, h); pathGeometry.AddGeometry(new EllipseGeometry(r)); var inflation = Math.Min(5.0, Math.Min(w/3, h/3)); r.Inflate(-inflation, -inflation); pathGeometry.AddGeometry(new EllipseGeometry(r)); return pathGeometry; } Geometry CreatePathFromNodeBoundary() { Geometry geometry; switch (Node.Attr.Shape) { case Shape.Box: case Shape.House: case Shape.InvHouse: case Shape.Diamond: case Shape.Octagon: case Shape.Hexagon: geometry = CreateGeometryFromMsaglCurve(Node.GeometryNode.BoundaryCurve); break; case Shape.DoubleCircle: geometry = DoubleCircle(); break; default: geometry = GetEllipseGeometry(); break; } return geometry; } Geometry CreateGeometryFromMsaglCurve(ICurve iCurve) { var pathGeometry = new PathGeometry(); var pathFigure = new PathFigure { IsClosed = true, IsFilled = true, StartPoint = Common.WpfPoint(iCurve.Start) }; var curve = iCurve as Curve; if (curve != null) { AddCurve(pathFigure, curve); } else { var rect = iCurve as RoundedRect; if (rect != null) AddCurve(pathFigure, rect.Curve); else { var ellipse = iCurve as Ellipse; if (ellipse != null) { return new EllipseGeometry(Common.WpfPoint(ellipse.Center), ellipse.AxisA.Length, ellipse.AxisB.Length); } var poly = iCurve as Polyline; if (poly != null) { var p = poly.StartPoint.Next; do { pathFigure.Segments.Add(new System.Windows.Media.LineSegment(Common.WpfPoint(p.Point), true)); p = p.NextOnPolyline; } while (p != poly.StartPoint); } } } pathGeometry.Figures.Add(pathFigure); return pathGeometry; } static void AddCurve(PathFigure pathFigure, Curve curve) { foreach (ICurve seg in curve.Segments) { var ls = seg as LineSegment; if (ls != null) pathFigure.Segments.Add(new System.Windows.Media.LineSegment(Common.WpfPoint(ls.End), true)); else { var ellipse = seg as Ellipse; if (ellipse != null) pathFigure.Segments.Add(new ArcSegment(Common.WpfPoint(ellipse.End), new Size(ellipse.AxisA.Length, ellipse.AxisB.Length), Point.Angle(new Point(1, 0), ellipse.AxisA), ellipse.ParEnd - ellipse.ParEnd >= Math.PI, !ellipse.OrientedCounterclockwise() ? SweepDirection.Counterclockwise : SweepDirection.Clockwise, true)); } } } Geometry GetEllipseGeometry() { return new EllipseGeometry(Common.WpfPoint(Node.BoundingBox.Center), Node.BoundingBox.Width/2, Node.BoundingBox.Height/2); } #region Implementation of IViewerObject public DrawingObject DrawingObject { get { return Node; } } public bool MarkedForDragging { get; set; } public event EventHandler MarkedForDraggingEvent; public event EventHandler UnmarkedForDraggingEvent; #endregion public IEnumerable<IViewerEdge> InEdges { get { return Node.InEdges.Select(e => _funcFromDrawingEdgeToVEdge(e)); } } public IEnumerable<IViewerEdge> OutEdges { get { return Node.OutEdges.Select(e => _funcFromDrawingEdgeToVEdge(e)); } } public IEnumerable<IViewerEdge> SelfEdges { get { return Node.SelfEdges.Select(e => _funcFromDrawingEdgeToVEdge(e)); } } public void SetStrokeFill() { throw new NotImplementedException(); } public void Invalidate() { if (!Node.IsVisible) { foreach (var fe in FrameworkElements) fe.Visibility = Visibility.Hidden; return; } BoundaryPath.Data = CreatePathFromNodeBoundary(); Common.PositionFrameworkElement(FrameworkElementOfNodeForLabel, Node.BoundingBox.Center, 1); SetFillAndStroke(); if (_subgraph == null) return; PositionTopMarginBorder((Cluster) _subgraph.GeometryNode); double collapseBorderSize = GetCollapseBorderSymbolSize(); var collapseButtonCenter = GetCollapseButtonCenter(collapseBorderSize); Common.PositionFrameworkElement(_collapseButtonBorder, collapseButtonCenter, 1); double w = collapseBorderSize*0.4; _collapseSymbolPath.Data = CreateCollapseSymbolPath(collapseButtonCenter + new Point(0, -w/2), w); _collapseSymbolPath.RenderTransform = ((Cluster) _subgraph.GeometryNode).IsCollapsed ? new RotateTransform(180, collapseButtonCenter.X, collapseButtonCenter.Y) : null; _topMarginRect.Visibility = _collapseSymbolPath.Visibility = _collapseButtonBorder.Visibility = Visibility.Visible; } public override string ToString() { return Node.Id; } internal void DetouchFromCanvas(Canvas graphCanvas) { if (BoundaryPath != null) graphCanvas.Children.Remove(BoundaryPath); if (FrameworkElementOfNodeForLabel != null) graphCanvas.Children.Remove(FrameworkElementOfNodeForLabel); } } }
//! \file ImageGR2.cs //! \date Tue Jul 21 03:54:51 2015 //! \brief AdvSys engine image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; using GameRes.Utility; namespace GameRes.Formats.AdvSys { [Export(typeof(ImageFormat))] public class Gr2Format : ImageFormat { public override string Tag { get { return "GR2"; } } public override string Description { get { return "AdvSys engine image format"; } } public override uint Signature { get { return 0x5F325247; } } // 'GR2_' public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[16]; if (16 != stream.Read (header, 0, 16)) return null; return new ImageMetaData { Width = LittleEndian.ToUInt16 (header, 4), Height = LittleEndian.ToUInt16 (header, 6), BPP = LittleEndian.ToInt16 (header, 12) * 8 }; } public override ImageData Read (Stream stream, ImageMetaData info) { stream.Position = 0x10; int stride = ((int)info.Width * info.BPP/8 + 3) & ~3; var pixels = new byte[stride * info.Height]; if (pixels.Length != stream.Read (pixels, 0, pixels.Length)) throw new InvalidFormatException ("Unexpected end of file"); PixelFormat format; switch (info.BPP) { case 32: format = PixelFormats.Bgra32; break; case 24: format = PixelFormats.Bgr24; break; case 16: format = PixelFormats.Bgr565; break; default: throw new NotSupportedException ("Not supported image bitdepth"); } return ImageData.Create (info, format, null, pixels, stride); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("Gr2Format.Write not implemented"); } } internal class PolaMetaData : ImageMetaData { public int UnpackedSize; } [Export(typeof(ImageFormat))] public class PolaFormat : Gr2Format { public override string Tag { get { return "GR2/Pola"; } } public override string Description { get { return "AdvSys engine compressed image format"; } } public override uint Signature { get { return 0x6C6F502A; } } // '*Pola*' public PolaFormat () { Extensions = new string[] { "gr2" }; } public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[20]; if (20 != stream.Read (header, 0, 20)) return null; if (!Binary.AsciiEqual (header, "*Pola* ")) return null; int unpacked_size = LittleEndian.ToInt32 (header, 8); using (var reader = new PolaReader (stream, 64)) { reader.Unpack(); using (var temp = new MemoryStream (reader.Data)) { var info = base.ReadMetaData (temp); if (null == info) return null; return new PolaMetaData { Width = info.Width, Height = info.Height, BPP = info.BPP, UnpackedSize = unpacked_size, }; } } } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = info as PolaMetaData; if (null == meta) throw new ArgumentException ("PolaFormat.Read should be supplied with PolaMetaData", "info"); stream.Position = 0x14; using (var reader = new PolaReader (stream, meta.UnpackedSize)) { reader.Unpack(); using (var temp = new MemoryStream (reader.Data)) return base.Read (temp, info); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PolaFormat.Write not implemented"); } } internal sealed class PolaReader : IDisposable { BinaryReader m_input; byte[] m_output; public byte[] Data { get { return m_output; } } public PolaReader (Stream input, int unpacked_size) { m_input = new ArcView.Reader (input); m_output = new byte[unpacked_size+2]; } public void Unpack () { NextBit(); int dst = 0; while (dst < m_output.Length-2) { if (0 != NextBit()) { m_output[dst++] = m_input.ReadByte(); continue; } int offset, count = 0; if (0 != NextBit()) { offset = m_input.ReadByte() - 256; if (0 == NextBit()) { count += 256; } if (0 == NextBit()) { offset -= 512; if (0 == NextBit()) { count *= 2; if (0 == NextBit()) count += 256; offset -= 512; if (0 == NextBit()) { count *= 2; if (0 == NextBit()) count += 256; offset -= 1024; if (0 == NextBit()) { offset -= 2048; count *= 2; if (0 == NextBit()) count += 256; } } } } offset -= count; if (0 != NextBit()) count = 3; else if (0 != NextBit()) count = 4; else if (0 != NextBit()) count = 5; else if (0 != NextBit()) count = 6; else if (0 != NextBit()) { if (0 != NextBit()) count = 8; else count = 7; } else if (0 == NextBit()) { count = 9; if (0 != NextBit()) count += 4; if (0 != NextBit()) count += 2; if (0 != NextBit()) ++count; } else { count = m_input.ReadByte() + 17; } if (dst + count > m_output.Length) count = m_output.Length - dst; Binary.CopyOverlapped (m_output, dst + offset, dst, count); dst += count; } else { offset = m_input.ReadByte() - 256; if (0 == NextBit()) { if (offset != -1) { int src = dst + offset; m_output[dst++] = m_output[src++]; m_output[dst++] = m_output[src++]; } else if (0 == NextBit()) break; } else { offset -= 256; if (0 == NextBit()) offset -= 1024; if (0 == NextBit()) offset -= 512; if (0 == NextBit()) offset -= 256; int src = dst + offset; m_output[dst++] = m_output[src++]; m_output[dst++] = m_output[src++]; } } } } int m_flag = 2; int NextBit () { int bit = m_flag & 1; m_flag >>= 1; if (1 == m_flag) { m_flag = m_input.ReadUInt16() | 0x10000; } return bit; } #region IDisposable Members bool m_disposed = false; public void Dispose () { if (!m_disposed) { m_input.Dispose(); m_disposed = true; } } #endregion } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: HttpModuleRegistry.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections; using System.Security; using System.Web; #endregion internal sealed class HttpModuleRegistry { private static Hashtable _moduleListByApp; private static readonly object _lock = new object(); public static bool RegisterInPartialTrust(HttpApplication application, IHttpModule module) { if (application == null) throw new ArgumentNullException("application"); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // On-demand allocate a map of modules per application. // if (_moduleListByApp == null) _moduleListByApp = new Hashtable(); // // Get the list of modules for the application. If this is // the first registration for the supplied application object // then setup a new and empty list. // IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) { moduleList = new ArrayList(4); _moduleListByApp.Add(application, moduleList); } else if (moduleList.Contains(module)) throw new ApplicationException("Duplicate module registration."); // // Add the module to list of registered modules for the // given application object. // moduleList.Add(module); } // // Setup a closure to automatically unregister the module // when the application fires its Disposed event. // Housekeeper housekeeper = new Housekeeper(module); application.Disposed += new EventHandler(housekeeper.OnApplicationDisposed); return true; } private static bool UnregisterInPartialTrust(HttpApplication application, IHttpModule module) { Debug.Assert(application != null); Debug.Assert(module != null); if (module == null) throw new ArgumentNullException("module"); if (IsHighlyTrusted()) return false; lock (_lock) { // // Get the module list for the given application object. // if (_moduleListByApp == null) return false; IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) return false; // // Remove the module from the list if it's in there. // int index = moduleList.IndexOf(module); if (index < 0) return false; moduleList.RemoveAt(index); // // If the list is empty then remove the application entry. // If this results in the entire map becoming empty then // release it. // if (moduleList.Count == 0) { _moduleListByApp.Remove(application); if (_moduleListByApp.Count == 0) _moduleListByApp = null; } } return true; } public static ICollection GetModules(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); try { IHttpModule[] modules = new IHttpModule[application.Modules.Count]; application.Modules.CopyTo(modules, 0); return modules; } catch (SecurityException) { // // Pass through because probably this is a partially trusted // environment that does not have access to the modules // collection over HttpApplication so we have to resort // to our own devices... // } lock (_lock) { if (_moduleListByApp == null) return new IHttpModule[0]; IList moduleList = (IList) _moduleListByApp[application]; if (moduleList == null) return new IHttpModule[0]; IHttpModule[] modules = new IHttpModule[moduleList.Count]; moduleList.CopyTo(modules, 0); return modules; } } private static bool IsHighlyTrusted() { #if NET_1_0 // // ASP.NET 1.0 applications always required and ran under full // trust so we just return true here. // return true; #else try { AspNetHostingPermission permission = new AspNetHostingPermission(AspNetHostingPermissionLevel.High); permission.Demand(); return true; } catch (SecurityException) { return false; } #endif } private HttpModuleRegistry() { throw new NotSupportedException(); } internal sealed class Housekeeper { private readonly IHttpModule _module; public Housekeeper(IHttpModule module) { _module = module; } public void OnApplicationDisposed(object sender, EventArgs e) { UnregisterInPartialTrust((HttpApplication) sender, _module); } } } }
/* * Copyright 2007 ZXing authors * * 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 ZXing.Common; namespace ZXing.QrCode.Internal { /// <author>Sean Owen</author> sealed class BitMatrixParser { private readonly BitMatrix bitMatrix; private Version parsedVersion; private FormatInformation parsedFormatInfo; private bool mirrored; /// <param name="bitMatrix">{@link BitMatrix} to parse</param> /// <throws>ReaderException if dimension is not >= 21 and 1 mod 4</throws> internal static BitMatrixParser createBitMatrixParser(BitMatrix bitMatrix) { int dimension = bitMatrix.Height; if (dimension < 21 || (dimension & 0x03) != 1) { return null; } return new BitMatrixParser(bitMatrix); } private BitMatrixParser(BitMatrix bitMatrix) { // Should only be called from createBitMatrixParser with the important checks before this.bitMatrix = bitMatrix; } /// <summary> <p>Reads format information from one of its two locations within the QR Code.</p> /// /// </summary> /// <returns> {@link FormatInformation} encapsulating the QR Code's format info /// </returns> /// <throws> ReaderException if both format information locations cannot be parsed as </throws> /// <summary> the valid encoding of format information /// </summary> internal FormatInformation readFormatInformation() { if (parsedFormatInfo != null) { return parsedFormatInfo; } // Read top-left format info bits int formatInfoBits1 = 0; for (int i = 0; i < 6; i++) { formatInfoBits1 = copyBit(i, 8, formatInfoBits1); } // .. and skip a bit in the timing pattern ... formatInfoBits1 = copyBit(7, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 8, formatInfoBits1); formatInfoBits1 = copyBit(8, 7, formatInfoBits1); // .. and skip a bit in the timing pattern ... for (int j = 5; j >= 0; j--) { formatInfoBits1 = copyBit(8, j, formatInfoBits1); } // Read the top-right/bottom-left pattern too int dimension = bitMatrix.Height; int formatInfoBits2 = 0; int jMin = dimension - 7; for (int j = dimension - 1; j >= jMin; j--) { formatInfoBits2 = copyBit(8, j, formatInfoBits2); } for (int i = dimension - 8; i < dimension; i++) { formatInfoBits2 = copyBit(i, 8, formatInfoBits2); } parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2); if (parsedFormatInfo != null) { return parsedFormatInfo; } return null; } /// <summary> <p>Reads version information from one of its two locations within the QR Code.</p> /// /// </summary> /// <returns> {@link Version} encapsulating the QR Code's version /// </returns> /// <throws> ReaderException if both version information locations cannot be parsed as </throws> /// <summary> the valid encoding of version information /// </summary> internal Version readVersion() { if (parsedVersion != null) { return parsedVersion; } int dimension = bitMatrix.Height; int provisionalVersion = (dimension - 17) >> 2; if (provisionalVersion <= 6) { return Version.getVersionForNumber(provisionalVersion); } // Read top-right version info: 3 wide by 6 tall int versionBits = 0; int ijMin = dimension - 11; for (int j = 5; j >= 0; j--) { for (int i = dimension - 9; i >= ijMin; i--) { versionBits = copyBit(i, j, versionBits); } } parsedVersion = Version.decodeVersionInformation(versionBits); if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) { return parsedVersion; } // Hmm, failed. Try bottom left: 6 wide by 3 tall versionBits = 0; for (int i = 5; i >= 0; i--) { for (int j = dimension - 9; j >= ijMin; j--) { versionBits = copyBit(i, j, versionBits); } } parsedVersion = Version.decodeVersionInformation(versionBits); if (parsedVersion != null && parsedVersion.DimensionForVersion == dimension) { return parsedVersion; } return null; } private int copyBit(int i, int j, int versionBits) { bool bit = mirrored ? bitMatrix[j, i] : bitMatrix[i, j]; return bit ? (versionBits << 1) | 0x1 : versionBits << 1; } /// <summary> <p>Reads the bits in the {@link BitMatrix} representing the finder pattern in the /// correct order in order to reconstruct the codewords bytes contained within the /// QR Code.</p> /// /// </summary> /// <returns> bytes encoded within the QR Code /// </returns> /// <throws> ReaderException if the exact number of bytes expected is not read </throws> internal byte[] readCodewords() { FormatInformation formatInfo = readFormatInformation(); if (formatInfo == null) return null; Version version = readVersion(); if (version == null) return null; // Get the data mask for the format used in this QR Code. This will exclude // some bits from reading as we wind through the bit matrix. int dimension = bitMatrix.Height; DataMask.unmaskBitMatrix(formatInfo.DataMask, bitMatrix, dimension); BitMatrix functionPattern = version.buildFunctionPattern(); bool readingUp = true; byte[] result = new byte[version.TotalCodewords]; int resultOffset = 0; int currentByte = 0; int bitsRead = 0; // Read columns in pairs, from right to left for (int j = dimension - 1; j > 0; j -= 2) { if (j == 6) { // Skip whole column with vertical alignment pattern; // saves time and makes the other code proceed more cleanly j--; } // Read alternatingly from bottom to top then top to bottom for (int count = 0; count < dimension; count++) { int i = readingUp ? dimension - 1 - count : count; for (int col = 0; col < 2; col++) { // Ignore bits covered by the function pattern if (!functionPattern[j - col, i]) { // Read a bit bitsRead++; currentByte <<= 1; if (bitMatrix[j - col, i]) { currentByte |= 1; } // If we've made a whole byte, save it off if (bitsRead == 8) { result[resultOffset++] = (byte)currentByte; bitsRead = 0; currentByte = 0; } } } } readingUp ^= true; // readingUp = !readingUp; // switch directions } if (resultOffset != version.TotalCodewords) { return null; } return result; } /** * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state. */ internal void remask() { if (parsedFormatInfo == null) { return; // We have no format information, and have no data mask } int dimension = bitMatrix.Height; DataMask.unmaskBitMatrix(parsedFormatInfo.DataMask, bitMatrix, dimension); } /** * Prepare the parser for a mirrored operation. * This flag has effect only on the {@link #readFormatInformation()} and the * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the * {@link #mirror()} method should be called. * * @param mirror Whether to read version and format information mirrored. */ internal void setMirror(bool mirror) { parsedVersion = null; parsedFormatInfo = null; mirrored = mirror; } /** Mirror the bit matrix in order to attempt a second reading. */ internal void mirror() { for (int x = 0; x < bitMatrix.Width; x++) { for (int y = x + 1; y < bitMatrix.Height; y++) { if (bitMatrix[x, y] != bitMatrix[y, x]) { bitMatrix.flip(y, x); bitMatrix.flip(x, y); } } } } } }
/* Copyright 2012-2022 Marco De Salvo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using RDFSharp.Model; using RDFSharp.Query; namespace RDFSharp.Test.Query { [TestClass] public class RDFQueryUtilitiesTest { #region Tests [DataTestMethod] [DataRow("http://res.org/")] public void ShouldParsePatternMemberAsUri(string uri) { RDFPatternMember pMember = RDFQueryUtilities.ParseRDFPatternMember(uri); Assert.IsNotNull(pMember); Assert.IsTrue(pMember is RDFResource pMemberResource && pMemberResource.Equals(new RDFResource(uri))); } [DataTestMethod] [DataRow("hello")] [DataRow("hello^^")] [DataRow("hello^^test")] [DataRow("hello@")] [DataRow("file/system")] public void ShouldParsePatternMemberAsPlainLiteral(string litVal) { RDFPatternMember pMember = RDFQueryUtilities.ParseRDFPatternMember(litVal); Assert.IsNotNull(pMember); Assert.IsTrue(pMember is RDFPlainLiteral pMemberLiteral && pMemberLiteral.Equals(new RDFPlainLiteral(litVal))); } [DataTestMethod] [DataRow("hello","en")] [DataRow("hello","en-US")] [DataRow("hello","en-US1-US2")] [DataRow("hello^^","en-US")] public void ShouldParsePatternMemberAsPlainLiteralWithLanguage(string litVal, string litLang) { RDFPatternMember pMember = RDFQueryUtilities.ParseRDFPatternMember($"{litVal}@{litLang}"); Assert.IsNotNull(pMember); Assert.IsTrue(pMember is RDFPlainLiteral pMemberLiteral && pMemberLiteral.Equals(new RDFPlainLiteral(litVal, litLang))); } [TestMethod] public void ShouldParsePatternMemberAsTypedLiteral() { RDFPatternMember pMember = RDFQueryUtilities.ParseRDFPatternMember("25^^http://www.w3.org/2001/XMLSchema#integer"); Assert.IsNotNull(pMember); Assert.IsTrue(pMember is RDFTypedLiteral pMemberLiteral && pMemberLiteral.Equals(new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER))); } [DataTestMethod] [DataRow(null, null, 0)] [DataRow(null, "ex:res1", -1)] [DataRow(null, "lit1", -1)] [DataRow(null, "lit1@en-US", -1)] [DataRow(null, "lit^^http://www.w3.org/2001/XMLSchema#string", -1)] [DataRow("ex:res1", null, 1)] [DataRow("lit1", null, 1)] [DataRow("lit1@en-US", null, 1)] [DataRow("lit^^http://www.w3.org/2001/XMLSchema#string", null, 1)] public void ShouldCompareNullPatternMembers(string leftVal, string rightVal, int expectedCompare) { RDFPatternMember leftPMember = null, rightPMember = null; if (leftVal != null) leftPMember = RDFQueryUtilities.ParseRDFPatternMember(leftVal); if (rightVal != null) rightPMember = RDFQueryUtilities.ParseRDFPatternMember(rightVal); Assert.IsTrue(RDFQueryUtilities.CompareRDFPatternMembers(leftPMember, rightPMember) == expectedCompare); } [DataTestMethod] [DataRow("ex:res1", "ex:res2", -1)] [DataRow("ex:res1", "ex:res1", 0)] [DataRow("ex:res2", "ex:res1", 1)] [DataRow("ex:res1", "lit", -1)] [DataRow("ex:res1", "alit", 1)] [DataRow("ex:res1", "lit@en-US", -1)] [DataRow("ex:res1", "alit@en-US", 1)] [DataRow("ex:res1", "lit^^http://www.w3.org/2001/XMLSchema#string", -1)] [DataRow("ex:res1", "alit^^http://www.w3.org/2001/XMLSchema#string", 1)] [DataRow("ex:res1", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] [DataRow("lit1", "ex:res1", 1)] [DataRow("lit1", "lit2", -1)] [DataRow("lit1", "lit1@en-US", -1)] [DataRow("lit1", "lit1", 0)] [DataRow("lit2", "lit1", 1)] [DataRow("lit1", "lit^^http://www.w3.org/2001/XMLSchema#string", 1)] [DataRow("lit1", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] [DataRow("lit1@en-US", "ex:res1", 1)] [DataRow("lit1@en-US", "lit2", -1)] [DataRow("lit1@en-US", "lit1@en-US", 0)] [DataRow("lit1@en-US", "lit1", 1)] [DataRow("lit1@en", "lit1@en-US", -1)] [DataRow("lit1@en", "lit^^http://www.w3.org/2001/XMLSchema#string", 1)] [DataRow("lit1@en", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "true^^http://www.w3.org/2001/XMLSchema#boolean", -1)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "false^^http://www.w3.org/2001/XMLSchema#boolean", 0)] [DataRow("true^^http://www.w3.org/2001/XMLSchema#boolean", "false^^http://www.w3.org/2001/XMLSchema#boolean", 1)] [DataRow("true^^http://www.w3.org/2001/XMLSchema#boolean", "true^^http://www.w3.org/2001/XMLSchema#boolean", 0)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "ex:res", -99)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "lit", -99)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "lit@en-US", -99)] [DataRow("false^^http://www.w3.org/2001/XMLSchema#boolean", "lit^^http://www.w3.org/2001/XMLSchema#string", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "25.8^^http://www.w3.org/2001/XMLSchema#float", -1)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "25.0^^http://www.w3.org/2001/XMLSchema#double", 0)] [DataRow("25.8^^http://www.w3.org/2001/XMLSchema#float", "25^^http://www.w3.org/2001/XMLSchema#integer", 1)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "ex:res", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "lit", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "lit@en-US", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "lit^^http://www.w3.org/2001/XMLSchema#string", -99)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "hellu^^http://www.w3.org/2001/XMLSchema#string", -1)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "hello^^http://www.w3.org/2001/XMLSchema#string", 0)] [DataRow("hellu^^http://www.w3.org/2001/XMLSchema#string", "hello^^http://www.w3.org/2001/XMLSchema#string", 1)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "ex:res", 1)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "ex:res", -99)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "hello", 0)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "hello", -99)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "hello@en-US", -1)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "hello@en-US", -99)] [DataRow("hello^^http://www.w3.org/2001/XMLSchema#string", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "hello^^http://www.w3.org/2001/XMLSchema#string", -99)] [DataRow("2022-03-04T12:00:00.000Z^^http://www.w3.org/2001/XMLSchema#dateTime", "2022-03-04T13:00:00.000Z^^http://www.w3.org/2001/XMLSchema#dateTime", -1)] [DataRow("2022-03-04T12:00:00Z^^http://www.w3.org/2001/XMLSchema#dateTime", "2022-03-04T12:00:00.0Z^^http://www.w3.org/2001/XMLSchema#dateTime", 0)] [DataRow("2022-03-04T12:00:00.000Z^^http://www.w3.org/2001/XMLSchema#dateTime", "2022-03-04T11:00:00Z^^http://www.w3.org/2001/XMLSchema#dateTime", 1)] [DataRow("12:00:00Z^^http://www.w3.org/2001/XMLSchema#time", "ex:res", -99)] [DataRow("ex:res", "12:00:00Z^^http://www.w3.org/2001/XMLSchema#time", -1)] [DataRow("12:00:00Z^^http://www.w3.org/2001/XMLSchema#time", "lit", -99)] [DataRow("lit", "12:00:00Z^^http://www.w3.org/2001/XMLSchema#time", -1)] [DataRow("12:00:00Z^^http://www.w3.org/2001/XMLSchema#time", "lit@en-US", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "2022-03-04Z^^http://www.w3.org/2001/XMLSchema#date", -99)] [DataRow("2022-03-04Z^^http://www.w3.org/2001/XMLSchema#date", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] [DataRow("P1Y^^http://www.w3.org/2001/XMLSchema#duration", "P1YT1H^^http://www.w3.org/2001/XMLSchema#duration", -1)] [DataRow("P1YT1H^^http://www.w3.org/2001/XMLSchema#duration", "P1YT1H0M0S^^http://www.w3.org/2001/XMLSchema#duration", 0)] [DataRow("P1YT1H^^http://www.w3.org/2001/XMLSchema#duration", "P1Y0M0D^^http://www.w3.org/2001/XMLSchema#duration", 1)] [DataRow("P1Y^^http://www.w3.org/2001/XMLSchema#duration", "ex:res", -99)] [DataRow("ex:res", "P1Y^^http://www.w3.org/2001/XMLSchema#duration", -99)] [DataRow("P1Y^^http://www.w3.org/2001/XMLSchema#duration", "lit", -99)] [DataRow("lit", "P1Y^^http://www.w3.org/2001/XMLSchema#duration", -99)] [DataRow("P1Y^^http://www.w3.org/2001/XMLSchema#duration", "lit@en-US", -99)] [DataRow("25^^http://www.w3.org/2001/XMLSchema#integer", "P1Y^^http://www.w3.org/2001/XMLSchema#duration", -99)] [DataRow("P1Y^^http://www.w3.org/2001/XMLSchema#duration", "25^^http://www.w3.org/2001/XMLSchema#integer", -99)] public void ShouldCompareNotNullPatternMembers(string leftVal, string rightVal, int expectedCompare) { RDFPatternMember leftPMember = RDFQueryUtilities.ParseRDFPatternMember(leftVal); RDFPatternMember rightPMember = RDFQueryUtilities.ParseRDFPatternMember(rightVal); switch (expectedCompare) { //Type Error case -99: Assert.IsTrue(RDFQueryUtilities.CompareRDFPatternMembers(leftPMember, rightPMember) == -99); break; //LowerThan case -1: Assert.IsTrue(RDFQueryUtilities.CompareRDFPatternMembers(leftPMember, rightPMember) < 0); break; //EqualsTo case 0: Assert.IsTrue(RDFQueryUtilities.CompareRDFPatternMembers(leftPMember, rightPMember) == 0); break; //GreaterThan case 1: Assert.IsTrue(RDFQueryUtilities.CompareRDFPatternMembers(leftPMember, rightPMember) > 0); break; } } [TestMethod] public void ShouldAbbreviateNamespaceByPrefixSearch() { (bool, string) result = RDFQueryUtilities.AbbreviateRDFPatternMember(new RDFResource("test:HTML"), new List<RDFNamespace>() { new RDFNamespace("test","http://test/") }); Assert.IsNotNull(result); Assert.IsTrue(result.Item1); Assert.IsTrue(result.Item2.Equals("test:HTML")); } [TestMethod] public void ShouldAbbreviateNamespaceByNamespaceSearch() { (bool, string) result = RDFQueryUtilities.AbbreviateRDFPatternMember(new RDFResource("http://test/HTML"), new List<RDFNamespace>() { new RDFNamespace("test","http://test/") }); Assert.IsNotNull(result); Assert.IsTrue(result.Item1); Assert.IsTrue(result.Item2.Equals("test:HTML")); } [TestMethod] public void ShouldAbbreviateNamespaceByNamespaceSearchMatchingFirst() { (bool, string) result = RDFQueryUtilities.AbbreviateRDFPatternMember(new RDFResource("http://test/HTML"), new List<RDFNamespace>() { new RDFNamespace("test1","http://test"), new RDFNamespace("test2","http://test") }); Assert.IsNotNull(result); Assert.IsTrue(result.Item1); Assert.IsTrue(result.Item2.Equals("test1:HTML")); } [TestMethod] public void ShouldAbbreviateNamespaceByNamespaceSearchAtSecondAttempt() { (bool, string) result = RDFQueryUtilities.AbbreviateRDFPatternMember(new RDFResource("http://test/HTML1"), new List<RDFNamespace>() { new RDFNamespace("test1","http://test/HTML"), new RDFNamespace("test2","http://test/") }); Assert.IsNotNull(result); Assert.IsTrue(result.Item1); Assert.IsTrue(result.Item2.Equals("test2:HTML1")); } [TestMethod] public void ShouldNotAbbreviateNamespaceBecauseNullPrefixes() { (bool, string) result = RDFQueryUtilities.AbbreviateRDFPatternMember(new RDFResource("http://test/HTML"), null); Assert.IsNotNull(result); Assert.IsFalse(result.Item1); Assert.IsTrue(result.Item2.Equals("http://test/HTML")); } [TestMethod] public void ShouldRemoveDuplicates() { List<RDFPatternMember> pMembers = new List<RDFPatternMember>() { new RDFResource("ex:res1"), new RDFResource("ex:res1"), new RDFPlainLiteral("lit1"), new RDFPlainLiteral("lit1"), new RDFPlainLiteral("lit1", "en-US"), new RDFPlainLiteral("lit1", "en-US"), new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER), new RDFTypedLiteral("25", RDFModelEnums.RDFDatatypes.XSD_INTEGER) }; List<RDFPatternMember> pMembersWithoutDuplicates = RDFQueryUtilities.RemoveDuplicates<RDFPatternMember>(pMembers); Assert.IsNotNull(pMembersWithoutDuplicates); Assert.IsTrue(pMembersWithoutDuplicates.Count == 4); } [TestMethod] public void ShouldThrowExceptionOnParsingNullPatternMember() => Assert.ThrowsException<RDFQueryException>(() => RDFQueryUtilities.ParseRDFPatternMember(null)); #endregion } }
using System; /// <summary> /// System.Convert.ToDecimal(Object) /// </summary> public class ConvertToDecimal14 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The object is a byte"); try { byte i = TestLibrary.Generator.GetByte(-55); object ob = i; decimal decimalValue = Convert.ToDecimal(ob); if (decimalValue != i) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The object is an int32"); try { Int32 i = TestLibrary.Generator.GetInt32(-55); object ob = i; decimal decimalValue = Convert.ToDecimal(ob); if (decimalValue != i) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The object is a double"); try { double i = TestLibrary.Generator.GetDouble(-55); object ob = i; decimal decimalValue = Convert.ToDecimal(ob); if (decimalValue != (i as IConvertible).ToDecimal(null)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: The object is a string"); try { string i = "-10001"; object ob = i; decimal decimalValue = Convert.ToDecimal(ob); if (decimalValue != -10001) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: The object is a custom class which implement the iconvertible interface"); try { MyClass myClass = new MyClass(); object ob = myClass; decimal decimalValue = Convert.ToDecimal(ob); if (decimalValue != -1) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The conversion is invalid"); try { char i = '1'; object ob = i; decimal decimalValue = Convert.ToDecimal(ob); TestLibrary.TestFramework.LogError("101", "The InvalidCastException was not thrown as expected"); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToDecimal14 test = new ConvertToDecimal14(); TestLibrary.TestFramework.BeginTestCase("ConvertToDecimal14"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } } public class MyClass : IConvertible { #region IConvertible Members public TypeCode GetTypeCode() { throw new System.Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { return -1; } public double ToDouble(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public float ToSingle(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public object ToType(Type conversionType, IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public uint ToUInt32(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } #endregion }
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Core { public static class KeyTests { public static readonly TheoryData<Algorithm> AsymmetricKeyAlgorithms = Registry.AsymmetricAlgorithms; public static readonly TheoryData<Algorithm> SymmetricKeyAlgorithms = Registry.SymmetricAlgorithms; public static readonly TheoryData<Algorithm> KeylessAlgorithms = Registry.KeylessAlgorithms; public static readonly TheoryData<Algorithm, KeyBlobFormat> PublicKeyBlobFormats = Registry.PublicKeyBlobFormats; public static readonly TheoryData<Algorithm, KeyBlobFormat> PrivateKeyBlobFormats = Registry.PrivateKeyBlobFormats; public static readonly TheoryData<Algorithm, KeyBlobFormat> SymmetricKeyBlobFormats = Registry.SymmetricKeyBlobFormats; #region Properties [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void PropertiesAsymmetric(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.True(k.HasPublicKey); Assert.NotNull(k.PublicKey); Assert.Same(a, k.PublicKey.Algorithm); Assert.True(k.PublicKey.Size > 0); Assert.True(k.Size > 0); } [Theory] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void PropertiesSymmetric(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.False(k.HasPublicKey); Assert.Throws<InvalidOperationException>(() => k.PublicKey); Assert.True(k.Size > 0); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void PropertiesAsymmetricAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); k.Dispose(); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.NotNull(k.PublicKey); Assert.Same(a, k.PublicKey.Algorithm); Assert.True(k.PublicKey.Size > 0); Assert.True(k.Size > 0); } [Theory] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void PropertiesSymmetricAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); k.Dispose(); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.False(k.HasPublicKey); Assert.Throws<InvalidOperationException>(() => k.PublicKey); Assert.True(k.Size > 0); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] public static void PropertiesAsymmetricAfterImport(Algorithm a, KeyBlobFormat format) { using var k1 = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); var b = k1.Export(format); using var k = Key.Import(a, b, format, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.True(k.HasPublicKey); Assert.NotNull(k.PublicKey); Assert.Same(a, k.PublicKey.Algorithm); Assert.True(k.PublicKey.Size > 0); Assert.True(k.Size > 0); } [Theory] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void PropertiesSymmetricAfterImport(Algorithm a, KeyBlobFormat format) { using var k1 = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); var b = k1.Export(format); using var k = Key.Import(a, b, format, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Same(a, k.Algorithm); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.False(k.HasPublicKey); Assert.Throws<InvalidOperationException>(() => k.PublicKey); Assert.True(k.Size > 0); } #endregion #region Ctor [Fact] public static void CtorWithNullAlgorithm() { Assert.Throws<ArgumentNullException>("algorithm", () => new Key(null!)); } [Theory] [MemberData(nameof(KeylessAlgorithms))] public static void CtorWithAlgorithmThatDoesNotUseKeys(Algorithm a) { Assert.Throws<NotSupportedException>(() => new Key(a)); } #endregion #region Create [Fact] public static void CreateWithNullAlgorithm() { Assert.Throws<ArgumentNullException>("algorithm", () => Key.Create(null!)); } [Theory] [MemberData(nameof(KeylessAlgorithms))] public static void CreateWithAlgorithmThatDoesNotUseKeys(Algorithm a) { Assert.Throws<NotSupportedException>(() => Key.Create(a)); } #endregion #region Dispose [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void DisposeMoreThanOnce(Algorithm a) { var k = new Key(a); k.Dispose(); k.Dispose(); k.Dispose(); } #endregion #region Import [Fact] public static void ImportWithNullAlgorithm() { Assert.Throws<ArgumentNullException>("algorithm", () => Key.Import(null!, ReadOnlySpan<byte>.Empty, 0)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void ImportWithFormatMin(Algorithm a) { Assert.Throws<ArgumentException>("format", () => Key.Import(a, ReadOnlySpan<byte>.Empty, (KeyBlobFormat)int.MinValue)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void ImportWithFormatMax(Algorithm a) { Assert.Throws<ArgumentException>("format", () => Key.Import(a, ReadOnlySpan<byte>.Empty, (KeyBlobFormat)int.MaxValue)); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] public static void ImportPrivateKeyEmpty(Algorithm a, KeyBlobFormat format) { Assert.Throws<FormatException>(() => Key.Import(a, ReadOnlySpan<byte>.Empty, format)); } [Theory] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void ImportSymmetricKeyEmpty(Algorithm a, KeyBlobFormat format) { Assert.Throws<FormatException>(() => Key.Import(a, ReadOnlySpan<byte>.Empty, format)); } #endregion #region TryImport [Fact] public static void TryImportWithNullAlgorithm() { Assert.Throws<ArgumentNullException>("algorithm", () => Key.TryImport(null!, ReadOnlySpan<byte>.Empty, 0, out var k, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None })); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void TryImportWithFormatMin(Algorithm a) { Assert.Throws<ArgumentException>("format", () => Key.TryImport(a, ReadOnlySpan<byte>.Empty, (KeyBlobFormat)int.MinValue, out var k, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None })); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void TryImportWithFormatMax(Algorithm a) { Assert.Throws<ArgumentException>("format", () => Key.TryImport(a, ReadOnlySpan<byte>.Empty, (KeyBlobFormat)int.MaxValue, out var k, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None })); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] public static void TryImportPrivateKeyEmpty(Algorithm a, KeyBlobFormat format) { Assert.False(Key.TryImport(a, ReadOnlySpan<byte>.Empty, format, out _, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None })); } [Theory] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void TryImportSymmetricKeyEmpty(Algorithm a, KeyBlobFormat format) { Assert.False(Key.TryImport(a, ReadOnlySpan<byte>.Empty, format, out _, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None })); } #endregion #region Export [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void ExportWithFormatMin(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); Assert.Throws<ArgumentException>("format", () => k.Export((KeyBlobFormat)int.MinValue)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void ExportWithFormatMax(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); Assert.Throws<ArgumentException>("format", () => k.Export((KeyBlobFormat)int.MaxValue)); } [Theory] [MemberData(nameof(PublicKeyBlobFormats))] public static void ExportPublicKey(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.NotNull(k.Export(format)); Assert.NotNull(k.Export(format)); Assert.NotNull(k.Export(format)); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void ExportKeyNotAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); Assert.Throws<InvalidOperationException>(() => k.Export(format)); Assert.Throws<InvalidOperationException>(() => k.Export(format)); Assert.Throws<InvalidOperationException>(() => k.Export(format)); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void ExportKeyExportAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); Assert.NotNull(k.Export(format)); Assert.NotNull(k.Export(format)); Assert.NotNull(k.Export(format)); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void ExportPrivateKeyArchivingAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextArchiving }); Assert.Equal(KeyExportPolicies.AllowPlaintextArchiving, k.ExportPolicy); Assert.NotNull(k.Export(format)); Assert.Throws<InvalidOperationException>(() => k.Export(format)); Assert.Throws<InvalidOperationException>(() => k.Export(format)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void ExportPublicKeyAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); k.Dispose(); k.Export(KeyBlobFormat.RawPublicKey); k.Export(KeyBlobFormat.RawPublicKey); k.Export(KeyBlobFormat.RawPublicKey); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void ExportPrivateKeyExportAllowedAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); k.Dispose(); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawPrivateKey)); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawPrivateKey)); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawPrivateKey)); } [Theory] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void ExportSymmetricKeyExportAllowedAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); k.Dispose(); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawSymmetricKey)); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawSymmetricKey)); Assert.Throws<ObjectDisposedException>(() => k.Export(KeyBlobFormat.RawSymmetricKey)); } #endregion #region GetExportBlobSize [Theory] [MemberData(nameof(SymmetricKeyBlobFormats))] [MemberData(nameof(PrivateKeyBlobFormats))] public static void GetExportBlobSize(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); var b = k.Export(format); Assert.NotNull(b); var blobSize = k.GetExportBlobSize(format); Assert.Equal(b.Length, blobSize); } #endregion #region TryExport [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void TryExportWithFormatMin(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); Assert.Throws<ArgumentException>("format", () => k.TryExport((KeyBlobFormat)int.MinValue, Span<byte>.Empty, out _)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void TryExportWithFormatMax(Algorithm a) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); Assert.Throws<ArgumentException>("format", () => k.TryExport((KeyBlobFormat)int.MaxValue, Span<byte>.Empty, out _)); } [Theory] [MemberData(nameof(PublicKeyBlobFormats))] public static void TryExportPublicKey(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); var expected = k.GetExportBlobSize(format); var b = new byte[expected + 100]; Assert.True(k.TryExport(format, b, out var actual)); Assert.Equal(expected, actual); Assert.True(k.TryExport(format, b, out actual)); Assert.Equal(expected, actual); Assert.True(k.TryExport(format, b, out actual)); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void TryExportKeyNotAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); Assert.Equal(KeyExportPolicies.None, k.ExportPolicy); var expected = k.GetExportBlobSize(format); var b = new byte[expected + 100]; Assert.Throws<InvalidOperationException>(() => k.TryExport(format, b, out _)); Assert.Throws<InvalidOperationException>(() => k.TryExport(format, b, out _)); Assert.Throws<InvalidOperationException>(() => k.TryExport(format, b, out _)); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void TryExportKeyExportAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); Assert.Equal(KeyExportPolicies.AllowPlaintextExport, k.ExportPolicy); var expected = k.GetExportBlobSize(format); var b = new byte[expected + 100]; Assert.True(k.TryExport(format, b, out var actual)); Assert.Equal(expected, actual); Assert.True(k.TryExport(format, b, out actual)); Assert.Equal(expected, actual); Assert.True(k.TryExport(format, b, out actual)); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(PrivateKeyBlobFormats))] [MemberData(nameof(SymmetricKeyBlobFormats))] public static void TryExportPrivateKeyArchivingAllowed(Algorithm a, KeyBlobFormat format) { using var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextArchiving }); Assert.Equal(KeyExportPolicies.AllowPlaintextArchiving, k.ExportPolicy); var expected = k.GetExportBlobSize(format); var b = new byte[expected + 100]; Assert.True(k.TryExport(format, b, out var actual)); Assert.Equal(expected, actual); Assert.Throws<InvalidOperationException>(() => k.TryExport(format, b, out _)); Assert.Throws<InvalidOperationException>(() => k.TryExport(format, b, out _)); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void TryExportPublicKeyAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.None }); k.Dispose(); var expected = k.GetExportBlobSize(KeyBlobFormat.RawPublicKey); var b = new byte[expected + 100]; k.TryExport(KeyBlobFormat.RawPublicKey, b, out var actual); Assert.Equal(expected, actual); k.TryExport(KeyBlobFormat.RawPublicKey, b, out actual); Assert.Equal(expected, actual); k.TryExport(KeyBlobFormat.RawPublicKey, b, out actual); Assert.Equal(expected, actual); } [Theory] [MemberData(nameof(AsymmetricKeyAlgorithms))] public static void TryExportPrivateKeyExportAllowedAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); k.Dispose(); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawPrivateKey, Span<byte>.Empty, out _)); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawPrivateKey, Span<byte>.Empty, out _)); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawPrivateKey, Span<byte>.Empty, out _)); } [Theory] [MemberData(nameof(SymmetricKeyAlgorithms))] public static void TryExportSymmetricKeyExportAllowedAfterDispose(Algorithm a) { var k = new Key(a, new KeyCreationParameters { ExportPolicy = KeyExportPolicies.AllowPlaintextExport }); k.Dispose(); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawSymmetricKey, Span<byte>.Empty, out _)); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawSymmetricKey, Span<byte>.Empty, out _)); Assert.Throws<ObjectDisposedException>(() => k.TryExport(KeyBlobFormat.RawSymmetricKey, Span<byte>.Empty, out _)); } #endregion } }
// 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.Collections.Generic; namespace Microsoft.AspNetCore.Razor.TagHelpers { /// <summary> /// A collection of <see cref="TagHelperAttribute"/>s. /// </summary> public class TagHelperAttributeList : ReadOnlyTagHelperAttributeList, IList<TagHelperAttribute> { /// <summary> /// Instantiates a new instance of <see cref="TagHelperAttributeList"/> with an empty collection. /// </summary> public TagHelperAttributeList() : base() { } /// <summary> /// Instantiates a new instance of <see cref="TagHelperAttributeList"/> with the specified /// <paramref name="attributes"/>. /// </summary> /// <param name="attributes">The collection to wrap.</param> public TagHelperAttributeList(IEnumerable<TagHelperAttribute> attributes) : base (new List<TagHelperAttribute>(attributes)) { if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } } /// <summary> /// Instantiates a new instance of <see cref="TagHelperAttributeList"/> with the specified /// <paramref name="attributes"/>. /// </summary> /// <param name="attributes">The collection to wrap.</param> public TagHelperAttributeList(List<TagHelperAttribute> attributes) : base(attributes) { if (attributes == null) { throw new ArgumentNullException(nameof(attributes)); } } /// <inheritdoc /> /// <remarks> /// <paramref name="value"/>'s <see cref="TagHelperAttribute.Name"/> must not be <c>null</c>. /// </remarks> public new TagHelperAttribute this[int index] { get { return base[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } Items[index] = value; } } /// <summary> /// Replaces the first <see cref="TagHelperAttribute"/> with <see cref="TagHelperAttribute.Name"/> matching /// <paramref name="name"/> and removes any additional matching <see cref="TagHelperAttribute"/>s. If a /// matching <see cref="TagHelperAttribute"/> is not found, adds a <see cref="TagHelperAttribute"/> with /// <paramref name="name"/> and <paramref name="value"/> to the end of the collection.</summary> /// <param name="name"> /// The <see cref="TagHelperAttribute.Name"/> of the <see cref="TagHelperAttribute"/> to set. /// </param> /// <param name="value"> /// The <see cref="TagHelperAttribute.Value"/> to set. /// </param> /// <remarks><paramref name="name"/> is compared case-insensitively.</remarks> public void SetAttribute(string name, object value) { var attribute = new TagHelperAttribute(name, value); SetAttribute(attribute); } /// <summary> /// Replaces the first <see cref="TagHelperAttribute"/> with <see cref="TagHelperAttribute.Name"/> matching /// <paramref name="attribute"/>'s <see cref="TagHelperAttribute.Name"/> and removes any additional matching /// <see cref="TagHelperAttribute"/>s. If a matching <see cref="TagHelperAttribute"/> is not found, adds the /// specified <paramref name="attribute"/> to the end of the collection. /// </summary> /// <param name="attribute"> /// The <see cref="TagHelperAttribute"/> to set. /// </param> /// <remarks><paramref name="attribute"/>'s <see cref="TagHelperAttribute.Name"/> is compared /// case-insensitively.</remarks> public void SetAttribute(TagHelperAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } var attributeReplaced = false; // Perf: Avoid allocating enumerator for (var i = 0; i < Items.Count; i++) { if (NameEquals(attribute.Name, Items[i])) { // We replace the first attribute with the provided attribute, remove all the rest. if (!attributeReplaced) { // We replace the first attribute we find with the same name. Items[i] = attribute; attributeReplaced = true; } else { Items.RemoveAt(i--); } } } // If we didn't replace an attribute value we should add value to the end of the collection. if (!attributeReplaced) { Add(attribute); } } /// <inheritdoc /> bool ICollection<TagHelperAttribute>.IsReadOnly => false; /// <summary> /// Adds a <see cref="TagHelperAttribute"/> to the end of the collection with the specified /// <paramref name="name"/> and <paramref name="value"/>. /// </summary> /// <param name="name">The <see cref="TagHelperAttribute.Name"/> of the attribute to add.</param> /// <param name="value">The <see cref="TagHelperAttribute.Value"/> of the attribute to add.</param> public void Add(string name, object value) { var attribute = new TagHelperAttribute(name, value); Items.Add(attribute); } /// <inheritdoc /> public void Add(TagHelperAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } Items.Add(attribute); } /// <inheritdoc /> public void Insert(int index, TagHelperAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } Items.Insert(index, attribute); } /// <inheritdoc /> /// <remarks> /// <paramref name="attribute"/>s <see cref="TagHelperAttribute.Name"/> is compared case-insensitively. /// </remarks> public bool Remove(TagHelperAttribute attribute) { if (attribute == null) { throw new ArgumentNullException(nameof(attribute)); } return Items.Remove(attribute); } /// <inheritdoc /> public void RemoveAt(int index) { Items.RemoveAt(index); } /// <summary> /// Removes all <see cref="TagHelperAttribute"/>s with <see cref="TagHelperAttribute.Name"/> matching /// <paramref name="name"/>. /// </summary> /// <param name="name"> /// The <see cref="TagHelperAttribute.Name"/> of <see cref="TagHelperAttribute"/>s to remove. /// </param> /// <returns> /// <c>true</c> if at least 1 <see cref="TagHelperAttribute"/> was removed; otherwise, <c>false</c>. /// </returns> /// <remarks><paramref name="name"/> is compared case-insensitively.</remarks> public bool RemoveAll(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } // Perf: Avoid allocating enumerator var removedAtLeastOne = false; for (var i = Items.Count - 1; i >= 0; i--) { if (NameEquals(name, Items[i])) { Items.RemoveAt(i); removedAtLeastOne = true; } } return removedAtLeastOne; } /// <inheritdoc /> public void Clear() { Items.Clear(); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/3/2009 10:10:33 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Numeric range using doubles /// </summary> public class Range { #region Private Variables /// <summary> /// Boolean, true if the upper bounds includes the maximum value. /// </summary> private bool _maxIsInclusive; /// <summary> /// The maximum value. If this is null, the upper range is unbounded. /// </summary> private double? _maximum; /// <summary> /// Boolean, true if the the lower bounds includes the minimum value. /// </summary> private bool _minIsInclusive; /// <summary> /// The minimum value. If this is null, the lower range is unbounded. /// </summary> private double? _minimum; #endregion #region Constructors /// <summary> /// Creates a new instance of Range (with undefined interval) /// </summary> public Range() { Minimum = null; Maximum = null; } /// <summary> /// Creates a new instance of Range /// </summary> /// <param name="value1">Either bound of the range</param> /// <param name="value2">The other bound of the range</param> public Range(double? value1, double? value2) { Minimum = value1; Maximum = value2; FixOrder(); } /// <summary> /// Creates an equality type range where both the minimum and maximum are the /// same value and both are inclusive. /// </summary> /// <param name="value"></param> public Range(double value) { Minimum = value; Maximum = value; MinIsInclusive = true; MaxIsInclusive = true; } /// <summary> /// A string expression that can be two separate numbers separated by a dash, /// </summary> /// <param name="expression"></param> public Range(string expression) { string exp = expression ?? "-"; if (exp.Contains(">=") || exp.Contains(">")) { _minIsInclusive = exp.Contains(">="); _maximum = null; double min; if (double.TryParse(exp.Replace(">=", string.Empty).Replace(">", string.Empty), out min)) { _minimum = min; } } else if (exp.Contains("<=") || exp.Contains("<")) { _maxIsInclusive = exp.Contains("<="); _minimum = null; double max; if (double.TryParse(exp.Replace("<=", string.Empty).Replace("<", string.Empty), out max)) { _maximum = max; } } else if (exp.Contains("-")) { // The default is to actually include the maximums, but not the minimums. _maxIsInclusive = true; // - can mean negative or the break. A minus before any numbers means // it is negative. Two dashes in the middle means the second number is negative. // If there is only one dash, treat it like a break, not a negative. int numDashes = CountOf(exp, "-"); string[] args = exp.Split(new[] { '-' }); bool minNegative = false; bool maxNegative = false; int minIndex = 0; int maxIndex = 1; if (numDashes > 1) { // -10 - 20 | 10 - -20 | -20 - -10 if (args[0] == string.Empty) { // -10 - 20 minNegative = true; minIndex = 1; maxIndex = 2; if (numDashes > 2) { // -20 - -10 maxNegative = true; maxIndex = 3; } } else { // the range could be out of order, like 10 - -20. maxNegative = true; maxIndex = 2; } } double min; double max; if (double.TryParse(args[minIndex], out min)) { Minimum = minNegative ? -min : min; } if (double.TryParse(args[maxIndex], out max)) { Maximum = maxNegative ? -max : max; } FixOrder(); } } #endregion #region Methods /// <summary> /// Expresses this range in string form. By default, ranges include the maximum, /// and exclude the minimum. A null value for one expression will result in a /// a semi-unbounded range using the greater than or less than symbols. A null /// expression for both values is completely unbounded and will result in a string /// that reads like [All Values]. /// </summary> /// <returns>A string representing the range.</returns> public override string ToString() { if (_minimum == null && _maximum == null) { return "[All Values]"; } if (_minimum == null) { return _maxIsInclusive ? "<= " + _maximum : "< " + _maximum; } if (_maximum == null) { return _minIsInclusive ? ">= " + _minimum : "> " + _minimum; } return _minimum + " - " + _maximum; } /// <summary> /// This is a slightly more complex specification where the numeric formatting /// controls how the generated string will appear. /// </summary> /// <param name="method">The interval snap method</param> /// <param name="digits">This is only used for rounding or significant figures, but controls those options</param> /// <returns>A string equivalent of this range, but using a number format.</returns> public string ToString(IntervalSnapMethod method, int digits) { if (_minimum == null && _maximum == null) { return "[All Values]"; } if (_minimum == null) { string max = Format(_maximum.Value, method, digits); return _maxIsInclusive ? "<= " + max : "< " + max; } if (_maximum == null) { string min = Format(_minimum.Value, method, digits); return _minIsInclusive ? ">= " + min : "> " + min; } return Format(_minimum.Value, method, digits) + " - " + Format(_maximum.Value, method, digits); } /// <summary> /// Generates a valid SQL query expression for this range, using the field string /// as the member being compared. The field string should already be bound in /// brackets, or put together as a normal composit like "[males]/[pop1990]" /// </summary> /// <param name="field">The field name to build into an expression. This should already be wrapped in square brackets.</param> /// <returns>The string SQL query expression.</returns> public string ToExpression(string field) { if (_minimum == null && _maximum == null) return string.Empty; string maxExp = _maxIsInclusive ? field + " <= " + _maximum : field + " < " + _maximum; string minExp = _minIsInclusive ? field + " >= " + _minimum : field + " > " + _minimum; if (_minimum == null) return maxExp; if (_maximum == null) return minExp; return minExp + " AND " + maxExp; } /// <summary> /// Tests to determine if this range contains the specified double value. /// </summary> /// <param name="value">the double value to test</param> /// <returns>Boolean, true if the value is within the current bounds.</returns> public bool Contains(double value) { if (_minimum == null && _maximum == null) return true; if (_minimum == null) { return _maxIsInclusive ? (value <= _maximum) : (value < _maximum); } if (_maximum == null) { return _minIsInclusive ? (value >= _minimum) : (value > _minimum); } if (_maxIsInclusive && _minIsInclusive) { return value >= _minimum && value <= _maximum; } if (_maxIsInclusive) { return value > _minimum && value <= _maximum; } if (_minIsInclusive) { return value >= _minimum && value < _maximum; } return value > _minimum && value < _maximum; } #endregion #region Properties /// <summary> /// Gets or sets teh Minimum value. If this is null, the lower range is unbounded. /// </summary> [Serialize("Minimum")] public double? Minimum { get { return _minimum; } set { _minimum = value; } } /// <summary> /// The maximum value. If this is null, the upper range is unbounded. /// </summary> [Serialize("Maximum")] public double? Maximum { get { return _maximum; } set { _maximum = value; } } /// <summary> /// Boolean, true if the the lower bounds includes the minimum value. /// </summary> [Serialize("MinIsInclusive")] public bool MinIsInclusive { get { return _minIsInclusive; } set { _minIsInclusive = value; } } /// <summary> /// Boolean, true if the upper bounds includes the maximum value. /// </summary> [Serialize("MaxIsInclusive")] public bool MaxIsInclusive { get { return _maxIsInclusive; } set { _maxIsInclusive = value; } } #endregion private static string Format(double value, IntervalSnapMethod method, int digits) { if (method == IntervalSnapMethod.None) { return value.ToString(); } if (method == IntervalSnapMethod.DataValue) { return value.ToString(); } if (method == IntervalSnapMethod.Rounding) { return value.ToString("N" + digits); } if (method == IntervalSnapMethod.SignificantFigures) { int dig = (int)Math.Ceiling(Math.Log10(Math.Abs(value))); dig = digits - dig; if (dig < 0) dig = 0; if (dig > 10) { return value.ToString("E" + digits); } return value.ToString("N" + dig); } return value.ToString("N"); } /// <summary> /// If the minimum and maximum are out of order, this reverses them. /// </summary> private void FixOrder() { if (Maximum == null || Minimum == null || Maximum.Value >= Minimum.Value) return; double? temp = _maximum; Maximum = Minimum; Minimum = temp; } private static int CountOf(string source, string instance) { int iStart = 0; int count = 0; while ((iStart = source.IndexOf(instance, iStart + 1)) > 0) { count++; } return count; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class TakesScreenshotTest : DriverTestFixture { [TearDown] public void SwitchToTop() { driver.SwitchTo().DefaultContent(); } [Test] public void GetScreenshotAsFile() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; string filename = Path.Combine(Path.GetTempPath(), "snapshot" + new Random().Next().ToString() + ".png"); Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); screenImage.SaveAsFile(filename, ScreenshotImageFormat.Png); Assert.That(File.Exists(filename), Is.True); Assert.That(new FileInfo(filename).Length, Is.GreaterThan(0)); File.Delete(filename); } [Test] public void GetScreenshotAsBase64() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); string base64 = screenImage.AsBase64EncodedString; Assert.That(base64.Length, Is.GreaterThan(0)); } [Test] public void GetScreenshotAsBinary() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = simpleTestPage; Screenshot screenImage = screenshotCapableDriver.GetScreenshot(); byte[] bytes = screenImage.AsByteArray; Assert.That(bytes.Length, Is.GreaterThan(0)); } [Test] public void ShouldCaptureScreenshotOfCurrentViewport() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldTakeScreenshotsOfAnElement() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen.html"); IWebElement element = driver.FindElement(By.Id("cell11")); ITakesScreenshot screenshotCapableElement = element as ITakesScreenshot; if (screenshotCapableElement == null) { return; } Screenshot screenImage = screenshotCapableElement.GetScreenshot(); byte[] imageData = screenImage.AsByteArray; Assert.That(imageData, Is.Not.Null); Assert.That(imageData.Length, Is.GreaterThan(0)); Color pixelColor = GetPixelColor(screenImage, 1, 1); string pixelColorString = FormatColorToHex(pixelColor.ToArgb()); Assert.AreEqual("#0f12f7", pixelColorString); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongX() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_x_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_y_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Chrome, "Chrome driver only captures visible viewport.")] [IgnoreBrowser(Browser.Edge, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Firefox, "Firfox driver only captures visible viewport.")] [IgnoreBrowser(Browser.IE, "IE driver only captures visible viewport.")] [IgnoreBrowser(Browser.EdgeLegacy, "Edge driver only captures visible viewport.")] [IgnoreBrowser(Browser.Safari, "Safari driver only captures visible viewport.")] public void ShouldCaptureScreenshotOfPageWithTooLongXandY() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_too_long.html"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); CompareColors(expectedColors, actualColors); } [Test] public void ShouldCaptureScreenshotAtFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); WaitFor(FrameToBeAvailableAndSwitchedTo("frame1"), "Did not switch to frame1"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(FrameToBeAvailableAndSwitchedTo("frame2"), "Did not switch to frame2"); WaitFor(ElementToBeVisibleWithId("content"), "Did not find visible element with id content"); driver.SwitchTo().DefaultContent(); WaitFor(TitleToBe("screen test"), "Title was not expected value"); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page CompareColors(expectedColors, actualColors); } [Test] public void ShouldCaptureScreenshotAtIFramePage() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); // Resize the window to avoid scrollbars in screenshot Size originalSize = driver.Manage().Window.Size; driver.Manage().Window.Size = new Size(1040, 700); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); driver.Manage().Window.Size = originalSize; HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_frames.html"); driver.SwitchTo().Frame(driver.FindElement(By.Id("frame2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page CompareColors(expectedColors, actualColors); } [Test] [IgnoreBrowser(Browser.Firefox, "Color comparisons fail on Firefox")] public void ShouldCaptureScreenshotAtIFramePageAfterSwitching() { ITakesScreenshot screenshotCapableDriver = driver as ITakesScreenshot; if (screenshotCapableDriver == null) { return; } driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("screen/screen_iframes.html"); // Resize the window to avoid scrollbars in screenshot Size originalSize = driver.Manage().Window.Size; driver.Manage().Window.Size = new Size(1040, 700); driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe2"))); Screenshot screenshot = screenshotCapableDriver.GetScreenshot(); driver.Manage().Window.Size = originalSize; HashSet<string> actualColors = ScanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); HashSet<string> expectedColors = GenerateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); expectedColors.UnionWith(GenerateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page CompareColors(expectedColors, actualColors); } private string FormatColorToHex(int colorValue) { string pixelColorString = string.Format("#{0:x2}{1:x2}{2:x2}", (colorValue & 0xFF0000) >> 16, (colorValue & 0x00FF00) >> 8, (colorValue & 0x0000FF)); return pixelColorString; } private void CompareColors(HashSet<string> expectedColors, HashSet<string> actualColors) { // Ignore black and white for further comparison actualColors.Remove("#000000"); actualColors.Remove("#ffffff"); Assert.That(actualColors, Is.EquivalentTo(expectedColors)); } private HashSet<string> GenerateExpectedColors(int initialColor, int stepColor, int numberOfSamplesX, int numberOfSamplesY) { HashSet<string> colors = new HashSet<string>(); int count = 1; for (int i = 1; i < numberOfSamplesX; i++) { for (int j = 1; j < numberOfSamplesY; j++) { int color = initialColor + (count * stepColor); string hex = FormatColorToHex(color); colors.Add(hex); count++; } } return colors; } private HashSet<string> ScanActualColors(Screenshot screenshot, int stepX, int stepY) { HashSet<string> colors = new HashSet<string>(); #if !NETCOREAPP2_0 && !NETSTANDARD2_0 try { Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); int height = bitmap.Height; int width = bitmap.Width; Assert.That(width, Is.GreaterThan(0)); Assert.That(height, Is.GreaterThan(0)); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { string hex = FormatColorToHex(bitmap.GetPixel(i, j).ToArgb()); colors.Add(hex); } } } catch (Exception e) { Assert.Fail("Unable to get actual colors from screenshot: " + e.Message); } Assert.That(colors.Count, Is.GreaterThan(0)); #endif return colors; } private Color GetPixelColor(Screenshot screenshot, int x, int y) { Color pixelColor = Color.Black; #if !NETCOREAPP2_0 && !NETSTANDARD2_0 Image image = Image.FromStream(new MemoryStream(screenshot.AsByteArray)); Bitmap bitmap = new Bitmap(image); pixelColor = bitmap.GetPixel(1, 1); #endif return pixelColor; } private Func<bool> FrameToBeAvailableAndSwitchedTo(string frameId) { return () => { try { IWebElement frameElement = driver.FindElement(By.Id(frameId)); driver.SwitchTo().Frame(frameElement); } catch(Exception) { return false; } return true; }; } private Func<bool> ElementToBeVisibleWithId(string elementId) { return () => { try { IWebElement element = driver.FindElement(By.Id(elementId)); return element.Displayed; } catch(Exception) { return false; } }; } private Func<bool> TitleToBe(string desiredTitle) { return () => driver.Title == desiredTitle; } } }
using System.IO.IsolatedStorage; namespace Kazyx.WPPMM.Utils { public class Preference { public const string postview_key = "transfer_postview"; public const string interval_enable_key = "interval_enable"; public const string interval_time_key = "interval_time"; public const string display_take_image_button_key = "display_take_image_button"; public const string display_histogram_key = "display_histogram"; public const string add_geotag = "add_geotag"; public const string fraiming_grids = "fraiming_grids"; public const string framing_grids_color = "framing_grids_color"; public const string fibonacci_origin = "fibonacci_origin"; public const string request_focus_frame_info = "request_focus_frame_info"; public const string prioritize_original_contents = "prioritize_original_contents"; public static bool IsPostviewTransferEnabled() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(postview_key)) { return (bool)settings[postview_key]; } else { return true; } } public static void SetPostviewTransferEnabled(bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(postview_key)) { settings.Remove(postview_key); } settings.Add(postview_key, enable); } public static bool IsIntervalShootingEnabled() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(interval_enable_key)) { return (bool)settings[interval_enable_key]; } else { return false; } } public static void SetIntervalShootingEnabled(bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(interval_enable_key)) { settings.Remove(interval_enable_key); } settings.Add(interval_enable_key, enable); } public static int IntervalTime() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(interval_time_key)) { return (int)settings[interval_time_key]; } else { return 10; } } public static void SetIntervalTime(int time) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(interval_time_key)) { settings.Remove(interval_time_key); } settings.Add(interval_time_key, time); } public static bool IsShootButtonDisplayed() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(display_take_image_button_key)) { return (bool)settings[display_take_image_button_key]; } else { return true; } } public static void SetShootButtonDisplayed(bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(display_take_image_button_key)) { settings.Remove(display_take_image_button_key); } settings.Add(display_take_image_button_key, enable); } public static bool IsHistogramDisplayed() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(display_histogram_key)) { return (bool)settings[display_histogram_key]; } return true; } public static void SetHistogramDisplayed(bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(display_histogram_key)) { settings.Remove(display_histogram_key); } settings.Add(display_histogram_key, enable); } public static bool GeotagEnabled() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(add_geotag)) { return (bool)settings[add_geotag]; } return false; } public static void SetGeotagEnabled(bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(add_geotag)) { settings.Remove(add_geotag); } settings.Add(add_geotag, enable); } public static string FramingGridsType() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(fraiming_grids)) { return (string)settings[fraiming_grids]; } return null; } public static void SetFramingGridsType(string type) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(fraiming_grids)) { settings.Remove(fraiming_grids); } settings.Add(fraiming_grids, type); } public static string FramingGridsColor() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(framing_grids_color)) { return (string)settings[framing_grids_color]; } return null; } public static void SetFramingGridsColor(string type) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(framing_grids_color)) { settings.Remove(framing_grids_color); } settings.Add(framing_grids_color, type); } public static string FibonacciOrigin() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(fibonacci_origin)) { return (string)settings[fibonacci_origin]; } return null; } public static void SetFibonacciOrigin(string type) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(fibonacci_origin)) { settings.Remove(fibonacci_origin); } settings.Add(fibonacci_origin, type); } public static bool RequestFocusFrameInfo() { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(request_focus_frame_info)) { return (bool)settings[request_focus_frame_info]; } return true; } public static void SetRequestFocusFrameInfo(bool setting) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(request_focus_frame_info)) { settings.Remove(request_focus_frame_info); } settings.Add(request_focus_frame_info, setting); } public static bool OriginalSizeContentsPrioritized { set { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(prioritize_original_contents)) { settings.Remove(prioritize_original_contents); } settings.Add(prioritize_original_contents, value); } get { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(prioritize_original_contents)) { return (bool)settings[prioritize_original_contents]; } return false; } } public static void SetPreference(string key, bool enable) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(key)) { settings.Remove(key); } settings.Add(key, enable); } public static bool GetPreference(string key) { var settings = IsolatedStorageSettings.ApplicationSettings; if (settings.Contains(key)) { return (bool)settings[key]; } else { return false; } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using FluentAssertions; using Xunit; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.TestFramework; using Microsoft.DotNet.Tools.Test.Utilities; namespace Microsoft.DotNet.Cli.Sln.Internal.Tests { public class GivenAnSlnFile : TestBase { private const string SolutionModified = @" Microsoft Visual Studio Solution File, Format Version 14.00 # Visual Studio 16 VisualStudioVersion = 16.0.26006.2 MinimumVisualStudioVersion = 11.0.40219.1 Project(""{7072A694-548F-4CAE-A58F-12D257D5F486}"") = ""AppModified"", ""AppModified\AppModified.csproj"", ""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = TRUE EndGlobalSection EndGlobal "; private const string SolutionWithAppAndLibProjects = @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26006.2 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject Project(""{13B669BE-BB05-4DDF-9536-439F39A36129}"") = ""Lib"", ""..\Lib\Lib.csproj"", ""{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|Any CPU.Build.0 = Debug|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.ActiveCfg = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x64.Build.0 = Debug|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.ActiveCfg = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Debug|x86.Build.0 = Debug|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.ActiveCfg = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|Any CPU.Build.0 = Release|Any CPU {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.ActiveCfg = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x64.Build.0 = Release|x64 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.ActiveCfg = Release|x86 {7072A694-548F-4CAE-A58F-12D257D5F486}.Release|x86.Build.0 = Release|x86 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|Any CPU.Build.0 = Debug|Any CPU {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x64.ActiveCfg = Debug|x64 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x64.Build.0 = Debug|x64 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x86.ActiveCfg = Debug|x86 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Debug|x86.Build.0 = Debug|x86 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|Any CPU.ActiveCfg = Release|Any CPU {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|Any CPU.Build.0 = Release|Any CPU {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x64.ActiveCfg = Release|x64 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x64.Build.0 = Release|x64 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x86.ActiveCfg = Release|x86 {21D9159F-60E6-4F65-BC6B-D01B71B15FFC}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "; [Fact] public void WhenGivenAValidSlnFileItReadsAndVerifiesContents() { var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionWithAppAndLibProjects); SlnFile slnFile = SlnFile.Read(tmpFile.Path); Console.WriteLine(new { slnFile_FormatVersion = slnFile.FormatVersion, slnFile_ProductDescription = slnFile.ProductDescription, slnFile_VisualStudioVersion = slnFile.VisualStudioVersion, slnFile_MinimumVisualStudioVersion = slnFile.MinimumVisualStudioVersion, slnFile_BaseDirectory = slnFile.BaseDirectory, slnFile_FullPath = slnFile.FullPath, tmpFilePath = tmpFile.Path }.ToString()); slnFile.FormatVersion.Should().Be("12.00"); slnFile.ProductDescription.Should().Be("Visual Studio 15"); slnFile.VisualStudioVersion.Should().Be("15.0.26006.2"); slnFile.MinimumVisualStudioVersion.Should().Be("10.0.40219.1"); slnFile.BaseDirectory.Should().Be(Path.GetDirectoryName(tmpFile.Path)); slnFile.FullPath.Should().Be(Path.GetFullPath(tmpFile.Path)); slnFile.Projects.Count.Should().Be(2); var project = slnFile.Projects[0]; project.Id.Should().Be("{7072A694-548F-4CAE-A58F-12D257D5F486}"); project.TypeGuid.Should().Be("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"); project.Name.Should().Be("App"); project.FilePath.Should().Be(Path.Combine("App", "App.csproj")); project = slnFile.Projects[1]; project.Id.Should().Be("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}"); project.TypeGuid.Should().Be("{13B669BE-BB05-4DDF-9536-439F39A36129}"); project.Name.Should().Be("Lib"); project.FilePath.Should().Be(Path.Combine("..", "Lib", "Lib.csproj")); slnFile.SolutionConfigurationsSection.Count.Should().Be(6); slnFile.SolutionConfigurationsSection .GetValue("Debug|Any CPU", string.Empty) .Should().Be("Debug|Any CPU"); slnFile.SolutionConfigurationsSection .GetValue("Debug|x64", string.Empty) .Should().Be("Debug|x64"); slnFile.SolutionConfigurationsSection .GetValue("Debug|x86", string.Empty) .Should().Be("Debug|x86"); slnFile.SolutionConfigurationsSection .GetValue("Release|Any CPU", string.Empty) .Should().Be("Release|Any CPU"); slnFile.SolutionConfigurationsSection .GetValue("Release|x64", string.Empty) .Should().Be("Release|x64"); slnFile.SolutionConfigurationsSection .GetValue("Release|x86", string.Empty) .Should().Be("Release|x86"); slnFile.ProjectConfigurationsSection.Count.Should().Be(2); var projectConfigSection = slnFile .ProjectConfigurationsSection .GetPropertySet("{7072A694-548F-4CAE-A58F-12D257D5F486}"); projectConfigSection.Count.Should().Be(12); projectConfigSection .GetValue("Debug|Any CPU.ActiveCfg", string.Empty) .Should().Be("Debug|Any CPU"); projectConfigSection .GetValue("Debug|Any CPU.Build.0", string.Empty) .Should().Be("Debug|Any CPU"); projectConfigSection .GetValue("Debug|x64.ActiveCfg", string.Empty) .Should().Be("Debug|x64"); projectConfigSection .GetValue("Debug|x64.Build.0", string.Empty) .Should().Be("Debug|x64"); projectConfigSection .GetValue("Debug|x86.ActiveCfg", string.Empty) .Should().Be("Debug|x86"); projectConfigSection .GetValue("Debug|x86.Build.0", string.Empty) .Should().Be("Debug|x86"); projectConfigSection .GetValue("Release|Any CPU.ActiveCfg", string.Empty) .Should().Be("Release|Any CPU"); projectConfigSection .GetValue("Release|Any CPU.Build.0", string.Empty) .Should().Be("Release|Any CPU"); projectConfigSection .GetValue("Release|x64.ActiveCfg", string.Empty) .Should().Be("Release|x64"); projectConfigSection .GetValue("Release|x64.Build.0", string.Empty) .Should().Be("Release|x64"); projectConfigSection .GetValue("Release|x86.ActiveCfg", string.Empty) .Should().Be("Release|x86"); projectConfigSection .GetValue("Release|x86.Build.0", string.Empty) .Should().Be("Release|x86"); projectConfigSection = slnFile .ProjectConfigurationsSection .GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}"); projectConfigSection.Count.Should().Be(12); projectConfigSection .GetValue("Debug|Any CPU.ActiveCfg", string.Empty) .Should().Be("Debug|Any CPU"); projectConfigSection .GetValue("Debug|Any CPU.Build.0", string.Empty) .Should().Be("Debug|Any CPU"); projectConfigSection .GetValue("Debug|x64.ActiveCfg", string.Empty) .Should().Be("Debug|x64"); projectConfigSection .GetValue("Debug|x64.Build.0", string.Empty) .Should().Be("Debug|x64"); projectConfigSection .GetValue("Debug|x86.ActiveCfg", string.Empty) .Should().Be("Debug|x86"); projectConfigSection .GetValue("Debug|x86.Build.0", string.Empty) .Should().Be("Debug|x86"); projectConfigSection .GetValue("Release|Any CPU.ActiveCfg", string.Empty) .Should().Be("Release|Any CPU"); projectConfigSection .GetValue("Release|Any CPU.Build.0", string.Empty) .Should().Be("Release|Any CPU"); projectConfigSection .GetValue("Release|x64.ActiveCfg", string.Empty) .Should().Be("Release|x64"); projectConfigSection .GetValue("Release|x64.Build.0", string.Empty) .Should().Be("Release|x64"); projectConfigSection .GetValue("Release|x86.ActiveCfg", string.Empty) .Should().Be("Release|x86"); projectConfigSection .GetValue("Release|x86.Build.0", string.Empty) .Should().Be("Release|x86"); slnFile.Sections.Count.Should().Be(3); var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties"); solutionPropertiesSection.Properties.Count.Should().Be(1); solutionPropertiesSection.Properties .GetValue("HideSolutionNode", string.Empty) .Should().Be("FALSE"); } [Fact] public void WhenGivenAValidSlnFileItModifiesSavesAndVerifiesContents() { var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionWithAppAndLibProjects); SlnFile slnFile = SlnFile.Read(tmpFile.Path); slnFile.FormatVersion = "14.00"; slnFile.ProductDescription = "Visual Studio 16"; slnFile.VisualStudioVersion = "16.0.26006.2"; slnFile.MinimumVisualStudioVersion = "11.0.40219.1"; slnFile.Projects.Count.Should().Be(2); var project = slnFile.Projects[0]; project.Id = "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"; project.TypeGuid = "{7072A694-548F-4CAE-A58F-12D257D5F486}"; project.Name = "AppModified"; project.FilePath = Path.Combine("AppModified", "AppModified.csproj"); slnFile.Projects.Remove(slnFile.Projects[1]); slnFile.SolutionConfigurationsSection.Count.Should().Be(6); slnFile.SolutionConfigurationsSection.Remove("Release|Any CPU"); slnFile.SolutionConfigurationsSection.Remove("Release|x64"); slnFile.SolutionConfigurationsSection.Remove("Release|x86"); slnFile.ProjectConfigurationsSection.Count.Should().Be(2); var projectConfigSection = slnFile .ProjectConfigurationsSection .GetPropertySet("{21D9159F-60E6-4F65-BC6B-D01B71B15FFC}"); slnFile.ProjectConfigurationsSection.Remove(projectConfigSection); slnFile.Sections.Count.Should().Be(3); var solutionPropertiesSection = slnFile.Sections.GetSection("SolutionProperties"); solutionPropertiesSection.Properties.Count.Should().Be(1); solutionPropertiesSection.Properties.SetValue("HideSolutionNode", "TRUE"); slnFile.Write(); File.ReadAllText(tmpFile.Path) .Should().Be(SolutionModified); } [Theory] [InlineData("Microsoft Visual Studio Solution File, Format Version ", 1)] [InlineData("First Line\nMicrosoft Visual Studio Solution File, Format Version ", 2)] [InlineData("First Line\nMicrosoft Visual Studio Solution File, Format Version \nThird Line", 2)] [InlineData("First Line\nSecondLine\nMicrosoft Visual Studio Solution File, Format Version \nFourth Line", 3)] public void WhenGivenASolutionWithMissingHeaderVersionItThrows(string fileContents, int lineNum) { var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(fileContents); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage($"Invalid format in line {lineNum}: File header is missing version"); } [Theory] [InlineData("Invalid Solution")] [InlineData("Invalid Solution\nSpanning Multiple Lines")] [InlineData("Microsoft Visual\nStudio Solution File,\nFormat Version ")] public void WhenGivenASolutionWithMissingHeaderItThrows(string fileContents) { var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(fileContents); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Expected file header not found"); } [Fact] public void WhenGivenASolutionWithMultipleGlobalSectionsItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Global EndGlobal Global EndGlobal "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 5: Global section specified more than once"); } [Fact] public void WhenGivenASolutionWithGlobalSectionNotClosedItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Global "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 3: Global section not closed"); } [Fact] public void WhenGivenASolutionWithProjectSectionNotClosedItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 3: Project section not closed"); } [Fact] public void WhenGivenASolutionWithInvalidProjectSectionItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Project""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""App"", ""App\App.csproj"", ""{7072A694-548F-4CAE-A58F-12D257D5F486}"" EndProject "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 3: Project section is missing '(' when parsing the line starting at position 0"); } [Fact] public void WhenGivenASolutionWithInvalidSectionTypeItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Global GlobalSection(SolutionConfigurationPlatforms) = thisIsUnknown EndGlobalSection EndGlobal "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 4: Invalid section type: thisIsUnknown"); } [Fact] public void WhenGivenASolutionWithMissingSectionIdTypeItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Global GlobalSection = preSolution EndGlobalSection EndGlobal "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 4: Section id missing"); } [Fact] public void WhenGivenASolutionWithSectionNotClosedItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution EndGlobal "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { SlnFile.Read(tmpFile.Path); }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 6: Closing section tag not found"); } [Fact] public void WhenGivenASolutionWithInvalidPropertySetItThrows() { const string SolutionFile = @" Microsoft Visual Studio Solution File, Format Version 12.00 Project(""{7072A694-548F-4CAE-A58F-12D257D5F486}"") = ""AppModified"", ""AppModified\AppModified.csproj"", ""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"" EndProject Global GlobalSection(ProjectConfigurationPlatforms) = postSolution {7072A694-548F-4CAE-A58F-12D257D5F486} Debug|Any CPU ActiveCfg = Debug|Any CPU EndGlobalSection EndGlobal "; var tmpFile = Temp.CreateFile(); tmpFile.WriteAllText(SolutionFile); Action action = () => { var slnFile = SlnFile.Read(tmpFile.Path); if (slnFile.ProjectConfigurationsSection.Count == 0) { // Need to force loading of nested property sets } }; action.ShouldThrow<InvalidSolutionFormatException>() .WithMessage("Invalid format in line 7: Property set is missing '.'"); } } }
// 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.Diagnostics.CodeAnalysis; namespace System.Net.Http.Headers { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public sealed class HttpResponseHeaders : HttpHeaders { private static readonly Dictionary<string, HttpHeaderParser> s_parserStore = CreateParserStore(); private static readonly HashSet<string> s_invalidHeaders = CreateInvalidHeaders(); private HttpGeneralHeaders _generalHeaders; private HttpHeaderValueCollection<string> _acceptRanges; private HttpHeaderValueCollection<AuthenticationHeaderValue> _wwwAuthenticate; private HttpHeaderValueCollection<AuthenticationHeaderValue> _proxyAuthenticate; private HttpHeaderValueCollection<ProductInfoHeaderValue> _server; private HttpHeaderValueCollection<string> _vary; #region Response Headers public HttpHeaderValueCollection<string> AcceptRanges { get { if (_acceptRanges == null) { _acceptRanges = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.AcceptRanges, this, HeaderUtilities.TokenValidator); } return _acceptRanges; } } public TimeSpan? Age { get { return HeaderUtilities.GetTimeSpanValue(HttpKnownHeaderNames.Age, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Age, value); } } public EntityTagHeaderValue ETag { get { return (EntityTagHeaderValue)GetParsedValues(HttpKnownHeaderNames.ETag); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.ETag, value); } } public Uri Location { get { return (Uri)GetParsedValues(HttpKnownHeaderNames.Location); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Location, value); } } public HttpHeaderValueCollection<AuthenticationHeaderValue> ProxyAuthenticate { get { if (_proxyAuthenticate == null) { _proxyAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>( HttpKnownHeaderNames.ProxyAuthenticate, this); } return _proxyAuthenticate; } } public RetryConditionHeaderValue RetryAfter { get { return (RetryConditionHeaderValue)GetParsedValues(HttpKnownHeaderNames.RetryAfter); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.RetryAfter, value); } } public HttpHeaderValueCollection<ProductInfoHeaderValue> Server { get { if (_server == null) { _server = new HttpHeaderValueCollection<ProductInfoHeaderValue>(HttpKnownHeaderNames.Server, this); } return _server; } } public HttpHeaderValueCollection<string> Vary { get { if (_vary == null) { _vary = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Vary, this, HeaderUtilities.TokenValidator); } return _vary; } } public HttpHeaderValueCollection<AuthenticationHeaderValue> WwwAuthenticate { get { if (_wwwAuthenticate == null) { _wwwAuthenticate = new HttpHeaderValueCollection<AuthenticationHeaderValue>( HttpKnownHeaderNames.WWWAuthenticate, this); } return _wwwAuthenticate; } } #endregion #region General Headers public CacheControlHeaderValue CacheControl { get { return _generalHeaders.CacheControl; } set { _generalHeaders.CacheControl = value; } } public HttpHeaderValueCollection<string> Connection { get { return _generalHeaders.Connection; } } public bool? ConnectionClose { get { return _generalHeaders.ConnectionClose; } set { _generalHeaders.ConnectionClose = value; } } public DateTimeOffset? Date { get { return _generalHeaders.Date; } set { _generalHeaders.Date = value; } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { return _generalHeaders.Pragma; } } public HttpHeaderValueCollection<string> Trailer { get { return _generalHeaders.Trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return _generalHeaders.TransferEncoding; } } public bool? TransferEncodingChunked { get { return _generalHeaders.TransferEncodingChunked; } set { _generalHeaders.TransferEncodingChunked = value; } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { return _generalHeaders.Upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { return _generalHeaders.Via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { return _generalHeaders.Warning; } } #endregion internal HttpResponseHeaders() { _generalHeaders = new HttpGeneralHeaders(this); base.SetConfiguration(s_parserStore, s_invalidHeaders); } private static Dictionary<string, HttpHeaderParser> CreateParserStore() { var parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase); parserStore.Add(HttpKnownHeaderNames.AcceptRanges, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.Age, TimeSpanHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.ETag, GenericHeaderParser.SingleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.Location, UriHeaderParser.RelativeOrAbsoluteUriParser); parserStore.Add(HttpKnownHeaderNames.ProxyAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.RetryAfter, GenericHeaderParser.RetryConditionParser); parserStore.Add(HttpKnownHeaderNames.Server, ProductInfoHeaderParser.MultipleValueParser); parserStore.Add(HttpKnownHeaderNames.Vary, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.WWWAuthenticate, GenericHeaderParser.MultipleValueAuthenticationParser); HttpGeneralHeaders.AddParsers(parserStore); return parserStore; } private static HashSet<string> CreateInvalidHeaders() { var invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HttpContentHeaders.AddKnownHeaders(invalidHeaders); return invalidHeaders; // Note: Reserved request header names are allowed as custom response header names. Reserved request // headers have no defined meaning or format when used on a response. This enables a client to accept // any headers sent from the server as either content headers or response headers. } internal static void AddKnownHeaders(HashSet<string> headerSet) { Debug.Assert(headerSet != null); headerSet.Add(HttpKnownHeaderNames.AcceptRanges); headerSet.Add(HttpKnownHeaderNames.Age); headerSet.Add(HttpKnownHeaderNames.ETag); headerSet.Add(HttpKnownHeaderNames.Location); headerSet.Add(HttpKnownHeaderNames.ProxyAuthenticate); headerSet.Add(HttpKnownHeaderNames.RetryAfter); headerSet.Add(HttpKnownHeaderNames.Server); headerSet.Add(HttpKnownHeaderNames.Vary); headerSet.Add(HttpKnownHeaderNames.WWWAuthenticate); } internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpResponseHeaders sourceResponseHeaders = sourceHeaders as HttpResponseHeaders; Debug.Assert(sourceResponseHeaders != null); // Copy special values, but do not overwrite _generalHeaders.AddSpecialsFrom(sourceResponseHeaders._generalHeaders); } } }
//----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- //============================================================================================= // Event Handlers. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onAdd( %this ) { // %this.setWindowTitle("Torque Gui Editor"); %this.onCreateMenu(); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onRemove( %this ) { if( isObject( GuiEditorGui.menuGroup ) ) GuiEditorGui.delete(); // cleanup %this.onDestroyMenu(); } //--------------------------------------------------------------------------------------------- /// Create the Gui Editor menu bar. function GuiEditCanvas::onCreateMenu(%this) { if(isObject(%this.menuBar)) return; //set up %cmdctrl variable so that it matches OS standards if( $platform $= "macos" ) { %cmdCtrl = "cmd"; %redoShortcut = "Cmd-Shift Z"; } else { %cmdCtrl = "Ctrl"; %redoShort = "Ctrl Y"; } // Menu bar %this.menuBar = new MenuBar() { dynamicItemInsertPos = 3; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "File"; internalName = "FileMenu"; item[0] = "New Gui..." TAB %cmdCtrl SPC "N" TAB %this @ ".create();"; item[1] = "Open..." TAB %cmdCtrl SPC "O" TAB %this @ ".open();"; item[2] = "Save" TAB %cmdCtrl SPC "S" TAB %this @ ".save( false, true );"; item[3] = "Save As..." TAB %cmdCtrl @ "-Shift S" TAB %this @ ".save( false );"; item[4] = "Save Selected As..." TAB %cmdCtrl @ "-Alt S" TAB %this @ ".save( true );"; item[5] = "-"; item[6] = "Revert Gui" TAB "" TAB %this @ ".revert();"; item[7] = "Add Gui From File..." TAB "" TAB %this @ ".append();"; item[8] = "-"; item[9] = "Open Gui File in Torsion" TAB "" TAB %this @".openInTorsion();"; item[10] = "-"; item[11] = "Close Editor" TAB "F10" TAB %this @ ".quit();"; item[12] = "Quit" TAB %cmdCtrl SPC "Q" TAB "quit();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Edit"; internalName = "EditMenu"; item[0] = "Undo" TAB %cmdCtrl SPC "Z" TAB "GuiEditor.undo();"; item[1] = "Redo" TAB %redoShortcut TAB "GuiEditor.redo();"; item[2] = "-"; item[3] = "Cut" TAB %cmdCtrl SPC "X" TAB "GuiEditor.saveSelection(); GuiEditor.deleteSelection();"; item[4] = "Copy" TAB %cmdCtrl SPC "C" TAB "GuiEditor.saveSelection();"; item[5] = "Paste" TAB %cmdCtrl SPC "V" TAB "GuiEditor.loadSelection();"; item[6] = "-"; item[7] = "Select All" TAB %cmdCtrl SPC "A" TAB "GuiEditor.selectAll();"; item[8] = "Deselect All" TAB %cmdCtrl SPC "D" TAB "GuiEditor.clearSelection();"; item[9] = "Select Parent(s)" TAB %cmdCtrl @ "-Alt Up" TAB "GuiEditor.selectParents();"; item[10] = "Select Children" TAB %cmdCtrl @ "-Alt Down" TAB "GuiEditor.selectChildren();"; item[11] = "Add Parent(s) to Selection" TAB %cmdCtrl @ "-Alt-Shift Up" TAB "GuiEditor.selectParents( true );"; item[12] = "Add Children to Selection" TAB %cmdCtrl @ "-Alt-Shift Down" TAB "GuiEditor.selectChildren( true );"; item[13] = "Select..." TAB "" TAB "GuiEditorSelectDlg.toggleVisibility();"; item[14] = "-"; item[15] = "Lock/Unlock Selection" TAB %cmdCtrl SPC "L" TAB "GuiEditor.toggleLockSelection();"; item[16] = "Hide/Unhide Selection" TAB %cmdCtrl SPC "H" TAB "GuiEditor.toggleHideSelection();"; item[17] = "-"; item[18] = "Group Selection" TAB %cmdCtrl SPC "G" TAB "GuiEditor.groupSelected();"; item[19] = "Ungroup Selection" TAB %cmdCtrl @ "-Shift G" TAB "GuiEditor.ungroupSelected();"; item[20] = "-"; item[21] = "Full Box Selection" TAB "" TAB "GuiEditor.toggleFullBoxSelection();"; item[22] = "-"; item[23] = "Grid Size" TAB %cmdCtrl SPC "," TAB "GuiEditor.showPrefsDialog();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Layout"; internalName = "LayoutMenu"; item[0] = "Align Left" TAB %cmdCtrl SPC "Left" TAB "GuiEditor.Justify(0);"; item[1] = "Center Horizontally" TAB "" TAB "GuiEditor.Justify(1);"; item[2] = "Align Right" TAB %cmdCtrl SPC "Right" TAB "GuiEditor.Justify(2);"; item[3] = "-"; item[4] = "Align Top" TAB %cmdCtrl SPC "Up" TAB "GuiEditor.Justify(3);"; item[5] = "Center Vertically" TAB "" TAB "GuiEditor.Justify(7);"; item[6] = "Align Bottom" TAB %cmdCtrl SPC "Down" TAB "GuiEditor.Justify(4);"; item[7] = "-"; item[8] = "Space Vertically" TAB "" TAB "GuiEditor.Justify(5);"; item[9] = "Space Horizontally" TAB "" TAB "GuiEditor.Justify(6);"; item[10] = "-"; item[11] = "Fit into Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents();"; item[12] = "Fit Width to Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents( true, false );"; item[13] = "Fit Height to Parent(s)" TAB "" TAB "GuiEditor.fitIntoParents( false, true );"; item[14] = "-"; item[15] = "Bring to Front" TAB "" TAB "GuiEditor.BringToFront();"; item[16] = "Send to Back" TAB "" TAB "GuiEditor.PushToBack();"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Move"; internalName = "MoveMenu"; item[0] = "Nudge Left" TAB "Left" TAB "GuiEditor.moveSelection( -1, 0);"; item[1] = "Nudge Right" TAB "Right" TAB "GuiEditor.moveSelection( 1, 0);"; item[2] = "Nudge Up" TAB "Up" TAB "GuiEditor.moveSelection( 0, -1);"; item[3] = "Nudge Down" TAB "Down" TAB "GuiEditor.moveSelection( 0, 1 );"; item[4] = "-"; item[5] = "Big Nudge Left" TAB "Shift Left" TAB "GuiEditor.moveSelection( - GuiEditor.snap2gridsize, 0 );"; item[6] = "Big Nudge Right" TAB "Shift Right" TAB "GuiEditor.moveSelection( GuiEditor.snap2gridsize, 0 );"; item[7] = "Big Nudge Up" TAB "Shift Up" TAB "GuiEditor.moveSelection( 0, - GuiEditor.snap2gridsize );"; item[8] = "Big Nudge Down" TAB "Shift Down" TAB "GuiEditor.moveSelection( 0, GuiEditor.snap2gridsize );"; }; new PopupMenu() { superClass = "MenuBuilder"; barTitle = "Snap"; internalName = "SnapMenu"; item[0] = "Snap Edges" TAB "Alt-Shift E" TAB "GuiEditor.toggleEdgeSnap();"; item[1] = "Snap Centers" TAB "Alt-Shift C" TAB "GuiEditor.toggleCenterSnap();"; item[2] = "-"; item[3] = "Snap to Guides" TAB "Alt-Shift G" TAB "GuiEditor.toggleGuideSnap();"; item[4] = "Snap to Controls" TAB "Alt-Shift T" TAB "GuiEditor.toggleControlSnap();"; item[5] = "Snap to Canvas" TAB "" TAB "GuiEditor.toggleCanvasSnap();"; item[6] = "Snap to Grid" TAB "" TAB "GuiEditor.toggleGridSnap();"; item[7] = "-"; item[8] = "Show Guides" TAB "" TAB "GuiEditor.toggleDrawGuides();"; item[9] = "Clear Guides" TAB "" TAB "GuiEditor.clearGuides();"; }; new PopupMenu() { superClass = "MenuBuilder"; internalName = "HelpMenu"; barTitle = "Help"; item[0] = "Online Documentation..." TAB "Alt F1" TAB "gotoWebPage( GuiEditor.documentationURL );"; item[1] = "Offline User Guid..." TAB "" TAB "gotoWebPage( GuiEditor.documentationLocal );"; item[2] = "Offline Reference Guide..." TAB "" TAB "shellExecute( GuiEditor.documentationReference );"; item[3] = "-"; item[4] = "Torque 3D Public Forums..." TAB "" TAB "gotoWebPage( \"http://www.garagegames.com/community/forums/73\" );"; item[5] = "Torque 3D Private Forums..." TAB "" TAB "gotoWebPage( \"http://www.garagegames.com/community/forums/63\" );"; }; }; %this.menuBar.attachToCanvas( Canvas, 0 ); } $GUI_EDITOR_MENU_EDGESNAP_INDEX = 0; $GUI_EDITOR_MENU_CENTERSNAP_INDEX = 1; $GUI_EDITOR_MENU_GUIDESNAP_INDEX = 3; $GUI_EDITOR_MENU_CONTROLSNAP_INDEX = 4; $GUI_EDITOR_MENU_CANVASSNAP_INDEX = 5; $GUI_EDITOR_MENU_GRIDSNAP_INDEX = 6; $GUI_EDITOR_MENU_DRAWGUIDES_INDEX = 8; $GUI_EDITOR_MENU_FULLBOXSELECT_INDEX = 21; //--------------------------------------------------------------------------------------------- /// Called before onSleep when the canvas content is changed function GuiEditCanvas::onDestroyMenu(%this) { if( !isObject( %this.menuBar ) ) return; // Destroy menus while( %this.menuBar.getCount() != 0 ) %this.menuBar.getObject( 0 ).delete(); %this.menuBar.removeFromCanvas(); %this.menuBar.delete(); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::onWindowClose(%this) { %this.quit(); } //============================================================================================= // Menu Commands. //============================================================================================= //--------------------------------------------------------------------------------------------- function GuiEditCanvas::create( %this ) { GuiEditorNewGuiDialog.init( "NewGui", "GuiControl" ); Canvas.pushDialog( GuiEditorNewGuiDialog ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::load( %this, %filename ) { %newRedefineBehavior = "replaceExisting"; if( isDefined( "$GuiEditor::loadRedefineBehavior" ) ) { // This trick allows to choose different redefineBehaviors when loading // GUIs. This is useful, for example, when loading GUIs that would lead to // problems when loading with their correct names because script behavior // would immediately attach. // // This allows to also edit the GUI editor's own GUI inside itself. %newRedefineBehavior = $GuiEditor::loadRedefineBehavior; } // Allow stomping objects while exec'ing the GUI file as we want to // pull the file's objects even if we have another version of the GUI // already loaded. %oldRedefineBehavior = $Con::redefineBehavior; $Con::redefineBehavior = %newRedefineBehavior; // Load up the gui. exec( %fileName ); $Con::redefineBehavior = %oldRedefineBehavior; // The GUI file should have contained a GUIControl which should now be in the instant // group. And, it should be the only thing in the group. if( !isObject( %guiContent ) ) { MessageBox( getEngineName(), "You have loaded a Gui file that was created before this version. It has been loaded but you must open it manually from the content list dropdown", "Ok", "Information" ); return 0; } GuiEditor.openForEditing( %guiContent ); GuiEditorStatusBar.print( "Loaded '" @ %filename @ "'" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::openInTorsion( %this ) { if( !GuiEditorContent.getCount() ) return; %guiObject = GuiEditorContent.getObject( 0 ); EditorOpenDeclarationInTorsion( %guiObject ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::open( %this ) { %openFileName = GuiBuilder::getOpenName(); if( %openFileName $= "" ) return; // Make sure the file is valid. if ((!isFile(%openFileName)) && (!isFile(%openFileName @ ".dso"))) return; %this.load( %openFileName ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::save( %this, %selectedOnly, %noPrompt ) { // Get the control we should save. if( %selectedOnly ) { %selected = GuiEditor.getSelection(); if( !%selected.getCount() ) return; else if( %selected.getCount() > 1 ) { MessageBox( "Invalid selection", "Only a single control hierarchy can be saved to a file. Make sure you have selected only one control in the tree view." ); return; } %currentObject = %selected.getObject( 0 ); } else if( GuiEditorContent.getCount() > 0 ) %currentObject = GuiEditorContent.getObject( 0 ); else return; // Store the current guide set on the control. GuiEditor.writeGuides( %currentObject ); %currentObject.canSaveDynamicFields = true; // Make sure the guides get saved out. // Construct a base filename. if( %currentObject.getName() !$= "" ) %name = %currentObject.getName() @ ".gui"; else %name = "Untitled.gui"; // Construct a path. if( %selectedOnly && %currentObject != GuiEditorContent.getObject( 0 ) && %currentObject.getFileName() $= GuiEditorContent.getObject( 0 ).getFileName() ) { // Selected child control that hasn't been yet saved to its own file. %currentFile = GuiEditor.LastPath @ "/" @ %name; %currentFile = makeRelativePath( %currentFile, getMainDotCsDir() ); } else { %currentFile = %currentObject.getFileName(); if( %currentFile $= "") { // No file name set on control. Force a prompt. %noPrompt = false; if( GuiEditor.LastPath !$= "" ) { %currentFile = GuiEditor.LastPath @ "/" @ %name; %currentFile = makeRelativePath( %currentFile, getMainDotCsDir() ); } else %currentFile = expandFileName( %name ); } else %currentFile = expandFileName( %currentFile ); } // Get the filename. if( !%noPrompt ) { %filename = GuiBuilder::getSaveName( %currentFile ); if( %filename $= "" ) return; } else %filename = %currentFile; // Save the Gui. if( isWriteableFileName( %filename ) ) { // // Extract any existent TorqueScript before writing out to disk // %fileObject = new FileObject(); %fileObject.openForRead( %filename ); %skipLines = true; %beforeObject = true; // %var++ does not post-increment %var, in torquescript, it pre-increments it, // because ++%var is illegal. %lines = -1; %beforeLines = -1; %skipLines = false; while( !%fileObject.isEOF() ) { %line = %fileObject.readLine(); if( %line $= "//--- OBJECT WRITE BEGIN ---" ) %skipLines = true; else if( %line $= "//--- OBJECT WRITE END ---" ) { %skipLines = false; %beforeObject = false; } else if( %skipLines == false ) { if(%beforeObject) %beforeNewFileLines[ %beforeLines++ ] = %line; else %newFileLines[ %lines++ ] = %line; } } %fileObject.close(); %fileObject.delete(); %fo = new FileObject(); %fo.openForWrite(%filename); // Write out the captured TorqueScript that was before the object before the object for( %i = 0; %i <= %beforeLines; %i++) %fo.writeLine( %beforeNewFileLines[ %i ] ); %fo.writeLine("//--- OBJECT WRITE BEGIN ---"); %fo.writeObject(%currentObject, "%guiContent = "); %fo.writeLine("//--- OBJECT WRITE END ---"); // Write out captured TorqueScript below Gui object for( %i = 0; %i <= %lines; %i++ ) %fo.writeLine( %newFileLines[ %i ] ); %fo.close(); %fo.delete(); %currentObject.setFileName( makeRelativePath( %filename, getMainDotCsDir() ) ); GuiEditorStatusBar.print( "Saved file '" @ %currentObject.getFileName() @ "'" ); } else MessageBox( "Error writing to file", "There was an error writing to file '" @ %currentFile @ "'. The file may be read-only.", "Ok", "Error" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::append( %this ) { // Get filename. %openFileName = GuiBuilder::getOpenName(); if( %openFileName $= "" || ( !isFile( %openFileName ) && !isFile( %openFileName @ ".dso" ) ) ) return; // Exec file. %oldRedefineBehavior = $Con::redefineBehavior; $Con::redefineBehavior = "renameNew"; exec( %openFileName ); $Con::redefineBehavior = %oldRedefineBehavior; // Find guiContent. if( !isObject( %guiContent ) ) { MessageBox( "Error loading GUI file", "The GUI content controls could not be found. This function can only be used with files saved by the GUI editor.", "Ok", "Error" ); return; } if( !GuiEditorContent.getCount() ) GuiEditor.openForEditing( %guiContent ); else { GuiEditor.getCurrentAddSet().add( %guiContent ); GuiEditor.readGuides( %guiContent ); GuiEditor.onAddNewCtrl( %guiContent ); GuiEditor.onHierarchyChanged(); } GuiEditorStatusBar.print( "Appended controls from '" @ %openFileName @ "'" ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::revert( %this ) { if( !GuiEditorContent.getCount() ) return; %gui = GuiEditorContent.getObject( 0 ); %filename = %gui.getFileName(); if( %filename $= "" ) return; if( MessageBox( "Revert Gui", "Really revert the current Gui? This cannot be undone.", "OkCancel", "Question" ) == $MROk ) %this.load( %filename ); } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::close( %this ) { } //--------------------------------------------------------------------------------------------- function GuiEditCanvas::quit( %this ) { %this.close(); GuiGroup.add(GuiEditorGui); // we must not delete a window while in its event handler, or we foul the event dispatch mechanism %this.schedule(10, delete); Canvas.setContent(GuiEditor.lastContent); $InGuiEditor = false; //Temp fix to disable MLAA when in GUI editor if( isObject(MLAAFx) && $MLAAFxGuiEditorTemp==true ) { MLAAFx.isEnabled = true; $MLAAFxGuiEditorTemp = false; } }
/* * Copyright (c) 2006-2014, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector4 : IComparable<Vector4>, IEquatable<Vector4> { /// <summary>X value</summary> public float X; /// <summary>Y value</summary> public float Y; /// <summary>Z value</summary> public float Z; /// <summary>W value</summary> public float W; #region Constructors public Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Vector4(Vector2 value, float z, float w) { X = value.X; Y = value.Y; Z = z; W = w; } public Vector4(Vector3 value, float w) { X = value.X; Y = value.Y; Z = value.Z; W = w; } public Vector4(float value) { X = value; Y = value; Z = value; W = value; } /// <summary> /// Constructor, builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing four four-byte floats</param> /// <param name="pos">Beginning position in the byte array</param> public Vector4(byte[] byteArray, int pos) { X = Y = Z = W = 0f; FromBytes(byteArray, pos); } public Vector4(Vector4 value) { X = value.X; Y = value.Y; Z = value.Z; W = value.W; } #endregion Constructors #region Public Methods public float Length() { return (float)Math.Sqrt(DistanceSquared(this, Zero)); } public float LengthSquared() { return DistanceSquared(this, Zero); } public void Normalize() { this = Normalize(this); } /// <summary> /// Test if this vector is equal to another vector, within a given /// tolerance range /// </summary> /// <param name="vec">Vector to test against</param> /// <param name="tolerance">The acceptable magnitude of difference /// between the two vectors</param> /// <returns>True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false</returns> public bool ApproxEquals(Vector4 vec, float tolerance) { Vector4 diff = this - vec; return (diff.LengthSquared() <= tolerance * tolerance); } /// <summary> /// IComparable.CompareTo implementation /// </summary> public int CompareTo(Vector4 vector) { return Length().CompareTo(vector.Length()); } /// <summary> /// Test if this vector is composed of all finite numbers /// </summary> public bool IsFinite() { return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z) && Utils.IsFinite(W)); } /// <summary> /// Builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 16 byte vector</param> /// <param name="pos">Beginning position in the byte array</param> public void FromBytes(byte[] byteArray, int pos) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); Array.Reverse(conversionBuffer, 12, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); W = BitConverter.ToSingle(conversionBuffer, 12); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); W = BitConverter.ToSingle(byteArray, pos + 12); } } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <returns>A 16 byte array containing X, Y, Z, and W</returns> public byte[] GetBytes() { byte[] byteArray = new byte[16]; ToBytes(byteArray, 0); return byteArray; } /// <summary> /// Writes the raw bytes for this vector to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 16 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(W), 0, dest, pos + 12, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(dest, pos + 0, 4); Array.Reverse(dest, pos + 4, 4); Array.Reverse(dest, pos + 8, 4); Array.Reverse(dest, pos + 12, 4); } } #endregion Public Methods #region Static Methods public static Vector4 Add(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return new Vector4( Utils.Clamp(value1.X, min.X, max.X), Utils.Clamp(value1.Y, min.Y, max.Y), Utils.Clamp(value1.Z, min.Z, max.Z), Utils.Clamp(value1.W, min.W, max.W)); } public static float Distance(Vector4 value1, Vector4 value2) { return (float)Math.Sqrt(DistanceSquared(value1, value2)); } public static float DistanceSquared(Vector4 value1, Vector4 value2) { return (value1.W - value2.W) * (value1.W - value2.W) + (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector4 Divide(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 Divide(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static float Dot(Vector4 vector1, Vector4 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return new Vector4( Utils.Lerp(value1.X, value2.X, amount), Utils.Lerp(value1.Y, value2.Y, amount), Utils.Lerp(value1.Z, value2.Z, amount), Utils.Lerp(value1.W, value2.W, amount)); } public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4( Math.Max(value1.X, value2.X), Math.Max(value1.Y, value2.Y), Math.Max(value1.Z, value2.Z), Math.Max(value1.W, value2.W)); } public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4( Math.Min(value1.X, value2.X), Math.Min(value1.Y, value2.Y), Math.Min(value1.Z, value2.Z), Math.Min(value1.W, value2.W)); } public static Vector4 Multiply(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 Multiply(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 Negate(Vector4 value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; value.W = -value.W; return value; } public static Vector4 Normalize(Vector4 vector) { const float MAG_THRESHOLD = 0.0000001f; float factor = DistanceSquared(vector, Zero); if (factor > MAG_THRESHOLD) { factor = 1f / (float)Math.Sqrt(factor); vector.X *= factor; vector.Y *= factor; vector.Z *= factor; vector.W *= factor; } else { vector.X = 0f; vector.Y = 0f; vector.Z = 0f; vector.W = 0f; } return vector; } public static Vector4 SmoothStep(Vector4 value1, Vector4 value2, float amount) { return new Vector4( Utils.SmoothStep(value1.X, value2.X, amount), Utils.SmoothStep(value1.Y, value2.Y, amount), Utils.SmoothStep(value1.Z, value2.Z, amount), Utils.SmoothStep(value1.W, value2.W, amount)); } public static Vector4 Subtract(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector4 Transform(Vector2 position, Matrix4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + matrix.M44); } public static Vector4 Transform(Vector3 position, Matrix4 matrix) { return new Vector4( (position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41, (position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42, (position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43, (position.X * matrix.M14) + (position.Y * matrix.M24) + (position.Z * matrix.M34) + matrix.M44); } public static Vector4 Transform(Vector4 vector, Matrix4 matrix) { return new Vector4( (vector.X * matrix.M11) + (vector.Y * matrix.M21) + (vector.Z * matrix.M31) + (vector.W * matrix.M41), (vector.X * matrix.M12) + (vector.Y * matrix.M22) + (vector.Z * matrix.M32) + (vector.W * matrix.M42), (vector.X * matrix.M13) + (vector.Y * matrix.M23) + (vector.Z * matrix.M33) + (vector.W * matrix.M43), (vector.X * matrix.M14) + (vector.Y * matrix.M24) + (vector.Z * matrix.M34) + (vector.W * matrix.M44)); } public static Vector4 Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector4( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture), float.Parse(split[3].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector4 result) { try { result = Parse(val); return true; } catch (Exception) { result = new Vector4(); return false; } } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Vector4) ? this == (Vector4)obj : false; } public bool Equals(Vector4 other) { return W == other.W && X == other.X && Y == other.Y && Z == other.Z; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode(); } public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// <summary> /// Get a string representation of the vector elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the vector</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); } #endregion Overrides #region Operators public static bool operator ==(Vector4 value1, Vector4 value2) { return value1.W == value2.W && value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector4 value1, Vector4 value2) { return !(value1 == value2); } public static Vector4 operator +(Vector4 value1, Vector4 value2) { value1.W += value2.W; value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector4 operator -(Vector4 value) { return new Vector4(-value.X, -value.Y, -value.Z, -value.W); } public static Vector4 operator -(Vector4 value1, Vector4 value2) { value1.W -= value2.W; value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, Vector4 value2) { value1.W *= value2.W; value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector4 operator *(Vector4 value1, float scaleFactor) { value1.W *= scaleFactor; value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector4 operator /(Vector4 value1, Vector4 value2) { value1.W /= value2.W; value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector4 operator /(Vector4 value1, float divider) { float factor = 1f / divider; value1.W *= factor; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } #endregion Operators /// <summary>A vector with a value of 0,0,0,0</summary> public readonly static Vector4 Zero = new Vector4(); /// <summary>A vector with a value of 1,1,1,1</summary> public readonly static Vector4 One = new Vector4(1f, 1f, 1f, 1f); /// <summary>A vector with a value of 1,0,0,0</summary> public readonly static Vector4 UnitX = new Vector4(1f, 0f, 0f, 0f); /// <summary>A vector with a value of 0,1,0,0</summary> public readonly static Vector4 UnitY = new Vector4(0f, 1f, 0f, 0f); /// <summary>A vector with a value of 0,0,1,0</summary> public readonly static Vector4 UnitZ = new Vector4(0f, 0f, 1f, 0f); /// <summary>A vector with a value of 0,0,0,1</summary> public readonly static Vector4 UnitW = new Vector4(0f, 0f, 0f, 1f); } }
namespace Volante { using System; using System.Collections; using System.Collections.Generic; public class TestThickIndex : ITest { public class Root : Persistent { public IIndex<string, RecordFull> strIdx; public IIndex<byte, RecordFull> byteIdx; } public void Run(TestConfig config) { int count = config.Count; var res = new TestIndexResult(); config.Result = res; IDatabase db = config.GetDatabase(); Root root = (Root)db.Root; Tests.Assert(null == root); root = new Root(); root.strIdx = db.CreateThickIndex<string, RecordFull>(); root.byteIdx = db.CreateThickIndex<byte, RecordFull>(); db.Root = root; Tests.Assert(typeof(string) == root.strIdx.KeyType); Tests.Assert(typeof(byte) == root.byteIdx.KeyType); int startWithOne = 0; int startWithFive = 0; string strFirst = "z"; string strLast = "0"; int n = 0; var inThickIndex = new Dictionary<byte, List<RecordFull>>(); foreach (var key in Tests.KeySeq(count)) { RecordFull rec = new RecordFull(key); if (rec.StrVal[0] == '1') startWithOne += 1; else if (rec.StrVal[0] == '5') startWithFive += 1; if (rec.StrVal.CompareTo(strFirst) < 0) strFirst = rec.StrVal; else if (rec.StrVal.CompareTo(strLast) > 0) strLast = rec.StrVal; root.strIdx.Put(rec.StrVal, rec); root.byteIdx.Put(rec.ByteVal, rec); n++; if (n % 100 == 0) db.Commit(); ; } db.Commit(); Tests.Assert(root.strIdx.Count == count); Tests.Assert(root.byteIdx.Count <= count); Tests.AssertDatabaseException(() => { root.strIdx.RemoveKey(""); }, DatabaseException.ErrorCode.KEY_NOT_UNIQUE); Tests.AssertDatabaseException(() => { root.strIdx.Remove(new Key("")); }, DatabaseException.ErrorCode.KEY_NOT_UNIQUE); foreach (var mk in inThickIndex.Keys) { var list = inThickIndex[mk]; while (list.Count > 1) { var el = list[0]; list.Remove(el); root.byteIdx.Remove(el.ByteVal, el); } } RecordFull[] recs; foreach (var key in Tests.KeySeq(count)) { RecordFull rec1 = root.strIdx[Convert.ToString(key)]; recs = root.byteIdx[rec1.ByteVal, rec1.ByteVal]; Tests.Assert(rec1 != null && recs.Length >= 1); Tests.Assert(rec1.ByteVal == recs[0].ByteVal); } // test for non-existent key Tests.Assert(null == root.strIdx.Get("-122")); recs = root.byteIdx.ToArray(); Tests.Assert(recs.Length == root.byteIdx.Count); var prevByte = byte.MinValue; n = 0; foreach (RecordFull rec in root.byteIdx) { Tests.Assert(rec.ByteVal >= prevByte); prevByte = rec.ByteVal; n += 1; } Tests.Assert(n == count); String prevStrKey = ""; n = 0; foreach (RecordFull rec in root.strIdx) { Tests.Assert(rec.StrVal.CompareTo(prevStrKey) >= 0); prevStrKey = rec.StrVal; n += 1; } IDictionaryEnumerator de = root.strIdx.GetDictionaryEnumerator(); n = VerifyDictionaryEnumerator(de, IterationOrder.AscentOrder); Tests.Assert(n == count); string mid = "0"; string max = long.MaxValue.ToString(); ; de = root.strIdx.GetDictionaryEnumerator(new Key(mid), new Key(max), IterationOrder.DescentOrder); VerifyDictionaryEnumerator(de, IterationOrder.DescentOrder); Tests.AssertDatabaseException( () => root.byteIdx.PrefixSearch("1"), DatabaseException.ErrorCode.INCOMPATIBLE_KEY_TYPE); // TODO: FAILED_TEST broken for altbtree, returns no results if (!config.AltBtree) { recs = root.strIdx.GetPrefix("1"); Tests.Assert(recs.Length > 0); foreach (var r in recs) { Tests.Assert(r.StrVal.StartsWith("1")); } } recs = root.strIdx.PrefixSearch("1"); Tests.Assert(startWithOne == recs.Length); foreach (var r in recs) { Tests.Assert(r.StrVal.StartsWith("1")); } recs = root.strIdx.PrefixSearch("5"); Tests.Assert(startWithFive == recs.Length); foreach (var r in recs) { Tests.Assert(r.StrVal.StartsWith("5")); } recs = root.strIdx.PrefixSearch("0"); Tests.Assert(0 == recs.Length); recs = root.strIdx.PrefixSearch("a"); Tests.Assert(0 == recs.Length); recs = root.strIdx.PrefixSearch(strFirst); Tests.Assert(recs.Length >= 1); Tests.Assert(recs[0].StrVal == strFirst); foreach (var r in recs) { Tests.Assert(r.StrVal.StartsWith(strFirst)); } recs = root.strIdx.PrefixSearch(strLast); Tests.Assert(recs.Length == 1); Tests.Assert(recs[0].StrVal == strLast); n = 0; foreach (var key in Tests.KeySeq(count)) { n++; if (n % 3 == 0) continue; string strKey = key.ToString(); RecordFull rec = root.strIdx.Get(strKey); root.strIdx.Remove(strKey, rec); } root.byteIdx.Clear(); int BTREE_THRESHOLD = 128; byte bKey = 1; for (int i = 0; i < BTREE_THRESHOLD + 10; i++) { RecordFull r = new RecordFull(0); if (i == 0) { root.byteIdx[bKey] = r; continue; } if (i == 1) { root.byteIdx.Set(bKey, r); continue; } root.byteIdx.Put(bKey, r); } Tests.AssertDatabaseException( () => root.byteIdx.Set(bKey, new RecordFull(1)), DatabaseException.ErrorCode.KEY_NOT_UNIQUE); Tests.AssertDatabaseException( () => root.byteIdx.Get(bKey), DatabaseException.ErrorCode.KEY_NOT_UNIQUE); recs = root.byteIdx.ToArray(); foreach (var r in recs) { root.byteIdx.Remove(bKey, r); } Tests.AssertDatabaseException( () => root.byteIdx.Remove(bKey, new RecordFull(0)), DatabaseException.ErrorCode.KEY_NOT_FOUND); IEnumerator<RecordFull> e = root.byteIdx.GetEnumerator(); while (e.MoveNext()) { } Tests.Assert(!e.MoveNext()); db.Close(); } static int VerifyDictionaryEnumerator(IDictionaryEnumerator de, IterationOrder order) { string prev = ""; if (order == IterationOrder.DescentOrder) prev = "9999999999999999999"; int i = 0; while (de.MoveNext()) { DictionaryEntry e1 = (DictionaryEntry)de.Current; DictionaryEntry e2 = de.Entry; Tests.Assert(e1.Equals(e2)); string k = (string)e1.Key; string k2 = (string)de.Key; Tests.Assert(k == k2); RecordFull v1 = (RecordFull)e1.Value; RecordFull v2 = (RecordFull)de.Value; Tests.Assert(v1.Equals(v2)); Tests.Assert(v1.StrVal == k); if (order == IterationOrder.AscentOrder) Tests.Assert(k.CompareTo(prev) >= 0); else Tests.Assert(k.CompareTo(prev) <= 0); prev = k; i++; } Tests.VerifyDictionaryEnumeratorDone(de); return i; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Collections.Tests { public class ArrayList_CopyToTests { #region "Test Data - Keep the data close to tests so it can vary independently from other tests" static string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", null, "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", null, "Thor", "Wildcat", null }; #endregion [Fact] public void TestCopyToBasic() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; String[] arrCopy = null; // // [] CopyTo an array normal // // [] Normal Copy Test 1 arrList = new ArrayList(strHeroes); arrCopy = new String[strHeroes.Length]; arrList.CopyTo(arrCopy); for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal(strHeroes[i], arrCopy[i]); } //[] Normal Copy Test 2 - copy 0 elements // Construct ArrayList. arrList = new ArrayList(); arrList.Add(null); arrList.Add(arrList); arrList.Add(null); arrList.Remove(null); arrList.Remove(null); arrList.Remove(arrList); Assert.Equal(0, arrList.Count); arrCopy = new String[strHeroes.Length]; // put some elements in arrCopy that should not be overriden for (int i = 0; i < strHeroes.Length; i++) { arrCopy[i] = strHeroes[i]; } //copying 0 elements into arrCopy arrList.CopyTo(arrCopy); // check to make sure sentinals stay the same for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal(strHeroes[i], arrCopy[i]); } //we'll make sure by copying only 0 arrList = new ArrayList(); arrCopy = new String[0]; //copying 0 elements into arrCopy arrList.CopyTo(arrCopy); Assert.Equal(0, arrCopy.Length); //[] Copy so that exception should be thrown Assert.Throws<ArgumentNullException>(() => { // Construct ArrayList. arrList = new ArrayList(); arrCopy = null; //copying 0 elements into arrCopy, into INVALID index of arrCopy arrList.CopyTo(arrCopy); }); } [Fact] public void TestArrayListWrappers() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; String[] arrCopy = null; arrList = new ArrayList(strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] CopyTo an array normal // arrCopy = new String[strHeroes.Length]; arrList.CopyTo(arrCopy, 0); for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal<string>(strHeroes[i], arrCopy[i]); } //[] Normal Copy Test 2 - copy 0 elements arrList.Clear(); arrList.Add(null); arrList.Add(arrList); arrList.Add(null); arrList.Remove(null); arrList.Remove(null); arrList.Remove(arrList); Assert.Equal(0, arrList.Count); arrCopy = new String[strHeroes.Length]; // put some elements in arrCopy that should not be overriden for (int i = 0; i < strHeroes.Length; i++) { arrCopy[i] = strHeroes[i]; } //copying 0 elements into arrCopy arrList.CopyTo(arrCopy, 1); // check to make sure sentinals stay the same for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal<string>(strHeroes[i], arrCopy[i]); } //[] Normal Copy Test 3 - copy 0 elements from the end arrList.Clear(); Assert.Equal(0, arrList.Count); arrCopy = new String[strHeroes.Length]; // put some elements in arrCopy that should not be overriden for (int i = 0; i < strHeroes.Length; i++) { arrCopy[i] = strHeroes[i]; } //copying 0 elements into arrCopy, into last valid index of arrCopy arrList.CopyTo(arrCopy, arrCopy.Length - 1); // check to make sure sentinals stay the same for (int i = 0; i < arrCopy.Length; i++) { Assert.Equal<string>(strHeroes[i], arrCopy[i]); } //[] Copy so that exception should be thrown arrList.Clear(); arrCopy = new String[2]; //copying 0 elements into arrCopy arrList.CopyTo(arrCopy, arrCopy.Length); // [] Copy so that exception should be thrown 2 arrList.Clear(); Assert.Equal(0, arrList.Count); arrCopy = new String[0]; //copying 0 elements into arrCopy arrList.CopyTo(arrCopy, 0); // [] CopyTo with negative index Assert.Throws<ArgumentOutOfRangeException>(() => arrList.CopyTo(arrCopy, -1)); // [] CopyTo with array with index is not large enough Assert.Throws<ArgumentException>(() => { arrList.Clear(); for (int i = 0; i < 10; i++) arrList.Add(i); arrList.CopyTo(new Object[11], 2); }); // [] CopyTo with null array Assert.Throws<ArgumentNullException>(() => arrList.CopyTo(null, 0)); // [] CopyTo with multidimentional array Assert.Throws<ArgumentException>(() => arrList.CopyTo(new Object[10, 10], 1)); } } [Fact] public void TestCopyToWithCount() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; string[] arrCopy = null; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; // // Construct array list. // arrList = new ArrayList(); Assert.NotNull(arrList); // Add items to the lists. for (int ii = 0; ii < strHeroes.Length; ++ii) { arrList.Add(strHeroes[ii]); } // Verify items added to list. Assert.Equal(strHeroes.Length, arrList.Count); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { arrList, ArrayList.Adapter(arrList), ArrayList.FixedSize(arrList), arrList.GetRange(0, arrList.Count), ArrayList.ReadOnly(arrList), ArrayList.Synchronized(arrList)}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Use CopyTo copy range of items to array. // int start = 3; int count = 15; // Allocate sting array. arrCopy = new String[100]; // Obtain string from ArrayList. arrList.CopyTo(start, arrCopy, start, count); // Verify the items in the array. for (int ii = start; ii < start + count; ++ii) { Assert.Equal(0, ((String)arrList[ii]).CompareTo(arrCopy[ii])); } // // [] Invalid Arguments // // 2nd throw ArgumentOutOfRangeException // rest throw ArgumentException Assert.ThrowsAny<ArgumentException>( () => arrList.CopyTo(0, arrCopy, -100, 1000) ); Assert.Throws<ArgumentOutOfRangeException>(() => arrList.CopyTo(-1, arrCopy, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => arrList.CopyTo(0, arrCopy, 0, -1)); // this is valid now arrCopy = new String[100]; arrList.CopyTo(arrList.Count, arrCopy, 0, 0); Assert.Throws<ArgumentException>(() => { arrCopy = new String[100]; arrList.CopyTo(arrList.Count - 1, arrCopy, 0, 24); }); Assert.Throws<ArgumentNullException>(() => arrList.CopyTo(0, null, 3, 15)); Assert.Throws<ArgumentException>(() => { arrCopy = new String[1]; arrList.CopyTo(0, arrCopy, 3, 15); }); Assert.Throws<ArgumentException>(() => arrList.CopyTo(0, new Object[arrList.Count, arrList.Count], 0, arrList.Count)); // same as above, some iteration throws different exceptions: ArgumentOutOfRangeException Assert.ThrowsAny<ArgumentException>(() => arrList.CopyTo(0, new Object[arrList.Count, arrList.Count], 0, -1)); } } } }
// 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.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Text.Unicode; namespace System { public sealed partial class Utf8String { private const int MAX_STACK_TRANSCODE_CHAR_COUNT = 128; // For values beyond U+FFFF, it's 4 UTF-8 bytes per 2 UTF-16 chars (2:1 ratio) private const int MAX_UTF8_BYTES_PER_UTF16_CHAR = 3; /* * CONSTRUCTORS * * Defining a new constructor for string-like types (like Utf8String) requires changes both * to the managed code below and to the native VM code. See the comment at the top of * src/vm/ecall.cpp for instructions on how to add new overloads. * * These ctors validate their input, throwing ArgumentException if the input does not represent * well-formed UTF-8 data. (In the case of transcoding ctors, the ctors throw if the input does * not represent well-formed UTF-16 data.) There are Create* factory methods which allow the caller * to control this behavior with finer granularity, including performing U+FFFD replacement instead * of throwing, or even suppressing validation altogether if the caller knows the input to be well- * formed. * * The reason a throwing behavior was chosen by default is that we don't want to surprise developers * if ill-formed data loses fidelity while being round-tripped through this type. Developers should * perform an explicit gesture to opt-in to lossy behavior, such as calling the factories explicitly * documented as performing such replacement. */ /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-8 data. /// </summary> /// <param name="value">The existing UTF-8 data from which to create a new <see cref="Utf8String"/>.</param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-8 data. /// </exception> /// <remarks> /// The UTF-8 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{byte}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{byte})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] public extern Utf8String(ReadOnlySpan<byte> value); #if !CORECLR static #endif private Utf8String Ctor(ReadOnlySpan<byte> value) { if (value.IsEmpty) { return Empty; } // Create and populate the Utf8String instance. Utf8String newString = FastAllocateSkipZeroInit(value.Length); Buffer.Memmove(ref newString.DangerousGetMutableReference(), ref MemoryMarshal.GetReference(value), (uint)value.Length); // Now perform validation. // Reminder: Perform validation over the copy, not over the source. if (!Utf8Utility.IsWellFormedUtf8(newString.AsBytes())) { throw new ArgumentException( message: SR.Utf8String_InputContainedMalformedUtf8, paramName: nameof(value)); } return newString; } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-8 data. /// </summary> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-8 data. /// </exception> /// <remarks> /// The UTF-8 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{byte}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{byte})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] public extern Utf8String(byte[] value, int startIndex, int length); #if !CORECLR static #endif private Utf8String Ctor(byte[] value, int startIndex, int length) { if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return Ctor(new ReadOnlySpan<byte>(value, startIndex, length)); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing null-terminated UTF-8 data. /// </summary> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-8 data. /// </exception> /// <remarks> /// The UTF-8 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{byte}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{byte})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] public extern unsafe Utf8String(byte* value); #if !CORECLR static #endif private unsafe Utf8String Ctor(byte* value) { if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return Ctor(new ReadOnlySpan<byte>(value, string.strlen(value))); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-16 data, transcoding the /// existing data to UTF-8 upon creation. /// </summary> /// <param name="value">The existing UTF-16 data from which to create a new <see cref="Utf8String"/>.</param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-16 data. /// </exception> /// <remarks> /// The UTF-16 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{char}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{char})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] public extern Utf8String(ReadOnlySpan<char> value); #if !CORECLR static #endif private Utf8String Ctor(ReadOnlySpan<char> value) { Utf8String? newString = CreateFromUtf16Common(value, replaceInvalidSequences: false); if (newString is null) { // Input buffer contained invalid UTF-16 data. throw new ArgumentException( message: SR.Utf8String_InputContainedMalformedUtf16, paramName: nameof(value)); } return newString; } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-16 data. /// </summary> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-16 data. /// </exception> /// <remarks> /// The UTF-16 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{char}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{char})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] public extern Utf8String(char[] value, int startIndex, int length); #if !CORECLR static #endif private Utf8String Ctor(char[] value, int startIndex, int length) { if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return Ctor(new ReadOnlySpan<char>(value, startIndex, length)); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing null-terminated UTF-16 data. /// </summary> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="value"/> does not represent well-formed UTF-16 data. /// </exception> /// <remarks> /// The UTF-16 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{char}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{char})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] public extern unsafe Utf8String(char* value); #if !CORECLR static #endif private unsafe Utf8String Ctor(char* value) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return Ctor(new ReadOnlySpan<char>(value, string.wcslen(value))); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-16 data. /// </summary> /// <remarks> /// The UTF-16 data in <paramref name="value"/> is validated for well-formedness upon construction, /// and an exception is thrown if the input is ill-formed. To avoid this exception, consider using /// <see cref="TryCreateFrom(ReadOnlySpan{char}, out Utf8String)"/> or <see cref="CreateFromRelaxed(ReadOnlySpan{char})"/>. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] public extern Utf8String(string value); #if !CORECLR static #endif private Utf8String Ctor(string value) { if (value is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return Ctor(value.AsSpan()); } /* * STATIC FACTORIES */ /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-8 data. /// </summary> /// <param name="buffer">The existing data from which to create the new <see cref="Utf8String"/>.</param> /// <param name="value"> /// When this method returns, contains a <see cref="Utf8String"/> with the same contents as <paramref name="buffer"/> /// if <paramref name="buffer"/> consists of well-formed UTF-8 data. Otherwise, <see langword="null"/>. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="buffer"/> contains well-formed UTF-8 data and <paramref name="value"/> /// contains the <see cref="Utf8String"/> encapsulating a copy of that data. Otherwise, <see langword="false"/>. /// </returns> /// <remarks> /// This method is a non-throwing equivalent of the constructor <see cref="Utf8String(ReadOnlySpan{byte})"/>. /// </remarks> public static bool TryCreateFrom(ReadOnlySpan<byte> buffer, [NotNullWhen(true)] out Utf8String? value) { if (buffer.IsEmpty) { value = Empty; // it's valid to create a Utf8String instance from an empty buffer; we'll return the Empty singleton return true; } // Create and populate the Utf8String instance. Utf8String newString = FastAllocateSkipZeroInit(buffer.Length); Buffer.Memmove(ref newString.DangerousGetMutableReference(), ref MemoryMarshal.GetReference(buffer), (uint)buffer.Length); // Now perform validation. // Reminder: Perform validation over the copy, not over the source. if (Utf8Utility.IsWellFormedUtf8(newString.AsBytes())) { value = newString; return true; } else { value = default; return false; } } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-16 data, transcoding the /// existing data to UTF-8 upon creation. /// </summary> /// <param name="buffer">The existing UTF-16 data from which to create a new <see cref="Utf8String"/>.</param> /// <param name="value"> /// When this method returns, contains a <see cref="Utf8String"/> with equivalent contents as <paramref name="buffer"/> /// if <paramref name="buffer"/> consists of well-formed UTF-16 data. Otherwise, <see langword="null"/>. /// </param> /// <returns> /// <see langword="true"/> if <paramref name="buffer"/> contains well-formed UTF-16 data and <paramref name="value"/> /// contains the <see cref="Utf8String"/> encapsulating equivalent data (as UTF-8). Otherwise, <see langword="false"/>. /// </returns> /// <remarks> /// This method is a non-throwing equivalent of the constructor <see cref="Utf8String(ReadOnlySpan{char})"/>. /// </remarks> public static bool TryCreateFrom(ReadOnlySpan<char> buffer, [NotNullWhen(true)] out Utf8String? value) { // Returning "false" from this method means only that the original input buffer didn't // contain well-formed UTF-16 data. This method could fail in other ways, such as // throwing an OutOfMemoryException if allocation of the output parameter fails. value = CreateFromUtf16Common(buffer, replaceInvalidSequences: false); return !(value is null); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-8 data. /// </summary> /// <param name="buffer">The existing data from which to create the new <see cref="Utf8String"/>.</param> /// <remarks> /// If <paramref name="buffer"/> contains any ill-formed UTF-8 subsequences, those subsequences will /// be replaced with <see cref="Rune.ReplacementChar"/> in the returned <see cref="Utf8String"/> instance. /// This may result in the returned <see cref="Utf8String"/> having different contents (and thus a different /// total byte length) than the source parameter <paramref name="buffer"/>. /// </remarks> public static Utf8String CreateFromRelaxed(ReadOnlySpan<byte> buffer) { if (buffer.IsEmpty) { return Empty; } // Create and populate the Utf8String instance. Utf8String newString = FastAllocateSkipZeroInit(buffer.Length); Buffer.Memmove(ref newString.DangerousGetMutableReference(), ref MemoryMarshal.GetReference(buffer), (uint)buffer.Length); // Now perform validation & fixup. return Utf8Utility.ValidateAndFixupUtf8String(newString); } /// <summary> /// Creates a <see cref="Utf8String"/> instance from existing UTF-16 data. /// </summary> /// <param name="buffer">The existing data from which to create the new <see cref="Utf8String"/>.</param> /// <remarks> /// If <paramref name="buffer"/> contains any ill-formed UTF-16 subsequences, those subsequences will /// be replaced with <see cref="Rune.ReplacementChar"/> in the returned <see cref="Utf8String"/> instance. /// This may result in the original string data not round-tripping properly; that is, calling /// <see cref="ToString"/> on the returned <see cref="Utf8String"/> instance may produce a <see cref="string"/> /// whose contents differ from <paramref name="buffer"/>. /// </remarks> public static Utf8String CreateFromRelaxed(ReadOnlySpan<char> buffer) { Utf8String? newString = CreateFromUtf16Common(buffer, replaceInvalidSequences: true); if (newString is null) { // This shouldn't happen unless somebody mutated the input buffer in the middle // of data processing. We just fail in this scenario rather than retrying. throw new ArgumentException( message: SR.Utf8String_InputContainedMalformedUtf16, paramName: nameof(buffer)); } return newString; } internal static Utf8String CreateFromRune(Rune value) { // Can skip zero-init since we're going to populate the entire buffer. Utf8String newString = FastAllocateSkipZeroInit(value.Utf8SequenceLength); if (value.IsAscii) { // Fast path: If an ASCII value, just allocate the one-byte string and fill in the single byte contents. newString.DangerousGetMutableReference() = (byte)value.Value; return newString; } else { // Slow path: If not ASCII, allocate a string of the appropriate length and fill in the multi-byte contents. int bytesWritten = value.EncodeToUtf8(newString.DangerousGetMutableSpan()); Debug.Assert(newString.Length == bytesWritten); return newString; } } // Returns 'null' if the input buffer does not represent well-formed UTF-16 data and 'replaceInvalidSequences' is false. private static Utf8String? CreateFromUtf16Common(ReadOnlySpan<char> value, bool replaceInvalidSequences) { // Shortcut: Since we expect most strings to be small-ish, first try a one-pass // operation where we transcode directly on to the stack and then copy the validated // data into the new Utf8String instance. It's still O(n), but it should have a smaller // constant factor than a typical "count + transcode" combo. OperationStatus status; Utf8String newString; if (value.Length <= MAX_STACK_TRANSCODE_CHAR_COUNT /* in chars */) { if (value.IsEmpty) { return Empty; } Span<byte> scratch = stackalloc byte[MAX_STACK_TRANSCODE_CHAR_COUNT * MAX_UTF8_BYTES_PER_UTF16_CHAR]; // largest possible expansion, as explained below status = Utf8.FromUtf16(value, scratch, out _, out int scratchBytesWritten, replaceInvalidSequences); Debug.Assert(status == OperationStatus.Done || status == OperationStatus.InvalidData); if (status == OperationStatus.InvalidData) { return null; } // At this point we know transcoding succeeded, so the original input data was well-formed. // We'll memcpy the scratch buffer into the new Utf8String instance, which is very fast. newString = FastAllocateSkipZeroInit(scratchBytesWritten); scratch.Slice(0, scratchBytesWritten).CopyTo(newString.DangerousGetMutableSpan()); return newString; } // First, determine how many UTF-8 bytes we'll need in order to represent this data. // This also checks the input data for well-formedness. long utf8CodeUnitCountAdjustment; unsafe { fixed (char* pChars = &MemoryMarshal.GetReference(value)) { if (Utf16Utility.GetPointerToFirstInvalidChar(pChars, value.Length, out utf8CodeUnitCountAdjustment, out int _) != (pChars + (uint)value.Length)) { return null; } } } // The max possible expansion transcoding UTF-16 to UTF-8 is that each input char corresponds // to 3 UTF-8 bytes. This is most common in CJK languages. Since the input buffer could be // up to int.MaxValue elements in length, we need to use a 64-bit value to hold the total // required UTF-8 byte length. However, the VM places restrictions on how large a Utf8String // instance can be, and the maximum allowed element count is just under int.MaxValue. (This // mirrors the restrictions already in place for System.String.) The VM will throw an // OutOfMemoryException if anybody tries to create a Utf8String instance larger than that, // so if we detect any sort of overflow we'll end up passing int.MaxValue down to the allocation // routine. This normalizes the OutOfMemoryException the caller sees. long totalUtf8BytesRequired = (uint)value.Length + utf8CodeUnitCountAdjustment; if (totalUtf8BytesRequired > int.MaxValue) { totalUtf8BytesRequired = int.MaxValue; } // We can get away with FastAllocateSkipZeroInit here because we're not going to return the // new Utf8String instance to the caller if we don't overwrite every byte of the buffer. newString = FastAllocateSkipZeroInit((int)totalUtf8BytesRequired); // Now transcode the UTF-16 input into the newly allocated Utf8String's buffer. We can't call the // "skip validation" transcoder because the caller could've mutated the input buffer between the // initial counting step and the transcoding step below. status = Utf8.FromUtf16(value, newString.DangerousGetMutableSpan(), out _, out int bytesWritten, replaceInvalidSequences: false); if (status != OperationStatus.Done || bytesWritten != newString.Length) { // Did somebody mutate our input buffer? Shouldn't be any other way this could happen. return null; } return newString; } /// <summary> /// Creates a new <see cref="Utf8String"/> instance, allowing the provided delegate to populate the /// instance data of the returned object. /// </summary> /// <typeparam name="TState">Type of the state object provided to <paramref name="action"/>.</typeparam> /// <param name="length">The length, in bytes, of the <see cref="Utf8String"/> instance to create.</param> /// <param name="state">The state object to provide to <paramref name="action"/>.</param> /// <param name="action">The callback which will be invoked to populate the returned <see cref="Utf8String"/>.</param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="action"/> populates the buffer with ill-formed UTF-8 data. /// </exception> /// <remarks> /// The runtime will perform UTF-8 validation over the contents provided by the <paramref name="action"/> delegate. /// If an invalid UTF-8 subsequence is detected, an exception is thrown. /// </remarks> public static Utf8String Create<TState>(int length, TState state, SpanAction<byte, TState> action) { if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } if (length == 0) { return Empty; // special-case empty input } // Create and populate the Utf8String instance. // Can't use FastAllocateSkipZeroInit here because we're handing the raw buffer to user code. Utf8String newString = FastAllocate(length); action(newString.DangerousGetMutableSpan(), state); // Now perform validation. if (!Utf8Utility.IsWellFormedUtf8(newString.AsBytes())) { throw new ArgumentException( message: SR.Utf8String_CallbackProvidedMalformedData, paramName: nameof(action)); } return newString; } /// <summary> /// Creates a new <see cref="Utf8String"/> instance, allowing the provided delegate to populate the /// instance data of the returned object. /// </summary> /// <typeparam name="TState">Type of the state object provided to <paramref name="action"/>.</typeparam> /// <param name="length">The length, in bytes, of the <see cref="Utf8String"/> instance to create.</param> /// <param name="state">The state object to provide to <paramref name="action"/>.</param> /// <param name="action">The callback which will be invoked to populate the returned <see cref="Utf8String"/>.</param> /// <remarks> /// The runtime will perform UTF-8 validation over the contents provided by the <paramref name="action"/> delegate. /// If an invalid UTF-8 subsequence is detected, the invalid subsequence is replaced with <see cref="Rune.ReplacementChar"/> /// in the returned <see cref="Utf8String"/> instance. This could result in the returned <see cref="Utf8String"/> instance /// having a different byte length than specified by the <paramref name="length"/> parameter. /// </remarks> public static Utf8String CreateRelaxed<TState>(int length, TState state, SpanAction<byte, TState> action) { if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } if (length == 0) { return Empty; // special-case empty input } // Create and populate the Utf8String instance. // Can't use FastAllocateSkipZeroInit here because we're handing the raw buffer to user code. Utf8String newString = FastAllocate(length); action(newString.DangerousGetMutableSpan(), state); // Now perform validation and fixup. return Utf8Utility.ValidateAndFixupUtf8String(newString); } /// <summary> /// Creates a new <see cref="Utf8String"/> instance populated with a copy of the provided contents. /// Please see remarks for important safety information about this method. /// </summary> /// <param name="utf8Contents">The contents to copy to the new <see cref="Utf8String"/>.</param> /// <remarks> /// This factory method can be used as an optimization to skip the validation step that the /// <see cref="Utf8String"/> constructors normally perform. The contract of this method requires that /// <paramref name="utf8Contents"/> contain only well-formed UTF-8 data, as <see cref="Utf8String"/> /// contractually guarantees that it contains only well-formed UTF-8 data, and runtime instability /// could occur if a caller violates this guarantee. /// </remarks> public static Utf8String UnsafeCreateWithoutValidation(ReadOnlySpan<byte> utf8Contents) { if (utf8Contents.IsEmpty) { return Empty; // special-case empty input } // Create and populate the Utf8String instance. Utf8String newString = FastAllocateSkipZeroInit(utf8Contents.Length); utf8Contents.CopyTo(newString.DangerousGetMutableSpan()); // The line below is removed entirely in release builds. Debug.Assert(Utf8Utility.IsWellFormedUtf8(newString.AsBytes()), "Buffer contained ill-formed UTF-8 data."); return newString; } /// <summary> /// Creates a new <see cref="Utf8String"/> instance, allowing the provided delegate to populate the /// instance data of the returned object. Please see remarks for important safety information about /// this method. /// </summary> /// <typeparam name="TState">Type of the state object provided to <paramref name="action"/>.</typeparam> /// <param name="length">The length, in bytes, of the <see cref="Utf8String"/> instance to create.</param> /// <param name="state">The state object to provide to <paramref name="action"/>.</param> /// <param name="action">The callback which will be invoked to populate the returned <see cref="Utf8String"/>.</param> /// <remarks> /// This factory method can be used as an optimization to skip the validation step that /// <see cref="Create{TState}(int, TState, SpanAction{byte, TState})"/> normally performs. The contract /// of this method requires that <paramref name="action"/> populate the buffer with well-formed UTF-8 /// data, as <see cref="Utf8String"/> contractually guarantees that it contains only well-formed UTF-8 data, /// and runtime instability could occur if a caller violates this guarantee. /// </remarks> public static Utf8String UnsafeCreateWithoutValidation<TState>(int length, TState state, SpanAction<byte, TState> action) { if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (action is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } if (length == 0) { return Empty; // special-case empty input } // Create and populate the Utf8String instance. // Can't use FastAllocateSkipZeroInit here because we're handing the raw buffer to user code. Utf8String newString = FastAllocate(length); action(newString.DangerousGetMutableSpan(), state); // The line below is removed entirely in release builds. Debug.Assert(Utf8Utility.IsWellFormedUtf8(newString.AsBytes()), "Callback populated the buffer with ill-formed UTF-8 data."); return newString; } /* * HELPER METHODS */ /// <summary> /// Creates a new zero-initialized instance of the specified length. Actual storage allocated is "length + 1" bytes /// because instances are null-terminated. /// </summary> /// <remarks> /// The implementation of this method checks its input argument for overflow. /// </remarks> [MethodImpl(MethodImplOptions.InternalCall)] private static extern Utf8String FastAllocate(int length); /// <summary> /// Creates a new instance of the specified length. Actual storage allocated is "length + 1" bytes /// because instances are null-terminated. Aside from the null terminator, the contents of the new /// instance are not zero-inited. Use only with first-party APIs which we know for a fact will /// initialize the entire contents of the Utf8String instance. /// </summary> /// <remarks> /// The implementation of this method checks its input argument for overflow. /// </remarks> private static Utf8String FastAllocateSkipZeroInit(int length) { // TODO_UTF8STRING: Actually skip zero-init. return FastAllocate(length); } } }
using System; using System.Collections.Specialized; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Xml; using Common.Logging; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Transport; using Rhino.ServiceBus.Util; namespace Rhino.ServiceBus.SqlQueues { [CLSCompliant(false)] public class SqlQueuesTransport : ITransport { private readonly Uri queueEndpoint; private readonly IEndpointRouter endpointRouter; private readonly IMessageSerializer messageSerializer; private readonly int threadCount; private readonly string connectionString; private SqlQueueManager _sqlQueueManager; private readonly Thread[] threads; private readonly string queueName; private volatile bool shouldContinue; private bool haveStarted; private readonly int numberOfRetries; private readonly IMessageBuilder<MessagePayload> messageBuilder; private const int SleepMax = 15000; [ThreadStatic] private static SqlQueueCurrentMessageInformation currentMessageInformation; private readonly ILog logger = LogManager.GetLogger(typeof(SqlQueuesTransport)); private TimeoutAction timeout; private CleanAction cleanUp; private ISqlQueue queue; private int _queueId; public SqlQueuesTransport(Uri queueEndpoint, IEndpointRouter endpointRouter, IMessageSerializer messageSerializer, int threadCount, string connectionString, int numberOfRetries, IMessageBuilder<MessagePayload> messageBuilder) { this.queueEndpoint = queueEndpoint; this.numberOfRetries = numberOfRetries; this.messageBuilder = messageBuilder; this.endpointRouter = endpointRouter; this.messageSerializer = messageSerializer; this.threadCount = threadCount; this.connectionString = connectionString; queueName = queueEndpoint.GetQueueName(); threads = new Thread[threadCount]; // This has to be the first subscriber to the transport events // in order to successfuly handle the errors semantics new ErrorAction(numberOfRetries).Init(this); messageBuilder.Initialize(Endpoint); } public void Dispose() { shouldContinue = false; logger.DebugFormat("Stopping transport for {0}", queueEndpoint); if (timeout != null) timeout.Dispose(); if (cleanUp != null) cleanUp.Dispose(); DisposeQueueManager(); if (!haveStarted) return; foreach (var thread in threads) { thread.Join(); } } private void DisposeQueueManager() { if (_sqlQueueManager != null) { const int retries = 5; int tries = 0; bool disposeRudely = false; while (true) { try { _sqlQueueManager.Dispose(); break; } catch (Exception) { tries += 1; if (tries > retries) { disposeRudely = true; break; } } } if (disposeRudely) _sqlQueueManager.DisposeRudely(); } } [CLSCompliant(false)] public IQueue Queue { get { return queue; } } protected void internalStart() { shouldContinue = true; _sqlQueueManager = new SqlQueueManager(queueEndpoint, connectionString); _queueId = _sqlQueueManager.CreateQueue(queueName); } public void Start() { if (haveStarted) return; internalStart(); queue = _sqlQueueManager.GetQueue(queueName); Task.Factory.StartNew(() => { cleanUp = new CleanAction(queue); timeout = new TimeoutAction(queue); logger.DebugFormat("Starting {0} threads to handle messages on {1}, number of retries: {2}", threadCount, queueEndpoint, numberOfRetries); for (var i = 0; i < threadCount; i++) { threads[i] = new Thread(ReceiveMessage) { Name = "Rhino Service Bus Worker Thread #" + i, IsBackground = true }; threads[i].Start(i); } }).ContinueWith(_ => internalPostStart(), TaskContinuationOptions.OnlyOnRanToCompletion); } protected void internalPostStart() { haveStarted = true; var started = Started; if (started != null) started(); } private void ReceiveMessage(object context) { int sleepTime = 1; while (shouldContinue) { Thread.Sleep(sleepTime); try { using (var tx = _sqlQueueManager.BeginTransaction()) { if (!_sqlQueueManager.Peek(_queueId)) { sleepTime += 100; sleepTime = Math.Min(sleepTime, SleepMax); continue; } sleepTime = 1; tx.Transaction.Commit(); } } catch (TimeoutException) { logger.DebugFormat("Could not find a message on {0} during the timeout period.", queueEndpoint); continue; } catch (SqlException e) { logger.Warn("Could not get message from database.", e); continue; } catch (ObjectDisposedException) { logger.DebugFormat("Shutting down the transport for {0} thread {1}.", queueEndpoint, context); return; } catch (InvalidOperationException e) { logger.Error( "An error occured while recieving a message, clearing connection pool and make a new attempt after some sleep.", e); SqlConnection.ClearAllPools(); sleepTime = SleepMax; continue; } catch (Exception e) { logger.Error( "An error occured while recieving a message, shutting down message processing thread", e); return; } if (shouldContinue == false) return; Message message; try { using (var tx = _sqlQueueManager.BeginTransaction()) { message = _sqlQueueManager.Receive(_queueId, TimeSpan.FromSeconds(10)); tx.Transaction.Commit(); } } catch (TimeoutException) { logger.DebugFormat("Could not find a message on {0} during the timeout period", queueEndpoint); continue; } catch (SqlException e) { logger.Debug("Could not get message from database.", e); continue; } catch (InvalidOperationException e) { logger.Error( "An error occured while recieving a message, clearing connection pool and make a new attempt after some sleep.", e); SqlConnection.ClearAllPools(); sleepTime = SleepMax; continue; } catch (Exception e) { logger.Error( "An error occured while recieving a message, shutting down message processing thread", e); return; } if (message.ProcessedCount > numberOfRetries) { using (var tx = _sqlQueueManager.BeginTransaction()) { Queue.MoveTo(SubQueue.Errors.ToString(), message); Queue.EnqueueDirectlyTo(SubQueue.Errors.ToString(), new MessagePayload { SentAt = DateTime.UtcNow, Data = null, Headers = new NameValueCollection { { "correlation-id", message.Id.ToString() }, { "retries", message.ProcessedCount.ToString(CultureInfo.InvariantCulture) } } }); tx.Transaction.Commit(); } continue; } var messageWithTimer = new MessageWithTimer { Message = message }; var messageProcessingTimer = new Timer(extendMessageLeaaseIfMessageStillInProgress, messageWithTimer, TimeSpan.FromSeconds(40), TimeSpan.FromMilliseconds(-1)); messageWithTimer.Timer = messageProcessingTimer; try { var msgType = (MessageType)Enum.Parse(typeof(MessageType), message.Headers["type"]); logger.DebugFormat("Starting to handle message {0} of type {1} on {2}", message.Id, msgType, queueEndpoint); switch (msgType) { case MessageType.AdministrativeMessageMarker: ProcessMessage(message, AdministrativeMessageArrived, AdministrativeMessageProcessingCompleted, null, null); break; case MessageType.ShutDownMessageMarker: //ignoring this one using (var tx = _sqlQueueManager.BeginTransaction()) { _sqlQueueManager.MarkMessageAsReady(message); tx.Transaction.Commit(); } break; case MessageType.TimeoutMessageMarker: var timeToSend = XmlConvert.ToDateTime(message.Headers["time-to-send"], XmlDateTimeSerializationMode.Unspecified); if (timeToSend > DateTime.Now) { timeout.Register(message); using (var tx = queue.BeginTransaction()) { queue.MoveTo(SubQueue.Timeout.ToString(), message); tx.Transaction.Commit(); } } else { ProcessMessage(message, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit, BeforeMessageTransactionRollback); } break; default: ProcessMessage(message, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit, BeforeMessageTransactionRollback); break; } } catch (Exception exception) { logger.Debug("Could not process message", exception); } message.FinishedProcessing = true; } } private void extendMessageLeaaseIfMessageStillInProgress(object state) { var message = state as MessageWithTimer; if (message == null) return; if (message.Message.FinishedProcessing) { message.Timer.Dispose(); message.Timer = null; return; } try { using (var tx = _sqlQueueManager.BeginTransaction()) { _sqlQueueManager.ExtendMessageLease(message.Message); message.Timer.Change(TimeSpan.FromMinutes(9.5), TimeSpan.FromMilliseconds(-1)); tx.Transaction.Commit(); } } catch (Exception ex) { logger.Warn("Failed to extend the message lease", ex); } } private void ProcessMessage( Message message, Func<CurrentMessageInformation, bool> messageRecieved, Action<CurrentMessageInformation, Exception> messageCompleted, Action<CurrentMessageInformation> beforeTransactionCommit, Action<CurrentMessageInformation> beforeTransactionRollback) { Exception ex = null; try { //deserialization errors do not count for module events object[] messages = DeserializeMessages(message); try { var messageId = new Guid(message.Headers["id"]); var source = new Uri(message.Headers["source"]); foreach (var msg in messages) { currentMessageInformation = new SqlQueueCurrentMessageInformation { AllMessages = messages, Message = msg, Destination = queueEndpoint, MessageId = messageId, Source = source, TransportMessageId = message.Id.ToString(), Queue = queue, TransportMessage = message }; if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false) Discard(currentMessageInformation.Message); } } catch (Exception e) { ex = e; logger.Error("Failed to process message", e); } } catch (Exception e) { ex = e; logger.Error("Failed to deserialize message", e); } finally { var messageHandlingCompletion = new SqlMessageHandlingCompletion(_sqlQueueManager, null, ex, messageCompleted, beforeTransactionCommit, beforeTransactionRollback, logger, MessageProcessingFailure, currentMessageInformation); messageHandlingCompletion.HandleMessageCompletion(); currentMessageInformation = null; } } private void Discard(object message) { logger.DebugFormat("Discarding message {0} ({1}) because there are no consumers for it.", message, currentMessageInformation.TransportMessageId); Send(new Endpoint { Uri = queueEndpoint.AddSubQueue(SubQueue.Discarded) }, new[] { message }); } private object[] DeserializeMessages(Message message) { try { return messageSerializer.Deserialize(new MemoryStream(message.Data)); } catch (Exception e) { try { logger.Error("Error when serializing message", e); var serializationError = MessageSerializationException; if (serializationError != null) { currentMessageInformation = new SqlQueueCurrentMessageInformation { Message = message, Source = new Uri(message.Headers["source"]), MessageId = new Guid(message.Headers["id"]), TransportMessageId = message.Id.ToString(), TransportMessage = message, Queue = queue, }; serializationError(currentMessageInformation, e); } } catch (Exception moduleEx) { logger.Error("Error when notifying about serialization exception", moduleEx); } throw; } } public Endpoint Endpoint { get { return endpointRouter.GetRoutedEndpoint(queueEndpoint); } } public int ThreadCount { get { return threadCount; } } public CurrentMessageInformation CurrentMessageInformation { get { return currentMessageInformation; } } public void Send(Endpoint destination, object[] msgs) { SendInternal(msgs, destination, nv => { }); } private void SendInternal(object[] msgs, Endpoint destination, Action<NameValueCollection> customizeHeaders) { var messageId = Guid.NewGuid(); var messageInformation = new OutgoingMessageInformation { Destination = destination, Messages = msgs, Source = Endpoint }; var payload = messageBuilder.BuildFromMessageBatch(messageInformation); logger.DebugFormat("Sending a message with id '{0}' to '{1}'", messageId, destination.Uri); customizeHeaders(payload.Headers); _sqlQueueManager.Send(destination.Uri, payload); var copy = MessageSent; if (copy == null) return; copy(new SqlQueueCurrentMessageInformation { AllMessages = msgs, Source = Endpoint.Uri, Destination = destination.Uri, MessageId = messageId, }); } public void Send(Endpoint endpoint, DateTime processAgainAt, object[] msgs) { SendInternal(msgs, endpoint, nv => { nv["time-to-send"] = processAgainAt.ToString("yyyy-MM-ddTHH:mm:ss.fffffff", CultureInfo.InvariantCulture); nv["type"] = MessageType.TimeoutMessageMarker.ToString(); }); } public void Reply(params object[] messages) { Send(new Endpoint { Uri = currentMessageInformation.Source }, messages); } public event Action<CurrentMessageInformation> MessageSent; public event Func<CurrentMessageInformation, bool> AdministrativeMessageArrived; public event Func<CurrentMessageInformation, bool> MessageArrived; public event Action<CurrentMessageInformation, Exception> MessageSerializationException; public event Action<CurrentMessageInformation, Exception> MessageProcessingFailure; public event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted; public event Action<CurrentMessageInformation> BeforeMessageTransactionRollback; public event Action<CurrentMessageInformation> BeforeMessageTransactionCommit; public event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted; public event Action Started; } public class MessageWithTimer { public Timer Timer { get; set; } public Message Message { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Utilities; using Microsoft.Rest.Modeler.Swagger.Model; using Microsoft.Rest.Generator; using System.Diagnostics; namespace Microsoft.Rest.Modeler.Swagger { /// <summary> /// The builder for building a generic swagger object into parameters, /// service types or Json serialization types. /// </summary> public class ObjectBuilder { protected SwaggerObject SwaggerObject { get; set; } protected SwaggerModeler Modeler { get; set; } public ObjectBuilder(SwaggerObject swaggerObject, SwaggerModeler modeler) { SwaggerObject = swaggerObject; Modeler = modeler; } public virtual IType ParentBuildServiceType(string serviceTypeName) { // Should not try to get parent from generic swagger object builder throw new InvalidOperationException(); } /// <summary> /// The visitor method for building service types. This is called when an instance of this class is /// visiting a _swaggerModeler to build a service type. /// </summary> /// <param name="serviceTypeName">name for the service type</param> /// <returns>built service type</returns> public virtual IType BuildServiceType(string serviceTypeName) { PrimaryType type = SwaggerObject.ToType(); Debug.Assert(type != null); if (type.Type == KnownPrimaryType.Object && "file".Equals(SwaggerObject.Format, StringComparison.OrdinalIgnoreCase)) { type = new PrimaryType(KnownPrimaryType.Stream); } type.Format = SwaggerObject.Format; if (SwaggerObject.Enum != null && type.Type == KnownPrimaryType.String && !(IsSwaggerObjectConstant(SwaggerObject))) { var enumType = new EnumType(); SwaggerObject.Enum.ForEach(v => enumType.Values.Add(new EnumValue { Name = v, SerializedName = v })); if (SwaggerObject.Extensions.ContainsKey(CodeGenerator.EnumObject)) { var enumObject = SwaggerObject.Extensions[CodeGenerator.EnumObject] as Newtonsoft.Json.Linq.JContainer; if (enumObject != null) { enumType.Name= enumObject["name"].ToString(); if (enumObject["modelAsString"] != null) { enumType.ModelAsString = bool.Parse(enumObject["modelAsString"].ToString()); } } enumType.SerializedName = enumType.Name; if (string.IsNullOrEmpty(enumType.Name)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "{0} extension needs to specify an enum name.", CodeGenerator.EnumObject)); } var existingEnum = Modeler.ServiceClient.EnumTypes.FirstOrDefault( e => e.Name.Equals(enumType.Name, StringComparison.OrdinalIgnoreCase)); if (existingEnum != null) { if (!existingEnum.Equals(enumType)) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Swagger document contains two or more {0} extensions with the same name '{1}' and different values.", CodeGenerator.EnumObject, enumType.Name)); } } else { Modeler.ServiceClient.EnumTypes.Add(enumType); } } else { enumType.ModelAsString = true; enumType.Name = string.Empty; enumType.SerializedName = string.Empty; } return enumType; } if (SwaggerObject.Type == DataType.Array) { string itemServiceTypeName; if (SwaggerObject.Items.Reference != null) { itemServiceTypeName = SwaggerObject.Items.Reference.StripDefinitionPath(); } else { itemServiceTypeName = serviceTypeName + "Item"; } var elementType = SwaggerObject.Items.GetBuilder(Modeler).BuildServiceType(itemServiceTypeName); return new SequenceType { ElementType = elementType }; } if (SwaggerObject.AdditionalProperties != null) { string dictionaryValueServiceTypeName; if (SwaggerObject.AdditionalProperties.Reference != null) { dictionaryValueServiceTypeName = SwaggerObject.AdditionalProperties.Reference.StripDefinitionPath(); } else { dictionaryValueServiceTypeName = serviceTypeName + "Value"; } return new DictionaryType { ValueType = SwaggerObject.AdditionalProperties.GetBuilder(Modeler) .BuildServiceType((dictionaryValueServiceTypeName)) }; } return type; } public static void PopulateParameter(IParameter parameter, SwaggerObject swaggerObject) { if (swaggerObject == null) { throw new ArgumentNullException("swaggerObject"); } if (parameter == null) { throw new ArgumentNullException("parameter"); } parameter.IsRequired = swaggerObject.IsRequired; parameter.DefaultValue = swaggerObject.Default; if (IsSwaggerObjectConstant(swaggerObject)) { parameter.DefaultValue = swaggerObject.Enum[0]; parameter.IsConstant = true; } var compositeType = parameter.Type as CompositeType; if (compositeType != null && compositeType.ComposedProperties.Any()) { if (compositeType.ComposedProperties.All(p => p.IsConstant)) { parameter.DefaultValue = "{}"; parameter.IsConstant = true; } } parameter.Documentation = swaggerObject.Description; parameter.CollectionFormat = swaggerObject.CollectionFormat; var enumType = parameter.Type as EnumType; if (enumType != null) { if (parameter.Documentation == null) { parameter.Documentation = string.Empty; } else { parameter.Documentation = parameter.Documentation.TrimEnd('.') + ". "; } parameter.Documentation += "Possible values include: " + string.Join(", ", enumType.Values.Select(v => string.Format(CultureInfo.InvariantCulture, "'{0}'", v.Name))); } swaggerObject.Extensions.ForEach(e => parameter.Extensions[e.Key] = e.Value); SetConstraints(parameter.Constraints, swaggerObject); } private static bool IsSwaggerObjectConstant(SwaggerObject swaggerObject) { return (swaggerObject.Enum != null && swaggerObject.Enum.Count == 1 && swaggerObject.IsRequired); } public static void SetConstraints(Dictionary<Constraint, string> constraints, SwaggerObject swaggerObject) { if (constraints == null) { throw new ArgumentNullException("constraints"); } if (swaggerObject == null) { throw new ArgumentNullException("swaggerObject"); } if (!string.IsNullOrEmpty(swaggerObject.Maximum) && !swaggerObject.ExclusiveMaximum) { constraints[Constraint.InclusiveMaximum] = swaggerObject.Maximum; } if (!string.IsNullOrEmpty(swaggerObject.Maximum) && swaggerObject.ExclusiveMaximum) { constraints[Constraint.ExclusiveMaximum] = swaggerObject.Maximum; } if (!string.IsNullOrEmpty(swaggerObject.Minimum) && !swaggerObject.ExclusiveMinimum) { constraints[Constraint.InclusiveMinimum] = swaggerObject.Minimum; } if (!string.IsNullOrEmpty(swaggerObject.Minimum) && swaggerObject.ExclusiveMinimum) { constraints[Constraint.ExclusiveMinimum] = swaggerObject.Minimum; } if (!string.IsNullOrEmpty(swaggerObject.MaxLength)) { constraints[Constraint.MaxLength] = swaggerObject.MaxLength; } if (!string.IsNullOrEmpty(swaggerObject.MinLength)) { constraints[Constraint.MinLength] = swaggerObject.MinLength; } if (!string.IsNullOrEmpty(swaggerObject.Pattern)) { constraints[Constraint.Pattern] = swaggerObject.Pattern; } if (!string.IsNullOrEmpty(swaggerObject.MaxItems)) { constraints[Constraint.MaxItems] = swaggerObject.MaxItems; } if (!string.IsNullOrEmpty(swaggerObject.MinItems)) { constraints[Constraint.MinItems] = swaggerObject.MinItems; } if (!string.IsNullOrEmpty(swaggerObject.MultipleOf)) { constraints[Constraint.MultipleOf] = swaggerObject.MultipleOf; } if (swaggerObject.UniqueItems) { constraints[Constraint.UniqueItems] = "true"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Adapted from fasta C# .NET Core #2 program // http://benchmarksgame.alioth.debian.org/u64q/program.php?test=fasta&lang=csharpcore&id=2 // aka (as of 2017-09-01) rev 1.2 of https://alioth.debian.org/scm/viewvc.php/benchmarksgame/bench/fasta/fasta.csharp-2.csharp?root=benchmarksgame&view=log // Best-scoring single-threaded C# .NET Core version as of 2017-09-01 /* The Computer Language Benchmarks Game http://benchmarksgame.alioth.debian.org/ contributed by Isaac Gouy optimizations by Alp Toker <alp@atoker.com> */ using System; using System.IO; using System.Text; using Microsoft.Xunit.Performance; [assembly: OptimizeForBenchmarks] namespace BenchmarksGame { public class Fasta_2 { static int Main(string[] args) { int n = args.Length > 0 ? Int32.Parse(args[0]) : 1000; Bench(n, true); return 100; } [Benchmark(InnerIterationCount = 2500)] public static void RunBench() { Benchmark.Iterate(() => Bench(5000, false)); } static void Bench(int n, bool verbose) { MakeCumulative(HomoSapiens); MakeCumulative(IUB); using (Stream s = (verbose ? Console.OpenStandardOutput() : Stream.Null)) { MakeRepeatFasta("ONE", "Homo sapiens alu", Encoding.ASCII.GetBytes(ALU), n * 2, s); MakeRandomFasta("TWO", "IUB ambiguity codes", IUB, n * 3, s); MakeRandomFasta("THREE", "Homo sapiens frequency", HomoSapiens, n * 5, s); } } // The usual pseudo-random number generator const int IM = 139968; const int IA = 3877; const int IC = 29573; static int seed = 42; static double random(double max) { return max * ((seed = (seed * IA + IC) % IM) * (1.0 / IM)); } // Weighted selection from alphabet static string ALU = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" + "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" + "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" + "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" + "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" + "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" + "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; class Frequency { public byte c; public double p; public Frequency(char c, double p) { this.c = (byte)c; this.p = p; } } static Frequency[] IUB = { new Frequency ('a', 0.27), new Frequency ('c', 0.12), new Frequency ('g', 0.12), new Frequency ('t', 0.27), new Frequency ('B', 0.02), new Frequency ('D', 0.02), new Frequency ('H', 0.02), new Frequency ('K', 0.02), new Frequency ('M', 0.02), new Frequency ('N', 0.02), new Frequency ('R', 0.02), new Frequency ('S', 0.02), new Frequency ('V', 0.02), new Frequency ('W', 0.02), new Frequency ('Y', 0.02) }; static Frequency[] HomoSapiens = { new Frequency ('a', 0.3029549426680), new Frequency ('c', 0.1979883004921), new Frequency ('g', 0.1975473066391), new Frequency ('t', 0.3015094502008) }; static void MakeCumulative(Frequency[] a) { double cp = 0.0; for (int i = 0; i < a.Length; i++) { cp += a[i].p; a[i].p = cp; } } // naive static byte SelectRandom(Frequency[] a) { double r = random(1.0); for (int i = 0; i < a.Length; i++) if (r < a[i].p) return a[i].c; return a[a.Length - 1].c; } const int LineLength = 60; static int index = 0; static byte[] buf = new byte[1024]; static void MakeRandomFasta(string id, string desc, Frequency[] a, int n, Stream s) { index = 0; int m = 0; byte[] descStr = Encoding.ASCII.GetBytes(">" + id + " " + desc + "\n"); s.Write(descStr, 0, descStr.Length); while (n > 0) { m = n < LineLength ? n : LineLength; if (buf.Length - index < m) { s.Write(buf, 0, index); index = 0; } for (int i = 0; i < m; i++) { buf[index++] = SelectRandom(a); } buf[index++] = (byte)'\n'; n -= LineLength; } if (index != 0) s.Write(buf, 0, index); } static void MakeRepeatFasta(string id, string desc, byte[] alu, int n, Stream s) { index = 0; int m = 0; int k = 0; int kn = alu.Length; byte[] descStr = Encoding.ASCII.GetBytes(">" + id + " " + desc + "\n"); s.Write(descStr, 0, descStr.Length); while (n > 0) { m = n < LineLength ? n : LineLength; if (buf.Length - index < m) { s.Write(buf, 0, index); index = 0; } for (int i = 0; i < m; i++) { if (k == kn) k = 0; buf[index++] = alu[k]; k++; } buf[index++] = (byte)'\n'; n -= LineLength; } if (index != 0) s.Write(buf, 0, index); } } }
using System; using UnityEngine; public enum LogDestinationType { editorConsole = 1, file = 2, guiConsole = 4 } public enum DisableContext { onError = 1, onException = 2, onFailedAssertion = 4 } public enum NGLogType { Assert = 1, Error = 2, Exception = 4, Log = 8, Warning = 16 } namespace NG.Logging { public static class Debug { public static NGLogType noFilter { get { return NGLogType.Assert | NGLogType.Error | NGLogType.Exception | NGLogType.Log | NGLogType.Warning; } } public static LogDestinationType logDestinations = LogDestinationType.editorConsole | LogDestinationType.file | LogDestinationType.guiConsole; public static DisableContext disableContext = DisableContext.onError | DisableContext.onException | DisableContext.onFailedAssertion; private static ILogger _consoleLogger = null; public static ILogger consoleLogger { get { Init(); if (_consoleLogger == null) { _consoleLogger = UnityEngine.Debug.unityLogger; _consoleLogger.logEnabled = consoleLogEnabled; _consoleLogger.filterLogType = (LogType.Assert | LogType.Error | LogType.Exception | LogType.Log | LogType.Warning); } return _consoleLogger; } } private static FileLogger _fileLogger = null; public static FileLogger fileLogger { get { Init(); if (_fileLogger == null) { _fileLogger = new FileLogger(fileLogEnabled, fileLogFilter); } return _fileLogger; } set { _fileLogger = value; } } private static GuiLogger _guiLogger = null; public static GuiLogger guiLogger { get { Init(); if (_guiLogger == null) { _guiLogger = new GuiLogger(guiLogEnabled, guiLogFilter); } return _guiLogger; } set { _guiLogger = value; } } private static NGLogType _consoleLogFilter = noFilter; public static NGLogType consoleLogFilter { get { Init(); return _consoleLogFilter; } set { _consoleLogFilter = value; } } private static NGLogType _fileLogFilter = noFilter; public static NGLogType fileLogFilter { get { Init(); return _fileLogFilter; } set { _fileLogFilter = value; fileLogger.ngFilterLogType = value; } } private static NGLogType _guiLogFilter = noFilter; public static NGLogType guiLogFilter { get { Init(); return _guiLogFilter; } set { _guiLogFilter = value; guiLogger.ngFilterLogType = value; } } public static bool _consoleLogEnabled = true; public static bool consoleLogEnabled { get { Init(); return _consoleLogEnabled; } set { consoleLogger.logEnabled = value; _consoleLogEnabled = value; } } private static bool _fileLogEnabled = true; public static bool fileLogEnabled { get { Init(); return _fileLogEnabled; } set { fileLogger.logEnabled = value; _fileLogEnabled = value; } } private static bool _guiLogEnabled = true; public static bool guiLogEnabled { get { Init(); return _guiLogEnabled; } set { _guiLogEnabled = value; guiLogger.logEnabled = value; } } public static bool ShouldAttemptDisableContext(DisableContext currentContext) { return ((disableContext & currentContext) == currentContext); } public static void AttemptDisableContext(DisableContext currentContext, UnityEngine.Object context) { if (!ShouldAttemptDisableContext(currentContext)) return; if (context == null) return; try { MonoBehaviour monobehaviour = (MonoBehaviour)context; if (monobehaviour != null) { monobehaviour.enabled = false; return; } } catch(Exception){ } try { GameObject gameObject = (GameObject)context; if (gameObject != null) { gameObject.SetActive(false); return; } } catch(Exception){ } } // TODO /// <summary> /// Use this later for loading settings /// </summary> private static bool didInit = false; private static void Init() { if (didInit) return; didInit = true; NGDebugLoggerSettingsLoader.LoadSettings(); } public static bool ShouldLogToConsole(LogType logType) { if (!consoleLogEnabled) return false; if ((logDestinations & LogDestinationType.editorConsole) != LogDestinationType.editorConsole) return false; NGLogType ngLogType = logType.ToNGLogType(); if ((consoleLogFilter & ngLogType) != ngLogType) return false; return true; } public static bool shouldLogToFile { get { return fileLogEnabled && ((logDestinations & LogDestinationType.file) == LogDestinationType.file); } } public static bool ShouldLogToGuiConsole(LogType logType) { if (!guiLogEnabled) return false; if ((logDestinations & LogDestinationType.guiConsole) != LogDestinationType.guiConsole) return false; NGLogType ngLogType = logType.ToNGLogType(); if ((guiLogFilter & ngLogType) != ngLogType) return false; return true; } public static string TimeStamp { get { return "[" + DateTime.Now.ToString() + "]"; } } public static string FormatTagConsole(string tag) { string compose = TimeStamp; if (!string.IsNullOrEmpty(tag)) compose += " [" + tag + "]"; return compose; } #region LOG public static void Log(string tag, object message, UnityEngine.Object context) { string formattedTag = FormatTagConsole(tag); if (ShouldLogToConsole(LogType.Log)) { consoleLogger.Log(formattedTag, message, context); } if (shouldLogToFile) fileLogger.Log(tag, message, context); if (ShouldLogToGuiConsole(LogType.Log)) guiLogger.Log(formattedTag, message, context); } public static void Log(object message) { Log(null, message, null); } public static void Log(object message, UnityEngine.Object context) { Log(null, message, context); } public static void LogFormat(UnityEngine.Object context, string format, params object[] args) { if (ShouldLogToConsole(LogType.Log)) consoleLogger.LogFormat(LogType.Log, context, TimeStamp + ": " + format, args); if (shouldLogToFile) fileLogger.LogFormat(LogType.Log, context, format, args); if (ShouldLogToGuiConsole(LogType.Log)) guiLogger.LogFormat(LogType.Log, context, TimeStamp + ": " + format, args); } public static void LogFormat(string format, params object[] args) { LogFormat(null, format, args); } #endregion #region WARNING public static void LogWarning(string tag, object message, UnityEngine.Object context) { string formattedTag = FormatTagConsole(tag); if (ShouldLogToConsole(LogType.Warning)) consoleLogger.LogWarning(formattedTag, message, context); if (shouldLogToFile) fileLogger.LogWarning(tag, message, context); if (ShouldLogToGuiConsole(LogType.Warning)) guiLogger.LogWarning(formattedTag, message, context); } public static void LogWarning(object message) { LogWarning(null, message, null); } public static void LogWarning(object message, UnityEngine.Object context) { LogWarning(null, message, context); } public static void LogWarningFormat(UnityEngine.Object context, string format, params object[] args) { if (ShouldLogToConsole(LogType.Warning)) consoleLogger.LogFormat(LogType.Warning, context, TimeStamp + ": " + format, args); if (shouldLogToFile) fileLogger.LogFormat(LogType.Warning, context, format, args); if (ShouldLogToGuiConsole(LogType.Warning)) guiLogger.LogFormat(LogType.Warning, context, TimeStamp + ": " + format, args); } public static void LogWarningFormat(string format, params object[] args) { LogWarningFormat(null, format, args); } #endregion #region ERROR public static void LogError(string tag, object message, UnityEngine.Object context) { string formattedTag = FormatTagConsole(tag); if (ShouldLogToConsole(LogType.Error)) consoleLogger.LogError(formattedTag, message, context); if (shouldLogToFile) fileLogger.LogError(tag, message, context); if (ShouldLogToGuiConsole(LogType.Error)) guiLogger.LogError(formattedTag, message, context); AttemptDisableContext(DisableContext.onError, context); } public static void LogError(object message) { LogError(null, message, null); } public static void LogError(object message, UnityEngine.Object context) { LogError(null, message, context); } public static void LogErrorFormat(UnityEngine.Object context, string format, params object[] args) { if (ShouldLogToConsole(LogType.Error)) consoleLogger.LogFormat(LogType.Error, context, TimeStamp + ": " + format, args); ; if (shouldLogToFile) fileLogger.LogError(null, string.Format(format, args), context); if (ShouldLogToGuiConsole(LogType.Error)) guiLogger.LogFormat(LogType.Error, context, TimeStamp + ": " + format, args); AttemptDisableContext(DisableContext.onError, context); } public static void LogErrorFormat(string format, params object[] args) { LogErrorFormat(null, format, args); } #endregion #region EXCEPTION public static void LogException(Exception exception, UnityEngine.Object context) { if (ShouldLogToConsole(LogType.Exception)) consoleLogger.LogException(exception, context); if (shouldLogToFile) fileLogger.LogException(exception, context); if (ShouldLogToGuiConsole(LogType.Error)) guiLogger.LogException(exception, context); AttemptDisableContext(DisableContext.onException, context); } public static void LogException(Exception exception) { LogException(exception, null); } #endregion // I think these might be better in a custom assertion class /* [Conditional("UNITY_ASSERTIONS")] public static void LogAssertion(object message) { } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertion(object message, UnityEngine.Object context) { } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertionFormat(string format, params object[] args) { } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertionFormat(UnityEngine.Object context, string format, params object[] args) { } */ } public static class NGLogTypeExt { public static NGLogType All = NGLogType.Assert | NGLogType.Error | NGLogType.Exception | NGLogType.Log | NGLogType.Warning; public static NGLogType ToNGLogType(this LogType unityLogType) { switch (unityLogType) { case LogType.Error: return NGLogType.Error; case LogType.Assert: return NGLogType.Assert; case LogType.Warning: return NGLogType.Warning; case LogType.Log: return NGLogType.Log; case LogType.Exception: return NGLogType.Exception; default: return 0; } } } }
using System; using NUnit.Framework; using System.Text; #if FX1_1 using IList_ServiceElement = System.Collections.IList; using List_ServiceElement = System.Collections.ArrayList; using IList_ServiceAttribute = System.Collections.IList; using List_ServiceAttribute = System.Collections.ArrayList; #else using IList_ServiceElement = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceElement>; using List_ServiceElement = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceElement>; using IList_ServiceAttribute = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceAttribute>; using List_ServiceAttribute = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceAttribute>; #endif using InTheHand.Net.Bluetooth; using InTheHand.Net.Bluetooth.AttributeIds; namespace InTheHand.Net.Tests.Sdp2 { [TestFixture] public class CoverArgException { //public delegate void CoverStreamLikeReadOrWriteMethod(byte[]buf, int offset, int length); public delegate object CoverStreamLikeReadOrWriteMethod(byte[] buf, int offset, int length); public static void CoverStreamLikeReadOrWrite(CoverStreamLikeReadOrWriteMethod method) { byte[] data = null; try { method(null, 0, 1); Assert.Fail("buf=null did not throw!"); } catch (ArgumentNullException) { } data = new byte[5]; try { method(data, 0, 0); Assert.Fail("length=0 did not throw!"); } catch (ArgumentOutOfRangeException) { } try { method(data, -1, 1); Assert.Fail("offset=-1 did not throw!"); } catch (ArgumentOutOfRangeException) { } try { method(data, 0, 6); Assert.Fail("overrun did not throw!"); } catch (ArgumentException) { } try { method(data, 2, 4); Assert.Fail("overrun with offset did not throw!"); } catch (ArgumentException) { } } //-------------------------------------------------------------- [Test, ExpectedException(typeof(ArgumentNullException))] public void Parser_Parse1Null() { new ServiceRecordParser().Parse(null); } #if ! FX1_1 [Test] public void Parser_ParseNull() { CoverStreamLikeReadOrWriteMethod method = new ServiceRecordParser().Parse; CoverStreamLikeReadOrWrite(method); } #endif [Test] [ExpectedException(typeof(System.Net.ProtocolViolationException), ExpectedMessage = "The top element must be a Element Sequence type.")] public void Parser_ParseNonElementSeqThusNotCompleteRecord() { byte[] buf = { 0x09, 0x12, 0x34 }; new ServiceRecordParser().Parse(buf); } //-------------------------------------------------------------- [Test] [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = "Unknown ElementType 'Unknown'." +"\r\nParameter name: type")] public void EtdFromTypeUnknown() { ServiceRecordParser.GetEtdForType(ElementType.Unknown); } [Test] [ExpectedException(typeof(ArgumentOutOfRangeException), ExpectedMessage = "Unknown ElementType '10000'." + "\r\nParameter name: type")] public void EtdFromTypeInvalid() { ServiceRecordParser.GetEtdForType((ElementType)10000); } //-------------------------------------------------------------- [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Type ElementSequence and ElementAlternative need an list of ServiceElement.")] public void Element_Ctor_NonListForElementSeqAlt() { new ServiceElement(ElementType.ElementSequence, "booooom"); } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Type ElementSequence and ElementAlternative must be used for an list of ServiceElement.")] public void Element_Ctor_ListForNonElementSeqAlt() { new ServiceElement(ElementType.Int16, new List_ServiceElement()); } private ServiceElement CreateInt16ServiceElement() { return new ServiceElement(ElementType.Int16, (Int16)11); } [Test, ExpectedException(typeof(ArgumentNullException))] public void Element_GetStringENull() { Encoding enc = null; CreateInt16ServiceElement().GetValueAsString(enc); } [Test, ExpectedException(typeof(ArgumentNullException))] public void Element_GetStringLNull() { LanguageBaseItem enc = null; CreateInt16ServiceElement().GetValueAsString(enc); } //-------------------------------------------------------------- [Test, ExpectedException(typeof(InvalidOperationException))] public void Element_GetWrongType_String() { Encoding enc = Encoding.UTF8; CreateInt16ServiceElement().GetValueAsString(enc); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Element_GetWrongType_Uuid() { CreateInt16ServiceElement().GetValueAsUuid(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Element_GetWrongType_ElemArray() { object foo = CreateInt16ServiceElement().GetValueAsElementArray(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Element_GetWrongType_ElemList() { object foo = CreateInt16ServiceElement().GetValueAsElementList(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void Element_GetWrongType_Uri() { object foo = CreateInt16ServiceElement().GetValueAsUri(); } //-------------------------------------------------------------- [Test, ExpectedException(typeof(ArgumentNullException))] public void Utils_Dump_NullWriter() { ServiceRecord rec = new ServiceRecord(new List_ServiceAttribute()); ServiceRecordUtilities.Dump(null, rec); } [Test, ExpectedException(typeof(ArgumentNullException))] public void Utils_Dump_NullRecord() { ServiceRecordUtilities.Dump(new System.IO.StringWriter(), null); } [Test, ExpectedException(typeof(ArgumentNullException))] public void Utils_DumpRaw_NullWriter() { ServiceRecord rec = new ServiceRecord(new List_ServiceAttribute()); ServiceRecordUtilities.DumpRaw(null, rec); } [Test, ExpectedException(typeof(ArgumentNullException))] public void Utils_DumpRaw_NullRecord() { ServiceRecordUtilities.DumpRaw(new System.IO.StringWriter(), null); } //-------------------------------------------------------------- [Test, ExpectedException(typeof(ArgumentNullException))] public void AttributeIdLookup_NullType() { LanguageBaseItem langBase; AttributeIdLookup.GetName(UniversalAttributeId.ProtocolDescriptorList, null, new LanguageBaseItem[0], out langBase); } [Test, ExpectedException(typeof(ArgumentNullException))] public void AttributeIdLookup_NullLangBaseList() { LanguageBaseItem langBase; AttributeIdLookup.GetName(UniversalAttributeId.ProtocolDescriptorList, new Type[] { typeof(UniversalAttributeId) }, null, out langBase); } }//class }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// Alert /// </summary> [DataContract] public partial class Alert : IEquatable<Alert> { /// <summary> /// Initializes a new instance of the <see cref="Alert" /> class. /// </summary> [JsonConstructorAttribute] public Alert() { } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; private set; } /// <summary> /// Gets or Sets Level /// </summary> [DataMember(Name="level", EmitDefaultValue=false)] public string Level { get; private set; } /// <summary> /// Gets or Sets Message /// </summary> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; private set; } /// <summary> /// Gets or Sets Link /// </summary> [DataMember(Name="link", EmitDefaultValue=false)] public string Link { get; private set; } /// <summary> /// Gets or Sets LinkText /// </summary> [DataMember(Name="linkText", EmitDefaultValue=false)] public string LinkText { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets ExpirationDate /// </summary> [DataMember(Name="expirationDate", EmitDefaultValue=false)] public DateTime? ExpirationDate { get; private set; } /// <summary> /// Gets or Sets AcknowledgeDate /// </summary> [DataMember(Name="acknowledgeDate", EmitDefaultValue=false)] public DateTime? AcknowledgeDate { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Alert {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Level: ").Append(Level).Append("\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append(" Link: ").Append(Link).Append("\n"); sb.Append(" LinkText: ").Append(LinkText).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" ExpirationDate: ").Append(ExpirationDate).Append("\n"); sb.Append(" AcknowledgeDate: ").Append(AcknowledgeDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as Alert); } /// <summary> /// Returns true if Alert instances are equal /// </summary> /// <param name="other">Instance of Alert to be compared</param> /// <returns>Boolean</returns> public bool Equals(Alert other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ) && ( this.Level == other.Level || this.Level != null && this.Level.Equals(other.Level) ) && ( this.Message == other.Message || this.Message != null && this.Message.Equals(other.Message) ) && ( this.Link == other.Link || this.Link != null && this.Link.Equals(other.Link) ) && ( this.LinkText == other.LinkText || this.LinkText != null && this.LinkText.Equals(other.LinkText) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.ExpirationDate == other.ExpirationDate || this.ExpirationDate != null && this.ExpirationDate.Equals(other.ExpirationDate) ) && ( this.AcknowledgeDate == other.AcknowledgeDate || this.AcknowledgeDate != null && this.AcknowledgeDate.Equals(other.AcknowledgeDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); if (this.Level != null) hash = hash * 59 + this.Level.GetHashCode(); if (this.Message != null) hash = hash * 59 + this.Message.GetHashCode(); if (this.Link != null) hash = hash * 59 + this.Link.GetHashCode(); if (this.LinkText != null) hash = hash * 59 + this.LinkText.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.ExpirationDate != null) hash = hash * 59 + this.ExpirationDate.GetHashCode(); if (this.AcknowledgeDate != null) hash = hash * 59 + this.AcknowledgeDate.GetHashCode(); return hash; } } } }
// 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.Contracts; using System.Threading.Tasks; namespace System.IO { // This class implements a text reader that reads from a string. // public class StringReader : TextReader { private string _s; private int _pos; private int _length; public StringReader(string s) { if (s == null) { throw new ArgumentNullException("s"); } _s = s; _length = s == null ? 0 : s.Length; } protected override void Dispose(bool disposing) { _s = null; _pos = 0; _length = 0; base.Dispose(disposing); } // Returns the next available character without actually reading it from // the underlying string. The current position of the StringReader is not // changed by this operation. The returned value is -1 if no further // characters are available. // [Pure] public override int Peek() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos]; } // Reads the next character from the underlying string. The returned value // is -1 if no further characters are available. // public override int Read() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } if (_pos == _length) { return -1; } return _s[_pos++]; } // Reads a block of characters. This method will read up to count // characters from this StringReader into the buffer character // array starting at position index. Returns the actual number of // characters read, or zero if the end of the string is reached. // public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int n = _length - _pos; if (n > 0) { if (n > count) { n = count; } _s.CopyTo(_pos, buffer, index, n); _pos += n; } return n; } public override string ReadToEnd() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } string s; if (_pos == 0) { s = _s; } else { s = _s.Substring(_pos, _length - _pos); } _pos = _length; return s; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the underlying string has been reached. // public override string ReadLine() { if (_s == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed); } int i = _pos; while (i < _length) { char ch = _s[i]; if (ch == '\r' || ch == '\n') { string result = _s.Substring(_pos, i - _pos); _pos = i + 1; if (ch == '\r' && _pos < _length && _s[_pos] == '\n') { _pos++; } return result; } i++; } if (i > _pos) { string result = _s.Substring(_pos, i - _pos); _pos = i; return result; } return null; } #region Task based Async APIs public override Task<string> ReadLineAsync() { return Task.FromResult(ReadLine()); } public override Task<string> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } public override Task<int> ReadBlockAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(ReadBlock(buffer, index, count)); } public override Task<int> ReadAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return Task.FromResult(Read(buffer, index, count)); } #endregion } }
using System; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Macs { /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ class MacCFBBlockCipher : IBlockCipher { private byte[] IV; private byte[] cfbV; private byte[] cfbOutV; private readonly int blockSize; private readonly IBlockCipher cipher; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ public MacCFBBlockCipher( IBlockCipher cipher, int bitBlockSize) { this.cipher = cipher; this.blockSize = bitBlockSize / 8; this.IV = new byte[cipher.GetBlockSize()]; this.cfbV = new byte[cipher.GetBlockSize()]; this.cfbOutV = new byte[cipher.GetBlockSize()]; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) { Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length); } else { Array.Copy(iv, 0, IV, 0, IV.Length); } parameters = ivParam.Parameters; } Reset(); cipher.Init(true, parameters); } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CFB" * and the block size in bits. */ public string AlgorithmName { get { return cipher.AlgorithmName + "/CFB" + (blockSize * 8); } } public bool IsPartialBlockOkay { get { return true; } } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int GetBlockSize() { return blockSize; } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + blockSize) > outBytes.Length) throw new DataLengthException("output buffer too short"); cipher.ProcessBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the cipher text // for (int i = 0; i < blockSize; i++) { outBytes[outOff + i] = (byte)(cfbOutV[i] ^ input[inOff + i]); } // // change over the input block. // Array.Copy(cfbV, blockSize, cfbV, 0, cfbV.Length - blockSize); Array.Copy(outBytes, outOff, cfbV, cfbV.Length - blockSize, blockSize); return blockSize; } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { IV.CopyTo(cfbV, 0); cipher.Reset(); } public void GetMacBlock( byte[] mac) { cipher.ProcessBlock(cfbV, 0, mac, 0); } } public class CfbBlockCipherMac : IMac { private byte[] mac; private byte[] Buffer; private int bufOff; private MacCFBBlockCipher cipher; private IBlockCipherPadding padding; private int macSize; /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. */ public CfbBlockCipherMac( IBlockCipher cipher) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, null) { } /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, IBlockCipherPadding padding) : this(cipher, 8, (cipher.GetBlockSize() * 8) / 2, padding) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits) : this(cipher, cfbBitSize, macSizeInBits, null) { } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * </p> * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding a padding to be used. */ public CfbBlockCipherMac( IBlockCipher cipher, int cfbBitSize, int macSizeInBits, IBlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) throw new ArgumentException("MAC size must be multiple of 8"); mac = new byte[cipher.GetBlockSize()]; this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; Buffer = new byte[this.cipher.GetBlockSize()]; bufOff = 0; } public string AlgorithmName { get { return cipher.AlgorithmName; } } public void Init( ICipherParameters parameters) { Reset(); cipher.Init(true, parameters); } public int GetMacSize() { return macSize; } public void Update( byte input) { if (bufOff == Buffer.Length) { cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; } Buffer[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int blockSize = cipher.GetBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, Buffer, bufOff, gapLen); resultLen += cipher.ProcessBlock(Buffer, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.ProcessBlock(input, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, Buffer, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); // pad with zeroes if (this.padding == null) { while (bufOff < blockSize) { Buffer[bufOff++] = 0; } } else { padding.AddPadding(Buffer, bufOff); } cipher.ProcessBlock(Buffer, 0, mac, 0); cipher.GetMacBlock(mac); Array.Copy(mac, 0, output, outOff, macSize); Reset(); return macSize; } /** * Reset the mac generator. */ public void Reset() { // Clear the buffer. Array.Clear(Buffer, 0, Buffer.Length); bufOff = 0; // Reset the underlying cipher. cipher.Reset(); } } }
using OpenTK; using SageCS.Graphics; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; // TODO: // fix the ReadString method // unknown chunks: // 64 size of 4 bytes // 96 vertex normals for bump mapping? (specular and diffuse normals) // 97 vertex normals for bump mapping? (specular and diffuse normals) // 643 compressed animation data namespace SageCS.Core.Loaders { class W3DLoader { private static string modelName = ""; private static Model model; private static string hierarchyName = ""; private static Hierarchy hierarchy; private static W3DMesh mesh; private static string texName = ""; private static string matName = ""; //###################################################################################### //# structs //###################################################################################### struct Version { public long major; public long minor; } //###################################################################################### //# basic methods //###################################################################################### private static string ReadString(BinaryReader br) { List<byte> data = new List<byte>(); byte b = br.ReadByte(); while (b != 0) { data.Add(b); b = br.ReadByte(); } return System.Text.Encoding.UTF8.GetString(data.ToArray<byte>()); } private static string ReadFixedString(BinaryReader br) { byte[] data = br.ReadBytes(16); return System.Text.Encoding.UTF8.GetString(data); } private static string ReadLongFixedString(BinaryReader br) { byte[] data = br.ReadBytes(32); return System.Text.Encoding.UTF8.GetString(data); } private static Vector4 ReadRGBA(BinaryReader br) { return new Vector4(br.ReadByte(), br.ReadByte(), br.ReadByte(), br.ReadByte()); } private static uint getChunkSize(uint data) { return (data & 0x7FFFFFFF); } private static uint ReadLong(BinaryReader br) { return br.ReadUInt32(); } private static uint[] ReadLongArray(BinaryReader br, uint ChunkEnd) { List<uint> data = new List<uint>(); while (br.BaseStream.Position < ChunkEnd) { data.Add(ReadLong(br)); } return data.ToArray(); } private static uint ReadShort(BinaryReader br) { return br.ReadUInt16(); } private static float ReadFloat(BinaryReader br) { return (float)br.ReadSingle(); } private static byte ReadByte(BinaryReader br) { return br.ReadByte(); } private static Vector3 ReadVector(BinaryReader br) { return new Vector3(ReadFloat(br), ReadFloat(br), ReadFloat(br)); } private static Quaternion ReadQuaternion(BinaryReader br) { return new Quaternion(ReadFloat(br), ReadFloat(br), ReadFloat(br), ReadFloat(br)); } private static Version GetVersion(long data) { Version v = new Version(); v.major = data >> 16; v.minor = data & 0xFFFF; return v; } //####################################################################################### //# Hierarchy //####################################################################################### private static void ReadHierarchyHeader(BinaryReader br) { Version version = GetVersion(ReadLong(br)); hierarchyName = ReadFixedString(br); long pivotCount = ReadLong(br); Vector3 centerPos = ReadVector(br); hierarchy = new Hierarchy(pivotCount, centerPos); } private static void ReadPivots(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { string name = ReadFixedString(br); long parentID = ReadLong(br); Vector3 position = ReadVector(br); Vector3 eulerAngles = ReadVector(br); Quaternion rotation = ReadQuaternion(br); hierarchy.addPivot(name, parentID, position, eulerAngles, rotation); } } private static void ReadPivotFixups(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { Vector3 pivot_fixup = ReadVector(br); } } private static void ReadHierarchy(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 257: ReadHierarchyHeader(br); break; case 258: ReadPivots(br, subChunkEnd); break; case 259: ReadPivotFixups(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in Hierarchy"); br.ReadBytes((int)Chunksize); break; } } Hierarchy.AddHierarchy(hierarchyName, hierarchy); } //####################################################################################### //# Animation //####################################################################################### private static void ReadAnimationHeader(BinaryReader br) { Version version = GetVersion(ReadLong(br)); string name = ReadFixedString(br); string hieraName = ReadFixedString(br); long numFrames = ReadLong(br); long frameRate = ReadLong(br); } private static void ReadAnimationChannel(BinaryReader br, uint ChunkEnd) { uint firstFrame = ReadShort(br); uint lastFrame = ReadShort(br); uint vectorLen = ReadShort(br); uint type = ReadShort(br); uint pivot = ReadShort(br); uint pad = ReadShort(br); switch (vectorLen) { case 1: while (br.BaseStream.Position < ChunkEnd) { ReadFloat(br); } break; case 4: while (br.BaseStream.Position < ChunkEnd) { ReadQuaternion(br); } break; default: Console.WriteLine("invalid vector len: " + vectorLen + "in AnimationChannel"); while (br.BaseStream.Position < ChunkEnd) { ReadByte(br); } break; } } private static void ReadAnimation(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 513: ReadAnimationHeader(br); break; case 514: ReadAnimationChannel(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in Animation"); br.ReadBytes((int)Chunksize); break; } } } private static void ReadCompressedAnimationHeader(BinaryReader br) { Version version = GetVersion(ReadLong(br)); string name = ReadFixedString(br); string hieraName = ReadFixedString(br); long numFrames = ReadLong(br); uint frameRate = ReadShort(br); uint flavor = ReadShort(br); } private static void ReadTimeCodedAnimVector(BinaryReader br, uint ChunkEnd) { // A time code is a uint32 that prefixes each vector // the MSB is used to indicate a binary (non interpolated) movement uint magigNum = ReadShort(br); //0 or 256 or 512 -> interpolation type? /compression of the Q-Channels? (0, 256, 512) -> (0, 8, 16 bit) byte vectorLen = ReadByte(br); byte flag = ReadByte(br); //is x or y or z or quat uint timeCodesCount = ReadShort(br); uint pivot = ReadShort(br); // will be (NumTimeCodes * ((VectorLen * 4) + 4)) -> works if the magic num is 0 // so only the Q-Channels are compressed? switch (vectorLen) { case 1: while (br.BaseStream.Position < ChunkEnd) { ReadByte(br); } break; case 4: while (br.BaseStream.Position < ChunkEnd) { ReadByte(br); } break; default: Console.WriteLine("invalid vector len: " + vectorLen + "in TimeCodedAnimVector"); while (br.BaseStream.Position < ChunkEnd) { ReadByte(br); } break; } } private static void ReadCompressedAnimation(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 641: ReadCompressedAnimationHeader(br); break; case 642: br.ReadBytes((int)Chunksize); break; case 643: br.ReadBytes((int)Chunksize); break; case 644: ReadTimeCodedAnimVector(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in CompressedAnimation"); br.ReadBytes((int)Chunksize); break; } } } //####################################################################################### //# HLod //####################################################################################### private static void ReadHLodHeader(BinaryReader br) { Version version = GetVersion(ReadLong(br)); long lodCount = ReadLong(br); string modelName = ReadFixedString(br); string HTreeName = ReadFixedString(br); } private static void ReadHLodArrayHeader(BinaryReader br) { long modelCount = ReadLong(br); float maxScreenSize = ReadFloat(br); } private static void ReadHLodSubObject(BinaryReader br) { long boneIndex = ReadLong(br); string name = ReadLongFixedString(br); } private static void ReadHLodArray(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 1795: ReadHLodArrayHeader(br); break; case 1796: ReadHLodSubObject(br); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in HLodArray"); br.ReadBytes((int)Chunksize); break; } } } private static void ReadHLod(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 1793: ReadHLodHeader(br); break; case 1794: ReadHLodArray(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in HLod"); br.ReadBytes((int)Chunksize); break; } } } //####################################################################################### //# Box //####################################################################################### private static void ReadBox(BinaryReader br) { Model.Box box = new Model.Box(); Version version = GetVersion(ReadLong(br)); long attributes = ReadLong(br); string name = ReadLongFixedString(br); Vector4 color = ReadRGBA(br); box.center = ReadVector(br); box.extend = ReadVector(br); model.box = box; } //####################################################################################### //# Texture //####################################################################################### private static void ReadTexture(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; W3DMesh.Texture tex = new W3DMesh.Texture(); switch (Chunktype) { case 50: texName = ReadString(br); tex.type = W3DMesh.textureType.standard; break; case 51: tex.attributes = ReadShort(br); tex.animType = ReadShort(br); tex.frameCount = ReadLong(br); tex.frameRate = ReadFloat(br); tex.type = W3DMesh.textureType.animated; break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTexture"); br.ReadBytes((int)Chunksize); break; } mesh.textures.Add(texName, tex); } } private static void ReadTextureArray(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 49: ReadTexture(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTextureArray"); br.ReadBytes((int)Chunksize); break; } } } //####################################################################################### //# Material //####################################################################################### private static void ReadMeshTextureCoordArray(BinaryReader br, uint ChunkEnd) { List<Vector2> txCoords = new List<Vector2>(); while (br.BaseStream.Position < ChunkEnd) { txCoords.Add(new Vector2(ReadFloat(br), ReadFloat(br))); } mesh.texCoords.Add(txCoords.ToArray<Vector2>()); } private static void ReadMeshTextureStage(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 73: //texture ids ReadLongArray(br, subChunkEnd); break; case 74: ReadMeshTextureCoordArray(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshTextureStage"); br.ReadBytes((int)Chunksize); break; } } } private static void ReadMeshMaterialPass(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 57: //vertex material ids ReadLongArray(br, subChunkEnd); break; case 58: //shader ids ReadLongArray(br, subChunkEnd); break; case 59: //vertex colors //do nothing with them br.ReadBytes((int)Chunksize); break; case 63: //unknown chunk //size seems to be always 4 br.ReadBytes((int)Chunksize); break; case 72: ReadMeshTextureStage(br, subChunkEnd); break; case 74: ReadMeshTextureCoordArray(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterialPass"); br.ReadBytes((int)Chunksize); break; } } } private static void ReadMaterial(BinaryReader br, uint ChunkEnd) { W3DMesh.Material mat = new W3DMesh.Material(); while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 44: matName = ReadString(br); break; case 45: mat.vmAttributes = ReadLong(br); mat.ambient = ReadRGBA(br); mat.diffuse = ReadRGBA(br); mat.specular = ReadRGBA(br); mat.emissive = ReadRGBA(br); mat.shininess = ReadFloat(br); mat.opacity = ReadFloat(br); mat.translucency = ReadFloat(br); break; case 46: mat.vmArgs0 = ReadString(br); break; case 47: mat.vmArgs1 = ReadString(br); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterial"); br.ReadBytes((int)Chunksize); break; } } mesh.materials.Add(matName, mat); } private static void ReadMeshMaterialArray(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 43: ReadMaterial(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshMaterialArray"); br.ReadBytes((int)Chunksize); break; } } } //####################################################################################### //# Vertices //####################################################################################### private static Vector3[] ReadMeshVerticesArray(BinaryReader br, uint ChunkEnd) { List<Vector3> vecs = new List<Vector3>(); while (br.BaseStream.Position < ChunkEnd) { vecs.Add(ReadVector(br)); } return vecs.ToArray<Vector3>(); } private static void ReadMeshVertexInfluences(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint boneIdx = ReadShort(br); uint xtraIdx = ReadShort(br); uint boneInf = ReadShort(br)/100; uint xtraInf = ReadShort(br)/100; } } //####################################################################################### //# Faces //####################################################################################### private static void ReadMeshFaceArray(BinaryReader br, uint ChunkEnd) { List<uint> vertIds = new List<uint>(); while (br.BaseStream.Position < ChunkEnd) { vertIds.Add(ReadLong(br)); vertIds.Add(ReadLong(br)); vertIds.Add(ReadLong(br)); uint attrs = ReadLong(br); Vector3 normal = ReadVector(br); float distance = ReadFloat(br); } mesh.vertIDs = vertIds.ToArray<uint>(); } //####################################################################################### //# Shader //####################################################################################### private static void ReadMeshShaderArray(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { W3DMesh.Shader shader = new W3DMesh.Shader(); shader.depthCompare = ReadByte(br); shader.depthMask = ReadByte(br); shader.colorMask = ReadByte(br); shader.destBlend = ReadByte(br); shader.fogFunc = ReadByte(br); shader.priGradient = ReadByte(br); shader.secGradient = ReadByte(br); shader.srcBlend = ReadByte(br); shader.texturing = ReadByte(br); shader.detailColorFunc = ReadByte(br); shader.detailAlphaFunc = ReadByte(br); shader.shaderPreset = ReadByte(br); shader.alphaTest = ReadByte(br); shader.postDetailColorFunc = ReadByte(br); shader.postDetailAlphaFunc = ReadByte(br); byte pad = ReadByte(br); mesh.shaders.Add(shader); } } //####################################################################################### //# Bump Maps //####################################################################################### private static void ReadNormalMapHeader(BinaryReader br) { byte number = ReadByte(br); string typeName = ReadLongFixedString(br); long reserved = ReadLong(br); } private static void ReadNormalMapEntryStruct(BinaryReader br, uint ChunkEnd, W3DMesh.Texture tex) { long type = ReadLong(br); //1 texture, 2 bumpScale/ specularExponent, 5 color, 7 alphaTest long size = ReadLong(br); string name = ReadString(br); switch (name) { case "DiffuseTexture": long unknown = ReadLong(br); texName = ReadString(br); break; case "NormalMap": long unknown_nrm = ReadLong(br); tex.normalMap = ReadString(br); break; case "BumpScale": tex.bumpScale = ReadFloat(br); break; case "AmbientColor": tex.ambientColor = ReadRGBA(br); break; case "DiffuseColor": tex.diffuseColor = ReadRGBA(br); break; case "SpecularColor": tex.specularColor = ReadRGBA(br); break; case "SpecularExponent": tex.specularExponent = ReadFloat(br); break; case "AlphaTestEnable": tex.alphaTestEnable = ReadByte(br); break; default: //Console.WriteLine("##W3D: unknown entryStruct: " + name + " in MeshNormalMapEntryStruct (size: " + size + ")"); while (br.BaseStream.Position < ChunkEnd) ReadByte(br); break; } } private static void ReadNormalMap(BinaryReader br, uint ChunkEnd) { W3DMesh.Texture tex = new W3DMesh.Texture(); tex.type = W3DMesh.textureType.bumpMapped; while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 82: ReadNormalMapHeader(br); break; case 83: ReadNormalMapEntryStruct(br, subChunkEnd, tex); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshNormalMap"); br.ReadBytes((int)Chunksize); break; } } mesh.textures.Add(texName, tex); } private static void ReadBumpMapArray(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 81: ReadNormalMap(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshBumpMapArray"); br.ReadBytes((int)Chunksize); break; } } } //####################################################################################### //# AABTree (Axis-aligned-bounding-box) //####################################################################################### private static void ReadAABTreeHeader(BinaryReader br, uint ChunkEnd) { long nodeCount = ReadLong(br); long polyCount = ReadLong(br); //padding of the header while (br.BaseStream.Position < ChunkEnd) { br.ReadBytes(4); } } private static void ReadAABTreePolyIndices(BinaryReader br, uint ChunkEnd) { List<long> polyIndices = new List<long>(); while (br.BaseStream.Position < ChunkEnd) { polyIndices.Add(ReadLong(br)); } } private static void ReadAABTreeNodes(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { Vector3 min = ReadVector(br); Vector3 max = ReadVector(br); long frontOrPoly0 = ReadLong(br); long backOrPoly = ReadLong(br); // if within these, check their children // etc bis du irgendwann angekommen bist wos nur noch poly eintraege gibt dann hast du nen index und nen count parameter der dir sagt wo die polys die von dieser bounding box umschlossen sind liegen und wie viele es sind // die gehst du dann alle durch wo du halt einfach nen test machst ob deine position xyz in dem poly liegt oder ausserhalb } } private static void ReadAABTree(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 145: ReadAABTreeHeader(br, subChunkEnd); break; case 146: ReadAABTreePolyIndices(br, subChunkEnd); break; case 147: ReadAABTreeNodes(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in MeshAABTree"); br.ReadBytes((int)Chunksize); break; } } } //###################################################################################### //# mesh //###################################################################################### private static void ReadMeshHeader(BinaryReader br) { Version version = GetVersion(ReadLong(br)); uint attrs = ReadLong(br); string meshName = ReadFixedString(br); string containerName = ReadFixedString(br); uint faceCount = ReadLong(br); uint vertCount = ReadLong(br); uint matlCount = ReadLong(br); uint damageStageCount = ReadLong(br); uint sortLevel = ReadLong(br); uint prelitVersion = ReadLong(br); uint futureCount = ReadLong(br); uint vertChannelCount = ReadLong(br); uint faceChannelCount = ReadLong(br); Vector3 minCorner = ReadVector(br); Vector3 maxCorner = ReadVector(br); Vector3 sphCenter = ReadVector(br); float sphRadius = ReadFloat(br); mesh = new W3DMesh(faceCount); modelName = containerName; } private static void ReadMesh(BinaryReader br, uint ChunkEnd) { while (br.BaseStream.Position < ChunkEnd) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint subChunkEnd = (uint)br.BaseStream.Position + Chunksize; switch (Chunktype) { case 2: //mesh vertices mesh.vertices = ReadMeshVerticesArray(br, subChunkEnd); break; case 3072: //mesh vertices copy //unused br.ReadBytes((int)Chunksize); break; case 3: //mesh normals ReadMeshVerticesArray(br, subChunkEnd); break; case 3073: //mesh normals copy //unused br.ReadBytes((int)Chunksize); break; case 12: //mesh user text -> contains sometimes shader settings? //unused br.ReadBytes((int)Chunksize); break; case 14: //mesh vertices infs ReadMeshVertexInfluences(br, subChunkEnd); break; case 31: //mesh header ReadMeshHeader(br); break; case 32: //mesh faces ReadMeshFaceArray(br, subChunkEnd); break; case 34: //mesh shade indices ReadLongArray(br, subChunkEnd); break; case 40: //mesh material set info //unused br.ReadBytes((int)Chunksize); break; case 41: //mesh shader array ReadMeshShaderArray(br, subChunkEnd); break; case 42: //mesh material array ReadMeshMaterialArray(br, subChunkEnd); break; case 48: //mesh texture array ReadTextureArray(br, subChunkEnd); break; case 56: //mesh material pass ReadMeshMaterialPass(br, subChunkEnd); break; case 80: //mesh bump map array ReadBumpMapArray(br, subChunkEnd); break; case 96: //unknown chunk -> specular or diffuse normals?? br.ReadBytes((int)Chunksize); break; case 97: //unknown chunk -> specular or diffuse normals?? br.ReadBytes((int)Chunksize); break; case 144: //mesh aabtree ReadAABTree(br, subChunkEnd); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in Mesh"); br.ReadBytes((int)Chunksize); break; } } model.meshes.Add(mesh); } //###################################################################################### //# main import //###################################################################################### public static void Load(Stream s) { BinaryReader br = new BinaryReader(s); long filesize = s.Length; while (s.Position < filesize) { uint Chunktype = ReadLong(br); uint Chunksize = getChunkSize(ReadLong(br)); uint ChunkEnd = (uint)s.Position + Chunksize; switch (Chunktype) { case 0: //mesh //if the w3d file contains mesh data create a new model object if (model == null) { model = new Model(); Model.AddModel(modelName, model); } ReadMesh(br, ChunkEnd); break; case 256: //Hierarchy ReadHierarchy(br, ChunkEnd); break; case 512: //Animation ReadAnimation(br, ChunkEnd); break; case 640: //CompressedAnimation ReadCompressedAnimation(br, ChunkEnd); break; case 1792: //HLod ReadHLod(br, ChunkEnd); break; case 1856: //Box ReadBox(br); break; default: Console.WriteLine("unknown chunktype: " + Chunktype + " in File"); br.ReadBytes((int)Chunksize); break; } } } } }
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved. // See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Reflection; using Prolix.Collections; using Prolix.Data; using Prolix.Extensions.Collections; using Prolix.Extensions.Reflection; using Prolix.Logic; namespace Prolix.Ioc { /// <summary> /// Dependency resolver specification /// </summary> public abstract class Resolver : IDisposable { #region Fields bool _disposed = false; #endregion #region Public Properties public List<Assembly> Assemblies { get; } = new List<Assembly>(); public IDictionary<Type, Type> Contexts { get; } = new WeakDictionary<Type, Type>(); public IDictionary<Type, Type> Services { get; } = new WeakDictionary<Type, Type>(); public IDictionary<Type, Type> SharedServices { get; } = new WeakDictionary<Type, Type>(); public ICollection<Type> Instances { get; } = new HashSet<Type>(); public ICollection<Type> Factories { get; } = new HashSet<Type>(); public ICollection<Type> Types { get; } = new HashSet<Type>(); public IDictionary<Type, Type> Descriptors { get; } = new WeakDictionary<Type, Type>(); #endregion #region Abstract Methods /// <summary> /// Registers a dependency /// </summary> /// <typeparam name="TC">The implemented type</typeparam> /// <typeparam name="TA">The interface type</typeparam> /// <param name="lifetime">The lifetime type</param> public abstract void Register<TC, TA>(DepedencyLifetime lifetime = DepedencyLifetime.PerDependency) where TC : class, TA where TA : class; /// <summary> /// Registers a dependency /// </summary> /// <typeparam name="T">The implemented type</typeparam> /// <param name="lifetime">The lifetime type</param> public abstract void Register<T>(DepedencyLifetime lifetime = DepedencyLifetime.PerDependency) where T : class; /// <summary> /// Registers an instance /// </summary> /// <typeparam name="T">The interface type</typeparam> /// <param name="instance">The dependency instance</param> /// <param name="lifetime">The lifetime type</param> public abstract void Register<T>(T instance, DepedencyLifetime lifetime = DepedencyLifetime.PerDependency) where T : class; /// <summary> /// Registers a dependency through an initialiser /// </summary> /// <typeparam name="T">The interface type</typeparam> /// <param name="builder">The expression initialiser</param> public abstract void Register<T>(Func<T> builder) where T : class; /// <summary> /// Registers a dependency /// </summary> /// <param name="concreteType">The concrete type</param> /// <param name="abstractType">The interface type</param> /// <param name="lifetime">The lifetime type</param> /// <param name="name">The name for a named dependency</param> public abstract void Register(Type concreteType, Type abstractType, DepedencyLifetime lifetime = DepedencyLifetime.PerDependency, string name = null); /// <summary> /// Register a dependency /// </summary> /// <param name="concreteType">The concrete type</param> /// <param name="lifetime">The lifetime type</param> public abstract void Register(Type concreteType, DepedencyLifetime lifetime = DepedencyLifetime.PerDependency); /// <summary> /// Registers a dependency through an initialiser /// </summary> /// <param name="abstractType">The interface type</param> /// <param name="builder">The expression initialiser</param> public abstract void Register(Type abstractType, Func<object> builder); /// <summary> /// Resolves a dependency /// </summary> /// <typeparam name="T">The interface type</typeparam> /// <returns>The concrete instance</returns> public abstract T Resolve<T>() where T : class; /// <summary> /// Resolves all dependencies /// </summary> /// <typeparam name="T">The interface type</typeparam> /// <returns>The concrete instances</returns> public abstract IEnumerable<T> ResolveAll<T>() where T : class; /// <summary> /// Resolves a dependency /// </summary> /// <param name="abstractType">The interface type</param> /// <returns>The boxed instance</returns> public abstract object Resolve(Type abstractType); /// <summary> /// Resolves all dependencies /// </summary> /// <param name="abstractType">The interface type</param> /// <returns>All boxed instances</returns> public abstract IEnumerable<object> ResolveAll(Type abstractType); /// <summary> /// Check if a type is registered /// </summary> /// <typeparam name="T">The interface type</typeparam> /// <returns>TRUE is the type is registered</returns> public abstract bool IsRegistered<T>() where T : class; /// <summary> /// Check if a type is registered /// </summary> /// <param name="abstractType">The interface type</param> /// <returns>TRUE is the type is registered</returns> public abstract bool IsRegistered(Type abstractType); /// <summary> /// Finishes the dependency registration /// </summary> public abstract void Finish(); /// <summary> /// Releases the internal container /// </summary> public abstract void Release(); /// <summary> /// Creates a child container /// </summary> /// <returns> /// A copy of the parent container /// </returns> public abstract Resolver CreateChild(); #endregion #region Public Methods /// <summary> /// Builds the container /// </summary> /// <summary> /// Initializes the application /// </summary> public virtual void Build() { var coreAssembly = GetType().GetAssembly(); ScanAssembly(coreAssembly); // Contexts RegisterContext(); // Services RegisterServices(); // Shared Services RegisterSharedServices(); // Instances RegisterInstance(); // Factories RegisterFactory(); // Types RegisterTypes(); // Model Descriptors RegisterDescriptors(); // Finish the ioc container Finish(); } /// <summary> /// Searchs an Assembly for registrable Services /// </summary> /// <typeparam name="T">The class inside the Assembly that will be part of the search.</typeparam> public void ScanAssembly<T>() { var assembly = typeof(T).GetAssembly(); ScanAssembly(assembly); } /// <summary> /// Searchs an Assembly for registrable Services /// </summary> /// <param name="assembly">The Assembly that will be part of the search.</param> public void ScanAssembly(Assembly assembly) { if (Assemblies.Contains(assembly)) return; Assemblies.Add(assembly); var contextMappings = assembly.MapTypes<IContext>(); var serviceMappings = assembly.MapTypes<IService>(); var sharedServiceMappings = assembly.MapTypes<ISharedService>(); var instanceTypes = assembly.FindInterfaces<IInstance>(); var factoryTypes = assembly.FindInterfaces<IFactory>(true); var descriptorMappings = assembly.MapGenericTypes<IModelDescriptor>(true); Contexts.AddRange(contextMappings); Services.AddRange(serviceMappings); SharedServices.AddRange(sharedServiceMappings); Instances.AddRange(instanceTypes); Factories.AddRange(factoryTypes); Descriptors.AddRange(descriptorMappings); } /// <summary> /// Searchs an Assembly for a specific Services /// </summary> /// <typeparam name="T">The type that will be registered.</typeparam> public void ScanTypes<T>(Assembly assembly) { var types = assembly.FindInterfaces<T>(); Types.AddRange(types); } #endregion #region Disposing Logic /// <summary> /// Free all resources /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); // Shut FxCop up } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) Release(); _disposed = true; } } #endregion #region Private Methods void RegisterContext() { foreach (var type in Contexts) { Register(type.Key, type.Value, DepedencyLifetime.PerLifetime); // Map the generic IDbContext to make it acessible through all assemblies if (type.Key.ImplementsInterface(typeof(IDbContext))) Register(type.Key, typeof(IDbContext), DepedencyLifetime.PerLifetime); } } void RegisterServices() { foreach (var type in Services) { Register(type.Key, type.Value, DepedencyLifetime.PerDependency); } } void RegisterSharedServices() { foreach (var type in SharedServices) { Register(type.Key, type.Value, DepedencyLifetime.PerDependency, type.Key.Name); } } void RegisterInstance() { foreach (var type in Instances) { Register(type, DepedencyLifetime.PerLifetime); } } void RegisterFactory() { foreach (var type in Factories) { IFactory factory = type.Instantiate<IFactory>(); if (factory != null) { Register(factory.Type, factory.CreateInstance); } } } void RegisterTypes() { foreach (var type in Types) { Register(type, DepedencyLifetime.PerDependency); } } void RegisterDescriptors() { // Original descriptor search is Descriptor/Model (to avoid key collision) var mappings = new WeakDictionary<Type, Type>(); // Creating a Model/Descriptor Weak Dictionary foreach (var map in Descriptors) mappings.Add(map.Value, map.Key); DescriptorManager.Configure(mappings); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts.Definition; using Microsoft.VisualStudio.Services.ReleaseManagement.WebApi.Contracts; using Microsoft.VisualStudio.Services.WebApi; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts { public class JenkinsArtifact : AgentService, IArtifactExtension { public Type ExtensionType => typeof(IArtifactExtension); public AgentArtifactType ArtifactType => AgentArtifactType.Jenkins; private const char Backslash = '\\'; private const char ForwardSlash = '/'; public static int CommitDataVersion = 1; public static string CommitIdKey = "commitId"; public static string CommitDateKey = "date"; public static string AuthorKey = "author"; public static string FullNameKey = "fullName"; public static string CommitMessageKey = "msg"; public static string RepoKindKey = "kind"; public static string RemoteUrlsKey = "remoteUrls"; public static string GitRepoName = "git"; public async Task DownloadAsync( IExecutionContext executionContext, ArtifactDefinition artifactDefinition, string localFolderPath) { ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition)); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath)); var jenkinsDetails = artifactDefinition.Details as JenkinsArtifactDetails; executionContext.Output(StringUtil.Loc("RMGotJenkinsArtifactDetails")); executionContext.Output(StringUtil.Loc("RMJenkinsJobName", jenkinsDetails.JobName)); executionContext.Output(StringUtil.Loc("RMJenkinsBuildId", jenkinsDetails.BuildId)); IGenericHttpClient client = HostContext.GetService<IGenericHttpClient>(); if (!IsValidBuild(client, jenkinsDetails)) { throw new ArtifactDownloadException(StringUtil.Loc("RMJenkinsInvalidBuild", jenkinsDetails.BuildId)); } Stream downloadedStream = null; string downloadArtifactsUrl = string.Format( CultureInfo.InvariantCulture, "{0}/job/{1}/{2}/artifact/{3}/*zip*/", jenkinsDetails.Url, jenkinsDetails.JobName, jenkinsDetails.BuildId, jenkinsDetails.RelativePath); executionContext.Output(StringUtil.Loc("RMPrepareToGetFromJenkinsServer")); HttpResponseMessage response = client.GetAsync(downloadArtifactsUrl, jenkinsDetails.AccountName, jenkinsDetails.AccountPassword, jenkinsDetails.AcceptUntrustedCertificates).Result; if (response.IsSuccessStatusCode) { downloadedStream = response.Content.ReadAsStreamAsync().Result; } else if (response.StatusCode == HttpStatusCode.NotFound) { executionContext.Warning(StringUtil.Loc("RMJenkinsNoArtifactsFound", jenkinsDetails.BuildId)); return; } else { throw new ArtifactDownloadException(StringUtil.Loc("RMDownloadArtifactUnexpectedError")); } var parentFolder = GetParentFolderName(jenkinsDetails.RelativePath); Trace.Info($"Found parentFolder {parentFolder} for relative path {jenkinsDetails.RelativePath}"); executionContext.Output(StringUtil.Loc("RMDownloadingJenkinsArtifacts")); var zipStreamDownloader = HostContext.GetService<IZipStreamDownloader>(); await zipStreamDownloader.DownloadFromStream( executionContext, downloadedStream, string.IsNullOrEmpty(parentFolder) ? "archive" : string.Empty, parentFolder, localFolderPath); } public async Task DownloadCommitsAsync(IExecutionContext context, ArtifactDefinition artifactDefinition, string commitsWorkFolder) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition)); Trace.Entering(); var jenkinsDetails = artifactDefinition.Details as JenkinsArtifactDetails; int startJobId = 0, endJobId = 0; if (!string.IsNullOrEmpty(jenkinsDetails.EndCommitArtifactVersion)) { if (int.TryParse(jenkinsDetails.EndCommitArtifactVersion, out endJobId)) { context.Output(StringUtil.Loc("RMDownloadingCommits")); if (int.TryParse(jenkinsDetails.StartCommitArtifactVersion, out startJobId)) { if (startJobId < endJobId) { context.Output(StringUtil.Loc("DownloadingJenkinsCommitsBetween", startJobId, endJobId)); } else if (startJobId > endJobId) { context.Output(StringUtil.Loc("JenkinsRollbackDeployment", startJobId, endJobId)); // swap the job IDs to fetch the roll back commits int swap = startJobId; startJobId = endJobId; endJobId = swap; } else if (startJobId == endJobId) { context.Output(StringUtil.Loc("JenkinsNoCommitsToFetch")); return; } } else { context.Debug(StringUtil.Loc("JenkinsDownloadingChangeFromCurrentBuild")); } try { IEnumerable<Change> changes = await DownloadCommits(context, jenkinsDetails, startJobId, endJobId); if (changes.Any()) { string commitsFileName = GetCommitsFileName(jenkinsDetails.Alias); string commitsFilePath = Path.Combine(commitsWorkFolder, commitsFileName); context.Debug($"Commits will be written to {commitsFilePath}"); WriteCommitsToFile(context, changes, commitsFilePath); context.Debug($"Commits written to {commitsFilePath}"); context.QueueAttachFile(CoreAttachmentType.FileAttachment, commitsFileName, commitsFilePath); } } catch (Exception ex) { context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("DownloadingJenkinsCommitsFailedWithException", jenkinsDetails.Alias, ex.ToString()) }); return; } } else { context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("JenkinsCommitsInvalidEndJobId", jenkinsDetails.EndCommitArtifactVersion, jenkinsDetails.Alias) }); return; } } else { context.Debug("No commit details found in the agent artifact. Not downloading the commits"); } } private string GetCommitsFileName(string artifactAlias) { return StringUtil.Format("commits_{0}_v{1}.json", artifactAlias, CommitDataVersion); } private void WriteCommitsToFile(IExecutionContext context, IEnumerable<Change> commits, string commitsFilePath) { IOUtil.DeleteFile(commitsFilePath); if (commits.Any()) { using(StreamWriter sw = File.CreateText(commitsFilePath)) using(JsonTextWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; jw.WriteStartArray(); foreach (Change commit in commits) { JObject.FromObject(commit).WriteTo(jw); } jw.WriteEnd(); } } } private Change ConvertCommitToChange(IExecutionContext context, JToken token, bool isGitRepo, string rootUrl) { Trace.Entering(); // Use mustache parser? Change change = new Change(); var resultDictionary = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(token.ToString()); if (resultDictionary.ContainsKey(CommitIdKey)) { change.Id = resultDictionary[CommitIdKey].ToString(); } if (resultDictionary.ContainsKey(CommitMessageKey)) { change.Message = resultDictionary[CommitMessageKey].ToString(); } if (resultDictionary.ContainsKey(AuthorKey)) { string authorDetail = resultDictionary[AuthorKey].ToString(); var author = JsonConvert.DeserializeObject<Dictionary<string, string>>(authorDetail); change.Author = new IdentityRef { DisplayName = author[FullNameKey] }; } if (resultDictionary.ContainsKey(CommitDateKey)) { DateTime value; if (DateTime.TryParse(resultDictionary[CommitDateKey].ToString(), out value)) { change.Timestamp = value; } } if (isGitRepo && !string.IsNullOrEmpty(rootUrl)) { change.DisplayUri = new Uri(StringUtil.Format("{0}/commit/{1}", rootUrl, change.Id)); } context.Debug(StringUtil.Format("Found commit {0}", change.Id)); return change; } private Tuple<int, int> GetCommitJobIdIndex(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int startJobId, int endJobId) { Trace.Entering(); string url = StringUtil.Format("{0}/job/{1}/api/json?tree=allBuilds[number]", artifactDetails.Url, artifactDetails.JobName); int startIndex = -1, endIndex = -1, index = 0; var listOfBuildResult = DownloadCommitsJsonContent(context, url, artifactDetails, "$.allBuilds[*].number").Result; foreach (JToken token in listOfBuildResult) { long value = 0; if (long.TryParse((string)token, out value)) { if (value == startJobId) { startIndex = index; } if (value == endJobId) { endIndex = index; } if (startIndex > 0 && endIndex > 0) { break; } index++; } } context.Debug(StringUtil.Format("Found startIndex {0} and endIndex {1}", startIndex, endIndex)); if (startIndex < 0 || endIndex < 0) { throw new CommitsDownloadException(StringUtil.Loc("JenkinsBuildDoesNotExistsForCommits", startJobId, endJobId, startIndex, endIndex)); } return Tuple.Create<int, int>(startIndex, endIndex); } private async Task<IEnumerable<Change>> DownloadCommits(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int jobId) { context.Output(StringUtil.Format("Getting changeSet associated with build {0} ", jobId)); string commitsUrl = StringUtil.Format("{0}/job/{1}/{2}/api/json?tree=number,result,changeSet[items[commitId,date,msg,author[fullName]]]", artifactDetails.Url, artifactDetails.JobName, jobId); var commitsResult = await DownloadCommitsJsonContent(context, commitsUrl, artifactDetails, "$.changeSet.items[*]"); string rootUrl; bool isGitRepo = IsGitRepo(context, artifactDetails, jobId, out rootUrl); return commitsResult.Select(x => ConvertCommitToChange(context, x, isGitRepo, rootUrl)); } private async Task<IEnumerable<Change>> DownloadCommits(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int startJobId, int endJobId) { Trace.Entering(); if (startJobId == 0) { context.Debug($"StartJobId does not exist, downloading changeSet from build {endJobId}"); return await DownloadCommits(context, artifactDetails, endJobId); } //#1. Figure out the index of build numbers Tuple<int, int> result = GetCommitJobIdIndex(context, artifactDetails, startJobId, endJobId); int startIndex = result.Item1; int endIndex = result.Item2; //#2. Download the commits using range string buildParameter = (startIndex >= 100 || endIndex >= 100) ? "allBuilds" : "builds"; // jenkins by default will return only 100 top builds. Have to use "allBuilds" if we are dealing with build which are older than 100 builds string commitsUrl = StringUtil.Format("{0}/job/{1}/api/json?tree={2}[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{{3},{4}}}", artifactDetails.Url, artifactDetails.JobName, buildParameter, endIndex, startIndex); var changeSetResult = await DownloadCommitsJsonContent(context, commitsUrl, artifactDetails, StringUtil.Format("$.{0}[*].changeSet.items[*]", buildParameter)); string rootUrl; bool isGitRepo = IsGitRepo(context, artifactDetails, endJobId, out rootUrl); return changeSetResult.Select(x => ConvertCommitToChange(context, x, isGitRepo, rootUrl)); } private async Task<string> DownloadCommitsJsonContent(IExecutionContext executionContext, string url, JenkinsArtifactDetails artifactDetails) { Trace.Entering(); executionContext.Debug($"Querying Jenkins server with the api {url}"); string result = await HostContext.GetService<IGenericHttpClient>() .GetStringAsync(url, artifactDetails.AccountName, artifactDetails.AccountPassword, artifactDetails.AcceptUntrustedCertificates); if (!string.IsNullOrEmpty(result)) { executionContext.Debug($"Found result from Jenkins server: {result}"); } return result; } private async Task<IEnumerable<JToken>> DownloadCommitsJsonContent(IExecutionContext executionContext, string url, JenkinsArtifactDetails artifactDetails, string jsonPath) { Trace.Entering(); string result = await DownloadCommitsJsonContent(executionContext, url, artifactDetails); if (!string.IsNullOrEmpty(result)) { executionContext.Debug($"result will be filtered with {jsonPath}"); return ParseToken(result, jsonPath); } return new List<JToken>(); } private bool IsGitRepo(IExecutionContext executionContext, JenkinsArtifactDetails artifactDetails, int jobId, out string rootUrl) { bool isGitRepo = false; rootUrl = string.Empty; executionContext.Debug("Checking if Jenkins job uses git scm"); string repoUrl = StringUtil.Format("{0}/job/{1}/{2}/api/json?tree=actions[remoteUrls],changeSet[kind]", artifactDetails.Url, artifactDetails.JobName, jobId); var repoResult = DownloadCommitsJsonContent(executionContext, repoUrl, artifactDetails).Result; if (repoResult != null) { executionContext.Debug($"repo query result from Jenkins api {repoResult.ToString()}"); var repoKindResult = ParseToken(repoResult.ToString(), "$.changeSet.kind"); if (repoKindResult != null && repoKindResult.Any()) { string repoKind = repoKindResult.First().ToString(); executionContext.Debug($"Parsed repo result {repoKind}"); if (!string.IsNullOrEmpty(repoKind) && repoKind.Equals(GitRepoName, StringComparison.OrdinalIgnoreCase)) { executionContext.Debug("Its a git repo, checking if it has root url"); var rootUrlResult = ParseToken(repoResult.ToString(), "$.actions[?(@.remoteUrls)]"); if (rootUrlResult != null && rootUrlResult.Any()) { var resultDictionary = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(rootUrlResult.First().ToString()); if (resultDictionary.ContainsKey(RemoteUrlsKey) && resultDictionary[RemoteUrlsKey].Any()) { rootUrl = resultDictionary[RemoteUrlsKey].First().ToString(); isGitRepo = true; executionContext.Debug($"Found the git repo root url {rootUrl}"); } } } } } return isGitRepo; } private IEnumerable<JToken> ParseToken(string jsonResult, string jsonPath) { JObject parsedJson = JObject.Parse(jsonResult); return parsedJson.SelectTokens(jsonPath); } public IArtifactDetails GetArtifactDetails(IExecutionContext context, AgentArtifactDefinition agentArtifactDefinition) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(agentArtifactDefinition, nameof(agentArtifactDefinition)); Trace.Entering(); var artifactDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(agentArtifactDefinition.Details); ServiceEndpoint jenkinsEndpoint = context.Endpoints.FirstOrDefault(e => string.Equals(e.Name, artifactDetails["ConnectionName"], StringComparison.OrdinalIgnoreCase)); if (jenkinsEndpoint == null) { throw new InvalidOperationException(StringUtil.Loc("RMJenkinsEndpointNotFound", agentArtifactDefinition.Name)); } string relativePath; var jobName = string.Empty; var allFieldsPresents = artifactDetails.TryGetValue("RelativePath", out relativePath) && artifactDetails.TryGetValue("JobName", out jobName); bool acceptUntrusted = jenkinsEndpoint.Data != null && jenkinsEndpoint.Data.ContainsKey("acceptUntrustedCerts") && StringUtil.ConvertToBoolean(jenkinsEndpoint.Data["acceptUntrustedCerts"]); string startCommitArtifactVersion = string.Empty; string endCommitArtifactVersion = string.Empty; artifactDetails.TryGetValue("StartCommitArtifactVersion", out startCommitArtifactVersion); artifactDetails.TryGetValue("EndCommitArtifactVersion", out endCommitArtifactVersion); if (allFieldsPresents) { return new JenkinsArtifactDetails { RelativePath = relativePath, AccountName = jenkinsEndpoint.Authorization.Parameters[EndpointAuthorizationParameters.Username], AccountPassword = jenkinsEndpoint.Authorization.Parameters[EndpointAuthorizationParameters.Password], BuildId = Convert.ToInt32(agentArtifactDefinition.Version, CultureInfo.InvariantCulture), JobName = jobName, Url = jenkinsEndpoint.Url, AcceptUntrustedCertificates = acceptUntrusted, StartCommitArtifactVersion = startCommitArtifactVersion, EndCommitArtifactVersion = endCommitArtifactVersion, Alias = agentArtifactDefinition.Alias }; } else { throw new InvalidOperationException(StringUtil.Loc("RMArtifactDetailsIncomplete")); } } private bool IsValidBuild(IGenericHttpClient client, JenkinsArtifactDetails jenkinsDetails) { var buildUrl = string.Format( CultureInfo.InvariantCulture, "{0}/job/{1}/{2}/", jenkinsDetails.Url, jenkinsDetails.JobName, jenkinsDetails.BuildId); HttpResponseMessage response = client.GetAsync(buildUrl, jenkinsDetails.AccountName, jenkinsDetails.AccountPassword, jenkinsDetails.AcceptUntrustedCertificates).Result; return response.IsSuccessStatusCode; } private static string GetParentFolderName(string relativePath) { // Sometime the Jenkins artifact relative path would be simply / indicating read from root. This will retrun empty string at such scenarios. return relativePath.TrimEnd(Backslash).TrimEnd(ForwardSlash).Replace(Backslash, ForwardSlash).Split(ForwardSlash).Last(); } } }
// 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 Xunit; namespace System.ComponentModel.DataAnnotations.Tests { public class CustomValidationAttributeTests : ValidationAttributeTestBase { private static readonly ValidationContext s_testValidationContext = new ValidationContext(new object()); protected override IEnumerable<TestCase> ValidValues() { yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), "AnyString"); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgs)), new TestClass("AnyString")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped)), "AnyString"); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), new TestClass("AnyString")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), new TestStruct() { Value = "Valid Value" }); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), new TestStruct() { Value = "Valid Value" }); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), new DerivedTestClass("AnyString")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), false); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123456L); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123.456F); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), 123.456D); } protected override IEnumerable<TestCase> InvalidValues() { yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)), new TestClass("AnyString")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgs)), "AnyString"); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped)), new TestClass("AnyString")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped)), "AnyString"); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgGenericStruct)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgNullable)), new TestStruct()); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodTwoArgsWithFirstNullable)), new TestStruct() { Value = "Invalid Value" }); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), new TestClass("NotInt")); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodIntegerArg)), new DateTime(2014, 3, 19)); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgDateTime)), null); yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgDateTime)), "abcdef"); // Implements IConvertible (throws NotSupportedException - is caught) yield return new TestCase(GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgInt)), new IConvertibleImplementor() { IntThrow = new NotSupportedException() }); } protected override bool RespectsErrorMessage => false; private static CustomValidationAttribute GetAttribute(string name) => new CustomValidationAttribute(typeof(CustomValidator), name); [Theory] [InlineData(typeof(CustomValidator), "SomeMethod")] [InlineData(null, null)] [InlineData(typeof(string), "")] [InlineData(typeof(int), " \t\r\n")] public static void Ctor_Type_String(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Equal(validatorType, attribute.ValidatorType); Assert.Equal(method, attribute.Method); } [Theory] [InlineData(typeof(CustomValidator), nameof(CustomValidator.ValidationMethodDerivedReturnTypeReturnsSomeError))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full .NET Frameworks had a restriction, that prevented to use custom ValidationResult. .NET Core allows to return class derived from ValidatioResult")] public static void Ctor_Type_String_IgnoreNetFramework(Type validatorType, string method) { Ctor_Type_String(validatorType, method); } [Fact] public void FormatErrorMessage_NotPerformedValidation_ContainsName() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)); string errorMessage = attribute.FormatErrorMessage("name"); Assert.Contains("name", errorMessage); Assert.Equal(errorMessage, attribute.FormatErrorMessage("name")); } [Fact] public void FormatErrorMessage_PerformedValidation_DoesNotContainName() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArg)); Assert.False(attribute.IsValid(new TestClass("AnyString"))); string errorMessage = attribute.FormatErrorMessage("name"); Assert.DoesNotContain("name", errorMessage); Assert.Equal(errorMessage, attribute.FormatErrorMessage("name")); } [Theory] [InlineData(nameof(CustomValidator.CorrectValidationMethodOneArg), false)] [InlineData(nameof(CustomValidator.CorrectValidationMethodOneArgStronglyTyped), false)] [InlineData(nameof(CustomValidator.CorrectValidationMethodTwoArgs), true)] [InlineData(nameof(CustomValidator.CorrectValidationMethodTwoArgsStronglyTyped), true)] public static void RequiresValidationContext_Get_ReturnsExpected(string method, bool expected) { CustomValidationAttribute attribute = GetAttribute(method); // The full .NET Framework has a bug where CustomValidationAttribute doesn't // validate the context. See https://github.com/dotnet/corefx/issues/18360. if (PlatformDetection.IsFullFramework) { Assert.False(attribute.RequiresValidationContext); } else { Assert.Equal(expected, attribute.RequiresValidationContext); } } public static IEnumerable<object[]> BadlyFormed_TestData() { yield return new object[] { null, "Does not matter" }; yield return new object[] { typeof(NonPublicCustomValidator), "Does not matter" }; yield return new object[] { typeof(CustomValidator), null }; yield return new object[] { typeof(CustomValidator), "" }; yield return new object[] { typeof(CustomValidator), "NonExistentMethod" }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.NonPublicValidationMethod) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.NonStaticValidationMethod) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodDoesNotReturnValidationResult) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodWithNoArgs) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodWithByRefArg) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodTwoArgsButSecondIsNotValidationContext) }; yield return new object[] { typeof(CustomValidator), nameof(CustomValidator.ValidationMethodThreeArgs) }; } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core fixes a bug where CustomValidationAttribute doesn't validate the context. See https://github.com/dotnet/corefx/issues/18360")] [MemberData(nameof(BadlyFormed_TestData))] public static void RequiresValidationContext_BadlyFormed_NetCore_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.RequiresValidationContext); } [Theory] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The full .NET Framework has a bug where CustomValidationAttribute doesn't validate the context. See https://github.com/dotnet/corefx/issues/18360")] [MemberData(nameof(BadlyFormed_TestData))] public static void RequiresValidationContext_BadlyFormed_NetFx_DoesNotThrow(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.False(attribute.RequiresValidationContext); } [Theory] [MemberData(nameof(BadlyFormed_TestData))] public static void Validate_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.Validate("Does not matter", s_testValidationContext)); } [Theory] [MemberData(nameof(BadlyFormed_TestData))] public static void FormatErrorMessage_BadlyFormed_ThrowsInvalidOperationException(Type validatorType, string method) { CustomValidationAttribute attribute = new CustomValidationAttribute(validatorType, method); Assert.Throws<InvalidOperationException>(() => attribute.FormatErrorMessage("name")); } [Fact] public static void Validate_IConvertibleThrowsCustomException_IsNotCaught() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.CorrectValidationMethodOneArgInt)); Assert.Throws<ArithmeticException>(() => attribute.Validate(new IConvertibleImplementor() { IntThrow = new ArithmeticException() }, s_testValidationContext)); } [Fact] public static void Validate_MethodThrowsCustomException_IsNotCaught() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.ValidationMethodThrowsException)); AssertExtensions.Throws<ArgumentException>(null, () => attribute.Validate(new IConvertibleImplementor(), s_testValidationContext)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full .NET Frameworks had a restriction, that prevented to use custom ValidationResult. .NET Core allows to return class derived from ValidatioResult")] public static void GetValidationResult_MethodReturnDerivedValidationResult_ReturnsExpected() { CustomValidationAttribute attribute = GetAttribute(nameof(CustomValidator.ValidationMethodDerivedReturnTypeReturnsSomeError)); ValidationResult validationResult = attribute.GetValidationResult(new object(), s_testValidationContext); Assert.Equal(DerivedValidationResult.SomeError, validationResult); } internal class NonPublicCustomValidator { public static ValidationResult ValidationMethodOneArg(object o) => ValidationResult.Success; } public class CustomValidator { internal static ValidationResult NonPublicValidationMethod(object o) => ValidationResult.Success; public ValidationResult NonStaticValidationMethod(object o) => ValidationResult.Success; public static string ValidationMethodDoesNotReturnValidationResult(object o) => null; public static ValidationResult ValidationMethodWithNoArgs() => ValidationResult.Success; public static ValidationResult ValidationMethodWithByRefArg(ref object o) => ValidationResult.Success; public static ValidationResult ValidationMethodTwoArgsButSecondIsNotValidationContext(object o, object someOtherObject) { return ValidationResult.Success; } public static ValidationResult ValidationMethodThrowsException(object o) { throw new ArgumentException(); } public static ValidationResult ValidationMethodThreeArgs(object o, ValidationContext context, object someOtherObject) { return ValidationResult.Success; } public static DerivedValidationResult ValidationMethodDerivedReturnTypeReturnsSomeError(object o) => DerivedValidationResult.SomeError; public static ValidationResult CorrectValidationMethodOneArg(object o) { if (o is string) { return ValidationResult.Success; } return new ValidationResult("Validation failed - not a string"); } public static ValidationResult CorrectValidationMethodOneArgStronglyTyped(string s) => ValidationResult.Success; public static ValidationResult CorrectValidationMethodTwoArgs(object o, ValidationContext context) { if (o is TestClass) { return ValidationResult.Success; } return new ValidationResult("Validation failed - not a TestClass"); } public static ValidationResult CorrectValidationMethodTwoArgsStronglyTyped(TestClass tc, ValidationContext context) { return ValidationResult.Success; } public static ValidationResult CorrectValidationMethodIntegerArg(int i) => ValidationResult.Success; public static ValidationResult CorrectValidationMethodOneArgNullable(TestStruct? testStruct) { if (testStruct == null) { return ValidationResult.Success; } var ts = (TestStruct)testStruct; if ("Valid Value".Equals(ts.Value)) { return ValidationResult.Success; } return new ValidationResult("Validation failed - neither null nor Value=\"Valid Value\""); } public static ValidationResult CorrectValidationMethodOneArgGenericStruct(GenericStruct<int> testStruct) { return ValidationResult.Success; } public static ValidationResult CorrectValidationMethodTwoArgsWithFirstNullable(TestStruct? testStruct, ValidationContext context) { if (testStruct == null) { return ValidationResult.Success; } var ts = (TestStruct)testStruct; if ("Valid Value".Equals(ts.Value)) { return ValidationResult.Success; } return new ValidationResult("Validation failed - neither null nor Value=\"Valid Value\""); } public static ValidationResult CorrectValidationMethodOneArgDateTime(DateTime dateTime) => ValidationResult.Success; public static ValidationResult CorrectValidationMethodOneArgInt(int i) => ValidationResult.Success; } public class TestClass { public TestClass(string message) { } } public class DerivedTestClass : TestClass { public DerivedTestClass(string message) : base(message) { } } public struct TestStruct { public string Value { get; set; } } public struct GenericStruct<T> { } public class DerivedValidationResult : ValidationResult { public DerivedValidationResult(string errorMessage): base(errorMessage) { } public static readonly DerivedValidationResult SomeError = new DerivedValidationResult("Some Error") { AdditionalData = "Additional Data" }; public string AdditionalData { get; set; } } [Fact] public static void AllowMultiple() { Assert.Equal(3, TypeDescriptor.GetAttributes(typeof(AllowMultipleClass)).Count); } [CustomValidation(typeof(AllowMultipleClass), nameof(AllowMultipleClass.Method1))] [CustomValidation(typeof(AllowMultipleClass), nameof(AllowMultipleClass.Method2))] [CustomValidation(typeof(AllowMultipleClass), nameof(AllowMultipleClass.Method3))] [CustomValidation(typeof(AllowMultipleClass), nameof(AllowMultipleClass.Method3))] public class AllowMultipleClass { public void Method1() { } public void Method2() { } public void Method3() { } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class ResourceGroupOperationsExtensions { /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGroupCreateOrUpdateResult CreateOrUpdate(this IResourceGroupOperations operations, ResourceGroupCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).CreateOrUpdateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='parameters'> /// Required. Your documentation here. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGroupCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceGroupOperations operations, ResourceGroupCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(parameters, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IResourceGroupOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).DeleteAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Required. Your documentation here. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IResourceGroupOperations operations, string resourceGroupName) { return operations.DeleteAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGroupGetResult Get(this IResourceGroupOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).GetAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGroupGetResult> GetAsync(this IResourceGroupOperations operations, string resourceGroupName) { return operations.GetAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGroupListResult List(this IResourceGroupOperations operations) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGroupListResult> ListAsync(this IResourceGroupOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGroupListResult ListNext(this IResourceGroupOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='nextLink'> /// Required. Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGroupListResult> ListNextAsync(this IResourceGroupOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. /// </param> /// <returns> /// Your documentation here. /// </returns> public static ResourceGroupListResourcesResult ListResources(this IResourceGroupOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IResourceGroupOperations)s).ListResourcesAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Your documentation here. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IResourceGroupOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<ResourceGroupListResourcesResult> ListResourcesAsync(this IResourceGroupOperations operations, string resourceGroupName) { return operations.ListResourcesAsync(resourceGroupName, CancellationToken.None); } } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Text; using System.Web.UI.WebControls; using Rainbow.Framework; using Rainbow.Framework.Data; using Rainbow.Framework.DataTypes; using Rainbow.Framework.Monitoring; using Rainbow.Framework.Scheduler; using Rainbow.Framework.Settings; using Rainbow.Framework.Web.UI.WebControls; using Label=Rainbow.Framework.Web.UI.WebControls.Label; using Path=System.IO.Path; namespace Rainbow.Content.Web.Modules { /// <summary> /// Rainbow Monitoring Module - Shows website usage stats /// Written by: Paul Yarrow, paul@paulyarrow.com /// </summary> public partial class Monitoring : PortalModuleControl, ISchedulable { protected DataView myDataView; protected string sortField; protected string sortDirection; protected CheckBox CheckBoxIncludeAdmin; protected Label lblMessage; protected SqlCommand sqlComm1; protected SqlDataAdapter sqlDA1; protected string lastReportType; /// <summary> /// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13 /// </summary> public Monitoring() { // modified by Hongwei Shen SettingItemGroup group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; int groupBase = (int) group; SettingItem setSortField = new SettingItem( new ListDataType("ActivityTime;ActivityType;Name;PortalName;TabName;UserHostAddress;UserAgent")); setSortField.Required = true; setSortField.Value = "ActivityTime"; setSortField.Group = group; setSortField.Order = groupBase + 20; //1; _baseSettings.Add("SortField", setSortField); } /// <summary> /// The Page_Load event handler on this User Control is used to /// determine sort field and order, and then databind the required /// monitoring table rows, generating a graph if necessary. /// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13 /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void Monitoring_Load(object sender, EventArgs e) { if (Config.EnableMonitoring) { // Set the variables correctly depending // on whether this is the first page view if (Page.IsPostBack == false) { sortField = Settings["SortField"].ToString(); sortDirection = "ASC"; if (sortField == "ActivityTime") { sortDirection = "DESC"; } ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; txtStartDate.Text = DateTime.Now.AddDays(-6).ToShortDateString(); txtEndDate.Text = DateTime.Now.ToShortDateString(); } else { sortField = (string) ViewState["SortField"]; sortDirection = (string) ViewState["sortDirection"]; } lastReportType = cboReportType.SelectedItem.Value; BindGrid(); MonitoringPanel.Visible = true; ErrorLabel.Visible = false; } else { ErrorLabel.Text = "Monitoring is disabled. Put EnableMonitoring to true in web.config."; MonitoringPanel.Visible = false; ErrorLabel.Visible = true; } } /// <summary> /// The SortTasks event handler sorts the monitoring list (a DataGrid control) /// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13 /// </summary> /// <param name="source">The source.</param> /// <param name="e">The <see cref="T:System.Web.UI.WebControls.DataGridSortCommandEventArgs"/> instance containing the event data.</param> protected void SortTasks(Object source, DataGridSortCommandEventArgs e) { if (sortField == e.SortExpression) { if (sortDirection == "ASC") { sortDirection = "DESC"; } else { sortDirection = "ASC"; } } else { if (e.SortExpression == "DueDate") { sortDirection = "DESC"; } } ViewState["SortField"] = e.SortExpression; ViewState["sortDirection"] = sortDirection; BindGrid(); } /// <summary> /// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13 /// </summary> protected void BindGrid() { if (txtStartDate.Text.Length > 0 && txtEndDate.Text.Length > 0) { // Read in the data regardless //MonitoringDB monitorDB = new MonitoringDB(); DateTime startDate = DateTime.Parse(txtStartDate.Text); DateTime endDate = DateTime.Parse(txtEndDate.Text); bool showChart = true; string chartType = string.Empty; switch (cboReportType.SelectedItem.Value) { case "Detailed Site Log": if (cboReportType.SelectedItem.Value != lastReportType) { sortField = "ActivityTime"; sortDirection = "DESC"; ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; } showChart = false; break; case "Page Popularity": if (cboReportType.SelectedItem.Value != lastReportType) { sortField = "Requests"; sortDirection = "DESC"; ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; } chartType = "pie"; break; case "Most Active Users": if (cboReportType.SelectedItem.Value != lastReportType) { sortField = "Actions"; sortDirection = "DESC"; ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; } chartType = "pie"; break; case "Page Views By Day": if (cboReportType.SelectedItem.Value != lastReportType) { sortField = "[Date]"; sortDirection = "ASC"; ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; } chartType = "bar"; break; case "Page Views By Browser Type": if (cboReportType.SelectedItem.Value != lastReportType) { sortField = "[Views]"; sortDirection = "DESC"; ViewState["SortField"] = sortField; ViewState["sortDirection"] = sortDirection; } chartType = "pie"; break; } DataSet monitorData = Utility.GetMonitoringStats(startDate, endDate, cboReportType.SelectedItem.Value, portalSettings.ActivePage.PageID, CheckBoxIncludeMonitorPage.Checked, CheckBoxIncludeAdminUser.Checked, CheckBoxPageRequests.Checked, CheckBoxLogons.Checked, CheckBoxLogouts.Checked, CheckBoxIncludeMyIPAddress.Checked, portalSettings.PortalID); myDataView = monitorData.Tables[0].DefaultView; myDataView.Sort = sortField + " " + sortDirection; myDataGrid.DataSource = myDataView; myDataGrid.DataBind(); if (monitorData.Tables[0].Rows.Count > 0) { myDataGrid.Visible = true; LabelNoData.Visible = false; } else { myDataGrid.Visible = false; LabelNoData.Visible = true; } if (showChart) { StringBuilder xValues = new StringBuilder(); StringBuilder yValues = new StringBuilder(); foreach (DataRow dr in monitorData.Tables[0].Rows) { xValues.Append(dr[0]); yValues.Append(dr[1]); xValues.Append("|"); yValues.Append("|"); } if (xValues.Length > 0 && yValues.Length > 0) { xValues.Remove(xValues.Length - 1, 1); yValues.Remove(yValues.Length - 1, 1); ChartImage.ImageUrl = HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Monitoring/ChartGenerator.aspx?" + "xValues=" + xValues.ToString() + "&yValues=" + yValues.ToString() + "&ChartType=" + chartType); ChartImage.Visible = true; } else { ChartImage.Visible = false; } } else { ChartImage.Visible = false; } } } /// <summary> /// Initial Revision by Paul Yarrow, paul@paulyarrow.com, 2003-07-13 /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{3B8E3585-58B7-4f56-8AB6-C04A2BFA6589}"); } } /// <summary> /// Admin Module /// </summary> /// <value></value> public override bool AdminModule { get { return true; } } # region Install / Uninstall Implementation /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Install(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Uninstall(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql"); ArrayList errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } #endregion #region Web Form Designer generated code /// <summary> /// Raises Init event /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { this.cboReportType.SelectedIndexChanged += new EventHandler(this.cboReportType_SelectedIndexChanged); this.cmdDisplay.Click += new EventHandler(this.cmdDisplay_Click); this.Load += new EventHandler(this.Monitoring_Load); base.OnInit(e); } #endregion /// <summary> /// Handles the Click event of the cmdDisplay control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void cmdDisplay_Click(object sender, EventArgs e) { if (Page.IsValid == true) { BindGrid(); } } /// <summary> /// Handles the SelectedIndexChanged event of the cboReportType control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void cboReportType_SelectedIndexChanged(object sender, EventArgs e) { BindGrid(); } /// <summary> /// Called after ScheduleDo if it doesn't throw any exception /// </summary> /// <param name="task"></param> public void ScheduleCommit(SchedulerTask task) { // TODO: Add Monitoring.ScheduleCommit implementation } /// <summary> /// Called when a task occurs /// </summary> /// <param name="task"></param> public void ScheduleDo(SchedulerTask task) { // TODO: Add Monitoring.ScheduleDo implementation } /// <summary> /// Called after ScheduleDo if it throws an exception /// </summary> /// <param name="task"></param> public void ScheduleRollback(SchedulerTask task) { // TODO: Add Monitoring.ScheduleRollback implementation } } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(AudioSource))] public class BufferShuffler : MonoBehaviour { public AudioClip ClipToShuffle; public float SecondsPerShuffle; public float SecondsPerCrossfade; public float maxClipLength; private AudioClip _clipToShuffle; private float[] _clipData = new float[0]; private float[] _clipDataR = new float[0]; private float[] _clipDataL = new float[0]; private float[] _nextClipData = new float[0]; private float[] _nextClipDataR = new float[0]; private float[] _nextClipDataL = new float[0]; private AudioSource _bufferShufflerAudioSource; private int _buffersPerShuffle; private int _crossFadeSamples; private int _currentShuffleBuffer; private int _shuffleCounter; private int _theLastStartIndex; private bool _firstShuffle; private int _startIndex; private int _clipLengthSamples; private int _clipChannels; private int _bufferSize; private bool _stereo; private bool _clipLoaded; private bool _clipSwapped; private int _fadeIndex; private int _dspSize; private int _qSize; private int _outputSampleRate; private int _clipSampleRate; private System.Random _randomGenerator; void Awake(){ maxClipLength = ((float)Mathf.RoundToInt (ClipToShuffle.length * 10f)) / 10f - SecondsPerCrossfade * 2f; SecondsPerCrossfade = 0.05f; SecondsPerShuffle = maxClipLength; } void Start() { _bufferShufflerAudioSource = GetComponent<AudioSource> (); _randomGenerator = new System.Random(); AudioSettings.GetDSPBufferSize(out _dspSize, out _qSize); _outputSampleRate = AudioSettings.outputSampleRate; LoadNewClip(ClipToShuffle); //StartCoroutine (PlaySound ()); } public void SetSecondsPerShuffle(float secondsPerShuffle) { if (SecondsPerShuffle > ClipToShuffle.length) { Debug.LogError("Seconds Per Shuffle longer than length of clip. " + "Seconds Per Shuffle must be less than the length of the audio clip."); } SecondsPerShuffle = secondsPerShuffle; } public void SetSecondsPerCrossfade(float secondsPerCrossfade) { if (SecondsPerCrossfade > SecondsPerShuffle/2) { Debug.LogError("Seconds Per Crossfade longer than length of shuffle. " + "Seconds Per Shuffle must be less than the length of the shuffle. " + "Reccomended length is <= " + SecondsPerShuffle/2); } SecondsPerCrossfade = secondsPerCrossfade; } public void LoadNewClip(AudioClip clip) { LoadNewClip(clip, SecondsPerShuffle, SecondsPerCrossfade); } public void LoadNewClip(AudioClip clip, float secondsPerShuffle) { LoadNewClip(clip, secondsPerShuffle, SecondsPerCrossfade); } public void LoadNewClip(AudioClip clip, float secondsPerShuffle, float secondsPerCrossfade) { _clipSwapped = false; _clipLoaded = false; _clipToShuffle = clip; ClipToShuffle = clip; _clipChannels = clip.channels; _clipLengthSamples = clip.samples; _clipSampleRate = clip.frequency; if (_clipSampleRate != _outputSampleRate) { Debug.LogError("Clip sample rate doesn't match output sample rate. Alter clip sample rate in clip import settings, or output sample rate in Project->Preferences->Audio"); return; } _nextClipData = new float[_clipLengthSamples]; _nextClipDataR = new float[(_clipLengthSamples / _clipChannels)]; _nextClipDataL = new float[(_clipLengthSamples / _clipChannels)]; _stereo = _clipChannels == 2; clip.GetData(_nextClipData, 0); if (_stereo) { for (var i = 0; i < _clipLengthSamples-1; i = i + _clipChannels) { _nextClipDataL[i / 2] = _nextClipData[i]; _nextClipDataR[i / 2] = _nextClipData[i + 1]; } } else { _clipToShuffle.GetData(_nextClipDataL, 0); } SetSecondsPerShuffle(secondsPerShuffle); SetSecondsPerCrossfade(secondsPerCrossfade); _clipLoaded = true; } void Update() { // Mathf.Clamp (SecondsPerShuffle, SecondsPerCrossfade, maxClipLength); if (_clipToShuffle != ClipToShuffle) { LoadNewClip(ClipToShuffle); } } private int GetStartIndex() { if (_currentShuffleBuffer == _shuffleCounter) { _theLastStartIndex = _startIndex + (_bufferSize/_clipChannels); _currentShuffleBuffer = _buffersPerShuffle; _shuffleCounter = 0; int maxEndIndex = (_clipLengthSamples-((_bufferSize*_currentShuffleBuffer) + _crossFadeSamples))/_clipChannels; _startIndex = _randomGenerator.Next(_crossFadeSamples, maxEndIndex-1); _startIndex = _startIndex - _crossFadeSamples; _firstShuffle = true; _fadeIndex = 0; return _startIndex; } else { _shuffleCounter++; _startIndex = _startIndex + (_bufferSize / _clipChannels); _firstShuffle = false; return _startIndex; } } void OnAudioFilterRead(float[] data, int channels) { //if clip isn't loaded, just return if (!_clipLoaded) return; //if clip is stereo, then the buffer size equals the length of the array //this is b/c of how audioclip array data distribution works if (_stereo) { _bufferSize = data.Length; } else //if the clip is mono? then the buffer size equals the length of the array divided by the number of channels { _bufferSize = data.Length / channels; } float bufferSizeInSeconds = (float)_bufferSize/(float)_outputSampleRate; _buffersPerShuffle = Mathf.RoundToInt(SecondsPerShuffle / bufferSizeInSeconds); _crossFadeSamples = _bufferSize * Mathf.RoundToInt(SecondsPerCrossfade / bufferSizeInSeconds); if (_clipLoaded && !_clipSwapped) { _clipData = _nextClipData; _clipDataR = _nextClipDataR; _clipDataL = _nextClipDataL; _shuffleCounter = _currentShuffleBuffer; } int theStartIndex = GetStartIndex(); if (_clipLoaded && !_clipSwapped) { _fadeIndex = _crossFadeSamples; _clipSwapped = true; } if (!_clipSwapped) return; //go through the entire clip array, apply filter (shuffle around audio data) var clipIndex = 0; for (var i = 0; i < data.Length; i = i + channels) { if ((_fadeIndex + clipIndex) < _crossFadeSamples) { int currentClipIndex = theStartIndex + clipIndex; int lastClipIndex = _theLastStartIndex + clipIndex; int progressIndex = clipIndex + _fadeIndex; float currentClipPercent = Mathf.Sin((0.5f * progressIndex +Mathf.PI)/_crossFadeSamples); float lastClipPercent = Mathf.Cos((0.5f * progressIndex +Mathf.PI)/_crossFadeSamples); data[i] = (_clipDataL[currentClipIndex] * currentClipPercent) + (_clipDataL[lastClipIndex] * lastClipPercent); if (channels == 2 && _stereo) data[i + 1] = (_clipDataR[currentClipIndex]*currentClipPercent) + (_clipDataR[lastClipIndex] * lastClipPercent); else if (channels == 2) data[i + 1] = (_clipDataL[currentClipIndex + 1] * currentClipPercent) + (_clipDataL[lastClipIndex] * lastClipPercent); } else { data[i] = _clipDataL[theStartIndex + clipIndex]; if (channels == 2 && _stereo) data[i + 1] = _clipDataR[theStartIndex + clipIndex]; else if (channels == 2) data[i + 1] = _clipDataL[theStartIndex + clipIndex]; } clipIndex++; } _fadeIndex += clipIndex; _theLastStartIndex += clipIndex; } public bool soundIsPlaying(){ return _bufferShufflerAudioSource.isPlaying; } public IEnumerator PlaySound(){ _bufferShufflerAudioSource.Play (); yield return new WaitForSeconds (maxClipLength); _bufferShufflerAudioSource.Stop (); yield return new WaitForSeconds (2f); } public float CurrentAudioTime(){ return _bufferShufflerAudioSource.time; } }
/* * Copyright (c) 2012 crdx * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Windows.Forms; using System.Xml; namespace ArachNGIN.Files.Settings { /// <summary> /// Class for storing app settings in app directory /// </summary> public sealed class PortableSettingsProvider : SettingsProvider, IApplicationSettingsProvider { private const string RootNodeName = "settings"; private const string LocalSettingsNodeName = "localSettings"; private const string GlobalSettingsNodeName = "globalSettings"; private const string ClassName = "PortableSettingsProvider"; private string _appName; private XmlDocument _xmlDocument; private string FilePath { get { var appname = Path.GetDirectoryName(Application.ExecutablePath); return Path.Combine(appname, string.Format("{0}.settings", ApplicationName)); } } private XmlNode LocalSettingsNode { get { var settingsNode = GetSettingsNode(LocalSettingsNodeName); var machineNode = settingsNode.SelectSingleNode(Environment.MachineName.ToLowerInvariant()); if (machineNode != null) return machineNode; machineNode = RootDocument.CreateElement(Environment.MachineName.ToLowerInvariant()); settingsNode.AppendChild(machineNode); return machineNode; } } private XmlNode GlobalSettingsNode { get { return GetSettingsNode(GlobalSettingsNodeName); } } private XmlNode RootNode { get { return RootDocument.SelectSingleNode(RootNodeName); } } private XmlDocument RootDocument { get { if (_xmlDocument != null) return _xmlDocument; try { _xmlDocument = new XmlDocument(); _xmlDocument.Load(FilePath); } catch (Exception) { // ignored } if (_xmlDocument != null && _xmlDocument.SelectSingleNode(RootNodeName) != null) return _xmlDocument; _xmlDocument = GetBlankXmlDocument(); return _xmlDocument; } } /// <summary> /// Gets or sets the name of the currently running application. /// </summary> public override string ApplicationName { get { return Path.GetFileNameWithoutExtension(Application.ExecutablePath); } set { _appName = value; } } /// <summary> /// Gets the friendly name used to refer to the provider during configuration. /// </summary> public override string Name { get { return ClassName; } } /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config"> /// A collection of the name/value pairs representing the provider-specific attributes specified in /// the configuration for this provider. /// </param> public override void Initialize(string name, NameValueCollection config) { base.Initialize(Name, config); } /// <summary> /// Sets the values of the specified group of property settings. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext" /> describing the current application usage.</param> /// <param name="collection"> /// A <see cref="T:System.Configuration.SettingsPropertyValueCollection" /> representing the group /// of property settings to set. /// </param> public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { foreach (SettingsPropertyValue propertyValue in collection) SetValue(propertyValue); try { RootDocument.Save(FilePath); } catch (Exception) { /* * If this is a portable application and the device has been * removed then this will fail, so don't do anything. It's * probably better for the application to stop saving settings * rather than just crashing outright. Probably. */ } } /// <summary> /// Returns the collection of settings property values for the specified application instance and settings property /// group. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext" /> describing the current application use.</param> /// <param name="collection"> /// A <see cref="T:System.Configuration.SettingsPropertyCollection" /> containing the settings /// property group whose values are to be retrieved. /// </param> /// <returns> /// A <see cref="T:System.Configuration.SettingsPropertyValueCollection" /> containing the values for the specified /// settings property group. /// </returns> public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { var values = new SettingsPropertyValueCollection(); foreach (SettingsProperty property in collection) values.Add(new SettingsPropertyValue(property) { SerializedValue = GetValue(property) }); return values; } /// <summary> /// Sets the value. /// </summary> /// <param name="propertyValue">The property value.</param> private void SetValue(SettingsPropertyValue propertyValue) { var targetNode = IsGlobal(propertyValue.Property) ? GlobalSettingsNode : LocalSettingsNode; var settingNode = targetNode.SelectSingleNode(string.Format("setting[@name='{0}']", propertyValue.Name)); if (settingNode != null) { settingNode.InnerText = propertyValue.SerializedValue.ToString(); } else { settingNode = RootDocument.CreateElement("setting"); var nameAttribute = RootDocument.CreateAttribute("name"); nameAttribute.Value = propertyValue.Name; if (settingNode.Attributes != null) settingNode.Attributes.Append(nameAttribute); settingNode.InnerText = propertyValue.SerializedValue.ToString(); targetNode.AppendChild(settingNode); } } /// <summary> /// Gets the value. /// </summary> /// <param name="property">The property.</param> /// <returns></returns> private string GetValue(SettingsProperty property) { var targetNode = IsGlobal(property) ? GlobalSettingsNode : LocalSettingsNode; var settingNode = targetNode.SelectSingleNode(string.Format("setting[@name='{0}']", property.Name)); if (settingNode == null) return property.DefaultValue != null ? property.DefaultValue.ToString() : string.Empty; return settingNode.InnerText; } private static bool IsGlobal(SettingsProperty property) { foreach (DictionaryEntry attribute in property.Attributes) if ((Attribute)attribute.Value is SettingsManageabilityAttribute) return true; return false; } private XmlNode GetSettingsNode(string name) { var settingsNode = RootNode.SelectSingleNode(name); if (settingsNode != null) return settingsNode; settingsNode = RootDocument.CreateElement(name); RootNode.AppendChild(settingsNode); return settingsNode; } /// <summary> /// Gets the blank XML document. /// </summary> /// <returns></returns> public XmlDocument GetBlankXmlDocument() { var blankXmlDocument = new XmlDocument(); blankXmlDocument.AppendChild(blankXmlDocument.CreateXmlDeclaration("1.0", "utf-8", string.Empty)); blankXmlDocument.AppendChild(blankXmlDocument.CreateElement(RootNodeName)); return blankXmlDocument; } #region IApplicationSettingsProvider Members /// <summary> /// Resets the application settings associated with the specified application to their default values. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext" /> describing the current application usage.</param> public void Reset(SettingsContext context) { LocalSettingsNode.RemoveAll(); GlobalSettingsNode.RemoveAll(); _xmlDocument.Save(FilePath); } /// <summary> /// Returns the value of the specified settings property for the previous version of the same application. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext" /> describing the current application usage.</param> /// <param name="property">The <see cref="T:System.Configuration.SettingsProperty" /> whose value is to be returned.</param> /// <returns> /// A <see cref="T:System.Configuration.SettingsPropertyValue" /> containing the value of the specified property /// setting as it was last set in the previous version of the application; or null if the setting cannot be found. /// </returns> public SettingsPropertyValue GetPreviousVersion(SettingsContext context, SettingsProperty property) { // do nothing return new SettingsPropertyValue(property); } /// <summary> /// Indicates to the provider that the application has been upgraded. This offers the provider an opportunity to /// upgrade its stored settings as appropriate. /// </summary> /// <param name="context">A <see cref="T:System.Configuration.SettingsContext" /> describing the current application usage.</param> /// <param name="properties"> /// A <see cref="T:System.Configuration.SettingsPropertyCollection" /> containing the settings /// property group whose values are to be retrieved. /// </param> public void Upgrade(SettingsContext context, SettingsPropertyCollection properties) { } #endregion IApplicationSettingsProvider Members } }
using J2N.Collections.Generic.Extensions; using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; using System; using System.Collections; using System.Collections.Generic; using System.Text; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = Lucene.Net.Util.ArrayUtil; using AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// A <see cref="Query"/> that matches documents containing a particular sequence of terms. /// A <see cref="PhraseQuery"/> is built by QueryParser for input like <c>"new york"</c>. /// /// <para/>This query may be combined with other terms or queries with a <see cref="BooleanQuery"/>. /// <para/> /// Collection initializer note: To create and populate a <see cref="PhraseQuery"/> /// in a single statement, you can use the following example as a guide: /// /// <code> /// var phraseQuery = new PhraseQuery() { /// new Term("field", "microsoft"), /// new Term("field", "office") /// }; /// </code> /// Note that as long as you specify all of the parameters, you can use either /// <see cref="Add(Term)"/> or <see cref="Add(Term, int)"/> /// as the method to use to initialize. If there are multiple parameters, each parameter set /// must be surrounded by curly braces. /// </summary> public class PhraseQuery : Query, IEnumerable<Term> // LUCENENET specific - implemented IEnumerable<Term>, which allows for use of collection initializer. See: https://stackoverflow.com/a/9195144 { private string field; private IList<Term> terms = new JCG.List<Term>(4); private IList<int?> positions = new JCG.List<int?>(4); private int maxPosition = 0; private int slop = 0; /// <summary> /// Constructs an empty phrase query. </summary> public PhraseQuery() { } /// <summary> /// Sets the number of other words permitted between words in query phrase. /// If zero, then this is an exact phrase search. For larger values this works /// like a <c>WITHIN</c> or <c>NEAR</c> operator. /// /// <para/>The slop is in fact an edit-distance, where the units correspond to /// moves of terms in the query phrase out of position. For example, to switch /// the order of two words requires two moves (the first move places the words /// atop one another), so to permit re-orderings of phrases, the slop must be /// at least two. /// /// <para/>More exact matches are scored higher than sloppier matches, thus search /// results are sorted by exactness. /// /// <para/>The slop is zero by default, requiring exact matches. /// </summary> public virtual int Slop { get => slop; set { if (value < 0) throw new ArgumentException("slop value cannot be negative"); slop = value; } } /// <summary> /// Adds a term to the end of the query phrase. /// The relative position of the term is the one immediately after the last term added. /// </summary> public virtual void Add(Term term) { int position = 0; if (positions.Count > 0) { position = (int)positions[positions.Count - 1] + 1; } Add(term, position); } /// <summary> /// Adds a term to the end of the query phrase. /// The relative position of the term within the phrase is specified explicitly. /// this allows e.g. phrases with more than one term at the same position /// or phrases with gaps (e.g. in connection with stopwords). /// </summary> public virtual void Add(Term term, int position) { if (terms.Count == 0) { field = term.Field; } else if (!term.Field.Equals(field, StringComparison.Ordinal)) { throw new ArgumentException("All phrase terms must be in the same field: " + term); } terms.Add(term); positions.Add(position); if (position > maxPosition) { maxPosition = position; } } /// <summary> /// Returns the set of terms in this phrase. </summary> public virtual Term[] GetTerms() { return terms.ToArray(); } /// <summary> /// Returns the relative positions of terms in this phrase. /// </summary> public virtual int[] GetPositions() { int[] result = new int[positions.Count]; for (int i = 0; i < positions.Count; i++) { result[i] = (int)positions[i]; } return result; } public override Query Rewrite(IndexReader reader) { if (terms.Count == 0) { BooleanQuery bq = new BooleanQuery(); bq.Boost = Boost; return bq; } else if (terms.Count == 1) { TermQuery tq = new TermQuery(terms[0]); tq.Boost = Boost; return tq; } else { return base.Rewrite(reader); } } internal class PostingsAndFreq : IComparable<PostingsAndFreq> { internal readonly DocsAndPositionsEnum postings; internal readonly int docFreq; internal readonly int position; internal readonly Term[] terms; internal readonly int nTerms; // for faster comparisons public PostingsAndFreq(DocsAndPositionsEnum postings, int docFreq, int position, params Term[] terms) { this.postings = postings; this.docFreq = docFreq; this.position = position; nTerms = terms == null ? 0 : terms.Length; if (nTerms > 0) { if (terms.Length == 1) { this.terms = terms; } else { Term[] terms2 = new Term[terms.Length]; Array.Copy(terms, 0, terms2, 0, terms.Length); Array.Sort(terms2); this.terms = terms2; } } else { this.terms = null; } } public virtual int CompareTo(PostingsAndFreq other) { if (docFreq != other.docFreq) { return docFreq - other.docFreq; } if (position != other.position) { return position - other.position; } if (nTerms != other.nTerms) { return nTerms - other.nTerms; } if (nTerms == 0) { return 0; } for (int i = 0; i < terms.Length; i++) { int res = terms[i].CompareTo(other.terms[i]); if (res != 0) { return res; } } return 0; } public override int GetHashCode() { const int prime = 31; int result = 1; result = prime * result + docFreq; result = prime * result + position; for (int i = 0; i < nTerms; i++) { result = prime * result + terms[i].GetHashCode(); } return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } PostingsAndFreq other = (PostingsAndFreq)obj; if (docFreq != other.docFreq) { return false; } if (position != other.position) { return false; } if (terms == null) { return other.terms == null; } return Arrays.Equals(terms, other.terms); } } private class PhraseWeight : Weight { private readonly PhraseQuery outerInstance; internal readonly Similarity similarity; internal readonly Similarity.SimWeight stats; internal TermContext[] states; public PhraseWeight(PhraseQuery outerInstance, IndexSearcher searcher) { this.outerInstance = outerInstance; this.similarity = searcher.Similarity; IndexReaderContext context = searcher.TopReaderContext; states = new TermContext[outerInstance.terms.Count]; TermStatistics[] termStats = new TermStatistics[outerInstance.terms.Count]; for (int i = 0; i < outerInstance.terms.Count; i++) { Term term = outerInstance.terms[i]; states[i] = TermContext.Build(context, term); termStats[i] = searcher.TermStatistics(term, states[i]); } stats = similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.field), termStats); } public override string ToString() { return "weight(" + outerInstance + ")"; } public override Query Query => outerInstance; public override float GetValueForNormalization() { return stats.GetValueForNormalization(); } public override void Normalize(float queryNorm, float topLevelBoost) { stats.Normalize(queryNorm, topLevelBoost); } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.terms.Count > 0); AtomicReader reader = context.AtomicReader; IBits liveDocs = acceptDocs; PostingsAndFreq[] postingsFreqs = new PostingsAndFreq[outerInstance.terms.Count]; Terms fieldTerms = reader.GetTerms(outerInstance.field); if (fieldTerms == null) { return null; } // Reuse single TermsEnum below: TermsEnum te = fieldTerms.GetEnumerator(); for (int i = 0; i < outerInstance.terms.Count; i++) { Term t = outerInstance.terms[i]; TermState state = states[i].Get(context.Ord); if (state == null) // term doesnt exist in this segment { if (Debugging.AssertsEnabled) Debugging.Assert(TermNotInReader(reader, t), "no termstate found but term exists in reader"); return null; } te.SeekExact(t.Bytes, state); DocsAndPositionsEnum postingsEnum = te.DocsAndPositions(liveDocs, null, DocsAndPositionsFlags.NONE); // PhraseQuery on a field that did not index // positions. if (postingsEnum == null) { if (Debugging.AssertsEnabled) Debugging.Assert(te.SeekExact(t.Bytes), "termstate found but no term exists in reader"); // term does exist, but has no positions throw new InvalidOperationException("field \"" + t.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + t.Text() + ")"); } postingsFreqs[i] = new PostingsAndFreq(postingsEnum, te.DocFreq, (int)outerInstance.positions[i], t); } // sort by increasing docFreq order if (outerInstance.slop == 0) { ArrayUtil.TimSort(postingsFreqs); } if (outerInstance.slop == 0) // optimize exact case { ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, similarity.GetSimScorer(stats, context)); if (s.noDocs) { return null; } else { return s; } } else { return new SloppyPhraseScorer(this, postingsFreqs, outerInstance.slop, similarity.GetSimScorer(stats, context)); } } // only called from assert private bool TermNotInReader(AtomicReader reader, Term term) { return reader.DocFreq(term) == 0; } public override Explanation Explain(AtomicReaderContext context, int doc) { Scorer scorer = GetScorer(context, context.AtomicReader.LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = outerInstance.slop == 0 ? scorer.Freq : ((SloppyPhraseScorer)scorer).SloppyFreq; SimScorer docScorer = similarity.GetSimScorer(stats, context); ComplexExplanation result = new ComplexExplanation(); result.Description = "weight(" + Query + " in " + doc + ") [" + similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq)); result.AddDetail(scoreExplanation); result.Value = scoreExplanation.Value; result.Match = true; return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } public override Weight CreateWeight(IndexSearcher searcher) { return new PhraseWeight(this, searcher); } /// <seealso cref="Lucene.Net.Search.Query.ExtractTerms(ISet{Term})"/> public override void ExtractTerms(ISet<Term> queryTerms) { queryTerms.UnionWith(terms); } /// <summary> /// Prints a user-readable version of this query. </summary> public override string ToString(string f) { StringBuilder buffer = new StringBuilder(); if (field != null && !field.Equals(f, StringComparison.Ordinal)) { buffer.Append(field); buffer.Append(":"); } buffer.Append("\""); string[] pieces = new string[maxPosition + 1]; for (int i = 0; i < terms.Count; i++) { int pos = (int)positions[i]; string s = pieces[pos]; if (s == null) { s = (terms[i]).Text(); } else { s = s + "|" + (terms[i]).Text(); } pieces[pos] = s; } for (int i = 0; i < pieces.Length; i++) { if (i > 0) { buffer.Append(' '); } string s = pieces[i]; if (s == null) { buffer.Append('?'); } else { buffer.Append(s); } } buffer.Append("\""); if (slop != 0) { buffer.Append("~"); buffer.Append(slop); } buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } /// <summary> /// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary> public override bool Equals(object o) { if (!(o is PhraseQuery)) { return false; } PhraseQuery other = (PhraseQuery)o; return (this.Boost == other.Boost) && (this.slop == other.slop) && this.terms.Equals(other.terms) && this.positions.Equals(other.positions); } /// <summary> /// Returns a hash code value for this object. </summary> public override int GetHashCode() { return J2N.BitConversion.SingleToInt32Bits(Boost) ^ slop ^ terms.GetHashCode() ^ positions.GetHashCode(); } /// <summary> /// Returns an enumerator that iterates through the <see cref="terms"/> collection. /// </summary> /// <returns>An enumerator that can be used to iterate through the <see cref="terms"/> collection.</returns> // LUCENENET specific public IEnumerator<Term> GetEnumerator() { return this.terms.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through the <see cref="terms"/> collection. /// </summary> /// <returns>An enumerator that can be used to iterate through the <see cref="terms"/> collection.</returns> // LUCENENET specific IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.Configuration.SystemWebSectionGroup.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.Configuration { sealed public partial class SystemWebSectionGroup : System.Configuration.ConfigurationSectionGroup { #region Methods and constructors public SystemWebSectionGroup() { } #endregion #region Properties and indexers public AnonymousIdentificationSection AnonymousIdentification { get { return default(AnonymousIdentificationSection); } } public AuthenticationSection Authentication { get { return default(AuthenticationSection); } } public AuthorizationSection Authorization { get { return default(AuthorizationSection); } } public System.Configuration.DefaultSection BrowserCaps { get { return default(System.Configuration.DefaultSection); } } public ClientTargetSection ClientTarget { get { return default(ClientTargetSection); } } public CompilationSection Compilation { get { return default(CompilationSection); } } public CustomErrorsSection CustomErrors { get { return default(CustomErrorsSection); } } public DeploymentSection Deployment { get { return default(DeploymentSection); } } public System.Configuration.DefaultSection DeviceFilters { get { return default(System.Configuration.DefaultSection); } } public FullTrustAssembliesSection FullTrustAssemblies { get { return default(FullTrustAssembliesSection); } } public GlobalizationSection Globalization { get { return default(GlobalizationSection); } } public HealthMonitoringSection HealthMonitoring { get { return default(HealthMonitoringSection); } } public HostingEnvironmentSection HostingEnvironment { get { return default(HostingEnvironmentSection); } } public HttpCookiesSection HttpCookies { get { return default(HttpCookiesSection); } } public HttpHandlersSection HttpHandlers { get { return default(HttpHandlersSection); } } public HttpModulesSection HttpModules { get { return default(HttpModulesSection); } } public HttpRuntimeSection HttpRuntime { get { return default(HttpRuntimeSection); } } public IdentitySection Identity { get { return default(IdentitySection); } } public MachineKeySection MachineKey { get { return default(MachineKeySection); } } public MembershipSection Membership { get { return default(MembershipSection); } } public System.Configuration.ConfigurationSection MobileControls { get { return default(System.Configuration.ConfigurationSection); } } public PagesSection Pages { get { return default(PagesSection); } } public PartialTrustVisibleAssembliesSection PartialTrustVisibleAssemblies { get { return default(PartialTrustVisibleAssembliesSection); } } public ProcessModelSection ProcessModel { get { return default(ProcessModelSection); } } public ProfileSection Profile { get { return default(ProfileSection); } } public System.Configuration.DefaultSection Protocols { get { return default(System.Configuration.DefaultSection); } } public RoleManagerSection RoleManager { get { return default(RoleManagerSection); } } public SecurityPolicySection SecurityPolicy { get { return default(SecurityPolicySection); } } public SessionStateSection SessionState { get { return default(SessionStateSection); } } public SiteMapSection SiteMap { get { return default(SiteMapSection); } } public TraceSection Trace { get { return default(TraceSection); } } public TrustSection Trust { get { return default(TrustSection); } } public UrlMappingsSection UrlMappings { get { return default(UrlMappingsSection); } } public WebControlsSection WebControls { get { return default(WebControlsSection); } } public WebPartsSection WebParts { get { return default(WebPartsSection); } } public System.Web.Services.Configuration.WebServicesSection WebServices { get { return default(System.Web.Services.Configuration.WebServicesSection); } } public XhtmlConformanceSection XhtmlConformance { get { return default(XhtmlConformanceSection); } } #endregion } }
#region Usings using System; using System.IO; using System.Linq; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using Extend; using JetBrains.Annotations; using Stomp.Net.Stomp.Transport; #endregion namespace Stomp.Net.Transport { /// <summary> /// SSL transport. /// </summary> public class SslTransport : TcpTransport { #region Ctor /// <summary> /// Initializes a new instance of the <see cref="TcpTransport" /> class. /// </summary> /// <exception cref="ArgumentNullException">stompConnectionSettings can not be null.</exception> /// <param name="location">The URI.</param> /// <param name="socket">The socket to use.</param> /// <param name="wireFormat">A <see cref="IWireFormat" />.</param> /// <param name="stompConnectionSettings">Some STOMP connection settings.</param> public SslTransport( Uri location, Socket socket, IWireFormat wireFormat, [NotNull] StompConnectionSettings stompConnectionSettings ) : base( location, socket, wireFormat ) { stompConnectionSettings.ThrowIfNull( nameof(stompConnectionSettings) ); _stompConnectionSettings = stompConnectionSettings; } #endregion #region Protected Members /// <summary> /// Creates a stream for the transport socket. /// </summary> /// <returns>Returns the newly created stream.</returns> protected override Stream CreateSocketStream() { if ( _sslStream != null ) return _sslStream; _sslStream = new(new NetworkStream( Socket ), false, ValidateServerCertificate, SelectLocalCertificate); try { var remoteCertName = _stompConnectionSettings.TransportSettings.SslSettings.ServerName ?? RemoteAddress.Host; var authThread = new Thread( () => _sslStream.AuthenticateAsClientAsync( remoteCertName, LoadCertificates(), SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false ) .ConfigureAwait( false ) .GetAwaiter() .GetResult() ); authThread.Start(); authThread.Join(); Tracer.Info( "SSL connection established." ); } catch ( Exception ex ) { if ( Tracer.IsErrorEnabled ) { Tracer.Error( "Authentication failed - closing the connection." ); Tracer.Error( $"Exception: {ex}" ); } throw; } return _sslStream; } #endregion #region Fields /// <summary> /// Stores the STOMP connections settings. /// </summary> private readonly StompConnectionSettings _stompConnectionSettings; /// <summary> /// The SSL stream. /// </summary> private SslStream _sslStream; #endregion #region Private Members private X509Certificate2Collection LoadCertificates() { var collection = new X509Certificate2Collection(); if ( _stompConnectionSettings.TransportSettings.SslSettings.ClientCertFilename.IsNotEmpty() ) { var certificate = new X509Certificate2( _stompConnectionSettings.TransportSettings.SslSettings.ClientCertFilename, _stompConnectionSettings.TransportSettings.SslSettings.ClientCertPassword ); collection.Add( certificate ); } else { var name = _stompConnectionSettings.TransportSettings.SslSettings.KeyStoreName.IsEmpty() ? StoreName.My.ToString() : _stompConnectionSettings.TransportSettings.SslSettings.KeyStoreName; var location = StoreLocation.CurrentUser; if ( _stompConnectionSettings.TransportSettings.SslSettings.KeyStoreLocation.IsNotEmpty() ) if ( String.Compare( _stompConnectionSettings.TransportSettings.SslSettings.KeyStoreLocation, "CurrentUser", StringComparison.OrdinalIgnoreCase ) == 0 ) location = StoreLocation.CurrentUser; else if ( String.Compare( _stompConnectionSettings.TransportSettings.SslSettings.KeyStoreLocation, "LocalMachine", StringComparison.OrdinalIgnoreCase ) == 0 ) location = StoreLocation.LocalMachine; else throw new StompException( "Invalid StoreLocation given on URI" ); using var store = new X509Store( name, location ); store.Open( OpenFlags.ReadOnly ); collection = store.Certificates; } return collection; } private X509Certificate SelectLocalCertificate( Object sender, String targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, String[] acceptableIssuers ) { if ( localCertificates.Count == 1 ) { Tracer.Info( "Found only one matching cert. skip CE compare" ); return localCertificates[0]; } if ( localCertificates.Count <= 1 || _stompConnectionSettings.TransportSettings.SslSettings.ClientCertSubject == null ) return null; var match = localCertificates .Cast<X509Certificate2>() .FirstOrDefault( certificate => String.Compare( certificate.Subject, _stompConnectionSettings.TransportSettings.SslSettings.ClientCertSubject, StringComparison.OrdinalIgnoreCase ) == 0 ); if ( match == null && Tracer.IsWarnEnabled ) Tracer.Warn( $"Found no matching cert. with Subject '{_stompConnectionSettings.TransportSettings.SslSettings.ClientCertSubject}'" ); return match; } private Boolean ValidateServerCertificate( Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors ) { switch ( sslPolicyErrors ) { case SslPolicyErrors.None: return true; case SslPolicyErrors.RemoteCertificateChainErrors: Tracer.Error( "Chain Status errors: " ); if ( Tracer.IsErrorEnabled ) foreach ( var status in chain.ChainStatus ) { Tracer.Error( "Chain Status error: " + status.Status ); Tracer.Error( "Chain Status information: " + status.StatusInformation ); } break; case SslPolicyErrors.RemoteCertificateNameMismatch: Tracer.Error( "Mismatch between Remote Cert Name." ); break; case SslPolicyErrors.RemoteCertificateNotAvailable: Tracer.Error( "The Remote Certificate was not Available." ); break; default: throw new ArgumentOutOfRangeException( nameof(sslPolicyErrors), sslPolicyErrors, $"Policy '{sslPolicyErrors}' is not supported." ); } // Configuration may or may not allow us to connect with an invalid broker cert. return _stompConnectionSettings.TransportSettings.SslSettings.AcceptInvalidBrokerCert; } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.VirtualNetworks; using Microsoft.WindowsAzure.Management.VirtualNetworks.Models; namespace Microsoft.WindowsAzure.Management.VirtualNetworks { internal partial class ReservedIPOperations : IServiceOperations<VirtualNetworkManagementClient>, IReservedIPOperations { /// <summary> /// Initializes a new instance of the ReservedIPOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ReservedIPOperations(VirtualNetworkManagementClient client) { this._client = client; } private VirtualNetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.VirtualNetworkManagementClient. /// </summary> public VirtualNetworkManagementClient Client { get { return this._client; } } /// <summary> /// Preview Only. The Create Reserved IP operation creates a reserved /// IP from your the subscription. /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<VirtualNetworkOperationStatusResponse> BeginCreatingAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/networking/reservedips"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement reservedIPElement = new XElement(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(reservedIPElement); if (parameters.Name != null) { XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; reservedIPElement.Add(nameElement); } if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; reservedIPElement.Add(labelElement); } if (parameters.AffinityGroup != null) { XElement affinityGroupElement = new XElement(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); affinityGroupElement.Value = parameters.AffinityGroup; reservedIPElement.Add(affinityGroupElement); } if (parameters.ServiceName != null) { XElement serviceNameElement = new XElement(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); serviceNameElement.Value = parameters.ServiceName; reservedIPElement.Add(serviceNameElement); } if (parameters.DeploymentName != null) { XElement deploymentNameElement = new XElement(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure")); deploymentNameElement.Value = parameters.DeploymentName; reservedIPElement.Add(deploymentNameElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result VirtualNetworkOperationStatusResponse result = null; result = new VirtualNetworkOperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Preview Only. The Delete Reserved IP operation removes a reserved /// IP from your the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> BeginDeletingAsync(string ipName, CancellationToken cancellationToken) { // Validate if (ipName == null) { throw new ArgumentNullException("ipName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ipName", ipName); Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/networking/reservedips/" + ipName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<VirtualNetworkOperationStatusResponse> CreateAsync(NetworkReservedIPCreateParameters parameters, CancellationToken cancellationToken) { VirtualNetworkManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); VirtualNetworkOperationStatusResponse response = await client.ReservedIPs.BeginCreatingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); VirtualNetworkOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<VirtualNetworkOperationStatusResponse> DeleteAsync(string ipName, CancellationToken cancellationToken) { VirtualNetworkManagementClient client = this.Client; bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ipName", ipName); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } try { if (shouldTrace) { client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId)); } cancellationToken.ThrowIfCancellationRequested(); OperationResponse response = await client.ReservedIPs.BeginDeletingAsync(ipName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); VirtualNetworkOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; } if (shouldTrace) { Tracing.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.ErrorCode = result.Error.Code; ex.ErrorMessage = result.Error.Message; if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } return result; } finally { if (client != null && shouldTrace) { client.Dispose(); } } } /// <summary> /// Preview Only. The Get Reserved IP operation retrieves the details /// for virtual IP reserved for the subscription. /// </summary> /// <param name='ipName'> /// The name of the reserved IP to retrieve. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Preview Only. A reserved IP associated with your subscription. /// </returns> public async Task<NetworkReservedIPGetResponse> GetAsync(string ipName, CancellationToken cancellationToken) { // Validate if (ipName == null) { throw new ArgumentNullException("ipName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("ipName", ipName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/networking/reservedips/" + ipName; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result NetworkReservedIPGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new NetworkReservedIPGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement reservedIPElement = responseDoc.Element(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure")); if (reservedIPElement != null) { XElement nameElement = reservedIPElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; result.Name = nameInstance; } XElement addressElement = reservedIPElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure")); if (addressElement != null) { string addressInstance = addressElement.Value; result.Address = addressInstance; } XElement idElement = reservedIPElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement labelElement = reservedIPElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; result.Label = labelInstance; } XElement affinityGroupElement = reservedIPElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; result.AffinityGroup = affinityGroupInstance; } XElement stateElement = reservedIPElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; result.State = stateInstance; } XElement inUseElement = reservedIPElement.Element(XName.Get("InUse", "http://schemas.microsoft.com/windowsazure")); if (inUseElement != null) { bool inUseInstance = bool.Parse(inUseElement.Value); result.InUse = inUseInstance; } XElement serviceNameElement = reservedIPElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; result.ServiceName = serviceNameInstance; } XElement deploymentNameElement = reservedIPElement.Element(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure")); if (deploymentNameElement != null) { string deploymentNameInstance = deploymentNameElement.Value; result.DeploymentName = deploymentNameInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Preview Only. The List Reserved IP operation retrieves the virtual /// IPs reserved for the subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Preview Only. The response structure for the Server List operation /// </returns> public async Task<NetworkReservedIPListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/networking/reservedips"; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.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), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result NetworkReservedIPListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new NetworkReservedIPListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement reservedIPsSequenceElement = responseDoc.Element(XName.Get("ReservedIPs", "http://schemas.microsoft.com/windowsazure")); if (reservedIPsSequenceElement != null) { foreach (XElement reservedIPsElement in reservedIPsSequenceElement.Elements(XName.Get("ReservedIP", "http://schemas.microsoft.com/windowsazure"))) { NetworkReservedIPListResponse.ReservedIP reservedIPInstance = new NetworkReservedIPListResponse.ReservedIP(); result.ReservedIPs.Add(reservedIPInstance); XElement nameElement = reservedIPsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; reservedIPInstance.Name = nameInstance; } XElement addressElement = reservedIPsElement.Element(XName.Get("Address", "http://schemas.microsoft.com/windowsazure")); if (addressElement != null) { string addressInstance = addressElement.Value; reservedIPInstance.Address = addressInstance; } XElement idElement = reservedIPsElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; reservedIPInstance.Id = idInstance; } XElement labelElement = reservedIPsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; reservedIPInstance.Label = labelInstance; } XElement affinityGroupElement = reservedIPsElement.Element(XName.Get("AffinityGroup", "http://schemas.microsoft.com/windowsazure")); if (affinityGroupElement != null) { string affinityGroupInstance = affinityGroupElement.Value; reservedIPInstance.AffinityGroup = affinityGroupInstance; } XElement stateElement = reservedIPsElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { string stateInstance = stateElement.Value; reservedIPInstance.State = stateInstance; } XElement inUseElement = reservedIPsElement.Element(XName.Get("InUse", "http://schemas.microsoft.com/windowsazure")); if (inUseElement != null) { bool inUseInstance = bool.Parse(inUseElement.Value); reservedIPInstance.InUse = inUseInstance; } XElement serviceNameElement = reservedIPsElement.Element(XName.Get("ServiceName", "http://schemas.microsoft.com/windowsazure")); if (serviceNameElement != null) { string serviceNameInstance = serviceNameElement.Value; reservedIPInstance.ServiceName = serviceNameInstance; } XElement deploymentNameElement = reservedIPsElement.Element(XName.Get("DeploymentName", "http://schemas.microsoft.com/windowsazure")); if (deploymentNameElement != null) { string deploymentNameInstance = deploymentNameElement.Value; reservedIPInstance.DeploymentName = deploymentNameInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using UnityEngine; [ExecuteInEditMode] public class PotOrbit : MonoBehaviour { public GameObject target; MeshRenderer render; SkinnedMeshRenderer srender; MeshFilter filter; public float distance = 10.0f; public float xSpeed = 250.0f; public float ySpeed = 120.0f; public float zSpeed = 120.0f; public float yMinLimit = -20.0f; public float yMaxLimit = 80.0f; public float xMinLimit = -20.0f; public float xMaxLimit = 20.0f; private float x = 0.0f; private float y = 0.0f; private Vector3 center; public bool Dynamic = false; public Vector3 offset; public Vector3 EditTest; Vector3 tpos = new Vector3(); // target pos void Start() { NewTarget(target); if ( target ) { tpos = target.transform.position; Vector3 angles = Quaternion.LookRotation(tpos - transform.position).eulerAngles; x = angles.y; y = angles.x; distance = (tpos - transform.position).magnitude; } else { Vector3 angles = transform.eulerAngles; x = angles.y; y = angles.x; } nx = x; ny = y; nz = distance; vx = 0.0f; vy = 0.0f; // Make the rigid body not change rotation Rigidbody rb = GetComponent<Rigidbody>(); if ( rb ) rb.freezeRotation = true; } private float easeInOutQuint(float start, float end, float value) { value /= .5f; end -= start; if ( value < 1 ) return end / 2 * value * value * value * value * value + start; value -= 2; return end / 2 * (value * value * value * value * value + 2) + start; } float easeInQuad(float start, float end, float value) { value /= 1.0f; end -= start; return end * value * value + start; } float easeInSine(float start, float end, float value) { end -= start; return -end * Mathf.Cos(value / 1.0f * (Mathf.PI / 2.0f)) + end + start; } float t = 0.0f; public void NewTarget(GameObject targ) { if ( target != targ ) { target = targ; t = 0.0f; if ( target ) { filter = (MeshFilter)target.GetComponent(typeof(MeshFilter)); if ( filter != null ) { //center = filter.mesh.bounds.center; center = filter.sharedMesh.bounds.center; } else { render = (MeshRenderer)target.GetComponent(typeof(MeshRenderer)); if ( render != null ) center = render.bounds.center; else { srender = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer)); if ( srender != null ) center = srender.bounds.center; } } } } } public float trantime = 4.0f; float vx = 0.0f; float vy = 0.0f; float vz = 0.0f; public float nx = 0.0f; public float ny = 0.0f; public float nz = 0.0f; public float delay = 0.2f; public float delayz = 0.2f; public float mindist = 1.0f; void LateUpdate() { if ( target ) { if ( Input.GetMouseButton(1) ) { nx = x + Input.GetAxis("Mouse X") * xSpeed * 0.02f; ny = y - Input.GetAxis("Mouse Y") * ySpeed * 0.02f; } if ( !Application.isPlaying ) { x = nx; y = ny; } else { x = Mathf.SmoothDamp(x, nx, ref vx, delay); //0.21f); //, 100.0f, Time.deltaTime); y = Mathf.SmoothDamp(y, ny, ref vy, delay); //0.21f); //, 100.0f, Time.deltaTime); } // NOTE: If you get an exception for this line it means you dont have a scroll wheel input setup in // the input manager, go to Edit/Project Settings/Input and set the Mouse ScrollWheel setting to use 3rd mouse axis nz = nz - (Input.GetAxis("Mouse ScrollWheel") * zSpeed); y = ClampAngle(y, yMinLimit, yMaxLimit); //x = ClampAngle(x, xMinLimit, xMaxLimit); if ( !Application.isPlaying ) { distance = nz; } else distance = Mathf.SmoothDamp(distance, nz, ref vz, delayz); //Vector3 crot = transform.localRotation.eulerAngles; if ( distance < mindist ) { distance = mindist; nz = mindist; } Vector3 c; if ( Dynamic ) { if ( filter != null ) { c = target.transform.TransformPoint(filter.mesh.bounds.center + offset); } else { if ( render != null ) c = target.transform.TransformPoint(render.bounds.center + offset); else { if ( srender != null ) c = target.transform.TransformPoint(srender.bounds.center + offset); else c = target.transform.TransformPoint(center + offset); } } } else c = target.transform.TransformPoint(center + offset); // Want to ease to new target pos if ( t < trantime ) { t = trantime; //+= Time.deltaTime; tpos.x = easeInSine(tpos.x, c.x, t / trantime); tpos.y = easeInSine(tpos.y, c.y, t / trantime); tpos.z = easeInSine(tpos.z, c.z, t / trantime); } else tpos = c; Quaternion rotation = Quaternion.Euler(y, x, 0.0f); Vector3 position = rotation * new Vector3(0.0f, 0.0f, -distance) + tpos; //c; transform.rotation = rotation; transform.position = position; } } static float ClampAngle(float angle, float min, float max) { if ( angle < -360.0f ) angle += 360.0f; if ( angle > 360.0f ) angle -= 360.0f; return Mathf.Clamp(angle, min, max); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: Managed ACL wrapper for Win32 semaphores. ** ** ===========================================================*/ using System; using System.Collections; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Security.AccessControl { // Derive this list of values from winnt.h and MSDN docs: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp // Win32's interesting values are SEMAPHORE_MODIFY_STATE (0x2) and // SEMAPHORE_ALL_ACCESS (0x1F0003). I don't know what 0x1 is. [Flags] public enum SemaphoreRights { Modify = 0x000002, Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, Synchronize = 0x100000, // SYNCHRONIZE FullControl = 0x1F0003 } public sealed class SemaphoreAccessRule : AccessRule { // Constructor for creating access rules for registry objects public SemaphoreAccessRule(IdentityReference identity, SemaphoreRights eventRights, AccessControlType type) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public SemaphoreAccessRule(String identity, SemaphoreRights eventRights, AccessControlType type) : this(new NTAccount(identity), (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal SemaphoreAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } public SemaphoreRights SemaphoreRights { get { return (SemaphoreRights)base.AccessMask; } } } public sealed class SemaphoreAuditRule : AuditRule { public SemaphoreAuditRule(IdentityReference identity, SemaphoreRights eventRights, AuditFlags flags) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } internal SemaphoreAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } public SemaphoreRights SemaphoreRights { get { return (SemaphoreRights)base.AccessMask; } } } public sealed class SemaphoreSecurity : NativeObjectSecurity { public SemaphoreSecurity() : base(true, ResourceType.KernelObject) { } public SemaphoreSecurity(String name, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, name, includeSections, HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } internal SemaphoreSecurity(SafeWaitHandle handle, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, handle, includeSections, HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } private static Exception HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Interop.Errors.ERROR_INVALID_NAME: case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_FILE_NOT_FOUND: if ((name != null) && (name.Length != 0)) exception = new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); else exception = new WaitHandleCannotBeOpenedException(); break; } return exception; } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new SemaphoreAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new SemaphoreAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules |= AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } internal void Persist(SafeWaitHandle handle) { // Let the underlying ACL API's demand unmanaged code. WriteLock(); try { AccessControlSections persistSections = GetAccessControlSectionsFromChanges(); if (persistSections == AccessControlSections.None) return; // Don't need to persist anything. base.Persist(handle, persistSections); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } public void AddAccessRule(SemaphoreAccessRule rule) { base.AddAccessRule(rule); } public void SetAccessRule(SemaphoreAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(SemaphoreAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(SemaphoreAccessRule rule) { return base.RemoveAccessRule(rule); } public void RemoveAccessRuleAll(SemaphoreAccessRule rule) { base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(SemaphoreAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } public void AddAuditRule(SemaphoreAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(SemaphoreAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(SemaphoreAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(SemaphoreAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(SemaphoreAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override Type AccessRightType { get { return typeof(SemaphoreRights); } } public override Type AccessRuleType { get { return typeof(SemaphoreAccessRule); } } public override Type AuditRuleType { get { return typeof(SemaphoreAuditRule); } } } }
// 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 SubtractByte() { var test = new SimpleBinaryOpTest__SubtractByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } 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__SubtractByte { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / sizeof(Byte); private const int RetElementCount = VectorSize / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable; static SimpleBinaryOpTest__SubtractByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__SubtractByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Subtract( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Subtract( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Subtract( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Subtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.Subtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__SubtractByte(); var result = Sse2.Subtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Subtract(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "") { if ((byte)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((byte)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using ESRI.ArcGIS.esriSystem; namespace GeoprocessingInDotNet { class Module1 { private static LicenseInitializer m_AOLicenseInitializer = new GeoprocessingInDotNet.LicenseInitializer(); [STAThread()] static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine }, new esriLicenseExtensionCode[] { }); //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDownApplication() m_AOLicenseInitializer.ShutdownApplication(); //Call the main execution of the application RunTheApp(); } // INSTRUCTIONS: // // 1. Create the following directories on your hard drive: // C:\gp // C:\gp\AirportsAndGolf // C:\gp\output // // 2. Copy the RunModel.xml file in this sample to C:\gp // // 3. Copy all of the shapefile sample data in the directory: // <your ArcGIS Developer Kit installation location>\Samples\data\AirportsAndGolf // to: // C:\gp\AirportsAndGolf // // 4. You must create a .NET Assembly from the custom model MY_CUSTOM_TOOLBOX.tbx // that is provided with this sample. To create the .NET Assembly do the following: // Right click on the project name in the Solution Explorer and choose 'Add ArcGIS Toolbox Reference...' // In the ArcGIS Toolbox Reference dialog that opens: // - For the Toolbox: Navigate to the MY_CUSTOM_TOOLBOX.tbx in this sample // - Accept the defaults for the 'Generated Assembly Name' and 'Generated Assembly Namespace' // - Specify the 'Generated Assembly Version' to be: 1.0.0.0 // - Uncheck the 'Sign the Generated Assembly' // - Click OK // // 5. You should now be able to compile this sample and run it. /// <summary> /// Main execution of our application /// </summary> /// <remarks></remarks> public static void RunTheApp() { // Give message prompting the user for input Console.WriteLine("Enter the full path/filename of the xml driver file for the application."); Console.WriteLine("Example: C:\\gp\\RunModel.xml"); Console.Write(">"); // Obtain the input from the user System.String xmlPathFile = Console.ReadLine(); // Let the user know something is happening Console.WriteLine("Processing..."); //Get all of the models parameters System.Collections.Specialized.HybridDictionary modelParametersHybridDictionary = ReadXMLConfigurationFile(xmlPathFile); // Run the model System.String modelProcessingResultsString = ExecuteCustomGeoprocessingFunction(modelParametersHybridDictionary); // Display the results to the user Console.WriteLine(modelProcessingResultsString); // Close the application after the users hits any key Console.ReadLine(); } /// <summary> /// Read in the arguments from the .xml file that we be used to run our model /// </summary> /// <param name="xmlPathFile">The full path and filename of the .xml file. Example: "C:\gp\RunModel.xml"</param> /// <returns>A HybridDictionary that contains the arguments to run our model.</returns> /// <remarks></remarks> public static System.Collections.Specialized.HybridDictionary ReadXMLConfigurationFile(System.String xmlPathFile) { System.Collections.Specialized.HybridDictionary modelParametersHybridDictionary = new System.Collections.Specialized.HybridDictionary(); try { //Read the XML configuration file System.Xml.XmlDocument XMLdoc = new System.Xml.XmlDocument(); XMLdoc.Load(xmlPathFile); // MY_CUSTOM_TOOLBOX System.Xml.XmlNode xMY_CUSTOM_TOOLBOX = XMLdoc["MY_CUSTOM_TOOLBOX"]; // GolfFinder System.Xml.XmlNode xGolfFinder = xMY_CUSTOM_TOOLBOX["GolfFinder"]; // BufferDistance System.Xml.XmlNode xBufferDistance = xGolfFinder["BufferDistance"]; modelParametersHybridDictionary.Add("BufferDistance", xBufferDistance.InnerText); // Airports System.Xml.XmlNode xAirports = xGolfFinder["Airports"]; modelParametersHybridDictionary.Add("Airports", xAirports.InnerText); // Golf System.Xml.XmlNode xGolf = xGolfFinder["Golf"]; modelParametersHybridDictionary.Add("Golf", xGolf.InnerText); // AirportBuffer System.Xml.XmlNode xAirportBuffer = xGolfFinder["AirportBuffer"]; modelParametersHybridDictionary.Add("AirportBuffer", xAirportBuffer.InnerText); // GolfNearAirports System.Xml.XmlNode xGolfNearAirports = xGolfFinder["GolfNearAirports"]; modelParametersHybridDictionary.Add("GolfNearAirports", xGolfNearAirports.InnerText); return modelParametersHybridDictionary; } catch (Exception ex) { //The XML read was unsuccessful. Return an empty HybridDictionary return modelParametersHybridDictionary; } } /// <summary> /// Run the Geoprocessing model /// </summary> /// <param name="modelParametersHybridDictionary">A HybridDictionary that contains all of the arguments to run the model</param> /// <returns>A message of how well the model executed</returns> /// <remarks></remarks> public static System.String ExecuteCustomGeoprocessingFunction(System.Collections.Specialized.HybridDictionary modelParametersHybridDictionary) { try { // Create a Geoprocessor object ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor(); // Set the OverwriteOutput setting to True gp.OverwriteOutput = true; // Create a new instance of our custom model MYCUSTOMTOOLBOX.GolfFinder myModel = new MYCUSTOMTOOLBOX.GolfFinder(); // Set the custom models parameters. myModel.BufferDistance = modelParametersHybridDictionary["BufferDistance"]; myModel.AIRPORT = modelParametersHybridDictionary["Airports"]; myModel.GOLF = modelParametersHybridDictionary["Golf"]; myModel.AirportBuffer = modelParametersHybridDictionary["AirportBuffer"]; myModel.Golf_Courses_Near_Airports = modelParametersHybridDictionary["GolfNearAirports"]; // Execute the model and obtain the result from the run ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult geoProcessorResult = (ESRI.ArcGIS.Geoprocessing.IGeoProcessorResult)gp.Execute(myModel, null); if (geoProcessorResult == null) { // We have an error running the model. // If the run fails a Nothing (VB.NET) or null (C#) is returned from the gp.Execute object sev = 2; string messages = gp.GetMessages(ref sev); return messages; } else { // The model completed successfully return "Output successful. The shapefiles are locacted at: " + geoProcessorResult.ReturnValue.ToString(); } } catch (Exception ex) { // Catch any other errors return "Error running the model. Debug the application and test again."; } } } }
// 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.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentStackTests { [Fact] public static void Test0_Empty() { ConcurrentStack<int> s = new ConcurrentStack<int>(); int item; Assert.False(s.TryPop(out item), "Test0_Empty: TryPop returned true when the stack is empty"); Assert.False(s.TryPeek(out item), "Test0_Empty: TryPeek returned true when the stack is empty"); Assert.True(s.TryPopRange(new int[1]) == 0, "Test0_Empty: TryPopRange returned non zero when the stack is empty"); int count = 15; for (int i = 0; i < count; i++) s.Push(i); Assert.Equal(count, s.Count); Assert.False(s.IsEmpty); } [Fact] public static void Test1_PushAndPop() { Test1_PushAndPop(0, 0); Test1_PushAndPop(9, 9); } [Fact] [OuterLoop] public static void Test1_PushAndPop01() { Test1_PushAndPop(3, 0); Test1_PushAndPop(1024, 512); } [Fact] public static void Test2_ConcPushAndPop() { Test2_ConcPushAndPop(3, 1024, 0); } [Fact] public static void Test2_ConcPushAndPop01() { Test2_ConcPushAndPop(8, 1024, 512); } [Fact] public static void Test3_Clear() { Test3_Clear(0); Test3_Clear(16); Test3_Clear(1024); } [Fact] public static void Test4_Enumerator() { Test4_Enumerator(0); Test4_Enumerator(16); } [Fact] [OuterLoop] public static void Test4_Enumerator01() { Test4_Enumerator(1024); } [Fact] public static void Test5_CtorAndCopyToAndToArray() { Test5_CtorAndCopyToAndToArray(0); Test5_CtorAndCopyToAndToArray(16); } [Fact] [OuterLoop] public static void Test5_CtorAndCopyToAndToArray01() { Test5_CtorAndCopyToAndToArray(1024); } [Fact] public static void Test6_PushRange() { Test6_PushRange(8, 10); Test6_PushRange(16, 100); } [Fact] public static void Test7_PopRange() { Test7_PopRange(8, 10); Test7_PopRange(16, 100); } [Fact] [OuterLoop] public static void Test_PushPopRange() { Test6_PushRange(128, 100); Test7_PopRange(128, 100); } // Pushes and pops a certain number of times, and validates the resulting count. // These operations happen sequentially in a somewhat-interleaved fashion. We use // a BCL stack on the side to validate contents are correctly maintained. private static void Test1_PushAndPop(int pushes, int pops) { // It utilized a random generator to do x number of pushes and // y number of pops where x = random, y = random. Removed it // because it used System.Runtime.Extensions. ConcurrentStack<int> s = new ConcurrentStack<int>(); Stack<int> s2 = new Stack<int>(); int donePushes = 0, donePops = 0; while (donePushes < pushes || donePops < pops) { for (int i = 0; i < 10; i++) { if (donePushes == pushes) break; int val = i; s.Push(val); s2.Push(val); donePushes++; Assert.Equal(s.Count, s2.Count); } for (int i = 0; i < 6; i++) { if (donePops == pops) break; if ((donePushes - donePops) <= 0) break; int e0, e1, e2; bool b0 = s.TryPeek(out e0); bool b1 = s.TryPop(out e1); e2 = s2.Pop(); donePops++; Assert.True(b0); Assert.True(b1); Assert.Equal(e0, e1); Assert.Equal(e1, e2); Assert.Equal(s.Count, s2.Count); } } Assert.Equal(pushes - pops, s.Count); } // Pushes and pops a certain number of times, and validates the resulting count. // These operations happen concurrently. private static void Test2_ConcPushAndPop(int threads, int pushes, int pops) { // It utilized a random generator to do x number of pushes and // y number of pops where x = random, y = random. Removed it // because it used System.Runtime.Extensions. ConcurrentStack<int> s = new ConcurrentStack<int>(); ManualResetEvent mre = new ManualResetEvent(false); Task[] tt = new Task[threads]; // Create all threads. for (int k = 0; k < tt.Length; k++) { tt[k] = Task.Run(delegate() { mre.WaitOne(); int donePushes = 0, donePops = 0; while (donePushes < pushes || donePops < pops) { for (int i = 0; i < 8; i++) { if (donePushes == pushes) break; s.Push(i); donePushes++; } for (int i = 0; i < 4; i++) { if (donePops == pops) break; if ((donePushes - donePops) <= 0) break; int e; if (s.TryPop(out e)) donePops++; } } }); } // Kick 'em off and wait for them to finish. mre.Set(); Task.WaitAll(tt); // Validate the count. Assert.Equal(threads * (pushes - pops), s.Count); } // Just validates clearing the stack's contents. private static void Test3_Clear(int count) { ConcurrentStack<int> s = new ConcurrentStack<int>(); for (int i = 0; i < count; i++) s.Push(i); s.Clear(); Assert.True(s.IsEmpty); Assert.Equal(0, s.Count); } // Just validates enumerating the stack. private static void Test4_Enumerator(int count) { ConcurrentStack<int> s = new ConcurrentStack<int>(); for (int i = 0; i < count; i++) s.Push(i); // Test enumerator. int j = count - 1; foreach (int x in s) { // Clear the stack to ensure concurrent modifications are dealt w/. if (x == count - 1) { int e; while (s.TryPop(out e)) ; } Assert.Equal(j, x); j--; } Assert.True(j <= 0, " > did not enumerate all elements in the stack"); } // Instantiates the stack w/ the enumerator ctor and validates the resulting copyto & toarray. private static void Test5_CtorAndCopyToAndToArray(int count) { int[] arr = new int[count]; for (int i = 0; i < count; i++) arr[i] = i; ConcurrentStack<int> s = new ConcurrentStack<int>(arr); // try toarray. int[] sa1 = s.ToArray(); Assert.Equal(arr.Length, sa1.Length); for (int i = 0; i < sa1.Length; i++) { Assert.Equal(arr[count - i - 1], sa1[i]); } int[] sa2 = new int[count]; s.CopyTo(sa2, 0); Assert.Equal(arr.Length, sa2.Length); for (int i = 0; i < sa2.Length; i++) { Assert.Equal(arr[count - i - 1], sa2[i]); } object[] sa3 = new object[count]; // test array variance. ((System.Collections.ICollection)s).CopyTo(sa3, 0); Assert.Equal(arr.Length, sa3.Length); for (int i = 0; i < sa3.Length; i++) { Assert.Equal(arr[count - i - 1], (int)sa3[i]); } } //Tests COncurrentSTack.PushRange private static void Test6_PushRange(int NumOfThreads, int localArraySize) { ConcurrentStack<int> stack = new ConcurrentStack<int>(); Task[] threads = new Task[NumOfThreads]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Factory.StartNew((obj) => { int index = (int)obj; int[] array = new int[localArraySize]; for (int j = 0; j < localArraySize; j++) { array[j] = index + j; } stack.PushRange(array); }, i * localArraySize, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } Task.WaitAll(threads); //validation for (int i = 0; i < threads.Length; i++) { int lastItem = -1; for (int j = 0; j < localArraySize; j++) { int currentItem = 0; Assert.True(stack.TryPop(out currentItem), String.Format("* Test6_PushRange({0},{1})L TryPop returned false.", NumOfThreads, localArraySize)); Assert.True((lastItem <= -1) || lastItem - currentItem == 1, String.Format("* Test6_PushRange({0},{1}): Failed {2} - {3} shouldn't be consecutive", NumOfThreads, localArraySize, lastItem, currentItem)); lastItem = currentItem; } } } //Tests ConcurrentStack.PopRange by pushing consecutive numbers and run n threads each thread tries to pop m itmes // the popped m items should be consecutive private static void Test7_PopRange(int NumOfThreads, int elementsPerThread) { int lastValue = NumOfThreads * elementsPerThread; List<int> allValues = new List<int>(); for (int i = 1; i <= lastValue; i++) allValues.Add(i); ConcurrentStack<int> stack = new ConcurrentStack<int>(allValues); Task[] threads = new Task[NumOfThreads]; int[] array = new int[threads.Length * elementsPerThread]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Factory.StartNew((obj) => { int index = (int)obj; int res = stack.TryPopRange(array, index, elementsPerThread); Assert.Equal(elementsPerThread, res); }, i * elementsPerThread, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } Task.WaitAll(threads); // validation for (int i = 0; i < NumOfThreads; i++) { for (int j = 1; j < elementsPerThread; j++) { int currentIndex = i * elementsPerThread + j; Assert.Equal(array[currentIndex - 1], array[currentIndex] + 1); } } } [Fact] public static void Test8_Exceptions() { ConcurrentStack<int> stack = null; Assert.Throws<ArgumentNullException>( () => stack = new ConcurrentStack<int>((IEnumerable<int>)null)); // "Test8_Exceptions: The constructor didn't throw ANE when null collection passed"); stack = new ConcurrentStack<int>(); //CopyTo Assert.Throws<ArgumentNullException>( () => stack.CopyTo(null, 0)); // "Test8_Exceptions: CopyTo didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.CopyTo(new int[1], -1)); // "Test8_Exceptions: CopyTo didn't throw AORE when negative array index passed"); //PushRange Assert.Throws<ArgumentNullException>( () => stack.PushRange(null)); // "Test8_Exceptions: PushRange didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], 0, -1)); // "Test8_Exceptions: PushRange didn't throw AORE when negative count passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], -1, 1)); // "Test8_Exceptions: PushRange didn't throw AORE when negative index passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], 2, 1)); // "Test8_Exceptions: PushRange didn't throw AORE when start index > array length"); Assert.Throws<ArgumentException>( () => stack.PushRange(new int[1], 0, 10)); // "Test8_Exceptions: PushRange didn't throw AE when count + index > array length"); //PopRange Assert.Throws<ArgumentNullException>( () => stack.TryPopRange(null)); // "Test8_Exceptions: TryPopRange didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], 0, -1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when negative count passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], -1, 1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when negative index passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], 2, 1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when start index > array length"); Assert.Throws<ArgumentException>( () => stack.TryPopRange(new int[1], 0, 10)); // "Test8_Exceptions: TryPopRange didn't throw AE when count + index > array length"); } [Fact] public static void Test9_Interfaces_Negative() { ConcurrentStack<int> stack = new ConcurrentStack<int>(); ICollection collection = stack; Assert.Throws<ArgumentNullException>( () => collection.CopyTo(null, 0)); // "TestICollection: ICollection.CopyTo didn't throw ANE when null collection passed for collection type: ConcurrentStack"); Assert.Throws<NotSupportedException>( () => { object obj = collection.SyncRoot; }); // "TestICollection: ICollection.SyncRoot didn't throw NotSupportedException! for collection type: ConcurrentStack"); } [Fact] public static void Test10_DebuggerAttributes() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ConcurrentStack<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ConcurrentStack<int>()); } [Fact] public static void Test9_Interfaces() { ConcurrentStack<int> stack = new ConcurrentStack<int>(); IProducerConsumerCollection<int> ipcc = stack; Assert.Equal(0, ipcc.Count); int item; Assert.False(ipcc.TryTake(out item)); Assert.True(ipcc.TryAdd(1)); ICollection collection = stack; Assert.False(collection.IsSynchronized); stack.Push(1); int count = stack.Count; IEnumerable enumerable = stack; foreach (object o in enumerable) count--; Assert.Equal(0, count); } } }
namespace Log4NetTools.ViewModels { using System; using System.Globalization; using System.IO; using System.Windows.Input; using Edi.Core.Interfaces.Documents; using Edi.Core.ViewModels.Command; using MsgBox; public class Log4NetViewModel : Edi.Core.ViewModels.FileBaseViewModel { #region fields public const string DocumentKey = "Log4NetView"; public const string Description = "Log4Net"; public const string FileFilterName = "Log4Net"; public const string DefaultFilter = "log4j"; private static int iNewFileCounter = 1; private string defaultFileType = "log4j"; private readonly static string defaultFileName = Edi.Util.Local.Strings.STR_FILE_DEFAULTNAME; private YalvLib.ViewModel.YalvViewModel mYalvVM = null; #endregion fields #region constructor /// <summary> /// ViewModel Class Constructor /// </summary> public Log4NetViewModel(IMessageBoxService msgBox) : base(Log4NetViewModel.DocumentKey, msgBox) { this.ScreenTip = Edi.Util.Local.Strings.STR_LOG4NET_DOCUMENTTAB_TT; this.ContentId = string.Empty; this.IsReadOnlyReason = Edi.Util.Local.Strings.STR_LOG4NET_READONY_REASON; this.FilePath = string.Format(CultureInfo.InvariantCulture, "{0} {1}.{2}", Log4NetViewModel.defaultFileName, Log4NetViewModel.iNewFileCounter++, this.defaultFileType); this.mYalvVM = new YalvLib.ViewModel.YalvViewModel(); } #endregion constructor #region properties public string ScreenTip { get; set; } public string IsReadOnlyReason { get; set; } #region FilePath private string mFilePath = null; /// <summary> /// Get/set complete path including file name to where this stored. /// This string is never null or empty. /// </summary> override public string FilePath { get { if (this.mFilePath == null || this.mFilePath == String.Empty) return string.Format(CultureInfo.CurrentCulture, "{0}.{1}", Log4NetViewModel.defaultFileName, this.defaultFileType); return this.mFilePath; } protected set { if (this.mFilePath != value) { this.mFilePath = value; this.RaisePropertyChanged(() => this.FilePath); this.RaisePropertyChanged(() => this.FileName); this.RaisePropertyChanged(() => this.Title); } } } #endregion #region Title /// <summary> /// Title is the string that is usually displayed - with or without dirty mark '*' - in the docking environment /// </summary> public override string Title { get { return this.FileName + (this.IsDirty == true ? "*" : string.Empty); } } #endregion #region FileName /// <summary> /// FileName is the string that is displayed whenever the application refers to this file, as in: /// string.Format(CultureInfo.CurrentCulture, "Would you like to save the '{0}' file", FileName) /// /// Note the absense of the dirty mark '*'. Use the Title property if you want to display the file /// name with or without dirty mark when the user has edited content. /// </summary> public override string FileName { get { // This option should never happen - its an emergency break for those cases that never occur if (FilePath == null || FilePath == String.Empty) return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", Log4NetViewModel.defaultFileName, this.defaultFileType); return System.IO.Path.GetFileName(FilePath); } } public override Uri IconSource { get { // This icon is visible in AvalonDock's Document Navigator window return new Uri("pack://application:,,,/Edi.Themes;component/Images/Documents/Log4net.png", UriKind.RelativeOrAbsolute); } } #endregion FileName #region DocumentCommands /// <summary> /// IsDirty indicates whether the file currently loaded /// in the editor was modified by the user or not /// (this should always be false since log4net documents cannot be edit and saved). /// </summary> override public bool IsDirty { get { return false; } set { throw new NotSupportedException("Log4Net documents cannot be saved therfore setting dirty cannot be useful."); } } /// <summary> /// Get whether edited data can be saved or not. /// This type of document does not have a save /// data implementation if this property returns false. /// (this is document specific and should always be overriden by descendents) /// </summary> override public bool CanSaveData { get { return false; } } override public bool CanSave() { return false; } override public bool CanSaveAs() { return false; } override public bool SaveFile(string filePath) { throw new NotImplementedException(); } #region CloseCommand RelayCommand<object> _closeCommand = null; public override ICommand CloseCommand { get { if (_closeCommand == null) { _closeCommand = new RelayCommand<object>((p) => this.OnClose(), (p) => base.CanClose()); } return _closeCommand; } } #endregion #endregion DocumentCommands public YalvLib.ViewModel.YalvViewModel Yalv { get { return this.mYalvVM; } } #endregion properties #region methods /// <summary> /// Get the path of the file or empty string if file does not exists on disk. /// </summary> /// <returns></returns> override public string GetFilePath() { try { if (System.IO.File.Exists(this.FilePath)) return System.IO.Path.GetDirectoryName(this.FilePath); } catch { } return string.Empty; } public static Log4NetViewModel LoadFile(IDocumentModel dm, object o, IMessageBoxService msgBox) { return Log4NetViewModel.LoadFile(dm.FileNamePath, msgBox); } /// <summary> /// Load a log4net file and return the corresponding viewmodel representation for it. /// </summary> /// <param name="filePath"></param> /// <returns></returns> private static Log4NetViewModel LoadFile(string filePath, IMessageBoxService msgBox) { bool IsFilePathReal = false; try { IsFilePathReal = File.Exists(filePath); } catch { } if (IsFilePathReal == false) return null; Log4NetViewModel vm = new Log4NetViewModel(msgBox); if (vm.OpenFile(filePath) == true) return vm; return null; } /// <summary> /// Attempt to open a file and load it into the viewmodel if it exists. /// </summary> /// <param name="filePath"></param> /// <returns>True if file exists and was succesfully loaded. Otherwise false.</returns> protected bool OpenFile(string filePath) { try { var isReal = File.Exists(filePath); if (isReal == true) { this.MDocumentModel.SetFileNamePath(filePath, isReal); this.FilePath = filePath; this.ContentId = this.mFilePath; // File may be blocked by another process // Try read-only shared method and set file access to read-only try { // XXX TODO Extend log4net FileOpen method to support base.FireFileProcessingResultEvent(...); this.mYalvVM.LoadFile(filePath); } catch (Exception ex) { _MsgBox.Show(ex.Message, Edi.Util.Local.Strings.STR_FILE_OPEN_ERROR_MSG_CAPTION, MsgBoxButtons.OK); return false; } } else return false; } catch (Exception exp) { _MsgBox.Show(exp.Message, Edi.Util.Local.Strings.STR_FILE_OPEN_ERROR_MSG_CAPTION, MsgBoxButtons.OK); return false; } return true; } /// <summary> /// Reloads/Refresh's the current document content with the content /// of the from disc. /// </summary> public override void ReOpen() { try { base.ReOpen(); this.OpenFile(this.FilePath); } catch (Exception exp) { _MsgBox.Show(exp.Message, Edi.Util.Local.Strings.STR_FILE_OPEN_ERROR_MSG_CAPTION, MsgBoxButtons.OK); } } #endregion } }