context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter.Default; using Microsoft.PythonTools.Parsing; namespace Microsoft.PythonTools.Interpreter { /// <summary> /// Base class for interpreter factories that have an executable file /// following CPython command-line conventions, a standard library that is /// stored on disk as .py files, and using <see cref="PythonTypeDatabase"/> /// for the completion database. /// </summary> public class PythonInterpreterFactoryWithDatabase : IPythonInterpreterFactoryWithDatabase, IDisposable { private PythonTypeDatabase _typeDb, _typeDbWithoutPackages; private IDisposable _generating; private bool _isValid, _isCheckingDatabase, _disposed; private readonly string _databasePath; #if DEBUG private bool _hasEverCheckedDatabase; #endif private string[] _missingModules; private string _isCurrentException; private FileSystemWatcher _verWatcher; private FileSystemWatcher _verDirWatcher; private readonly object _verWatcherLock = new object(); // Only one thread can be updating our current state private readonly SemaphoreSlim _isCurrentSemaphore = new SemaphoreSlim(1); // Only four threads can be updating any state. This is to prevent I/O // saturation when multiple threads refresh simultaneously. private static readonly SemaphoreSlim _sharedIsCurrentSemaphore = new SemaphoreSlim(4); /// <summary> /// Creates a new interpreter factory backed by a type database. /// </summary> /// <remarks> /// <see cref="RefreshIsCurrent"/> must be called after creation to /// ensure the database state is correctly reflected. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public PythonInterpreterFactoryWithDatabase( InterpreterConfiguration config, InterpreterFactoryCreationOptions options ) { if (config == null) { throw new ArgumentNullException(nameof(config)); } if (options == null) { options = new InterpreterFactoryCreationOptions(); } Configuration = config; _databasePath = options.DatabasePath; // Avoid creating a interpreter with an unsupported version. // https://github.com/Microsoft/PTVS/issues/706 try { var langVer = config.Version.ToLanguageVersion(); } catch (InvalidOperationException ex) { throw new ArgumentException(ex.Message, ex); } if (!GlobalInterpreterOptions.SuppressFileSystemWatchers && options.WatchFileSystem && !string.IsNullOrEmpty(DatabasePath)) { // Assume the database is valid if the version is up to date, then // switch to invalid after we've checked. _isValid = PythonTypeDatabase.IsDatabaseVersionCurrent(DatabasePath); _isCheckingDatabase = true; _verWatcher = CreateDatabaseVerWatcher(); _verDirWatcher = CreateDatabaseDirectoryWatcher(); #if DEBUG var creationStack = new StackTrace(true).ToString(); Task.Delay(1000).ContinueWith(t => { Debug.Assert( _hasEverCheckedDatabase, "Database check was not triggered for {0}".FormatUI(Configuration.Id), creationStack ); }); #endif } else { // Assume the database is valid _isValid = true; } if (!GlobalInterpreterOptions.SuppressPackageManagers) { try { var pm = options.PackageManager; if (pm != null) { pm.SetInterpreterFactory(this); pm.InstalledFilesChanged += PackageManager_InstalledFilesChanged; PackageManager = pm; } } catch (NotSupportedException) { } } } public virtual void BeginRefreshIsCurrent() { #if DEBUG _hasEverCheckedDatabase = true; #endif Task.Run(() => RefreshIsCurrent()).DoNotWait(); } private void PackageManager_InstalledFilesChanged(object sender, EventArgs e) { BeginRefreshIsCurrent(); } public InterpreterConfiguration Configuration { get; } public IPackageManager PackageManager { get; } /// <summary> /// Returns a new interpreter created with the specified factory. /// </summary> /// <remarks> /// This is intended for use by derived classes only. To get an /// interpreter instance, use <see cref="CreateInterpreter"/>. /// </remarks> public virtual IPythonInterpreter MakeInterpreter(PythonInterpreterFactoryWithDatabase factory) { return new CPythonInterpreter(factory); } public IPythonInterpreter CreateInterpreter() { return MakeInterpreter(this); } /// <summary> /// Returns the database for this factory. This database may be shared /// between callers and should be cloned before making modifications. /// /// This function never returns null. /// </summary> public PythonTypeDatabase GetCurrentDatabase() { if (_typeDb == null || _typeDb.DatabaseDirectory != DatabasePath) { _typeDb = MakeTypeDatabase(DatabasePath) ?? PythonTypeDatabase.CreateDefaultTypeDatabase(this); } return _typeDb; } /// <summary> /// Returns the database for this factory, optionally excluding package /// analysis. This database may be shared between callers and should be /// cloned before making modifications. /// /// This function never returns null. /// </summary> public PythonTypeDatabase GetCurrentDatabase(bool includeSitePackages) { if (includeSitePackages) { return GetCurrentDatabase(); } if (_typeDbWithoutPackages == null || _typeDbWithoutPackages.DatabaseDirectory != DatabasePath) { _typeDbWithoutPackages = MakeTypeDatabase(DatabasePath, false) ?? PythonTypeDatabase.CreateDefaultTypeDatabase(this); } return _typeDbWithoutPackages; } /// <summary> /// Returns a new database loaded from the specified path. If null is /// returned, <see cref="GetCurrentDatabase"/> will assume the default /// completion DB is intended. /// </summary> /// <remarks> /// This is intended for overriding in derived classes. To get a /// queryable database instance, use <see cref="GetCurrentDatabase"/> or /// <see cref="CreateInterpreter"/>. /// </remarks> public virtual PythonTypeDatabase MakeTypeDatabase(string databasePath, bool includeSitePackages = true) { if (!string.IsNullOrEmpty(databasePath) && !IsGenerating && PythonTypeDatabase.IsDatabaseVersionCurrent(databasePath)) { var paths = new List<string>(); paths.Add(databasePath); if (includeSitePackages) { paths.AddRange(PathUtils.EnumerateDirectories(databasePath, recurse: false)); } try { return new PythonTypeDatabase(this, paths); } catch (IOException) { } catch (UnauthorizedAccessException) { } } return PythonTypeDatabase.CreateDefaultTypeDatabase(this); } public virtual void GenerateDatabase(GenerateDatabaseOptions options, Action<int> onExit = null) { if (string.IsNullOrEmpty(DatabasePath)) { onExit?.Invoke(PythonTypeDatabase.NotSupportedExitCode); return; } if (IsGenerating) { onExit?.Invoke(PythonTypeDatabase.AlreadyGeneratingExitCode); return; } var req = new PythonTypeDatabaseCreationRequest { Factory = this, OutputPath = DatabasePath, SkipUnchanged = options.HasFlag(GenerateDatabaseOptions.SkipUnchanged) }; GenerateDatabase(req, onExit); } protected virtual void GenerateDatabase(PythonTypeDatabaseCreationRequest request, Action<int> onExit = null) { // Use the NoPackageManager instance if we don't have a package // manager, so that we still get a valid disposable object while we // are generating. var generating = _generating = (request.Factory.PackageManager ?? NoPackageManager.Instance).SuppressNotifications(); PythonTypeDatabase.GenerateAsync(request).ContinueWith(t => { int exitCode; try { exitCode = t.Result; } catch (Exception ex) { Debug.Fail(ex.ToString()); exitCode = PythonTypeDatabase.InvalidOperationExitCode; } if (exitCode != PythonTypeDatabase.AlreadyGeneratingExitCode) { generating.Dispose(); Interlocked.CompareExchange(ref _generating, null, generating); } onExit?.Invoke(exitCode); }); } /// <summary> /// Called to inform the interpreter that its database cannot be loaded /// and may need to be regenerated. /// </summary> public void NotifyCorruptDatabase() { _isValid = false; OnIsCurrentChanged(); OnNewDatabaseAvailable(); } public bool IsGenerating => _generating != null; private void OnDatabaseVerChanged(object sender, FileSystemEventArgs e) { Debug.Assert(!string.IsNullOrEmpty(DatabasePath)); if ((!e.Name.Equals("database.ver", StringComparison.OrdinalIgnoreCase) && !e.Name.Equals("database.pid", StringComparison.OrdinalIgnoreCase)) || !PathUtils.IsSubpathOf(DatabasePath, e.FullPath)) { return; } RefreshIsCurrent(); if (IsCurrent) { var generating = Interlocked.Exchange(ref _generating, null); generating?.Dispose(); OnIsCurrentChanged(); // This also clears the previous database so that we load the new // one next time someone requests it. OnNewDatabaseAvailable(); } } private bool IsValid { get { return _isValid && _missingModules == null && _isCurrentException == null; } } public virtual bool IsCurrent { get { return !IsGenerating && IsValid; } } public virtual bool IsCheckingDatabase { get { return _isCheckingDatabase; } } public virtual string DatabasePath { get { return _databasePath; } } public string GetAnalysisLogContent(IFormatProvider culture) { if (string.IsNullOrEmpty(DatabasePath)) { return "No log for this interpreter"; } var analysisLog = Path.Combine(DatabasePath, "AnalysisLog.txt"); if (File.Exists(analysisLog)) { try { return File.ReadAllText(analysisLog); } catch (Exception ex) { return string.Format( culture, "Error reading {0}. Please let analysis complete and try again.\r\n{1}", analysisLog, ex ); } } return null; } /// <summary> /// Called to manually trigger a refresh of <see cref="IsCurrent"/>. /// After completion, <see cref="IsCurrentChanged"/> will always be /// raised, regardless of whether the values were changed. /// </summary> public virtual void RefreshIsCurrent() { #if DEBUG // Indicate that we've arrived here at least once. Otherwise we // will assert. _hasEverCheckedDatabase = true; #endif if (GlobalInterpreterOptions.SuppressFileSystemWatchers || string.IsNullOrEmpty(DatabasePath)) { _isCheckingDatabase = false; _isValid = true; _missingModules = null; _isCurrentException = null; OnIsCurrentChanged(); return; } if (IsGenerating) { if (PythonTypeDatabase.IsDatabaseRegenerating(DatabasePath)) { _isValid = false; _missingModules = null; _isCurrentException = null; return; } var generating = Interlocked.Exchange(ref _generating, null); generating?.Dispose(); } try { if (!_isCurrentSemaphore.Wait(0)) { // Another thread is working on our state, so we will wait for // them to finish and return, since the value is up to date. _isCurrentSemaphore.Wait(); _isCurrentSemaphore.Release(); return; } } catch (ObjectDisposedException) { // We've been disposed and the call has come in from // externally, probably a timer. return; } try { _isCheckingDatabase = true; OnIsCurrentChanged(); // Wait for a slot that will allow us to scan the disk. This // prevents too many threads from updating at once and causing // I/O saturation. _sharedIsCurrentSemaphore.Wait(); try { if (PythonTypeDatabase.IsDatabaseRegenerating(DatabasePath) || !PythonTypeDatabase.IsDatabaseVersionCurrent(DatabasePath)) { // Skip the rest of the checks, because we know we're // not current. _isValid = false; _missingModules = null; _isCurrentException = null; } else { _isValid = true; HashSet<string> existingDatabase = null; string[] missingModules = null; for (int retries = 3; retries > 0; --retries) { try { existingDatabase = GetExistingDatabase(DatabasePath); break; } catch (UnauthorizedAccessException) { } catch (IOException) { } Thread.Sleep(100); } if (existingDatabase == null) { // This will either succeed or throw again. If it throws // then the error is reported to the user. existingDatabase = GetExistingDatabase(DatabasePath); } for (int retries = 3; retries > 0; --retries) { try { missingModules = GetMissingModules(existingDatabase); break; } catch (UnauthorizedAccessException) { } catch (IOException) { } Thread.Sleep(100); } if (missingModules == null) { // This will either succeed or throw again. If it throws // then the error is reported to the user. missingModules = GetMissingModules(existingDatabase); } if (missingModules.Length > 0) { var oldModules = _missingModules; if (oldModules == null || oldModules.Length != missingModules.Length || !oldModules.SequenceEqual(missingModules)) { } _missingModules = missingModules; } else { _missingModules = null; } } _isCurrentException = null; } finally { _sharedIsCurrentSemaphore.Release(); } } catch (Exception ex) { // Report the exception text as the reason. _isCurrentException = ex.ToString(); _missingModules = null; } finally { _isCheckingDatabase = false; try { _isCurrentSemaphore.Release(); } catch (ObjectDisposedException) { // The semaphore is not locked for disposal as it is only // used to prevent reentrance into this function. As a // result, it may have been disposed while we were in here. } } OnIsCurrentChanged(); } private static HashSet<string> GetExistingDatabase(string databasePath) { Debug.Assert(!string.IsNullOrEmpty(databasePath)); return new HashSet<string>( PathUtils.EnumerateFiles(databasePath, "*.idb").Select(f => Path.GetFileNameWithoutExtension(f)), StringComparer.InvariantCultureIgnoreCase ); } /// <summary> /// Returns a sequence of module names that are required for a database. /// If any of these are missing, the database will be marked as invalid. /// </summary> private IEnumerable<string> RequiredBuiltinModules { get { if (Configuration.Version.Major == 2) { yield return "__builtin__"; } else if (Configuration.Version.Major == 3) { yield return "builtins"; } } } private string[] GetMissingModules(HashSet<string> existingDatabase) { Debug.Assert(!string.IsNullOrEmpty(DatabasePath)); var searchPaths = PythonTypeDatabase.GetCachedDatabaseSearchPaths(DatabasePath); if (searchPaths == null) { // No cached search paths means our database is out of date. return existingDatabase .Except(RequiredBuiltinModules) .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase) .ToArray(); } return PythonTypeDatabase.GetDatabaseExpectedModules(Configuration.Version, searchPaths) .SelectMany() .Select(mp => mp.ModuleName) .Concat(RequiredBuiltinModules) .Where(m => !existingDatabase.Contains(m)) .OrderBy(name => name, StringComparer.InvariantCultureIgnoreCase) .ToArray(); } public event EventHandler IsCurrentChanged; public event EventHandler NewDatabaseAvailable; protected void OnIsCurrentChanged() { IsCurrentChanged?.Invoke(this, EventArgs.Empty); } /// <summary> /// Clears any cached type databases and raises the /// <see cref="NewDatabaseAvailable"/> event. /// </summary> protected void OnNewDatabaseAvailable() { _typeDb = null; _typeDbWithoutPackages = null; NewDatabaseAvailable?.Invoke(this, EventArgs.Empty); } static string GetPackageName(string fullName) { int firstDot = fullName.IndexOf('.'); return (firstDot > 0) ? fullName.Remove(firstDot) : fullName; } public virtual string GetFriendlyIsCurrentReason(IFormatProvider culture) { if (string.IsNullOrEmpty(DatabasePath)) { return "Interpreter has no database"; } var missingModules = _missingModules; if (_isCurrentException != null) { return "An error occurred. Click Copy to get full details."; } else if (_generating != null) { return "Currently regenerating"; } else if (PackageManager == null) { return "Interpreter has no library"; } else if (!Directory.Exists(DatabasePath)) { return "Database has never been generated"; } else if (!_isValid) { return "Database is corrupt or an old version"; } else if (missingModules != null) { if (missingModules.Length < 100) { return string.Format(culture, "The following modules have not been analyzed:{0} {1}", Environment.NewLine, string.Join(Environment.NewLine + " ", missingModules) ); } else { var packages = new List<string>( from m in missingModules group m by GetPackageName(m) into groupedByPackage where groupedByPackage.Count() > 1 orderby groupedByPackage.Key select groupedByPackage.Key ); if (packages.Count > 0 && packages.Count < 100) { return string.Format(culture, "{0} modules have not been analyzed.{2}Packages include:{2} {1}", missingModules.Length, string.Join(Environment.NewLine + " ", packages), Environment.NewLine ); } else { return string.Format(culture, "{0} modules have not been analyzed.", missingModules.Length ); } } } return "Up to date"; } public virtual string GetIsCurrentReason(IFormatProvider culture) { if (string.IsNullOrEmpty(DatabasePath)) { return "Interpreter has no database"; } var missingModules = _missingModules; var reason = "Database at " + DatabasePath; if (_isCurrentException != null) { return reason + " raised an exception while refreshing:" + Environment.NewLine + _isCurrentException; } else if (_generating != null) { return reason + " is regenerating"; } else if (PackageManager == null) { return "Interpreter has no library"; } else if (!Directory.Exists(DatabasePath)) { return reason + " does not exist"; } else if (!_isValid) { return reason + " is corrupt or an old version"; } else if (missingModules != null) { return reason + " does not contain the following modules:" + Environment.NewLine + string.Join(Environment.NewLine, missingModules); } return reason + " is up to date"; } public IEnumerable<string> GetUpToDateModules() { if (!Directory.Exists(DatabasePath)) { return Enumerable.Empty<string>(); } // Currently we assume that if the file exists, it's up to date. // PyLibAnalyzer will perform timestamp checks if the user manually // refreshes. return PathUtils.EnumerateFiles(DatabasePath, "*.idb") .Select(f => Path.GetFileNameWithoutExtension(f)); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (_verWatcher != null || _verDirWatcher != null) { lock (_verWatcherLock) { if (_verWatcher != null) { _verWatcher.EnableRaisingEvents = false; _verWatcher.Dispose(); _verWatcher = null; } if (_verDirWatcher != null) { _verDirWatcher.EnableRaisingEvents = false; _verDirWatcher.Dispose(); _verDirWatcher = null; } } } (PackageManager as IDisposable)?.Dispose(); _isCurrentSemaphore.Dispose(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Directory watchers private FileSystemWatcher CreateDatabaseDirectoryWatcher() { Debug.Assert(!string.IsNullOrEmpty(DatabasePath)); FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dirName = PathUtils.GetFileOrDirectoryName(DatabasePath); var dir = Path.GetDirectoryName(DatabasePath); while (PathUtils.IsValidPath(dir) && !Directory.Exists(dir)) { dirName = PathUtils.GetFileOrDirectoryName(dir); dir = Path.GetDirectoryName(dir); } if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = dirName, NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database directory FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Created += OnDatabaseFolderChanged; watcher.Renamed += OnDatabaseFolderChanged; watcher.Deleted += OnDatabaseFolderChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion watcher.Dispose(); watcher = null; } } return null; } } private FileSystemWatcher CreateDatabaseVerWatcher() { Debug.Assert(!string.IsNullOrEmpty(DatabasePath)); FileSystemWatcher watcher = null; lock (_verWatcherLock) { var dir = DatabasePath; if (Directory.Exists(dir)) { try { watcher = new FileSystemWatcher { IncludeSubdirectories = false, Path = dir, Filter = "database.*", NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite }; } catch (ArgumentException ex) { Debug.WriteLine("Error starting database.ver FileSystemWatcher:\r\n{0}", ex); return null; } watcher.Deleted += OnDatabaseVerChanged; watcher.Created += OnDatabaseVerChanged; watcher.Changed += OnDatabaseVerChanged; try { watcher.EnableRaisingEvents = true; return watcher; } catch (IOException) { // Raced with directory deletion. Fall through and find // a parent directory that exists. watcher.Dispose(); watcher = null; } } return null; } } private void OnDatabaseFolderChanged(object sender, FileSystemEventArgs e) { lock (_verWatcherLock) { if (_verWatcher != null) { _verWatcher.EnableRaisingEvents = false; _verWatcher.Dispose(); } if (_verDirWatcher != null) { _verDirWatcher.EnableRaisingEvents = false; _verDirWatcher.Dispose(); } _verDirWatcher = CreateDatabaseDirectoryWatcher(); _verWatcher = CreateDatabaseVerWatcher(); RefreshIsCurrent(); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using PriorityQueue = Lucene.Net.Util.PriorityQueue; namespace Lucene.Net.Index { /// <summary> Allows you to iterate over the {@link TermPositions} for multiple {@link Term}s as /// a single {@link TermPositions}. /// /// </summary> public class MultipleTermPositions : TermPositions { private sealed class TermPositionsQueue:PriorityQueue { internal TermPositionsQueue(System.Collections.IList termPositions) { Initialize(termPositions.Count); System.Collections.IEnumerator i = termPositions.GetEnumerator(); while (i.MoveNext()) { TermPositions tp = (TermPositions) i.Current; if (tp.Next()) Put(tp); } } internal TermPositions Peek() { return (TermPositions) Top(); } public override bool LessThan(System.Object a, System.Object b) { return ((TermPositions) a).Doc() < ((TermPositions) b).Doc(); } } private sealed class IntQueue { public IntQueue() { InitBlock(); } private void InitBlock() { _array = new int[_arraySize]; } private int _arraySize = 16; private int _index = 0; private int _lastIndex = 0; private int[] _array; internal void add(int i) { if (_lastIndex == _arraySize) growArray(); _array[_lastIndex++] = i; } internal int next() { return _array[_index++]; } internal void sort() { System.Array.Sort(_array, _index, _lastIndex - _index); } internal void clear() { _index = 0; _lastIndex = 0; } internal int size() { return (_lastIndex - _index); } private void growArray() { int[] newArray = new int[_arraySize * 2]; Array.Copy(_array, 0, newArray, 0, _arraySize); _array = newArray; _arraySize *= 2; } } private int _doc; private int _freq; private TermPositionsQueue _termPositionsQueue; private IntQueue _posList; /// <summary> Creates a new <code>MultipleTermPositions</code> instance. /// /// </summary> /// <exception cref="IOException"> /// </exception> public MultipleTermPositions(IndexReader indexReader, Term[] terms) { System.Collections.IList termPositions = new System.Collections.ArrayList(); for (int i = 0; i < terms.Length; i++) termPositions.Add(indexReader.TermPositions(terms[i])); _termPositionsQueue = new TermPositionsQueue(termPositions); _posList = new IntQueue(); } public bool Next() { if (_termPositionsQueue.Size() == 0) return false; _posList.clear(); _doc = _termPositionsQueue.Peek().Doc(); TermPositions tp; do { tp = _termPositionsQueue.Peek(); for (int i = 0; i < tp.Freq(); i++) _posList.add(tp.NextPosition()); if (tp.Next()) _termPositionsQueue.AdjustTop(); else { _termPositionsQueue.Pop(); tp.Close(); } } while (_termPositionsQueue.Size() > 0 && _termPositionsQueue.Peek().Doc() == _doc); _posList.sort(); _freq = _posList.size(); return true; } public int NextPosition() { return _posList.next(); } public bool SkipTo(int target) { while (_termPositionsQueue.Peek() != null && target > _termPositionsQueue.Peek().Doc()) { TermPositions tp = (TermPositions) _termPositionsQueue.Pop(); if (tp.SkipTo(target)) _termPositionsQueue.Put(tp); else tp.Close(); } return Next(); } public int Doc() { return _doc; } public int Freq() { return _freq; } public void Close() { while (_termPositionsQueue.Size() > 0) ((TermPositions) _termPositionsQueue.Pop()).Close(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual void Seek(Term arg0) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual void Seek(TermEnum termEnum) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual int Read(int[] arg0, int[] arg1) { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual int GetPayloadLength() { throw new System.NotSupportedException(); } /// <summary> Not implemented.</summary> /// <throws> UnsupportedOperationException </throws> public virtual byte[] GetPayload(byte[] data, int offset) { throw new System.NotSupportedException(); } /// <summary> </summary> /// <returns> false /// </returns> // TODO: Remove warning after API has been finalized public virtual bool IsPayloadAvailable() { return false; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileServerLDAPBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileActivationMode))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileServerLDAPProfileServerLDAPStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] public partial class LocalLBProfileServerLDAP : iControlInterface { public LocalLBProfileServerLDAP() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_activation_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileActivationMode [] get_activation_mode( string [] profile_names ) { object [] results = this.Invoke("get_activation_mode", new object [] { profile_names}); return ((LocalLBProfileActivationMode [])(results[0])); } public System.IAsyncResult Beginget_activation_mode(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_activation_mode", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileActivationMode [] Endget_activation_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileActivationMode [])(results[0])); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileServerLDAPProfileServerLDAPStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileServerLDAPProfileServerLDAPStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileServerLDAPProfileServerLDAPStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileServerLDAPProfileServerLDAPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileServerLDAPProfileServerLDAPStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileServerLDAPProfileServerLDAPStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileServerLDAPProfileServerLDAPStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileServerLDAPProfileServerLDAPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_activation_mode //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void set_activation_mode( string [] profile_names, LocalLBProfileActivationMode [] modes ) { this.Invoke("set_activation_mode", new object [] { profile_names, modes}); } public System.IAsyncResult Beginset_activation_mode(string [] profile_names,LocalLBProfileActivationMode [] modes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_activation_mode", new object[] { profile_names, modes}, callback, asyncState); } public void Endset_activation_mode(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileServerLDAP", RequestNamespace="urn:iControl:LocalLB/ProfileServerLDAP", ResponseNamespace="urn:iControl:LocalLB/ProfileServerLDAP")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileServerLDAP.ProfileServerLDAPStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileServerLDAPProfileServerLDAPStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileServerLDAP.ProfileServerLDAPStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileServerLDAPProfileServerLDAPStatistics { private LocalLBProfileServerLDAPProfileServerLDAPStatisticEntry [] statisticsField; public LocalLBProfileServerLDAPProfileServerLDAPStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class CascadeDeleteBehaviorForTask : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event"); migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Event_Campaign_CampaignId", table: "Event", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSignup_Event_EventId", table: "EventSignup", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Event_EventId", table: "EventSkill", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Skill_SkillId", table: "EventSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_Event_Campaign_CampaignId", table: "Event"); migrationBuilder.DropForeignKey(name: "FK_EventSignup_Event_EventId", table: "EventSignup"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Event_EventId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_EventSkill_Skill_SkillId", table: "EventSkill"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddForeignKey( name: "FK_AllReadyTask_Event_EventId", table: "AllReadyTask", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Event_Campaign_CampaignId", table: "Event", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSignup_Event_EventId", table: "EventSignup", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Event_EventId", table: "EventSkill", column: "EventId", principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_EventSkill_Skill_SkillId", table: "EventSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSignup_AllReadyTask_TaskId", table: "TaskSignup", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.NetworkSenders { using System; using System.IO; using System.Net; using System.Net.Sockets; using NLog.Common; /// <summary> /// Sends messages over the network as UDP datagrams. /// </summary> internal class UdpNetworkSender : QueuedNetworkSender { private ISocket _socket; private EndPoint _endpoint; private readonly EventHandler<SocketAsyncEventArgs> _socketOperationCompletedAsync; private AsyncHelpersTask? _asyncBeginRequest; /// <summary> /// Initializes a new instance of the <see cref="UdpNetworkSender"/> class. /// </summary> /// <param name="url">URL. Must start with udp://.</param> /// <param name="addressFamily">The address family.</param> public UdpNetworkSender(string url, AddressFamily addressFamily) : base(url) { AddressFamily = addressFamily; _socketOperationCompletedAsync = SocketOperationCompletedAsync; } internal AddressFamily AddressFamily { get; set; } internal int MaxMessageSize { get; set; } /// <summary> /// Creates the socket. /// </summary> /// <param name="addressFamily">The address family.</param> /// <param name="socketType">Type of the socket.</param> /// <param name="protocolType">Type of the protocol.</param> /// <returns>Implementation of <see cref="ISocket"/> to use.</returns> protected internal virtual ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { var proxy = new SocketProxy(addressFamily, socketType, protocolType); Uri uri; if (Uri.TryCreate(Address, UriKind.Absolute, out uri) && uri.Host.Equals(IPAddress.Broadcast.ToString(), StringComparison.OrdinalIgnoreCase)) { proxy.UnderlyingSocket.EnableBroadcast = true; } return proxy; } protected override void DoInitialize() { _endpoint = ParseEndpointAddress(new Uri(Address), AddressFamily); _socket = CreateSocket(_endpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); } protected override void DoClose(AsyncContinuation continuation) { base.DoClose(ex => CloseSocket(continuation, ex)); } private void CloseSocket(AsyncContinuation continuation, Exception pendingException) { try { var sock = _socket; _socket = null; sock?.Close(); continuation(pendingException); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } continuation(exception); } } protected override void BeginRequest(NetworkRequestArgs eventArgs) { var socketEventArgs = new SocketAsyncEventArgs(); socketEventArgs.Completed += _socketOperationCompletedAsync; socketEventArgs.RemoteEndPoint = _endpoint; SetSocketNetworkRequest(socketEventArgs, eventArgs); // Schedule async network operation to avoid blocking socket-operation (Allow adding more request) if (_asyncBeginRequest is null) _asyncBeginRequest = new AsyncHelpersTask(BeginRequestAsync); AsyncHelpers.StartAsyncTask(_asyncBeginRequest.Value, socketEventArgs); } private void BeginRequestAsync(object state) { BeginSocketRequest((SocketAsyncEventArgs)state); } private void BeginSocketRequest(SocketAsyncEventArgs args) { bool asyncOperation = false; do { try { asyncOperation = _socket.SendToAsync(args); } catch (SocketException ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending udp request"); args.SocketError = ex.SocketErrorCode; } catch (Exception ex) { InternalLogger.Error(ex, "NetworkTarget: Error sending udp request"); if (ex.InnerException is SocketException socketException) args.SocketError = socketException.SocketErrorCode; else args.SocketError = SocketError.OperationAborted; } args = asyncOperation ? null : SocketOperationCompleted(args); } while (args != null); } private void SetSocketNetworkRequest(SocketAsyncEventArgs socketEventArgs, NetworkRequestArgs networkRequest) { var messageLength = MaxMessageSize > 0 ? Math.Min(networkRequest.RequestBufferLength, MaxMessageSize) : networkRequest.RequestBufferLength; socketEventArgs.SetBuffer(networkRequest.RequestBuffer, networkRequest.RequestBufferOffset, messageLength); socketEventArgs.UserToken = networkRequest.AsyncContinuation; } private void SocketOperationCompletedAsync(object sender, SocketAsyncEventArgs args) { var nextRequest = SocketOperationCompleted(args); if (nextRequest != null) { BeginSocketRequest(nextRequest); } } private SocketAsyncEventArgs SocketOperationCompleted(SocketAsyncEventArgs args) { Exception socketException = null; if (args.SocketError != SocketError.Success) { socketException = new IOException($"Error: {args.SocketError.ToString()}, Address: {Address}"); } if (socketException is null && (args.Buffer.Length - args.Offset) > MaxMessageSize && MaxMessageSize > 0) { var messageLength = Math.Min(args.Buffer.Length - args.Offset - MaxMessageSize, MaxMessageSize); args.SetBuffer(args.Buffer, args.Offset + MaxMessageSize, messageLength); return args; } var asyncContinuation = args.UserToken as AsyncContinuation; var nextRequest = EndRequest(asyncContinuation, socketException); if (nextRequest.HasValue) { SetSocketNetworkRequest(args, nextRequest.Value); return args; } else { args.Completed -= _socketOperationCompletedAsync; args.Dispose(); return null; } } public override void CheckSocket() { if (_socket is null) { DoInitialize(); } } } }
// =========================================================== // Copyright (c) 2014-2015, Enrico Da Ros/kendar.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. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // =========================================================== using System; using System.Collections.Generic; namespace SharpTemplate.Parsers { /// <summary> /// Parser for the .sharp files /// </summary> public class SharpParser { /// <summary> /// Parse and generate the full SharpClass text /// </summary> /// <param name="toParse"></param> /// <param name="className"></param> /// <param name="nameSpace"></param> /// <returns></returns> public string Parse(string toParse, string className, string nameSpace) { var parsed = SplitBlocks(toParse); var elaborated = GenerateBlocks(parsed); var sharpClass = GenerateClass(elaborated, className, nameSpace); return sharpClass.ToString(); } /// <summary> /// Parse and generate a single SharpClass item /// </summary> /// <param name="toParse"></param> /// <param name="className"></param> /// <param name="nameSpace"></param> /// <returns></returns> public SharpClass ParseClass(string toParse, string className, string nameSpace) { var parsed = SplitBlocks(toParse); var elaborated = GenerateBlocks(parsed); return GenerateClass(elaborated, className, nameSpace); } /// <summary> /// Iterate the block and setup the SharpClass content /// </summary> /// <param name="elaborated"></param> /// <param name="className"></param> /// <param name="nameSpace"></param> /// <returns></returns> private SharpClass GenerateClass(IEnumerable<ParserBlock> elaborated, string className, string nameSpace) { var sharpClass = new SharpClass { ClassName = className, ClassNamespace = nameSpace }; foreach (var block in elaborated) { switch (block.Blocktype) { case (ParserBlockType.Base): if (!string.IsNullOrWhiteSpace(sharpClass.Base)) throw new Exception("Duplicate Base Tag"); sharpClass.Base = block.Content; break; case (ParserBlockType.Code): sharpClass.Content += block.Content; break; case (ParserBlockType.Direct): sharpClass.Content += block.Content; break; case (ParserBlockType.Model): if (!string.IsNullOrWhiteSpace(sharpClass.Model)) throw new Exception("Duplicate Model Tag"); sharpClass.Model = block.Content; break; case (ParserBlockType.Using): sharpClass.Using.Add(block.Content); break; } } if (string.IsNullOrWhiteSpace(sharpClass.Model)) { sharpClass.Model = "object"; } return sharpClass; } /// <summary> /// Identify special blocks in .sharp files, /// </summary> /// <param name="toParse"></param> /// <returns></returns> private static IEnumerable<string> SplitBlocks(string toParse) { var parsed = new List<string>(); int prevPos = 0; int pos = toParse.IndexOf("<#", prevPos, StringComparison.OrdinalIgnoreCase); // ReSharper disable once TooWideLocalVariableScope int newPos; while (pos >= 0) { newPos = toParse.IndexOf("#>", pos, StringComparison.OrdinalIgnoreCase); if (newPos >= 0) newPos += 2; if (pos > (prevPos + 1)) { var sblock = toParse.Substring(prevPos, pos - prevPos); if (sblock.Length > 0) parsed.Add(sblock); } var block = toParse.Substring(pos, newPos - pos); if (block.Length > 0) parsed.Add(block); prevPos = Math.Max(pos, newPos); pos = toParse.IndexOf("<#", prevPos, StringComparison.OrdinalIgnoreCase); if (pos < 0) { var sblock = toParse.Substring(prevPos); if (sblock.Length > 0) parsed.Add(sblock); } } return parsed; } /// <summary> /// Setup block contents /// </summary> /// <param name="parsed"></param> /// <returns></returns> private IEnumerable<ParserBlock> GenerateBlocks(IEnumerable<string> parsed) { var elaborated = new List<ParserBlock>(); var prevIsTyped = false; foreach (var block in parsed) { if (block.StartsWith("<#")) { var sblock = block.Substring(2, block.Length - 4); if (sblock.Length > 0) { var typed = BuildCodeType(sblock); elaborated.Add(typed); prevIsTyped = typed.Blocktype != ParserBlockType.Code; } } else { if (prevIsTyped) { prevIsTyped = false; if (block == "\r\n" || block == "\r\f" || block == "\n") { continue; } } var sblock = CleanStringBlock(block); if (sblock.Length > 0) elaborated.Add(new ParserBlock(sblock)); // ReSharper disable once RedundantAssignment prevIsTyped = false; } } return elaborated; } /// <summary> /// Setup the usage of Write, to write the text /// </summary> /// <param name="block"></param> /// <returns></returns> private string CleanStringBlock(string block) { var toWrite = "\r\nWrite(\""; block = block.Replace("\\", "\\\\"); block = block.Replace("\"", "\\\""); block = block.Replace("\n", "\\n"); block = block.Replace("\r", "\\r"); block = block.Replace("\f", "\\f"); toWrite += block; return toWrite + "\");\r\n"; } /// <summary> /// Identify special block types /// </summary> /// <param name="sblock"></param> /// <returns></returns> private ParserBlock BuildCodeType(string sblock) { var content = sblock; var blockType = ParserBlockType.Code; if (sblock.StartsWith("using#")) { content = sblock.Substring("using#".Length).Trim(); blockType = ParserBlockType.Using; } else if (sblock.StartsWith("model#")) { content = sblock.Substring("model#".Length).Trim(); blockType = ParserBlockType.Model; } else if (sblock.StartsWith("base#")) { content = sblock.Substring("base#".Length).Trim(); blockType = ParserBlockType.Base; } return new ParserBlock(content, blockType); } } }
using Gaming.Core; using MatterHackers.Agg; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; using System; using System.Collections.Generic; namespace Gaming.Game { public class DataViewGraph { private ColorF SentDataLineColor = new ColorF(200, 200, 0); private ColorF ReceivedDataLineColor = new ColorF(0, 200, 20); private ColorF BoxColor = new ColorF(10, 25, 240); private double m_DataViewMinY; private double m_DataViewMaxY; private bool m_DynamiclyScaleYRange; private Vector2 m_Position; private uint m_Width; private uint m_Height; private Dictionary<String, HistoryData> m_DataHistoryArray; private int m_ColorIndex; private VertexStorage m_LinesToDraw; internal class HistoryData { private int m_Capacity; private TwoSidedStack<double> m_Data; internal double m_TotalValue; internal Color m_Color; internal HistoryData(int Capacity, IColorType Color) { m_Color = Color.ToColor(); m_Capacity = Capacity; m_Data = new TwoSidedStack<double>(); Reset(); } public int Count { get { return m_Data.Count; } } internal void Add(double Value) { if (m_Data.Count == m_Capacity) { m_TotalValue -= m_Data.PopHead(); } m_Data.PushTail(Value); m_TotalValue += Value; } internal void Reset() { m_TotalValue = 0; m_Data.Zero(); } internal double GetItem(int ItemIndex) { if (ItemIndex < m_Data.Count) { return m_Data[ItemIndex]; } else { return 0; } } internal double GetMaxValue() { double Max = -9999999999; for (int i = 0; i < m_Data.Count; i++) { if (m_Data[i] > Max) { Max = m_Data[i]; } } return Max; } internal double GetMinValue() { double Min = 9999999999; for (int i = 0; i < m_Data.Count; i++) { if (m_Data[i] < Min) { Min = m_Data[i]; } } return Min; } internal double GetAverageValue() { return m_TotalValue / m_Data.Count; } }; public DataViewGraph(Vector2 RenderPosition) : this(RenderPosition, 80, 50, 0, 0) { m_DynamiclyScaleYRange = true; } public DataViewGraph(Vector2 RenderPosition, uint Width, uint Height) : this(RenderPosition, Width, Height, 0, 0) { m_DynamiclyScaleYRange = true; } public DataViewGraph(Vector2 RenderPosition, uint Width, uint Height, double StartMin, double StartMax) { m_LinesToDraw = new VertexStorage(); m_DataHistoryArray = new Dictionary<String, HistoryData>(); m_Width = Width; m_Height = Height; m_DataViewMinY = StartMin; m_DataViewMaxY = StartMax; if (StartMin == 0 && StartMax == 0) { m_DataViewMaxY = -999999; m_DataViewMinY = 999999; } m_Position = RenderPosition; m_DynamiclyScaleYRange = false; } public double GetAverageValue(String DataType) { HistoryData TrendLine; m_DataHistoryArray.TryGetValue(DataType, out TrendLine); if (TrendLine != null) { return TrendLine.GetAverageValue(); } return 0; } public void Draw(MatterHackers.Agg.Transform.ITransform Position, Graphics2D renderer) { double TextHeight = m_Position.Y - 20; double Range = (m_DataViewMaxY - m_DataViewMinY); VertexSourceApplyTransform TransformedLinesToDraw; Stroke StrockedTransformedLinesToDraw; RoundedRect BackGround = new RoundedRect(m_Position.X, m_Position.Y - 1, m_Position.X + m_Width, m_Position.Y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround = new VertexSourceApplyTransform(BackGround, Position); renderer.Render(TransformedBackGround, new Color(0, 0, 0, .5)); // if the 0 line is within the window than draw it. if (m_DataViewMinY < 0 && m_DataViewMaxY > 0) { m_LinesToDraw.remove_all(); m_LinesToDraw.MoveTo(m_Position.X, m_Position.Y + ((0 - m_DataViewMinY) * m_Height / Range)); m_LinesToDraw.LineTo(m_Position.X + m_Width, m_Position.Y + ((0 - m_DataViewMinY) * m_Height / Range)); TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, new Color(0, 0, 0, 1)); } double MaxMax = -999999999; double MinMin = 999999999; double MaxAverage = 0; foreach (KeyValuePair<String, HistoryData> historyKeyValue in m_DataHistoryArray) { HistoryData history = historyKeyValue.Value; m_LinesToDraw.remove_all(); MaxMax = System.Math.Max(MaxMax, history.GetMaxValue()); MinMin = System.Math.Min(MinMin, history.GetMinValue()); MaxAverage = System.Math.Max(MaxAverage, history.GetAverageValue()); for (int i = 0; i < m_Width - 1; i++) { if (i == 0) { m_LinesToDraw.MoveTo(m_Position.X + i, m_Position.Y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } else { m_LinesToDraw.LineTo(m_Position.X + i, m_Position.Y + ((history.GetItem(i) - m_DataViewMinY) * m_Height / Range)); } } TransformedLinesToDraw = new VertexSourceApplyTransform(m_LinesToDraw, Position); StrockedTransformedLinesToDraw = new Stroke(TransformedLinesToDraw); renderer.Render(StrockedTransformedLinesToDraw, history.m_Color); String Text = historyKeyValue.Key + ": Min:" + MinMin.ToString("0.0") + " Max:" + MaxMax.ToString("0.0"); renderer.DrawString(Text, m_Position.X, TextHeight - m_Height); TextHeight -= 20; } RoundedRect BackGround2 = new RoundedRect(m_Position.X, m_Position.Y - 1, m_Position.X + m_Width, m_Position.Y - 1 + m_Height + 2, 5); VertexSourceApplyTransform TransformedBackGround2 = new VertexSourceApplyTransform(BackGround2, Position); Stroke StrockedTransformedBackGround = new Stroke(TransformedBackGround2); renderer.Render(StrockedTransformedBackGround, new Color(0.0, 0, 0, 1)); //renderer.Color = BoxColor; //renderer.DrawRect(m_Position.x, m_Position.y - 1, m_Width, m_Height + 2); } public void AddData(String DataType, double NewData) { if (m_DynamiclyScaleYRange) { m_DataViewMaxY = System.Math.Max(m_DataViewMaxY, NewData); m_DataViewMinY = System.Math.Min(m_DataViewMinY, NewData); } if (!m_DataHistoryArray.ContainsKey(DataType)) { Color LineColor = new Color(255, 255, 255); switch (m_ColorIndex++ % 3) { case 0: LineColor = new Color(255, 55, 55); break; case 1: LineColor = new Color(55, 255, 55); break; case 2: LineColor = new Color(55, 55, 255); break; } m_DataHistoryArray.Add(DataType, new HistoryData((int)m_Width, LineColor)); } m_DataHistoryArray[DataType].Add(NewData); } public void Reset() { m_DataViewMaxY = 1; m_DataViewMinY = 99999; foreach (KeyValuePair<String, HistoryData> historyKeyValue in m_DataHistoryArray) { historyKeyValue.Value.Reset(); } } }; }
// 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. ////////////////////////////////////////////////////////// // L-1-4-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes using 2-deep nesting in // the same assembly and module // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class Test{ public static int Main(){ int mi_RetCode; mi_RetCode = B.Test(); if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } struct B{ public static int Test(){ A a = new A(); int mi_RetCode = 100; ///////////////////////////////// // Test nested class access if(Test_Nested(a.ClsPubInst.Cls2PubInst) != 100) mi_RetCode = 0; if(Test_Nested(a.ClsPubInst.Cls2AsmInst) != 100) mi_RetCode = 0; if(Test_Nested(a.ClsAsmInst.Cls2PubInst) != 100) mi_RetCode = 0; if(Test_Nested(a.ClsAsmInst.Cls2AsmInst) != 100) mi_RetCode = 0; // to get rid of compiler warning // warning CS0414: The private field 'A.ClsPrivStat' is assigned but its value is never used A.getClsPrivStat().ToString(); // to get rid of compiler warning // warning CS0414: The private field 'A.ClsPrivStat' is assigned but its value is never used A.Cls.getClsPrivStat().ToString(); return mi_RetCode; } public static int Test_Nested(A.Cls.Cls2 Nested_Cls){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS NESTED FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////// // Test instance field access Nested_Cls.Nest2FldPubInst = 100; if(Nested_Cls.Nest2FldPubInst != 100) mi_RetCode = 0; Nested_Cls.Nest2FldAsmInst = 100; if(Nested_Cls.Nest2FldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.Cls.Cls2.Nest2FldPubStat = 100; if(A.Cls.Cls2.Nest2FldPubStat != 100) mi_RetCode = 0; A.Cls.Cls2.Nest2FldAsmStat = 100; if(A.Cls.Cls2.Nest2FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance method access if(Nested_Cls.Nest2MethPubInst() != 100) mi_RetCode = 0; if(Nested_Cls.Nest2MethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(A.Cls.Cls2.Nest2MethPubStat() != 100) mi_RetCode = 0; if(A.Cls.Cls2.Nest2MethAsmStat() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(Nested_Cls.Test() != 100) mi_RetCode = 0; return mi_RetCode; } } struct A{ ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////////////// // Instance fields for nested classes public Cls ClsPubInst; private Cls ClsPrivInst; internal Cls ClsAsmInst; ///////////////////////////////////// // Static fields of nested classes #pragma warning disable 0414 public static Cls ClsPubStat = new Cls(); private static Cls ClsPrivStat = new Cls(); #pragma warning restore 0414 public static Cls getClsPrivStat() { return ClsPrivStat; } ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("A::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("A::MethPrivInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } public struct Cls{ ////////////////////////////// // Instance Fields public int NestFldPubInst; private int NestFldPrivInst; internal int NestFldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int NestFldPubStat; private static int NestFldPrivStat; internal static int NestFldAsmStat; //assembly ////////////////////////////////////// // Instance fields for nested classes public Cls2 Cls2PubInst; private Cls2 Cls2PrivInst; internal Cls2 Cls2AsmInst; ///////////////////////////////////// // Static fields of nested classes #pragma warning disable 0414 public static Cls ClsPubStat = new Cls(); private static Cls ClsPrivStat = new Cls(); #pragma warning restore 0414 public static Cls getClsPrivStat() { return ClsPrivStat; } ////////////////////////////// // Instance NestMethods public int NestMethPubInst(){ Console.WriteLine("A::NestMethPubInst()"); return 100; } private int NestMethPrivInst(){ Console.WriteLine("A::NestMethPrivInst()"); return 100; } internal int NestMethAsmInst(){ Console.WriteLine("A::NestMethAsmInst()"); return 100; } ////////////////////////////// // Static NestMethods public static int NestMethPubStat(){ Console.WriteLine("A::NestMethPubStat()"); return 100; } private static int NestMethPrivStat(){ Console.WriteLine("A::NestMethPrivStat()"); return 100; } internal static int NestMethAsmStat(){ Console.WriteLine("A::NestMethAsmStat()"); return 100; } public struct Cls2{ public int Test(){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS ENCLOSING FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //@csharp - C# will not allow nested classes to access non-static members of their enclosing classes ///////////////////////////////// // Test static field access FldPubStat = 100; if(FldPubStat != 100) mi_RetCode = 0; FldAsmStat = 100; if(FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(MethPubStat() != 100) mi_RetCode = 0; if(MethAsmStat() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class //@todo - Look at testing accessing one nested class from another, @bugug - NEED TO ADD SUCH TESTING, access the public nested class fields from here, etc... ///////////////////////////////// // Test static field access NestFldPubStat = 100; if(NestFldPubStat != 100) mi_RetCode = 0; NestFldAsmStat = 100; if(NestFldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(NestMethPubStat() != 100) mi_RetCode = 0; if(NestMethAsmStat() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int Nest2FldPubInst; private int Nest2FldPrivInst; internal int Nest2FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int Nest2FldPubStat; private static int Nest2FldPrivStat; internal static int Nest2FldAsmStat; //assembly ////////////////////////////// // Instance Nest2Methods public int Nest2MethPubInst(){ Console.WriteLine("A::Nest2MethPubInst()"); return 100; } private int Nest2MethPrivInst(){ Console.WriteLine("A::Nest2MethPrivInst()"); return 100; } internal int Nest2MethAsmInst(){ Console.WriteLine("A::Nest2MethAsmInst()"); return 100; } ////////////////////////////// // Static Nest2Methods public static int Nest2MethPubStat(){ Console.WriteLine("A::Nest2MethPubStat()"); return 100; } private static int Nest2MethPrivStat(){ Console.WriteLine("A::Nest2MethPrivStat()"); return 100; } internal static int Nest2MethAsmStat(){ Console.WriteLine("A::Nest2MethAsmStat()"); return 100; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// InterimServicing /// </summary> public sealed partial class InterimServicing : DirtyExtensibleObject, IIdentifiable { private DirtyValue<decimal?>? _beginningBalance; private DirtyValue<string?>? _borrCellPhoneNumber; private DirtyValue<string?>? _borrHomeEmail; private DirtyValue<string?>? _borrHomePhoneNumber; private DirtyValue<string?>? _borrowerFirstName; private DirtyValue<string?>? _borrowerLastName; private DirtyValue<string?>? _borrWorkPhoneNumber; private DirtyValue<string?>? _calcTriggered; private DirtyValue<decimal?>? _cityInsurance; private DirtyValue<string?>? _comments; private DirtyValue<decimal?>? _currentPrincipalBalance; private DirtyValue<decimal?>? _escrowBalance; private DirtyList<EscrowDisbursementTransaction>? _escrowDisbursementTransactions; private DirtyList<EscrowInterestTransaction>? _escrowInterestTransactions; private DirtyValue<decimal?>? _floodInsurance; private DirtyValue<string?>? _id; private DirtyList<InterimServicingTransaction>? _interimServicingTransactions; private DirtyValue<decimal?>? _lastPaymentAdditionalEscrow; private DirtyValue<decimal?>? _lastPaymentAdditionalPrincipal; private DirtyValue<decimal?>? _lastPaymentBuydownSubsidyAmount; private DirtyValue<decimal?>? _lastPaymentEscrowAmount; private DirtyValue<decimal?>? _lastPaymentEscrowCityPropertyTax; private DirtyValue<decimal?>? _lastPaymentEscrowFloodInsurance; private DirtyValue<decimal?>? _lastPaymentEscrowHazardInsurance; private DirtyValue<decimal?>? _lastPaymentEscrowMortgageInsurance; private DirtyValue<decimal?>? _lastPaymentEscrowOther1; private DirtyValue<decimal?>? _lastPaymentEscrowOther2; private DirtyValue<decimal?>? _lastPaymentEscrowOther3; private DirtyValue<decimal?>? _lastPaymentEscrowTax; private DirtyValue<decimal?>? _lastPaymentEscrowUSDAMonthlyPremium; private DirtyValue<string?>? _lastPaymentGuid; private DirtyValue<decimal?>? _lastPaymentInterest; private DirtyValue<decimal?>? _lastPaymentLateFee; private DirtyValue<decimal?>? _lastPaymentMiscFee; private DirtyValue<int?>? _lastPaymentNumber; private DirtyValue<decimal?>? _lastPaymentPrincipal; private DirtyValue<decimal?>? _lastPaymentPrincipalAndInterest; private DirtyValue<DateTime?>? _lastPaymentReceivedDate; private DirtyValue<DateTime?>? _lastPaymentStatementDate; private DirtyValue<decimal?>? _lastPaymentTotalAmountReceived; private DirtyValue<SchedulePaymentTransaction?>? _lastScheduledPayment; private DirtyValue<DateTime?>? _lastStatementPrintedDate; private DirtyList<LoanPurchaseTransaction>? _loanPurchaseTransactions; private DirtyValue<string?>? _loanSnapshotXml; private DirtyValue<string?>? _mailingCity; private DirtyValue<string?>? _mailingPostalCode; private DirtyValue<StringEnumValue<State>>? _mailingState; private DirtyValue<string?>? _mailingStreetAddress; private DirtyValue<string?>? _mortgageAccount; private DirtyValue<decimal?>? _nextEscrowTotalFloodInsurance; private DirtyValue<DateTime?>? _nextEscrowTotalFloodInsuranceDueDate; private DirtyValue<decimal?>? _nextEscrowTotalHazardInsurance; private DirtyValue<DateTime?>? _nextEscrowTotalHazardInsuranceDueDate; private DirtyValue<decimal?>? _nextEscrowTotalMortgageInsurance; private DirtyValue<DateTime?>? _nextEscrowTotalMortgageInsuranceDueDate; private DirtyValue<decimal?>? _nextEscrowTotalOtherTax1; private DirtyValue<DateTime?>? _nextEscrowTotalOtherTax1DueDate; private DirtyValue<decimal?>? _nextEscrowTotalOtherTax2; private DirtyValue<DateTime?>? _nextEscrowTotalOtherTax2DueDate; private DirtyValue<decimal?>? _nextEscrowTotalOtherTax3; private DirtyValue<DateTime?>? _nextEscrowTotalOtherTax3DueDate; private DirtyValue<decimal?>? _nextEscrowTotalPropertyTax; private DirtyValue<DateTime?>? _nextEscrowTotalPropertyTaxDueDate; private DirtyValue<decimal?>? _nextEscrowTotalTax; private DirtyValue<DateTime?>? _nextEscrowTotalTaxDueDate; private DirtyValue<decimal?>? _nextEscrowTotalUsdaMonthlyPremium; private DirtyValue<DateTime?>? _nextEscrowTotalUsdaMonthlyPremiumDueDate; private DirtyValue<decimal?>? _nextPaymentBuydownSubsidyAmount; private DirtyValue<decimal?>? _nextPaymentEscrowAmount; private DirtyValue<decimal?>? _nextPaymentEscrowCityPropertyTax; private DirtyValue<decimal?>? _nextPaymentEscrowFloodInsurance; private DirtyValue<decimal?>? _nextPaymentEscrowHazardInsurance; private DirtyValue<decimal?>? _nextPaymentEscrowMortgageInsurance; private DirtyValue<decimal?>? _nextPaymentEscrowOther1; private DirtyValue<decimal?>? _nextPaymentEscrowOther2; private DirtyValue<decimal?>? _nextPaymentEscrowOther3; private DirtyValue<decimal?>? _nextPaymentEscrowTax; private DirtyValue<decimal?>? _nextPaymentEscrowUSDAMonthlyPremium; private DirtyValue<decimal?>? _nextPaymentIndexCurrentValuePercent; private DirtyValue<decimal?>? _nextPaymentInterest; private DirtyValue<decimal?>? _nextPaymentLateFee; private DirtyValue<DateTime?>? _nextPaymentLatePaymentDate; private DirtyValue<decimal?>? _nextPaymentMiscFee; private DirtyValue<decimal?>? _nextPaymentPastDueAmount; private DirtyValue<DateTime?>? _nextPaymentPaymentDueDate; private DirtyValue<DateTime?>? _nextPaymentPaymentIndexDate; private DirtyValue<decimal?>? _nextPaymentPrincipal; private DirtyValue<decimal?>? _nextPaymentPrincipalAndInterest; private DirtyValue<decimal?>? _nextPaymentRequestedInterestRatePercent; private DirtyValue<DateTime?>? _nextPaymentStatementDueDate; private DirtyValue<decimal?>? _nextPaymentTotalAmountDue; private DirtyValue<decimal?>? _nextPaymentTotalAmountWithLateFee; private DirtyValue<decimal?>? _nextPaymentUnpaidLateFee; private DirtyValue<SchedulePaymentTransaction?>? _nextScheduledPayment; private DirtyValue<int?>? _numberOfDisbursement; private DirtyList<OtherTransaction>? _otherTransactions; private DirtyValue<DateTime?>? _paymentDueDatePrinted; private DirtyList<PaymentReversalTransaction>? _paymentReversalTransactions; private DirtyList<PaymentTransaction>? _paymentTransactions; private DirtyValue<string?>? _printedByUserId; private DirtyValue<string?>? _printedByUserName; private DirtyValue<decimal?>? _purchasedPrincipal; private DirtyList<SchedulePaymentTransaction>? _scheduledPayments; private DirtyList<SchedulePaymentTransaction>? _schedulePaymentTransactions; private DirtyValue<string?>? _servicerLoanNumber; private DirtyValue<StringEnumValue<ServicingStatus>>? _servicingStatus; private DirtyValue<DateTime?>? _servicingTransferDate; private DirtyValue<string?>? _subServicer; private DirtyValue<string?>? _subServicerLoanNumber; private DirtyValue<decimal?>? _totalAdditionalEscrow; private DirtyValue<decimal?>? _totalAdditionalEscrowYearToDate; private DirtyValue<decimal?>? _totalAdditionalPrincipal; private DirtyValue<decimal?>? _totalAdditionalPrincipalYearToDate; private DirtyValue<decimal?>? _totalAmountDisbursed; private DirtyValue<decimal?>? _totalBuydownSubsidyAmount; private DirtyValue<decimal?>? _totalBuydownSubsidyAmountYearToDate; private DirtyValue<decimal?>? _totalEscrow; private DirtyValue<decimal?>? _totalEscrowYearToDate; private DirtyValue<decimal?>? _totalHazardInsurance; private DirtyValue<decimal?>? _totalInterest; private DirtyValue<decimal?>? _totalInterestYearToDate; private DirtyValue<decimal?>? _totalLateFee; private DirtyValue<decimal?>? _totalLateFeeYearToDate; private DirtyValue<decimal?>? _totalMiscFee; private DirtyValue<decimal?>? _totalMiscFeeYearToDate; private DirtyValue<decimal?>? _totalMortgageInsurance; private DirtyValue<int?>? _totalNumberOfLatePayment; private DirtyValue<int?>? _totalNumberOfPayment; private DirtyValue<decimal?>? _totalOtherTaxes; private DirtyValue<decimal?>? _totalPAndI; private DirtyValue<decimal?>? _totalPAndIYearToDate; private DirtyValue<decimal?>? _totalPaymentCollected; private DirtyValue<decimal?>? _totalPaymentCollectedYearToDate; private DirtyValue<decimal?>? _totalPrincipal; private DirtyValue<decimal?>? _totalPrincipalYearToDate; private DirtyValue<decimal?>? _totalTaxes; private DirtyValue<decimal?>? _totalUsdaMonthlyPremium; private DirtyValue<decimal?>? _unpaidBuydownSubsidyAmount; private DirtyValue<decimal?>? _unpaidEscrow; private DirtyValue<decimal?>? _unpaidEscrowCityPropertyTax; private DirtyValue<decimal?>? _unpaidEscrowFloodInsurance; private DirtyValue<decimal?>? _unpaidEscrowHazardInsurance; private DirtyValue<decimal?>? _unpaidEscrowMortgageInsurance; private DirtyValue<decimal?>? _unpaidEscrowOther1; private DirtyValue<decimal?>? _unpaidEscrowOther2; private DirtyValue<decimal?>? _unpaidEscrowOther3; private DirtyValue<decimal?>? _unpaidEscrowTax; private DirtyValue<decimal?>? _unpaidEscrowUSDAMonthlyPremium; private DirtyValue<decimal?>? _unpaidInterest; private DirtyValue<decimal?>? _unpaidLateFee; private DirtyValue<decimal?>? _unpaidMiscrFee; private DirtyValue<decimal?>? _unpaidPrincipal; /// <summary> /// Intrm Serv Beginning Balance [SERVICE.X144] /// </summary> public decimal? BeginningBalance { get => _beginningBalance; set => SetField(ref _beginningBalance, value); } /// <summary> /// Intrm Serv Borr Cell [SERVICE.X142] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? BorrCellPhoneNumber { get => _borrCellPhoneNumber; set => SetField(ref _borrCellPhoneNumber, value); } /// <summary> /// Intrm Serv Borr Email [SERVICE.X143] /// </summary> public string? BorrHomeEmail { get => _borrHomeEmail; set => SetField(ref _borrHomeEmail, value); } /// <summary> /// Intrm Serv Borr Home Phone [SERVICE.X140] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? BorrHomePhoneNumber { get => _borrHomePhoneNumber; set => SetField(ref _borrHomePhoneNumber, value); } /// <summary> /// Intrm Serv Borrower First Name [SERVICE.X2] /// </summary> public string? BorrowerFirstName { get => _borrowerFirstName; set => SetField(ref _borrowerFirstName, value); } /// <summary> /// Intrm Serv Borrower Last Name [SERVICE.X3] /// </summary> public string? BorrowerLastName { get => _borrowerLastName; set => SetField(ref _borrowerLastName, value); } /// <summary> /// Intrm Serv Borr Business Phone [SERVICE.X141] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? BorrWorkPhoneNumber { get => _borrWorkPhoneNumber; set => SetField(ref _borrWorkPhoneNumber, value); } /// <summary> /// Intrm Serv Calc Flag [SERVICE.X999] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? CalcTriggered { get => _calcTriggered; set => SetField(ref _calcTriggered, value); } /// <summary> /// Intrm Serv Escrow Summary City Insurance [SERVICE.X90] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? CityInsurance { get => _cityInsurance; set => SetField(ref _cityInsurance, value); } /// <summary> /// Intrm Serv Comments [SERVICE.Comments] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? Comments { get => _comments; set => SetField(ref _comments, value); } /// <summary> /// Intrm Serv Pymnt Summary Prncpl Balance [SERVICE.X57] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? CurrentPrincipalBalance { get => _currentPrincipalBalance; set => SetField(ref _currentPrincipalBalance, value); } /// <summary> /// Intrm Serv Escrow Summary Balance [SERVICE.X81] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? EscrowBalance { get => _escrowBalance; set => SetField(ref _escrowBalance, value); } /// <summary> /// InterimServicing EscrowDisbursementTransactions /// </summary> [AllowNull] public IList<EscrowDisbursementTransaction> EscrowDisbursementTransactions { get => GetField(ref _escrowDisbursementTransactions); set => SetField(ref _escrowDisbursementTransactions, value); } /// <summary> /// InterimServicing EscrowInterestTransactions /// </summary> [AllowNull] public IList<EscrowInterestTransaction> EscrowInterestTransactions { get => GetField(ref _escrowInterestTransactions); set => SetField(ref _escrowInterestTransactions, value); } /// <summary> /// Intrm Serv Escrow Summary Flood Insurance [SERVICE.X89] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? FloodInsurance { get => _floodInsurance; set => SetField(ref _floodInsurance, value); } /// <summary> /// InterimServicing Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// InterimServicing InterimServicingTransactions /// </summary> [AllowNull] public IList<InterimServicingTransaction> InterimServicingTransactions { get => GetField(ref _interimServicingTransactions); set => SetField(ref _interimServicingTransactions, value); } /// <summary> /// Intrm Serv Last Pymnt Add'l Escrow [SERVICE.X86] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentAdditionalEscrow { get => _lastPaymentAdditionalEscrow; set => SetField(ref _lastPaymentAdditionalEscrow, value); } /// <summary> /// Intrm Serv Last Pymnt Add'l Pnicpl [SERVICE.X38] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentAdditionalPrincipal { get => _lastPaymentAdditionalPrincipal; set => SetField(ref _lastPaymentAdditionalPrincipal, value); } /// <summary> /// Intrm Serv Last Pymt Buydown Subsidy Amt [SERVICE.X101] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentBuydownSubsidyAmount { get => _lastPaymentBuydownSubsidyAmount; set => SetField(ref _lastPaymentBuydownSubsidyAmount, value); } /// <summary> /// Intrm Serv Last Pymnt Escrow [SERVICE.X36] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowAmount { get => _lastPaymentEscrowAmount; set => SetField(ref _lastPaymentEscrowAmount, value); } /// <summary> /// Intrm Serv Last Pymnt City Property Tax [SERVICE.X125] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowCityPropertyTax { get => _lastPaymentEscrowCityPropertyTax; set => SetField(ref _lastPaymentEscrowCityPropertyTax, value); } /// <summary> /// Intrm Serv Last Pymnt Escrow Tax [SERVICE.X124] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowFloodInsurance { get => _lastPaymentEscrowFloodInsurance; set => SetField(ref _lastPaymentEscrowFloodInsurance, value); } /// <summary> /// Intrm Serv Last Pymnt Hazard Insurance [SERVICE.X122] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowHazardInsurance { get => _lastPaymentEscrowHazardInsurance; set => SetField(ref _lastPaymentEscrowHazardInsurance, value); } /// <summary> /// Intrm Serv Last Pymnt Mortgage Insurance [SERVICE.X123] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowMortgageInsurance { get => _lastPaymentEscrowMortgageInsurance; set => SetField(ref _lastPaymentEscrowMortgageInsurance, value); } /// <summary> /// Intrm Serv Last Pymnt Other1 Escrow [SERVICE.X126] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowOther1 { get => _lastPaymentEscrowOther1; set => SetField(ref _lastPaymentEscrowOther1, value); } /// <summary> /// Intrm Serv Last Pymnt Other2 Escrow [SERVICE.X127] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowOther2 { get => _lastPaymentEscrowOther2; set => SetField(ref _lastPaymentEscrowOther2, value); } /// <summary> /// Intrm Serv Last Pymnt Other3 Escrow [SERVICE.X128] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowOther3 { get => _lastPaymentEscrowOther3; set => SetField(ref _lastPaymentEscrowOther3, value); } /// <summary> /// Intrm Serv Last Pymnt Escrow Tax [SERVICE.X121] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowTax { get => _lastPaymentEscrowTax; set => SetField(ref _lastPaymentEscrowTax, value); } /// <summary> /// Intrm Serv Last Pymnt USDA Monthly Premuim [SERVICE.X129] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentEscrowUSDAMonthlyPremium { get => _lastPaymentEscrowUSDAMonthlyPremium; set => SetField(ref _lastPaymentEscrowUSDAMonthlyPremium, value); } /// <summary> /// Intrm Serv Last Pymnt GUID [SERVICE.LASTGUID] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? LastPaymentGuid { get => _lastPaymentGuid; set => SetField(ref _lastPaymentGuid, value); } /// <summary> /// Intrm Serv Last Pymnt Interest [SERVICE.X35] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentInterest { get => _lastPaymentInterest; set => SetField(ref _lastPaymentInterest, value); } /// <summary> /// Intrm Serv Last Pymnt Late Fee [SERVICE.X37] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentLateFee { get => _lastPaymentLateFee; set => SetField(ref _lastPaymentLateFee, value); } /// <summary> /// Intrm Serv Last Pymnt Misc Fee [SERVICE.X85] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentMiscFee { get => _lastPaymentMiscFee; set => SetField(ref _lastPaymentMiscFee, value); } /// <summary> /// Intrm Serv Last Pymnt Pymnt Number [SERVICE.X30] /// </summary> [LoanFieldProperty(ReadOnly = true)] public int? LastPaymentNumber { get => _lastPaymentNumber; set => SetField(ref _lastPaymentNumber, value); } /// <summary> /// Intrm Serv Last Pymnt Principal [SERVICE.X34] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentPrincipal { get => _lastPaymentPrincipal; set => SetField(ref _lastPaymentPrincipal, value); } /// <summary> /// Intrm Serv Last Pymnt Prncpl and Int. [SERVICE.X83] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentPrincipalAndInterest { get => _lastPaymentPrincipalAndInterest; set => SetField(ref _lastPaymentPrincipalAndInterest, value); } /// <summary> /// Intrm Serv Last Pymnt Rcvd Date [SERVICE.X32] /// </summary> [LoanFieldProperty(ReadOnly = true)] public DateTime? LastPaymentReceivedDate { get => _lastPaymentReceivedDate; set => SetField(ref _lastPaymentReceivedDate, value); } /// <summary> /// Intrm Serv Last Pymnt Statement Date [SERVICE.X31] /// </summary> [LoanFieldProperty(ReadOnly = true)] public DateTime? LastPaymentStatementDate { get => _lastPaymentStatementDate; set => SetField(ref _lastPaymentStatementDate, value); } /// <summary> /// Intrm Serv Last Pymnt Amount Rcvd [SERVICE.X33] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? LastPaymentTotalAmountReceived { get => _lastPaymentTotalAmountReceived; set => SetField(ref _lastPaymentTotalAmountReceived, value); } /// <summary> /// InterimServicing LastScheduledPayment /// </summary> public SchedulePaymentTransaction? LastScheduledPayment { get => _lastScheduledPayment; set => SetField(ref _lastScheduledPayment, value); } /// <summary> /// Intrm Serv Current Status Last Statement Printed [SERVICE.X9] /// </summary> public DateTime? LastStatementPrintedDate { get => _lastStatementPrintedDate; set => SetField(ref _lastStatementPrintedDate, value); } /// <summary> /// InterimServicing LoanPurchaseTransactions /// </summary> [AllowNull] public IList<LoanPurchaseTransaction> LoanPurchaseTransactions { get => GetField(ref _loanPurchaseTransactions); set => SetField(ref _loanPurchaseTransactions, value); } /// <summary> /// InterimServicing LoanSnapshotXml /// </summary> public string? LoanSnapshotXml { get => _loanSnapshotXml; set => SetField(ref _loanSnapshotXml, value); } /// <summary> /// Intrm Serv Mailing Address City [SERVICE.X5] /// </summary> public string? MailingCity { get => _mailingCity; set => SetField(ref _mailingCity, value); } /// <summary> /// Intrm Serv Mailing Address ZIP Code [SERVICE.X7] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? MailingPostalCode { get => _mailingPostalCode; set => SetField(ref _mailingPostalCode, value); } /// <summary> /// Intrm Serv Mailing Address State [SERVICE.X6] /// </summary> public StringEnumValue<State> MailingState { get => _mailingState; set => SetField(ref _mailingState, value); } /// <summary> /// Intrm Serv Mailing Address Street [SERVICE.X4] /// </summary> public string? MailingStreetAddress { get => _mailingStreetAddress; set => SetField(ref _mailingStreetAddress, value); } /// <summary> /// Intrm Serv Mrtg Accnt No [SERVICE.X1] /// </summary> public string? MortgageAccount { get => _mortgageAccount; set => SetField(ref _mortgageAccount, value); } /// <summary> /// Intrm Serv Next Escrow Total Flood Insurance [SERVICE.X64] /// </summary> public decimal? NextEscrowTotalFloodInsurance { get => _nextEscrowTotalFloodInsurance; set => SetField(ref _nextEscrowTotalFloodInsurance, value); } /// <summary> /// Intrm Serv Next Escrow Flood Insurance Due Date [SERVICE.X65] /// </summary> public DateTime? NextEscrowTotalFloodInsuranceDueDate { get => _nextEscrowTotalFloodInsuranceDueDate; set => SetField(ref _nextEscrowTotalFloodInsuranceDueDate, value); } /// <summary> /// Intrm Serv Next Escrow Total Hzrd Insurance [SERVICE.X60] /// </summary> public decimal? NextEscrowTotalHazardInsurance { get => _nextEscrowTotalHazardInsurance; set => SetField(ref _nextEscrowTotalHazardInsurance, value); } /// <summary> /// Intrm Serv Next Escrow Hzrd Insurance Due Date [SERVICE.X61] /// </summary> public DateTime? NextEscrowTotalHazardInsuranceDueDate { get => _nextEscrowTotalHazardInsuranceDueDate; set => SetField(ref _nextEscrowTotalHazardInsuranceDueDate, value); } /// <summary> /// Intrm Serv Next Escrow Total Mortgage Insurance [SERVICE.X62] /// </summary> public decimal? NextEscrowTotalMortgageInsurance { get => _nextEscrowTotalMortgageInsurance; set => SetField(ref _nextEscrowTotalMortgageInsurance, value); } /// <summary> /// Intrm Serv Next Escrow Mortgage Insurance Due Date [SERVICE.X63] /// </summary> public DateTime? NextEscrowTotalMortgageInsuranceDueDate { get => _nextEscrowTotalMortgageInsuranceDueDate; set => SetField(ref _nextEscrowTotalMortgageInsuranceDueDate, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 1 [SERVICE.X68] /// </summary> public decimal? NextEscrowTotalOtherTax1 { get => _nextEscrowTotalOtherTax1; set => SetField(ref _nextEscrowTotalOtherTax1, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 1 Due Date [SERVICE.X69] /// </summary> public DateTime? NextEscrowTotalOtherTax1DueDate { get => _nextEscrowTotalOtherTax1DueDate; set => SetField(ref _nextEscrowTotalOtherTax1DueDate, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 2 [SERVICE.X70] /// </summary> public decimal? NextEscrowTotalOtherTax2 { get => _nextEscrowTotalOtherTax2; set => SetField(ref _nextEscrowTotalOtherTax2, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 2 Due Date [SERVICE.X71] /// </summary> public DateTime? NextEscrowTotalOtherTax2DueDate { get => _nextEscrowTotalOtherTax2DueDate; set => SetField(ref _nextEscrowTotalOtherTax2DueDate, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 3 [SERVICE.X72] /// </summary> public decimal? NextEscrowTotalOtherTax3 { get => _nextEscrowTotalOtherTax3; set => SetField(ref _nextEscrowTotalOtherTax3, value); } /// <summary> /// Intrm Serv Next Escrow Other Tax 3 Due Date [SERVICE.X73] /// </summary> public DateTime? NextEscrowTotalOtherTax3DueDate { get => _nextEscrowTotalOtherTax3DueDate; set => SetField(ref _nextEscrowTotalOtherTax3DueDate, value); } /// <summary> /// Intrm Serv Next Escrow Total PropertyTax [SERVICE.X66] /// </summary> public decimal? NextEscrowTotalPropertyTax { get => _nextEscrowTotalPropertyTax; set => SetField(ref _nextEscrowTotalPropertyTax, value); } /// <summary> /// Intrm Serv Next Escrow Property Tax Due Date [SERVICE.X67] /// </summary> public DateTime? NextEscrowTotalPropertyTaxDueDate { get => _nextEscrowTotalPropertyTaxDueDate; set => SetField(ref _nextEscrowTotalPropertyTaxDueDate, value); } /// <summary> /// Intrm Serv Next Escrow Total Taxes [SERVICE.X58] /// </summary> public decimal? NextEscrowTotalTax { get => _nextEscrowTotalTax; set => SetField(ref _nextEscrowTotalTax, value); } /// <summary> /// Intrm Serv Next Escrow Tax Due Date [SERVICE.X59] /// </summary> public DateTime? NextEscrowTotalTaxDueDate { get => _nextEscrowTotalTaxDueDate; set => SetField(ref _nextEscrowTotalTaxDueDate, value); } /// <summary> /// Intrm Serv Next Escrow USDA Monthly Premium [SERVICE.X105] /// </summary> public decimal? NextEscrowTotalUsdaMonthlyPremium { get => _nextEscrowTotalUsdaMonthlyPremium; set => SetField(ref _nextEscrowTotalUsdaMonthlyPremium, value); } /// <summary> /// Intrm Serv Next Escrow USDA Monthly Premium Due Date [SERVICE.X106] /// </summary> public DateTime? NextEscrowTotalUsdaMonthlyPremiumDueDate { get => _nextEscrowTotalUsdaMonthlyPremiumDueDate; set => SetField(ref _nextEscrowTotalUsdaMonthlyPremiumDueDate, value); } /// <summary> /// Intrm Serv Next Pymt Buydown Subsidy Amt [SERVICE.X100] /// </summary> public decimal? NextPaymentBuydownSubsidyAmount { get => _nextPaymentBuydownSubsidyAmount; set => SetField(ref _nextPaymentBuydownSubsidyAmount, value); } /// <summary> /// Intrm Serv Next Pymnt Escrow [SERVICE.X20] /// </summary> public decimal? NextPaymentEscrowAmount { get => _nextPaymentEscrowAmount; set => SetField(ref _nextPaymentEscrowAmount, value); } /// <summary> /// Intrm Serv Next Payment City Property Tax [SERVICE.X116] /// </summary> public decimal? NextPaymentEscrowCityPropertyTax { get => _nextPaymentEscrowCityPropertyTax; set => SetField(ref _nextPaymentEscrowCityPropertyTax, value); } /// <summary> /// Intrm Serv Next Payment Flood Insurance [SERVICE.X115] /// </summary> public decimal? NextPaymentEscrowFloodInsurance { get => _nextPaymentEscrowFloodInsurance; set => SetField(ref _nextPaymentEscrowFloodInsurance, value); } /// <summary> /// Intrm Serv Next Payment Hazard Insurance [SERVICE.X113] /// </summary> public decimal? NextPaymentEscrowHazardInsurance { get => _nextPaymentEscrowHazardInsurance; set => SetField(ref _nextPaymentEscrowHazardInsurance, value); } /// <summary> /// Intrm Serv Next Payment Mortgage Insurance [SERVICE.X114] /// </summary> public decimal? NextPaymentEscrowMortgageInsurance { get => _nextPaymentEscrowMortgageInsurance; set => SetField(ref _nextPaymentEscrowMortgageInsurance, value); } /// <summary> /// Intrm Serv Next Payment Other1 Escrow [SERVICE.X117] /// </summary> public decimal? NextPaymentEscrowOther1 { get => _nextPaymentEscrowOther1; set => SetField(ref _nextPaymentEscrowOther1, value); } /// <summary> /// Intrm Serv Next Payment Other2 Escrow [SERVICE.X119] /// </summary> public decimal? NextPaymentEscrowOther2 { get => _nextPaymentEscrowOther2; set => SetField(ref _nextPaymentEscrowOther2, value); } /// <summary> /// Intrm Serv Next Payment Other3 Escrow [SERVICE.X120] /// </summary> public decimal? NextPaymentEscrowOther3 { get => _nextPaymentEscrowOther3; set => SetField(ref _nextPaymentEscrowOther3, value); } /// <summary> /// Intrm Serv Next Payment Escrow Taxes [SERVICE.X112] /// </summary> public decimal? NextPaymentEscrowTax { get => _nextPaymentEscrowTax; set => SetField(ref _nextPaymentEscrowTax, value); } /// <summary> /// Intrm Serv Next Payment USDA Monthly Premuim [SERVICE.X118] /// </summary> public decimal? NextPaymentEscrowUSDAMonthlyPremium { get => _nextPaymentEscrowUSDAMonthlyPremium; set => SetField(ref _nextPaymentEscrowUSDAMonthlyPremium, value); } /// <summary> /// Intrm Serv Next Pymnt Index Rate [SERVICE.X16] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? NextPaymentIndexCurrentValuePercent { get => _nextPaymentIndexCurrentValuePercent; set => SetField(ref _nextPaymentIndexCurrentValuePercent, value); } /// <summary> /// Intrm Serv Next Pymnt Interest [SERVICE.X19] /// </summary> public decimal? NextPaymentInterest { get => _nextPaymentInterest; set => SetField(ref _nextPaymentInterest, value); } /// <summary> /// Intrm Serv Next Pymnt Late Fee [SERVICE.X25] /// </summary> public decimal? NextPaymentLateFee { get => _nextPaymentLateFee; set => SetField(ref _nextPaymentLateFee, value); } /// <summary> /// Intrm Serv Next Pymnt Late Pymnt Date [SERVICE.X15] /// </summary> public DateTime? NextPaymentLatePaymentDate { get => _nextPaymentLatePaymentDate; set => SetField(ref _nextPaymentLatePaymentDate, value); } /// <summary> /// Intrm Serv Next Pymnt Misc Fee [SERVICE.X23] /// </summary> public decimal? NextPaymentMiscFee { get => _nextPaymentMiscFee; set => SetField(ref _nextPaymentMiscFee, value); } /// <summary> /// Intrm Serv Next Pymnt Past Due Amnt [SERVICE.X21] /// </summary> public decimal? NextPaymentPastDueAmount { get => _nextPaymentPastDueAmount; set => SetField(ref _nextPaymentPastDueAmount, value); } /// <summary> /// Intrm Serv Next Pymnt Pymnt Due Date [SERVICE.X14] /// </summary> public DateTime? NextPaymentPaymentDueDate { get => _nextPaymentPaymentDueDate; set => SetField(ref _nextPaymentPaymentDueDate, value); } /// <summary> /// Intrm Serv Next Payment Index Date [SERVICE.X99] /// </summary> [LoanFieldProperty(ReadOnly = true)] public DateTime? NextPaymentPaymentIndexDate { get => _nextPaymentPaymentIndexDate; set => SetField(ref _nextPaymentPaymentIndexDate, value); } /// <summary> /// Intrm Serv Next Pymnt Principal [SERVICE.X18] /// </summary> public decimal? NextPaymentPrincipal { get => _nextPaymentPrincipal; set => SetField(ref _nextPaymentPrincipal, value); } /// <summary> /// Intrm Serv Next Pymnt Prncpl and Int. [SERVICE.X82] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NextPaymentPrincipalAndInterest { get => _nextPaymentPrincipalAndInterest; set => SetField(ref _nextPaymentPrincipalAndInterest, value); } /// <summary> /// Intrm Serv Next Pymnt Interest Rate [SERVICE.X17] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)] public decimal? NextPaymentRequestedInterestRatePercent { get => _nextPaymentRequestedInterestRatePercent; set => SetField(ref _nextPaymentRequestedInterestRatePercent, value); } /// <summary> /// Intrm Serv Next Pymnt Statement Due Date [SERVICE.X13] /// </summary> public DateTime? NextPaymentStatementDueDate { get => _nextPaymentStatementDueDate; set => SetField(ref _nextPaymentStatementDueDate, value); } /// <summary> /// Intrm Serv Next Pymnt Total Amnt Due [SERVICE.X24] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NextPaymentTotalAmountDue { get => _nextPaymentTotalAmountDue; set => SetField(ref _nextPaymentTotalAmountDue, value); } /// <summary> /// Intrm Serv Next Pymnt Total Amnt and Late Fee [SERVICE.X26] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? NextPaymentTotalAmountWithLateFee { get => _nextPaymentTotalAmountWithLateFee; set => SetField(ref _nextPaymentTotalAmountWithLateFee, value); } /// <summary> /// Intrm Serv Next Pymnt Unpaid Late Fee [SERVICE.X22] /// </summary> public decimal? NextPaymentUnpaidLateFee { get => _nextPaymentUnpaidLateFee; set => SetField(ref _nextPaymentUnpaidLateFee, value); } /// <summary> /// InterimServicing NextScheduledPayment /// </summary> public SchedulePaymentTransaction? NextScheduledPayment { get => _nextScheduledPayment; set => SetField(ref _nextScheduledPayment, value); } /// <summary> /// Intrm Serv Escrow Summary Number of Disbursement [SERVICE.X74] /// </summary> [LoanFieldProperty(ReadOnly = true)] public int? NumberOfDisbursement { get => _numberOfDisbursement; set => SetField(ref _numberOfDisbursement, value); } /// <summary> /// InterimServicing OtherTransactions /// </summary> [AllowNull] public IList<OtherTransaction> OtherTransactions { get => GetField(ref _otherTransactions); set => SetField(ref _otherTransactions, value); } /// <summary> /// Intrm Serv Pymnt Due Date Printed [SERVICE.X10] /// </summary> public DateTime? PaymentDueDatePrinted { get => _paymentDueDatePrinted; set => SetField(ref _paymentDueDatePrinted, value); } /// <summary> /// InterimServicing PaymentReversalTransactions /// </summary> [AllowNull] public IList<PaymentReversalTransaction> PaymentReversalTransactions { get => GetField(ref _paymentReversalTransactions); set => SetField(ref _paymentReversalTransactions, value); } /// <summary> /// InterimServicing PaymentTransactions /// </summary> [AllowNull] public IList<PaymentTransaction> PaymentTransactions { get => GetField(ref _paymentTransactions); set => SetField(ref _paymentTransactions, value); } /// <summary> /// Intrm Serv Current Status Printed By User ID [SERVICE.X12] /// </summary> public string? PrintedByUserId { get => _printedByUserId; set => SetField(ref _printedByUserId, value); } /// <summary> /// Intrm Serv Current Status Printed By User Name [SERVICE.X11] /// </summary> public string? PrintedByUserName { get => _printedByUserName; set => SetField(ref _printedByUserName, value); } /// <summary> /// Intrm Serv Purchase Advice Summary Principal [SERVICE.X139] /// </summary> public decimal? PurchasedPrincipal { get => _purchasedPrincipal; set => SetField(ref _purchasedPrincipal, value); } /// <summary> /// InterimServicing ScheduledPayments /// </summary> [AllowNull] public IList<SchedulePaymentTransaction> ScheduledPayments { get => GetField(ref _scheduledPayments); set => SetField(ref _scheduledPayments, value); } /// <summary> /// InterimServicing SchedulePaymentTransactions /// </summary> [AllowNull] public IList<SchedulePaymentTransaction> SchedulePaymentTransactions { get => GetField(ref _schedulePaymentTransactions); set => SetField(ref _schedulePaymentTransactions, value); } /// <summary> /// Intrm Serv Servicer Loan Number [SERVICE.X108] /// </summary> public string? ServicerLoanNumber { get => _servicerLoanNumber; set => SetField(ref _servicerLoanNumber, value); } /// <summary> /// Intrm Serv Current Status [SERVICE.X8] /// </summary> public StringEnumValue<ServicingStatus> ServicingStatus { get => _servicingStatus; set => SetField(ref _servicingStatus, value); } /// <summary> /// Intrm Serv Servicing Transfer Date [SERVICE.X109] /// </summary> public DateTime? ServicingTransferDate { get => _servicingTransferDate; set => SetField(ref _servicingTransferDate, value); } /// <summary> /// Intrm Serv Servicing Sub - Servicer [SERVICE.X110] /// </summary> public string? SubServicer { get => _subServicer; set => SetField(ref _subServicer, value); } /// <summary> /// Intrm Serv Sub - Servicer Loan Number [SERVICE.X111] /// </summary> public string? SubServicerLoanNumber { get => _subServicerLoanNumber; set => SetField(ref _subServicerLoanNumber, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Add'l Escrow [SERVICE.X53] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalAdditionalEscrow { get => _totalAdditionalEscrow; set => SetField(ref _totalAdditionalEscrow, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Add'l Escrow [SERVICE.X54] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalAdditionalEscrowYearToDate { get => _totalAdditionalEscrowYearToDate; set => SetField(ref _totalAdditionalEscrowYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Add'l Prncpl [SERVICE.X51] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalAdditionalPrincipal { get => _totalAdditionalPrincipal; set => SetField(ref _totalAdditionalPrincipal, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Add'l Prncpl [SERVICE.X52] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalAdditionalPrincipalYearToDate { get => _totalAdditionalPrincipalYearToDate; set => SetField(ref _totalAdditionalPrincipalYearToDate, value); } /// <summary> /// Intrm Serv Escrow Summary Total Amnt Disbursed [SERVICE.X80] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalAmountDisbursed { get => _totalAmountDisbursed; set => SetField(ref _totalAmountDisbursed, value); } /// <summary> /// Intrm Serv Pymt Summary Total Bdown Subsidy Amt [SERVICE.X102] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalBuydownSubsidyAmount { get => _totalBuydownSubsidyAmount; set => SetField(ref _totalBuydownSubsidyAmount, value); } /// <summary> /// Intrm Serv Pymt Summary Yr to Date Bdown Subsidy [SERVICE.X103] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalBuydownSubsidyAmountYearToDate { get => _totalBuydownSubsidyAmountYearToDate; set => SetField(ref _totalBuydownSubsidyAmountYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Escrow [SERVICE.X47] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalEscrow { get => _totalEscrow; set => SetField(ref _totalEscrow, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Escrow [SERVICE.X48] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalEscrowYearToDate { get => _totalEscrowYearToDate; set => SetField(ref _totalEscrowYearToDate, value); } /// <summary> /// Intrm Serv Escrow Summary Total Hzrd Insurance [SERVICE.X76] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalHazardInsurance { get => _totalHazardInsurance; set => SetField(ref _totalHazardInsurance, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Interest [SERVICE.X43] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalInterest { get => _totalInterest; set => SetField(ref _totalInterest, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Total Int [SERVICE.X44] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalInterestYearToDate { get => _totalInterestYearToDate; set => SetField(ref _totalInterestYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Late Fee [SERVICE.X49] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalLateFee { get => _totalLateFee; set => SetField(ref _totalLateFee, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Total Late Fee [SERVICE.X50] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalLateFeeYearToDate { get => _totalLateFeeYearToDate; set => SetField(ref _totalLateFeeYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Misc Fee [SERVICE.X87] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalMiscFee { get => _totalMiscFee; set => SetField(ref _totalMiscFee, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Total Misc Fee [SERVICE.X88] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalMiscFeeYearToDate { get => _totalMiscFeeYearToDate; set => SetField(ref _totalMiscFeeYearToDate, value); } /// <summary> /// Intrm Serv Escrow Summary Total Mrtg Insurance [SERVICE.X77] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalMortgageInsurance { get => _totalMortgageInsurance; set => SetField(ref _totalMortgageInsurance, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Nmbr of Late Pymnts [SERVICE.X40] /// </summary> [LoanFieldProperty(ReadOnly = true)] public int? TotalNumberOfLatePayment { get => _totalNumberOfLatePayment; set => SetField(ref _totalNumberOfLatePayment, value); } /// <summary> /// Intrm Serv Pymnt Summary Nmbr of Pymnt [SERVICE.X39] /// </summary> [LoanFieldProperty(ReadOnly = true)] public int? TotalNumberOfPayment { get => _totalNumberOfPayment; set => SetField(ref _totalNumberOfPayment, value); } /// <summary> /// Intrm Serv Escrow Summary Total Other Taxes [SERVICE.X79] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalOtherTaxes { get => _totalOtherTaxes; set => SetField(ref _totalOtherTaxes, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Prncpl and Int [SERVICE.X45] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPAndI { get => _totalPAndI; set => SetField(ref _totalPAndI, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Prncpl and Int [SERVICE.X46] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPAndIYearToDate { get => _totalPAndIYearToDate; set => SetField(ref _totalPAndIYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Pymnt Collected [SERVICE.X55] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPaymentCollected { get => _totalPaymentCollected; set => SetField(ref _totalPaymentCollected, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Pymnt Collected [SERVICE.X56] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPaymentCollectedYearToDate { get => _totalPaymentCollectedYearToDate; set => SetField(ref _totalPaymentCollectedYearToDate, value); } /// <summary> /// Intrm Serv Pymnt Summary Total Prncpl [SERVICE.X41] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPrincipal { get => _totalPrincipal; set => SetField(ref _totalPrincipal, value); } /// <summary> /// Intrm Serv Pymnt Summary Year to Date Total Prncpl [SERVICE.X42] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalPrincipalYearToDate { get => _totalPrincipalYearToDate; set => SetField(ref _totalPrincipalYearToDate, value); } /// <summary> /// Intrm Serv Escrow Summary Total Property City Taxes [SERVICE.X75] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalTaxes { get => _totalTaxes; set => SetField(ref _totalTaxes, value); } /// <summary> /// Intrm Serv Escrow Summary Total USDA Monthly Premium [SERVICE.X107] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? TotalUsdaMonthlyPremium { get => _totalUsdaMonthlyPremium; set => SetField(ref _totalUsdaMonthlyPremium, value); } /// <summary> /// Intrm Serv Escrow Sumry Unpaid Bdown Subsidy Amt [SERVICE.X104] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidBuydownSubsidyAmount { get => _unpaidBuydownSubsidyAmount; set => SetField(ref _unpaidBuydownSubsidyAmount, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow [SERVICE.X93] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrow { get => _unpaidEscrow; set => SetField(ref _unpaidEscrow, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow City Property Tax [SERVICE.X134] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowCityPropertyTax { get => _unpaidEscrowCityPropertyTax; set => SetField(ref _unpaidEscrowCityPropertyTax, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Flood Insurance [SERVICE.X133] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowFloodInsurance { get => _unpaidEscrowFloodInsurance; set => SetField(ref _unpaidEscrowFloodInsurance, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Hazard Insurance [SERVICE.X132] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowHazardInsurance { get => _unpaidEscrowHazardInsurance; set => SetField(ref _unpaidEscrowHazardInsurance, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Mortgage Insurance [SERVICE.X131] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowMortgageInsurance { get => _unpaidEscrowMortgageInsurance; set => SetField(ref _unpaidEscrowMortgageInsurance, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Other1 [SERVICE.X135] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowOther1 { get => _unpaidEscrowOther1; set => SetField(ref _unpaidEscrowOther1, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Other2 [SERVICE.X136] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowOther2 { get => _unpaidEscrowOther2; set => SetField(ref _unpaidEscrowOther2, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Other3 [SERVICE.X137] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowOther3 { get => _unpaidEscrowOther3; set => SetField(ref _unpaidEscrowOther3, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Escrow Tax [SERVICE.X130] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowTax { get => _unpaidEscrowTax; set => SetField(ref _unpaidEscrowTax, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid USDA Monthly Premium [SERVICE.X138] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidEscrowUSDAMonthlyPremium { get => _unpaidEscrowUSDAMonthlyPremium; set => SetField(ref _unpaidEscrowUSDAMonthlyPremium, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Interest [SERVICE.X92] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidInterest { get => _unpaidInterest; set => SetField(ref _unpaidInterest, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Late Fee [SERVICE.X95] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidLateFee { get => _unpaidLateFee; set => SetField(ref _unpaidLateFee, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Misc Fee [SERVICE.X94] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidMiscrFee { get => _unpaidMiscrFee; set => SetField(ref _unpaidMiscrFee, value); } /// <summary> /// Intrm Serv Payment Summary Unpaid Principal [SERVICE.X91] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? UnpaidPrincipal { get => _unpaidPrincipal; set => SetField(ref _unpaidPrincipal, value); } } }
//------------------------------------------------------------------------------ // <copyright from='1997' to='2001' company='Microsoft Corporation'> // Copyright (c) Microsoft Corporation. All Rights Reserved. // Information Contained Herein is Proprietary and Confidential. // </copyright> //------------------------------------------------------------------------------ namespace System.Management.Instrumentation { using System; using System.Reflection; using System.Collections; using System.Text.RegularExpressions; using System.Management; using System.Globalization; /// <summary> /// <para>Specifies that this assembly provides management instrumentation. This attribute should appear one time per assembly.</para> /// </summary> /// <remarks> /// <para>For more information about using attributes, see <see topic="cpconExtendingMetadataUsingAttributes" title="Extending Metadata Using Attributes"/> .</para> /// </remarks> [AttributeUsage(AttributeTargets.Assembly)] public class InstrumentedAttribute : Attribute { string namespaceName; string securityDescriptor; /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.Instrumentation.InstrumentedAttribute'/> class. /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.InstrumentedAttribute'/> /// class that is set for the root\default namespace. This is the default constructor.</para> /// </summary> public InstrumentedAttribute() : this(null, null) {} /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.InstrumentedAttribute'/> class that is set to the specified namespace for instrumentation within this assembly.</para> /// </summary> /// <param name='namespaceName'>The namespace for instrumentation instances and events.</param> public InstrumentedAttribute(string namespaceName) : this(namespaceName, null) {} /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.InstrumentedAttribute'/> class that is set to the specified namespace and security settings for instrumentation within this assembly.</para> /// </summary> /// <param name='namespaceName'>The namespace for instrumentation instances and events.</param> /// <param name='securityDescriptor'> A security descriptor that allows only the specified users or groups to run applications that provide the instrumentation supported by this assembly.</param> public InstrumentedAttribute(string namespaceName, string securityDescriptor) { // if(namespaceName != null) namespaceName = namespaceName.Replace('/', '\\'); if(namespaceName == null || namespaceName.Length == 0) namespaceName = "root\\default"; // bug#60933 Use a default namespace if null bool once = true; foreach(string namespacePart in namespaceName.Split('\\')) { if( namespacePart.Length == 0 || (once && String.Compare(namespacePart, "root", StringComparison.OrdinalIgnoreCase) != 0) // Must start with 'root' || !Regex.Match(namespacePart, @"^[a-z,A-Z]").Success // All parts must start with letter || Regex.Match(namespacePart, @"_$").Success // Must not end with an underscore || Regex.Match(namespacePart, @"[^a-z,A-Z,0-9,_,\u0080-\uFFFF]").Success) // Only letters, digits, or underscores { ManagementException.ThrowWithExtendedInfo(ManagementStatus.InvalidNamespace); } once = false; } this.namespaceName = namespaceName; this.securityDescriptor = securityDescriptor; } /// <summary> /// <para>Gets or sets the namespace for instrumentation instances and events in this assembly.</para> /// </summary> /// <value> /// <para>If not specified, the default namespace will be set as "\\.\root\default". /// Otherwise, a string indicating the name of the namespace for instrumentation /// instances and events in this assembly.</para> /// </value> /// <remarks> /// It is highly recommended that the namespace name be specified by the /// assembly, and that it should be a unique namespace per assembly, or per /// application. Having a specific namespace for each assembly or /// application instrumentation allows more granularity for securing access to /// instrumentation provided by different assemblies or applications. /// </remarks> public string NamespaceName { get { return namespaceName == null ? string.Empty : namespaceName; } } /// <summary> /// <para> Gets or sets a security descriptor that allows only the specified users or groups to run /// applications that provide the instrumentation supported by this assembly.</para> /// </summary> /// <value> /// <para> /// If null, the default value is defined to include the /// following security groups : <see langword='Local Administrators'/>, <see langword='Local System'/>, <see langword='Local Service'/>, <see langword='Network Service'/> and <see langword='Batch Logon'/>. This will only allow /// members of these security groups /// to publish data and fire events from this assembly.</para> /// <para>Otherwise, this is a string in SDDL format representing the security /// descriptor that defines which users and groups can provide instrumentation data /// and events from this application.</para> /// </value> /// <remarks> /// <para>Users or groups not specified in this /// security descriptor may still run the application, but cannot provide /// instrumentation from this assembly.</para> /// </remarks> /// <example> /// <para>The SDDL representing the default set of security groups defined above is as /// follows :</para> /// <para>O:BAG:BAD:(A;;0x10000001;;;BA)(A;;0x10000001;;;SY)(A;;0x10000001;;;LA)(A;;0x10000001;;;S-1-5-20)(A;;0x10000001;;;S-1-5-19)</para> /// <para>To add the <see langword='Power Users'/> group to the users allowed to fire events or publish /// instances from this assembly, the attribute should be specificed as /// follows :</para> /// <para>[Instrumented("root\\MyApplication", "O:BAG:BAD:(A;;0x10000001;;;BA)(A;;0x10000001;;;SY)(A;;0x10000001;;;LA)(A;;0x10000001;;;S-1-5-20)(A;;0x10000001;;;S-1-5-19)(A;;0x10000001;;;PU)")]</para> /// </example> public string SecurityDescriptor { get { // This will never return an empty string. Instead, it will // return null, or a non-zero length string if(null == securityDescriptor || securityDescriptor.Length == 0) return null; return securityDescriptor; } } internal static InstrumentedAttribute GetAttribute(Assembly assembly) { Object [] rg = assembly.GetCustomAttributes(typeof(InstrumentedAttribute), false); if(rg.Length > 0) return ((InstrumentedAttribute)rg[0]); return new InstrumentedAttribute(); } internal static Type[] GetInstrumentedTypes(Assembly assembly) { ArrayList types = new ArrayList(); // // The recursion has been moved to the parent level to avoid ineffiency of wading through all types // at each stage of recursion. Also, the recursive method has been replaced with the more correct: // GetInstrumentedParentTypes method (see comments on header). // foreach (Type type in assembly.GetTypes()) { if (IsInstrumentationClass(type)) { GetInstrumentedParentTypes(types, type); } } return (Type[])types.ToArray(typeof(Type)); } // // Recursive function that adds the type to the array and recurses on the parent type. The end condition // is either no parent type or a parent type which is not marked as instrumented. // static void GetInstrumentedParentTypes(ArrayList types, Type childType) { if (types.Contains(childType) == false) { Type parentType = InstrumentationClassAttribute.GetBaseInstrumentationType(childType) ; // // If we have a instrumented base type and it has not already // been included in the list of instrumented types // traverse the inheritance hierarchy. // if (parentType != null) { GetInstrumentedParentTypes(types, parentType); } types.Add(childType); } } static bool IsInstrumentationClass(Type type) { return (null != InstrumentationClassAttribute.GetAttribute(type)); } } /// <summary> /// <para>Specifies the type of instrumentation provided by a class.</para> /// </summary> /// <example> /// <code lang='C#'>using System; /// using System.Management; /// using System.Configuration.Install; /// using System.Management.Instrumentation; /// /// // This example demonstrates how to create a Management Event class by using /// // the InstrumentationClass attribute and to fire a Management Event from /// // managed code. /// /// // Specify which namespace the Management Event class is created in /// [assembly:Instrumented("Root/Default")] /// /// // Let the system know you will run InstallUtil.exe utility against /// // this assembly /// [System.ComponentModel.RunInstaller(true)] /// public class MyInstaller : DefaultManagementProjectInstaller {} /// /// // Create a Management Instrumentation Event class /// [InstrumentationClass(InstrumentationType.Event)] /// public class MyEvent /// { /// public string EventName; /// } /// /// public class WMI_InstrumentedEvent_Example /// { /// public static void Main() { /// MyEvent e = new MyEvent(); /// e.EventName = "Hello"; /// /// // Fire a Management Event /// Instrumentation.Fire(e); /// /// return; /// } /// } /// </code> /// <code lang='VB'>Imports System /// Imports System.Management /// Imports System.Configuration.Install /// Imports System.Management.Instrumentation /// /// ' This sample demonstrates how to create a Management Event class by using /// ' the InstrumentationClass attribute and to fire a Management Event from /// ' managed code. /// /// ' Specify which namespace the Manaegment Event class is created in /// &lt;assembly: Instrumented("Root/Default")&gt; /// /// ' Let the system know InstallUtil.exe utility will be run against /// ' this assembly /// &lt;System.ComponentModel.RunInstaller(True)&gt; _ /// Public Class MyInstaller /// Inherits DefaultManagementProjectInstaller /// End Class 'MyInstaller /// /// ' Create a Management Instrumentation Event class /// &lt;InstrumentationClass(InstrumentationType.Event)&gt; _ /// Public Class MyEvent /// Public EventName As String /// End Class /// /// Public Class Sample_EventProvider /// Public Shared Function Main(args() As String) As Integer /// Dim e As New MyEvent() /// e.EventName = "Hello" /// /// ' Fire a Management Event /// Instrumentation.Fire(e) /// /// Return 0 /// End Function /// End Class /// </code> /// </example> public enum InstrumentationType { /// <summary> /// <para>Specifies that the class provides instances for management instrumentation.</para> /// </summary> Instance, /// <summary> /// <para>Specifies that the class provides events for management instrumentation.</para> /// </summary> Event, /// <summary> /// <para>Specifies that the class defines an abstract class for management instrumentation.</para> /// </summary> Abstract } /// <summary> /// Specifies that a class provides event or instance instrumentation. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] public class InstrumentationClassAttribute : Attribute { InstrumentationType instrumentationType; string managedBaseClassName; /// <overload> /// Initializes a new instance /// of the <see cref='System.Management.Instrumentation.InstrumentationClassAttribute'/> class. /// </overload> /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.InstrumentationClassAttribute'/> class that is used if this type is derived from another type that has the <see cref='System.Management.Instrumentation.InstrumentationClassAttribute'/> attribute, or if this is a /// top-level instrumentation class (for example, an instance or abstract class /// without a base class, or an event derived from <see langword='__ExtrinsicEvent'/>).</para> /// </summary> /// <param name='instrumentationType'>The type of instrumentation provided by this class.</param> public InstrumentationClassAttribute(InstrumentationType instrumentationType) { this.instrumentationType = instrumentationType; } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.InstrumentationClassAttribute'/> class that /// has schema for an existing base class. The class must contain /// proper member definitions for the properties of the existing /// WMI base class.</para> /// </summary> /// <param name='instrumentationType'>The type of instrumentation provided by this class.</param> /// <param name='managedBaseClassName'>The name of the base class.</param> public InstrumentationClassAttribute(InstrumentationType instrumentationType, string managedBaseClassName) { this.instrumentationType = instrumentationType; this.managedBaseClassName = managedBaseClassName; } /// <summary> /// <para>Gets or sets the type of instrumentation provided by this class.</para> /// </summary> /// <value> /// Contains an <see cref='System.Management.Instrumentation.InstrumentationType'/> value that /// indicates whether this is an instrumented event, instance or abstract class. /// </value> public InstrumentationType InstrumentationType { get { return instrumentationType; } } /// <summary> /// <para>Gets or sets the name of the base class of this instrumentation class.</para> /// </summary> /// <value> /// <para>If not null, this string indicates the WMI baseclass that this class inherits /// from in the CIM schema.</para> /// </value> public string ManagedBaseClassName { get { // This will never return an empty string. Instead, it will // return null, or a non-zero length string if(null == managedBaseClassName || managedBaseClassName.Length == 0) return null; return managedBaseClassName; } } internal static InstrumentationClassAttribute GetAttribute(Type type) { // We don't want BaseEvent or Instance to look like that have an 'InstrumentedClass' attribute if(type == typeof(BaseEvent) || type == typeof(Instance)) return null; // We will inherit the 'InstrumentedClass' attribute from a base class Object [] rg = type.GetCustomAttributes(typeof(InstrumentationClassAttribute), true); if(rg.Length > 0) return ((InstrumentationClassAttribute)rg[0]); return null; } /// <summary> /// <para>Displays the <see langword='Type'/> of the base class.</para> /// </summary> /// <param name='type'></param> /// <returns> /// <para>The <see langword='Type'/> of the base class, if this class is derived from another /// instrumentation class; otherwise, null.</para> /// </returns> internal static Type GetBaseInstrumentationType(Type type) { // If the BaseType has a InstrumentationClass attribute, // we return the BaseType if(GetAttribute(type.BaseType) != null) return type.BaseType; return null; } } /// <summary> /// <para>Allows an instrumented class, or member of an instrumented class, /// to present an alternate name through management instrumentation.</para> /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)] public class ManagedNameAttribute : Attribute { string name; /// <summary> /// <para>Gets the name of the managed entity.</para> /// </summary> /// <value> /// Contains the name of the managed entity. /// </value> public string Name { get { return name ; } } /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.Instrumentation.ManagedNameAttribute'/> class that allows the alternate name to be specified /// for the type, field, property, method, or parameter to which this attribute is applied.</para> /// </summary> /// <param name='name'>The alternate name for the type, field, property, method, or parameter to which this attribute is applied.</param> public ManagedNameAttribute(string name) { this.name = name; } internal static string GetMemberName(MemberInfo member) { // This works for all sorts of things: Type, MethodInfo, PropertyInfo, FieldInfo Object [] rg = member.GetCustomAttributes(typeof(ManagedNameAttribute), false); if(rg.Length > 0) { // bug#69115 - if null or empty string are passed, we just ignore this attribute ManagedNameAttribute attr = (ManagedNameAttribute)rg[0]; if(attr.name != null && attr.name.Length != 0) return attr.name; } return member.Name; } internal static string GetBaseClassName(Type type) { InstrumentationClassAttribute attr = InstrumentationClassAttribute.GetAttribute(type); string name = attr.ManagedBaseClassName; if(name != null) return name; // Get managed base type's attribute InstrumentationClassAttribute attrParent = InstrumentationClassAttribute.GetAttribute(type.BaseType); // If the base type does not have a InstrumentationClass attribute, // return a base type based on the InstrumentationType if(null == attrParent) { switch(attr.InstrumentationType) { case InstrumentationType.Abstract: return null; case InstrumentationType.Instance: return null; case InstrumentationType.Event: return "__ExtrinsicEvent"; default: break; } } // Our parent was also a managed provider type. Use it's managed name. return GetMemberName(type.BaseType); } } /// <summary> /// <para>Allows a particular member of an instrumented class to be ignored /// by management instrumentation</para> /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)] public class IgnoreMemberAttribute : Attribute { } #if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES /// <summary> /// <para>[To be supplied.]</para> /// </summary> [AttributeUsage(AttributeTargets.Field)] public class InheritedPropertyAttribute : Attribute { internal static InheritedPropertyAttribute GetAttribute(FieldInfo field) { Object [] rg = field.GetCustomAttributes(typeof(InheritedPropertyAttribute), false); if(rg.Length > 0) return ((InheritedPropertyAttribute)rg[0]); return null; } } #endif #if SUPPORTS_WMI_DEFAULT_VAULES [AttributeUsage(AttributeTargets.Field)] internal class ManagedDefaultValueAttribute : Attribute { Object defaultValue; public ManagedDefaultValueAttribute(Object defaultValue) { this.defaultValue = defaultValue; } public static Object GetManagedDefaultValue(FieldInfo field) { Object [] rg = field.GetCustomAttributes(typeof(ManagedDefaultValueAttribute), false); if(rg.Length > 0) return ((ManagedDefaultValueAttribute)rg[0]).defaultValue; return null; } } #endif #if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE [AttributeUsage(AttributeTargets.Field)] internal class ManagedTypeAttribute : Attribute { Type type; public ManagedTypeAttribute(Type type) { this.type = type; } public static Type GetManagedType(FieldInfo field) { Object [] rg = field.GetCustomAttributes(typeof(ManagedTypeAttribute), false); if(rg.Length > 0) return ((ManagedTypeAttribute)rg[0]).type; return field.FieldType; } } #endif }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Timers; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace Aurora.Modules.Startup { public class RegisterRegionWithGridModule : ISharedRegionStartupModule, IGridRegisterModule { #region Declares private readonly Dictionary<string, string> genericInfo = new Dictionary<string, string>(); private readonly Dictionary<UUID, List<GridRegion>> m_knownNeighbors = new Dictionary<UUID, List<GridRegion>>(); private readonly List<IScene> m_scenes = new List<IScene>(); private IConfigSource m_config; #endregion #region IGridRegisterModule Members /// <summary> /// Update the grid server with new info about this region /// </summary> /// <param name = "scene"></param> public void UpdateGridRegion(IScene scene) { IGridService GridService = scene.RequestModuleInterface<IGridService>(); GridService.UpdateMap(BuildGridRegion(scene.RegionInfo)); } /// <summary> /// Register this region with the grid service /// </summary> /// <param name = "scene"></param> /// <param name = "returnResponseFirstTime">Should we try to walk the user through what went wrong?</param> public bool RegisterRegionWithGrid(IScene scene, bool returnResponseFirstTime, bool continueTrying) { GridRegion region = BuildGridRegion(scene.RegionInfo); IGenericsConnector g = DataManager.DataManager.RequestPlugin<IGenericsConnector>(); GridSessionID s = null; IGridService GridService = scene.RequestModuleInterface<IGridService>(); if (g != null) //Get the sessionID from the database if possible s = g.GetGeneric<GridSessionID>(scene.RegionInfo.RegionID, "GridSessionID", "GridSessionID"); if (s == null) { s = new GridSessionID {SessionID = scene.RegionInfo.GridSecureSessionID}; //Set it from the regionInfo if it knows anything } scene.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("PreRegisterRegion", region); //Tell the grid service about us RegisterRegion error = GridService.RegisterRegion(region, s.SessionID); if (error.Error == String.Empty) { s.SessionID = error.SessionID; //If it registered ok, we save the sessionID to the database and tlel the neighbor service about it scene.RegionInfo.GridSecureSessionID = error.SessionID; //Update our local copy of what our region flags are scene.RegionInfo.RegionFlags = error.RegionFlags; //Save the new SessionID to the database g.AddGeneric(scene.RegionInfo.RegionID, "GridSessionID", "GridSessionID", s.ToOSD()); m_knownNeighbors[scene.RegionInfo.RegionID] = error.Neighbors; return true; //Success } else { if (returnResponseFirstTime && !continueTrying) { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region with grid failed again - " + error.Error); return false; } //Parse the error and try to do something about it if at all possible if (error.Error == "Region location is reserved") { MainConsole.Instance.Error( "[RegisterRegionWithGrid]: Registration of region with grid failed - The region location you specified is reserved. You must move your region."); int X = 0, Y = 0; int.TryParse(MainConsole.Instance.Prompt("New Region Location X", "1000"), out X); int.TryParse(MainConsole.Instance.Prompt("New Region Location Y", "1000"), out Y); scene.RegionInfo.RegionLocX = X*Constants.RegionSize; scene.RegionInfo.RegionLocY = Y*Constants.RegionSize; IRegionLoader[] loaders = scene.RequestModuleInterfaces<IRegionLoader>(); foreach (IRegionLoader loader in loaders) { loader.UpdateRegionInfo(scene.RegionInfo.RegionName, scene.RegionInfo); } } else if (error.Error == "Region overlaps another region") { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - The region location you specified is already in use. You must move your region."); int X = 0, Y = 0; int.TryParse( MainConsole.Instance.Prompt("New Region Location X", (scene.RegionInfo.RegionLocX/256).ToString()), out X); int.TryParse( MainConsole.Instance.Prompt("New Region Location Y", (scene.RegionInfo.RegionLocY/256).ToString()), out Y); scene.RegionInfo.RegionLocX = X*Constants.RegionSize; scene.RegionInfo.RegionLocY = Y*Constants.RegionSize; IRegionLoader[] loaders = scene.RequestModuleInterfaces<IRegionLoader>(); foreach (IRegionLoader loader in loaders) { loader.UpdateRegionInfo(scene.RegionInfo.RegionName, scene.RegionInfo); } } else if (error.Error.Contains("Can't move this region")) { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - You can not move this region. Moving it back to its original position."); //Opensim Grid Servers don't have this functionality. try { string[] position = error.Error.Split(','); scene.RegionInfo.RegionLocX = int.Parse(position[1])*Constants.RegionSize; scene.RegionInfo.RegionLocY = int.Parse(position[2])*Constants.RegionSize; IRegionLoader[] loaders = scene.RequestModuleInterfaces<IRegionLoader>(); foreach (IRegionLoader loader in loaders) { loader.UpdateRegionInfo(scene.RegionInfo.RegionName, scene.RegionInfo); } } catch (Exception e) { MainConsole.Instance.Error( "Unable to move the region back to its original position, is this an opensim server? Please manually move the region back."); throw e; } } else if (error.Error == "Duplicate region name") { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - The region name you specified is already in use. Please change the name."); string oldRegionName = scene.RegionInfo.RegionName; scene.RegionInfo.RegionName = MainConsole.Instance.Prompt("New Region Name", ""); IRegionLoader[] loaders = scene.RequestModuleInterfaces<IRegionLoader>(); foreach (IRegionLoader loader in loaders) { loader.UpdateRegionInfo(oldRegionName, scene.RegionInfo); } } else if (error.Error == "Region locked out") { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid the failed - The region you are attempting to join has been blocked from connecting. Please connect another region."); MainConsole.Instance.Prompt("Press enter when you are ready to exit"); Environment.Exit(0); } else if (error.Error == "Could not reach grid service") { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - The grid service can not be found! Please make sure that you can connect to the grid server and that the grid server is on."); MainConsole.Instance.Error( "You should also make sure you've provided the correct address and port of the grid service."); string input = MainConsole.Instance.Prompt( "Press enter when you are ready to proceed, or type cancel to exit"); if (input == "cancel") { Environment.Exit(0); } } else if (error.Error == "Wrong Session ID") { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - Wrong Session ID for this region!"); MainConsole.Instance.Error( "This means that this region has failed to connect to the grid server and needs removed from it before it can connect again."); MainConsole.Instance.Error( "If you are running the Aurora.Server instance this region is connecting to, type \"clear grid region <RegionName>\" and then press enter on this console and it will work"); MainConsole.Instance.Error( "If you are not running the Aurora.Server instance this region is connecting to, please contact your grid operator so that he can fix it"); string input = MainConsole.Instance.Prompt( "Press enter when you are ready to proceed, or type cancel to exit"); if (input == "cancel") Environment.Exit(0); } else { MainConsole.Instance.Error("[RegisterRegionWithGrid]: Registration of region " + scene.RegionInfo.RegionName + " with the grid failed - " + error.Error + "!"); string input = MainConsole.Instance.Prompt( "Press enter when you are ready to proceed, or type cancel to exit"); if (input == "cancel") Environment.Exit(0); } return RegisterRegionWithGrid(scene, true, continueTrying); } } public List<GridRegion> GetNeighbors(IScene scene) { if (!m_knownNeighbors.ContainsKey(scene.RegionInfo.RegionID)) return new List<GridRegion>(); else return new List<GridRegion>(m_knownNeighbors[scene.RegionInfo.RegionID]); } public void AddGenericInfo(string key, string value) { genericInfo[key] = value; } #endregion #region GridSessionID class /// <summary> /// This class is used to save the GridSessionID for the given region/grid service /// </summary> public class GridSessionID : IDataTransferable { public UUID SessionID; public override void FromOSD(OSDMap map) { SessionID = map["SessionID"].AsUUID(); } public override OSDMap ToOSD() { OSDMap map = new OSDMap {{"SessionID", SessionID}}; return map; } public override Dictionary<string, object> ToKVP() { return Util.OSDToDictionary(ToOSD()); } public override void FromKVP(Dictionary<string, object> KVP) { FromOSD(Util.DictionaryToOSD(KVP)); } } #endregion #region ISharedRegionStartupModule Members public void Initialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { m_scenes.Add(scene); //Register the interface m_config = source; scene.RegisterModuleInterface<IGridRegisterModule>(this); //Now register our region with the grid RegisterRegionWithGrid(scene, false, true); } public void PostInitialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void FinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void PostFinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { scene.RequestModuleInterface<IAsyncMessageRecievedService>().OnMessageReceived += RegisterRegionWithGridModule_OnMessageReceived; } public void StartupComplete() { } public void Close(IScene scene) { //Deregister the interface scene.UnregisterModuleInterface<IGridRegisterModule>(this); m_scenes.Remove(scene); MainConsole.Instance.InfoFormat("[RegisterRegionWithGrid]: Deregistering region {0} from the grid...", scene.RegionInfo.RegionName); //Deregister from the grid server IGridService GridService = scene.RequestModuleInterface<IGridService>(); GridRegion r = BuildGridRegion(scene.RegionInfo); r.IsOnline = false; string error = ""; if ((error = GridService.UpdateMap(r)) != "") MainConsole.Instance.WarnFormat("[RegisterRegionWithGrid]: Deregister from grid failed for region {0}, {1}", scene.RegionInfo.RegionName, error); } public void DeleteRegion(IScene scene) { IGridService GridService = scene.RequestModuleInterface<IGridService>(); if (!GridService.DeregisterRegion(BuildGridRegion(scene.RegionInfo))) MainConsole.Instance.WarnFormat("[RegisterRegionWithGrid]: Deregister from grid failed for region {0}", scene.RegionInfo.RegionName); } #endregion private OSDMap RegisterRegionWithGridModule_OnMessageReceived(OSDMap message) { if (!message.ContainsKey("Method")) return null; if (message["Method"] == "NeighborChange") { OSDMap innerMessage = (OSDMap) message["Message"]; bool down = innerMessage["Down"].AsBoolean(); UUID regionID = innerMessage["Region"].AsUUID(); UUID targetregionID = innerMessage["TargetRegion"].AsUUID(); if (m_knownNeighbors.ContainsKey(targetregionID)) { if (down) { //Remove it m_knownNeighbors[targetregionID].RemoveAll(delegate(GridRegion r) { if (r.RegionID == regionID) return true; return false; }); } else { //Add it if it doesn't already exist if (m_knownNeighbors[targetregionID].Find(delegate(GridRegion rr) { if (rr.RegionID == regionID) return true; return false; }) == null) m_knownNeighbors[targetregionID].Add(m_scenes[0].GridService.GetRegionByUUID(UUID.Zero, regionID)); } } } return null; } private GridRegion BuildGridRegion(RegionInfo regionInfo) { GridRegion region = new GridRegion(regionInfo); OSDMap map = new OSDMap(); foreach (KeyValuePair<string, string> kvp in genericInfo) { map[kvp.Key] = kvp.Value; } region.GenericMap = map; return region; } } }
using CommandLine; using Mono.Cecil; using Neo.Compiler.MSIL; using Neo.Compiler.Optimizer; using Neo.IO.Json; using Neo.SmartContract; using Neo.SmartContract.Manifest; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Text; namespace Neo.Compiler { public class Program { public class Options { [Option('f', "file", Required = true, HelpText = "File for compile.")] public string File { get; set; } [Option('o', "optimize", Required = false, HelpText = "Optimize.")] public bool Optimize { get; set; } = false; } public static void Main(string[] args) { Parser.Default.ParseArguments<Options>(args).WithParsed(o => Environment.ExitCode = Compile(o)); } public static int Compile(Options options, ILogger log = null) { // Set console Console.OutputEncoding = Encoding.UTF8; log ??= new DefLogger(); log.Log("Neo.Compiler.MSIL console app v" + Assembly.GetAssembly(typeof(Program)).GetName().Version); var fileInfo = new FileInfo(options.File); // Set current directory if (!fileInfo.Exists) { log.Log("Could not find file " + fileInfo.FullName); return -1; } Stream fs; Stream fspdb; var onlyname = Path.GetFileNameWithoutExtension(fileInfo.Name); var path = fileInfo.Directory.FullName; if (!string.IsNullOrEmpty(path)) { try { Directory.SetCurrentDirectory(path); } catch { log.Log("Could not find path: " + path); return -1; } } switch (fileInfo.Extension.ToLowerInvariant()) { case ".csproj": { // Compile csproj file log.Log("Compiling from csproj project"); var output = Compiler.CompileCSProj(fileInfo.FullName); fs = new MemoryStream(output.Dll); fspdb = new MemoryStream(output.Pdb); break; } case ".vbproj": { // Compile vbproj file log.Log("Compiling from vbproj project"); var output = Compiler.CompileVBProj(fileInfo.FullName); fs = new MemoryStream(output.Dll); fspdb = new MemoryStream(output.Pdb); break; } case ".cs": { // Compile C# files log.Log("Compiling from c# source"); var output = Compiler.CompileCSFiles(new string[] { fileInfo.FullName }, new string[0]); fs = new MemoryStream(output.Dll); fspdb = new MemoryStream(output.Pdb); break; } case ".vb": { // Compile VB files log.Log("Compiling from VB source"); var output = Compiler.CompileVBFiles(new string[] { fileInfo.FullName }, new string[0]); fs = new MemoryStream(output.Dll); fspdb = new MemoryStream(output.Pdb); break; } case ".dll": { string filepdb = onlyname + ".pdb"; // Open file try { fs = fileInfo.OpenRead(); if (File.Exists(filepdb)) { fspdb = File.OpenRead(filepdb); } else { fspdb = null; } } catch (Exception err) { log.Log("Open File Error:" + err.ToString()); return -1; } break; } default: { log.Log("File format not supported by neon: " + path); return -1; } } ILModule mod = new ILModule(log); // Load module try { mod.LoadModule(fs, fspdb); } catch (Exception err) { log.Log("LoadModule Error:" + err.ToString()); return -1; } JObject abi; byte[] bytes; int bSucc = 0; string debugstr = null; NeoModule module; // Convert and build try { var conv = new ModuleConverter(log); ConvOption option = new ConvOption(); module = conv.Convert(mod, option); bytes = module.Build(); log.Log("convert succ"); Dictionary<int, int> addrConvTable = null; if (options.Optimize) { HashSet<int> entryPoints = new HashSet<int>(); foreach (var func in module.mapMethods) { entryPoints.Add(func.Value.funcaddr); } var optimize = NefOptimizeTool.Optimize(bytes, entryPoints.ToArray(), out addrConvTable); log.Log("optimization succ " + (((bytes.Length / (optimize.Length + 0.0)) * 100.0) - 100).ToString("0.00 '%'")); bytes = optimize; } try { abi = FuncExport.Export(module, bytes, addrConvTable); log.Log("gen abi succ"); } catch (Exception err) { log.Log("gen abi Error:" + err.ToString()); return -1; } try { var outjson = DebugExport.Export(module, bytes, addrConvTable); debugstr = outjson.ToString(false); log.Log("gen debug succ"); } catch (Exception err) { log.Log("gen debug Error:" + err.ToString()); } } catch (Exception err) { log.Log("Convert Error:" + err.ToString()); return -1; } // Write bytes try { string bytesname = onlyname + ".nef"; var nef = new NefFile { Compiler = "neon", Version = Version.Parse(((AssemblyFileVersionAttribute)Assembly.GetAssembly(typeof(Program)) .GetCustomAttribute(typeof(AssemblyFileVersionAttribute))).Version), Script = bytes, ScriptHash = bytes.ToScriptHash() }; nef.CheckSum = NefFile.ComputeChecksum(nef); File.Delete(bytesname); using (var stream = File.OpenWrite(bytesname)) using (var writer = new BinaryWriter(stream)) { nef.Serialize(writer); } log.Log("write:" + bytesname); bSucc++; } catch (Exception err) { log.Log("Write Bytes Error:" + err.ToString()); return -1; } try { var sbABI = abi.ToString(false); string abiname = onlyname + ".abi.json"; File.Delete(abiname); File.WriteAllText(abiname, sbABI.ToString()); log.Log("write:" + abiname); bSucc++; } catch (Exception err) { log.Log("Write abi Error:" + err.ToString()); return -1; } try { string debugname = onlyname + ".debug.json"; string debugzip = onlyname + ".nefdbgnfo"; var tempName = Path.GetTempFileName(); File.Delete(tempName); File.WriteAllText(tempName, debugstr); File.Delete(debugzip); using (var archive = ZipFile.Open(debugzip, ZipArchiveMode.Create)) { archive.CreateEntryFromFile(tempName, Path.GetFileName(debugname)); } File.Delete(tempName); log.Log("write:" + debugzip); bSucc++; } catch (Exception err) { log.Log("Write debug Error:" + err.ToString()); return -1; } try { string manifest = onlyname + ".manifest.json"; var defManifest = FuncExport.GenerateManifest(abi, module); File.Delete(manifest); File.WriteAllText(manifest, defManifest); log.Log("write:" + manifest); bSucc++; } catch (Exception err) { log.Log("Write manifest Error:" + err.ToString()); return -1; } try { fs.Dispose(); if (fspdb != null) fspdb.Dispose(); } catch { } if (bSucc == 4) { log.Log("SUCC"); return 0; } return -1; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionDisksClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionDiskRequest request = new GetRegionDiskRequest { Disk = "disk028b6875", Region = "regionedb20d96", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Disk response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionDiskRequest request = new GetRegionDiskRequest { Disk = "disk028b6875", Region = "regionedb20d96", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Disk responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Disk responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionDiskRequest request = new GetRegionDiskRequest { Disk = "disk028b6875", Region = "regionedb20d96", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Disk response = client.Get(request.Project, request.Region, request.Disk); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionDiskRequest request = new GetRegionDiskRequest { Disk = "disk028b6875", Region = "regionedb20d96", Project = "projectaa6ff846", }; Disk expectedResponse = new Disk { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Type = "typee2cc9d59", Zone = "zone255f4ea8", ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", LastAttachTimestamp = "last_attach_timestamp4fe3fe94", LicenseCodes = { -3549522739643304114L, }, ReplicaZones = { "replica_zonesc1977354", }, SourceImage = "source_image5e9c0c38", SourceImageId = "source_image_id954b5e55", LastDetachTimestamp = "last_detach_timestampffef196b", GuestOsFeatures = { new GuestOsFeature(), }, SourceSnapshotId = "source_snapshot_id008ab5dd", Users = { "users2a5cc69b", }, SourceSnapshot = "source_snapshot1fcf3da1", Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", Status = "status5444cb9a", ProvisionedIops = -3779563869670119518L, SourceStorageObject = "source_storage_object4e059972", DiskEncryptionKey = new CustomerEncryptionKey(), SourceSnapshotEncryptionKey = new CustomerEncryptionKey(), Licenses = { "licensesd1cc2f9d", }, LocationHint = "location_hint666f366c", Options = "optionsa965da93", SourceImageEncryptionKey = new CustomerEncryptionKey(), PhysicalBlockSizeBytes = -7292518380745299537L, Description = "description2cf9da67", SourceDisk = "source_disk0eec086f", SourceDiskId = "source_disk_id020f9fb8", SelfLink = "self_link7e87f12d", SatisfiesPzs = false, SizeGb = -3653169847519542788L, Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Disk>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Disk responseCallSettings = await client.GetAsync(request.Project, request.Region, request.Disk, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Disk responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.Disk, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyRegionDiskRequest request = new GetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyRegionDiskRequest request = new GetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyRegionDiskRequest request = new GetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Region, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyRegionDiskRequest request = new GetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Region, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyRegionDiskRequest request = new SetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyRegionDiskRequest request = new SetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyRegionDiskRequest request = new SetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyRegionDiskRequest request = new SetIamPolicyRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", RegionSetPolicyRequestResource = new RegionSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Region, request.Resource, request.RegionSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsRegionDiskRequest request = new TestIamPermissionsRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsRegionDiskRequest request = new TestIamPermissionsRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsRegionDiskRequest request = new TestIamPermissionsRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<RegionDisks.RegionDisksClient> mockGrpcClient = new moq::Mock<RegionDisks.RegionDisksClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsRegionDiskRequest request = new TestIamPermissionsRegionDiskRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionDisksClient client = new RegionDisksClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ConfigService.Model { /// <summary> /// An AWS Lambda function that evaluates configuration items to assess whether your AWS /// resources comply with your desired configurations. This function can run when AWS /// Config detects a configuration change or delivers a configuration snapshot. This function /// can evaluate any resource in the recording group. To define which of these are evaluated, /// specify a value for the <code>Scope</code> key. /// /// /// <para> /// For more information about developing and using AWS Config rules, see <a href="http://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html">Evaluating /// AWS Resource Configurations with AWS Config</a> in the <i>AWS Config Developer Guide</i>. /// </para> /// </summary> public partial class ConfigRule { private string _configRuleArn; private string _configRuleId; private string _configRuleName; private ConfigRuleState _configRuleState; private string _description; private string _inputParameters; private MaximumExecutionFrequency _maximumExecutionFrequency; private Scope _scope; private Source _source; /// <summary> /// Gets and sets the property ConfigRuleArn. /// <para> /// The Amazon Resource Name (ARN) of the AWS Config rule. /// </para> /// </summary> public string ConfigRuleArn { get { return this._configRuleArn; } set { this._configRuleArn = value; } } // Check to see if ConfigRuleArn property is set internal bool IsSetConfigRuleArn() { return this._configRuleArn != null; } /// <summary> /// Gets and sets the property ConfigRuleId. /// <para> /// The ID of the AWS Config rule. /// </para> /// </summary> public string ConfigRuleId { get { return this._configRuleId; } set { this._configRuleId = value; } } // Check to see if ConfigRuleId property is set internal bool IsSetConfigRuleId() { return this._configRuleId != null; } /// <summary> /// Gets and sets the property ConfigRuleName. /// <para> /// The name that you assign to the AWS Config rule. The name is required if you are adding /// a new rule. /// </para> /// </summary> public string ConfigRuleName { get { return this._configRuleName; } set { this._configRuleName = value; } } // Check to see if ConfigRuleName property is set internal bool IsSetConfigRuleName() { return this._configRuleName != null; } /// <summary> /// Gets and sets the property ConfigRuleState. /// <para> /// Indicates whether the AWS Config rule is active or currently being deleted by AWS /// Config. /// </para> /// /// <para> /// AWS Config sets the state of a rule to <code>DELETING</code> temporarily after you /// use the <code>DeleteConfigRule</code> request to delete the rule. After AWS Config /// finishes deleting a rule, the rule and all of its evaluations are erased and no longer /// available. /// </para> /// /// <para> /// You cannot add a rule to AWS Config that has the state set to <code>DELETING</code>. /// If you want to delete a rule, you must use the <code>DeleteConfigRule</code> request. /// </para> /// </summary> public ConfigRuleState ConfigRuleState { get { return this._configRuleState; } set { this._configRuleState = value; } } // Check to see if ConfigRuleState property is set internal bool IsSetConfigRuleState() { return this._configRuleState != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// The description that you provide for the AWS Config rule. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property InputParameters. /// <para> /// A string in JSON format that is passed to the AWS Config rule Lambda function. /// </para> /// </summary> public string InputParameters { get { return this._inputParameters; } set { this._inputParameters = value; } } // Check to see if InputParameters property is set internal bool IsSetInputParameters() { return this._inputParameters != null; } /// <summary> /// Gets and sets the property MaximumExecutionFrequency. /// <para> /// The maximum frequency at which the AWS Config rule runs evaluations. /// </para> /// /// <para> /// If your rule is periodic, meaning it runs an evaluation when AWS Config delivers a /// configuration snapshot, then it cannot run evaluations more frequently than AWS Config /// delivers the snapshots. For periodic rules, set the value of the <code>MaximumExecutionFrequency</code> /// key to be equal to or greater than the value of the <code>deliveryFrequency</code> /// key, which is part of <code>ConfigSnapshotDeliveryProperties</code>. To update the /// frequency with which AWS Config delivers your snapshots, use the <code>PutDeliveryChannel</code> /// action. /// </para> /// </summary> public MaximumExecutionFrequency MaximumExecutionFrequency { get { return this._maximumExecutionFrequency; } set { this._maximumExecutionFrequency = value; } } // Check to see if MaximumExecutionFrequency property is set internal bool IsSetMaximumExecutionFrequency() { return this._maximumExecutionFrequency != null; } /// <summary> /// Gets and sets the property Scope. /// <para> /// Defines which resources the AWS Config rule evaluates. The scope can include one or /// more resource types, a combination of a tag key and value, or a combination of one /// resource type and one or more resource IDs. Specify a scope to constrain the resources /// that are evaluated. If you do not specify a scope, the AWS Config Rule evaluates all /// resources in the recording group. /// </para> /// </summary> public Scope Scope { get { return this._scope; } set { this._scope = value; } } // Check to see if Scope property is set internal bool IsSetScope() { return this._scope != null; } /// <summary> /// Gets and sets the property Source. /// <para> /// Provides the rule owner (AWS or customer), the rule identifier, and the events that /// cause the function to evaluate your AWS resources. /// </para> /// </summary> public Source Source { get { return this._source; } set { this._source = value; } } // Check to see if Source property is set internal bool IsSetSource() { return this._source != null; } } }
/********************************************************************/ /* Office 2007 Renderer Project */ /* */ /* Use the Office2007Renderer class as a custom renderer by */ /* providing it to the ToolStripManager.Renderer property. Then */ /* all tool strips, menu strips, status strips etc will be drawn */ /* using the Office 2007 style renderer in your application. */ /* */ /* Author: Phil Wright */ /* Website: www.componentfactory.com */ /* Contact: phil.wright@componentfactory.com */ /********************************************************************/ using System.Drawing; using System.Windows.Forms; namespace Office2007Renderer { /// <summary> /// Provide Office 2007 Blue Theme colors /// </summary> public class Office2007ColorTable : ProfessionalColorTable { #region Static Fixed Colors - Blue Color Scheme private static Color _contextMenuBack = Color.FromArgb(250, 250, 250); private static Color _buttonPressedBegin = Color.FromArgb(248, 181, 106); private static Color _buttonPressedEnd = Color.FromArgb(255, 208, 134); private static Color _buttonPressedMiddle = Color.FromArgb(251, 140, 60); private static Color _buttonSelectedBegin = Color.FromArgb(255, 255, 222); private static Color _buttonSelectedEnd = Color.FromArgb(255, 203, 136); private static Color _buttonSelectedMiddle = Color.FromArgb(255, 225, 172); private static Color _menuItemSelectedBegin = Color.FromArgb(255, 213, 103); private static Color _menuItemSelectedEnd = Color.FromArgb(255, 228, 145); private static Color _checkBack = Color.FromArgb(255, 227, 149); private static Color _gripDark = Color.FromArgb(111, 157, 217); private static Color _gripLight = Color.FromArgb(255, 255, 255); private static Color _imageMargin = Color.FromArgb(233, 238, 238); private static Color _menuBorder = Color.FromArgb(134, 134, 134); private static Color _overflowBegin = Color.FromArgb(167, 204, 251); private static Color _overflowEnd = Color.FromArgb(101, 147, 207); private static Color _overflowMiddle = Color.FromArgb(167, 204, 251); private static Color _menuToolBack = Color.FromArgb(191, 219, 255); private static Color _separatorDark = Color.FromArgb(154, 198, 255); private static Color _separatorLight = Color.FromArgb(255, 255, 255); private static Color _statusStripLight = Color.FromArgb(215, 229, 247); private static Color _statusStripDark = Color.FromArgb(172, 201, 238); private static Color _toolStripBorder = Color.FromArgb(111, 157, 217); private static Color _toolStripContentEnd = Color.FromArgb(164, 195, 235); private static Color _toolStripBegin = Color.FromArgb(227, 239, 255); private static Color _toolStripEnd = Color.FromArgb(152, 186, 230); private static Color _toolStripMiddle = Color.FromArgb(222, 236, 255); private static Color _buttonBorder = Color.FromArgb(121, 153, 194); private static Color _textDisabled = Color.FromArgb(167, 167, 167); private static Color _textMenuStripItem = Color.FromArgb(21, 66, 139); private static Color _textStatusStripItem = Color.FromArgb(21, 66, 139); private static Color _textContextMenuItem = Color.FromArgb(21, 66, 139); private static Color _arrowDisabled = Color.FromArgb(167, 167, 167); private static Color _arrowLight = Color.FromArgb(106, 126, 197); private static Color _arrowDark = Color.FromArgb(64, 70, 90); private static Color _separatorMenuLight = Color.FromArgb(245, 245, 245); private static Color _separatorMenuDark = Color.FromArgb(197, 197, 197); private static Color _contextCheckBorder = Color.FromArgb(242, 149, 54); private static Color _contextCheckTick = Color.FromArgb(66, 75, 138); private static Color _statusStripBorderDark = Color.FromArgb(86, 125, 176); private static Color _statusStripBorderLight = Color.White; #endregion #region Identity /// <summary> /// Initialize a new instance of the Office2007ColorTable class. /// </summary> public Office2007ColorTable() { } #endregion #region ButtonPressed /// <summary> /// Gets the starting color of the gradient used when the button is pressed down. /// </summary> public override Color ButtonPressedGradientBegin { get { return _buttonPressedBegin; } } /// <summary> /// Gets the end color of the gradient used when the button is pressed down. /// </summary> public override Color ButtonPressedGradientEnd { get { return _buttonPressedEnd; } } /// <summary> /// Gets the middle color of the gradient used when the button is pressed down. /// </summary> public override Color ButtonPressedGradientMiddle { get { return _buttonPressedMiddle; } } #endregion #region ButtonSelected /// <summary> /// Gets the starting color of the gradient used when the button is selected. /// </summary> public override Color ButtonSelectedGradientBegin { get { return _buttonSelectedBegin; } } /// <summary> /// Gets the end color of the gradient used when the button is selected. /// </summary> public override Color ButtonSelectedGradientEnd { get { return _buttonSelectedEnd; } } /// <summary> /// Gets the middle color of the gradient used when the button is selected. /// </summary> public override Color ButtonSelectedGradientMiddle { get { return _buttonSelectedMiddle; } } /// <summary> /// Gets the border color to use with ButtonSelectedHighlight. /// </summary> public override Color ButtonSelectedHighlightBorder { get { return _buttonBorder; } } #endregion #region Check /// <summary> /// Gets the solid color to use when the check box is selected and gradients are being used. /// </summary> public override Color CheckBackground { get { return _checkBack; } } #endregion #region Grip /// <summary> /// Gets the color to use for shadow effects on the grip or move handle. /// </summary> public override Color GripDark { get { return _gripDark; } } /// <summary> /// Gets the color to use for highlight effects on the grip or move handle. /// </summary> public override Color GripLight { get { return _gripLight; } } #endregion #region ImageMargin /// <summary> /// Gets the starting color of the gradient used in the image margin of a ToolStripDropDownMenu. /// </summary> public override Color ImageMarginGradientBegin { get { return _imageMargin; } } #endregion #region MenuBorder /// <summary> /// Gets the border color or a MenuStrip. /// </summary> public override Color MenuBorder { get { return _menuBorder; } } #endregion #region MenuItem /// <summary> /// Gets the starting color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientBegin { get { return _toolStripBegin; } } /// <summary> /// Gets the end color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientEnd { get { return _toolStripEnd; } } /// <summary> /// Gets the middle color of the gradient used when a top-level ToolStripMenuItem is pressed down. /// </summary> public override Color MenuItemPressedGradientMiddle { get { return _toolStripMiddle; } } /// <summary> /// Gets the starting color of the gradient used when the ToolStripMenuItem is selected. /// </summary> public override Color MenuItemSelectedGradientBegin { get { return _menuItemSelectedBegin; } } /// <summary> /// Gets the end color of the gradient used when the ToolStripMenuItem is selected. /// </summary> public override Color MenuItemSelectedGradientEnd { get { return _menuItemSelectedEnd; } } #endregion #region MenuStrip /// <summary> /// Gets the starting color of the gradient used in the MenuStrip. /// </summary> public override Color MenuStripGradientBegin { get { return _menuToolBack; } } /// <summary> /// Gets the end color of the gradient used in the MenuStrip. /// </summary> public override Color MenuStripGradientEnd { get { return _menuToolBack; } } #endregion #region OverflowButton /// <summary> /// Gets the starting color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientBegin { get { return _overflowBegin; } } /// <summary> /// Gets the end color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientEnd { get { return _overflowEnd; } } /// <summary> /// Gets the middle color of the gradient used in the ToolStripOverflowButton. /// </summary> public override Color OverflowButtonGradientMiddle { get { return _overflowMiddle; } } #endregion #region RaftingContainer /// <summary> /// Gets the starting color of the gradient used in the ToolStripContainer. /// </summary> public override Color RaftingContainerGradientBegin { get { return _menuToolBack; } } /// <summary> /// Gets the end color of the gradient used in the ToolStripContainer. /// </summary> public override Color RaftingContainerGradientEnd { get { return _menuToolBack; } } #endregion #region Separator /// <summary> /// Gets the color to use to for shadow effects on the ToolStripSeparator. /// </summary> public override Color SeparatorDark { get { return _separatorDark; } } /// <summary> /// Gets the color to use to for highlight effects on the ToolStripSeparator. /// </summary> public override Color SeparatorLight { get { return _separatorLight; } } #endregion #region StatusStrip /// <summary> /// Gets the starting color of the gradient used on the StatusStrip. /// </summary> public override Color StatusStripGradientBegin { get { return _statusStripLight; } } /// <summary> /// Gets the end color of the gradient used on the StatusStrip. /// </summary> public override Color StatusStripGradientEnd { get { return _statusStripDark; } } #endregion #region ToolStrip /// <summary> /// Gets the border color to use on the bottom edge of the ToolStrip. /// </summary> public override Color ToolStripBorder { get { return _toolStripBorder; } } /// <summary> /// Gets the starting color of the gradient used in the ToolStripContentPanel. /// </summary> public override Color ToolStripContentPanelGradientBegin { get { return _toolStripContentEnd; } } /// <summary> /// Gets the end color of the gradient used in the ToolStripContentPanel. /// </summary> public override Color ToolStripContentPanelGradientEnd { get { return _menuToolBack; } } /// <summary> /// Gets the solid background color of the ToolStripDropDown. /// </summary> public override Color ToolStripDropDownBackground { get { return _contextMenuBack; } } /// <summary> /// Gets the starting color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientBegin { get { return _toolStripBegin; } } /// <summary> /// Gets the end color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientEnd { get { return _toolStripEnd; } } /// <summary> /// Gets the middle color of the gradient used in the ToolStrip background. /// </summary> public override Color ToolStripGradientMiddle { get { return _toolStripMiddle; } } /// <summary> /// Gets the starting color of the gradient used in the ToolStripPanel. /// </summary> public override Color ToolStripPanelGradientBegin { get { return _menuToolBack; } } /// <summary> /// Gets the end color of the gradient used in the ToolStripPanel. /// </summary> public override Color ToolStripPanelGradientEnd { get { return _menuToolBack; } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.IO; using System.Text; using System.Windows.Forms; using DeOps.Implementation; using DeOps.Interface; using DeOps.Services.Trust; namespace DeOps.Services.Mail { public partial class ComposeMail : ViewShell { CoreUI UI; MailService Mail; OpCore Core; ulong DefaultID; bool MessageSent; public string CustomTitle; public int ThreadID; List<ulong> ToIDs = new List<ulong>(); public ComposeMail(CoreUI ui, MailService mail, ulong id) { InitializeComponent(); UI = ui; Mail = mail; Core = mail.Core; DefaultID = id; if (id != 0) { ToTextBox.Text = Core.GetName(id); ToIDs.Add(id); } } private void ComposeMail_Load(object sender, EventArgs e) { MessageBody.InputBox.Select(); } public override string GetTitle(bool small) { if (small) return "Compose"; if(CustomTitle != null) return CustomTitle + Core.GetName(DefaultID); if (DefaultID != 0) return "Mail " + Core.GetName(DefaultID); return "Compose Mail"; } public override Size GetDefaultSize() { return new Size(450, 525); } public override Icon GetIcon() { return MailRes.Compose; } public override bool Fin() { if (!MessageSent && MessageBody.InputBox.Text.Length > 0) if (MessageBox.Show(this, "Discard Message?", "New Mail", MessageBoxButtons.YesNo) == DialogResult.No) return false; return true; } private void LinkAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { OpenFileDialog open = new OpenFileDialog(); open.Multiselect = true; open.Title = "Add Files to Mail"; open.Filter = "All files (*.*)|*.*"; if (open.ShowDialog() == DialogResult.OK) foreach (string path in open.FileNames) { bool added = false; foreach (AttachedFile attached in ListFiles.Items) if (attached.FilePath == path) added = true; if (!added) ListFiles.Items.Add(new AttachedFile(path)); } if (ListFiles.SelectedItem == null && ListFiles.Items.Count > 0) ListFiles.SelectedItem = ListFiles.Items[0]; } private void LinkRemove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (ListFiles.SelectedItem != null) { int index = ListFiles.Items.IndexOf(ListFiles.SelectedItem); ListFiles.Items.Remove(ListFiles.SelectedItem); if (ListFiles.Items.Count > 0) { if (index < ListFiles.Items.Count) ListFiles.SelectedItem = ListFiles.Items[index]; else if (index - 1 < ListFiles.Items.Count) ListFiles.SelectedItem = ListFiles.Items[index - 1]; } } } private void SendButton_Click(object sender, EventArgs e) { try { if(ToIDs.Count == 0) throw new Exception("Letter not addressed to anyone"); // files List<AttachedFile> files = new List<AttachedFile>(); foreach (AttachedFile file in ListFiles.Items) files.Add(file); // subject if (SubjectTextBox.Text.Length == 0) throw new Exception("Subject is blank"); // body if (MessageBody.InputBox.Text.Length == 0) throw new Exception("Message body is blank"); string message = (MessageBody.TextFormat == TextFormat.Plain) ? MessageBody.InputBox.Text : MessageBody.InputBox.Rtf; Mail.SendMail(ToIDs, files, SubjectTextBox.Text, message, MessageBody.TextFormat, GuiUtils.GetQuip(message, MessageBody.TextFormat), ThreadID); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } MessageSent = true; if (External != null) External.Close(); } private void CancelButton_Click(object sender, EventArgs e) { if (External != null) External.Close(); } private void BrowseTo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { AddUsersDialog add = new AddUsersDialog(UI, 0); string prefix = ToTextBox.Text.Length > 0 ? ", " : ""; if (add.ShowDialog(this) == DialogResult.OK) { foreach (ulong id in add.People) if (!ToIDs.Contains(id)) ToIDs.Add(id); UpdateToText(); } } private void RemovePersonLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { RemoveLinks form = new RemoveLinks(Core, ToIDs); if (form.ShowDialog(this) == DialogResult.OK) { foreach (ulong id in form.RemoveIDs) if (ToIDs.Contains(id)) ToIDs.Remove(id) ; UpdateToText(); } } void UpdateToText() { string text = ""; foreach (ulong id in ToIDs) text += Core.GetName(id) + ", "; ToTextBox.Text = text.TrimEnd(',', ' '); } private void BrowseCC_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.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. // * 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 Rodrigo B. de Oliveira 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 // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class ForStatement : Statement { protected DeclarationCollection _declarations; protected Expression _iterator; protected Block _block; protected Block _orBlock; protected Block _thenBlock; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ForStatement CloneNode() { return (ForStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public ForStatement CleanClone() { return (ForStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.ForStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnForStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( ForStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("ForStatement._modifier"); if (!Node.AllMatch(_declarations, other._declarations)) return NoMatch("ForStatement._declarations"); if (!Node.Matches(_iterator, other._iterator)) return NoMatch("ForStatement._iterator"); if (!Node.Matches(_block, other._block)) return NoMatch("ForStatement._block"); if (!Node.Matches(_orBlock, other._orBlock)) return NoMatch("ForStatement._orBlock"); if (!Node.Matches(_thenBlock, other._thenBlock)) return NoMatch("ForStatement._thenBlock"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_declarations != null) { Declaration item = existing as Declaration; if (null != item) { Declaration newItem = (Declaration)newNode; if (_declarations.Replace(item, newItem)) { return true; } } } if (_iterator == existing) { this.Iterator = (Expression)newNode; return true; } if (_block == existing) { this.Block = (Block)newNode; return true; } if (_orBlock == existing) { this.OrBlock = (Block)newNode; return true; } if (_thenBlock == existing) { this.ThenBlock = (Block)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { ForStatement clone = new ForStatement(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _declarations) { clone._declarations = _declarations.Clone() as DeclarationCollection; clone._declarations.InitializeParent(clone); } if (null != _iterator) { clone._iterator = _iterator.Clone() as Expression; clone._iterator.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as Block; clone._block.InitializeParent(clone); } if (null != _orBlock) { clone._orBlock = _orBlock.Clone() as Block; clone._orBlock.InitializeParent(clone); } if (null != _thenBlock) { clone._thenBlock = _thenBlock.Clone() as Block; clone._thenBlock.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _declarations) { _declarations.ClearTypeSystemBindings(); } if (null != _iterator) { _iterator.ClearTypeSystemBindings(); } if (null != _block) { _block.ClearTypeSystemBindings(); } if (null != _orBlock) { _orBlock.ClearTypeSystemBindings(); } if (null != _thenBlock) { _thenBlock.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(Declaration))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public DeclarationCollection Declarations { get { return _declarations ?? (_declarations = new DeclarationCollection(this)); } set { if (_declarations != value) { _declarations = value; if (null != _declarations) { _declarations.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Iterator { get { return _iterator; } set { if (_iterator != value) { _iterator = value; if (null != _iterator) { _iterator.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block Block { get { if (_block == null) { _block = new Block(); _block.InitializeParent(this); } return _block; } set { if (_block != value) { _block = value; if (null != _block) { _block.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block OrBlock { get { return _orBlock; } set { if (_orBlock != value) { _orBlock = value; if (null != _orBlock) { _orBlock.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block ThenBlock { get { return _thenBlock; } set { if (_thenBlock != value) { _thenBlock = value; if (null != _thenBlock) { _thenBlock.InitializeParent(this); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Globalization; using Xunit; public class Queue_TrimToSize { public bool runTest() { //////////// Global Variables used for all tests String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; Queue que; Object dequeuedValue; try { ///////////////////////// START TESTS //////////////////////////// iCountTestcases++; que = new Queue(); try { que.TrimToSize(); } catch (Exception) { iCountErrors++; } que = new Queue(); for (int i = 0; i < 1000; i++) { que.Enqueue(i); } try { que.TrimToSize(); } catch (Exception) { iCountErrors++; } que = new Queue(100000); try { que.TrimToSize(); } catch (Exception) { iCountErrors++; } //[]Empty Queue iCountTestcases++; que = new Queue(); que.TrimToSize(); if (que.Count != 0) { iCountErrors++; } que.Enqueue(100); if ((int)(dequeuedValue = que.Dequeue()) != 100) { iCountErrors++; } //[]After Clear iCountTestcases++; que = new Queue(); // Insert 50 items in the Queue for (int i = 0; i < 100; i++) { que.Enqueue(i); } que.Clear(); que.TrimToSize(); if (que.Count != 0) { iCountErrors++; } que.Enqueue(100); if ((int)(dequeuedValue = que.Dequeue()) != 100) { iCountErrors++; } //[]After Dequeue all items iCountTestcases++; que = new Queue(); // Insert 50 items in the Queue for (int i = 0; i < 100; i++) { que.Enqueue(i); } for (int i = 0; i < 100; i++) { que.Dequeue(); } que.TrimToSize(); if (que.Count != 0) { iCountErrors++; } que.Enqueue(100); if ((int)(dequeuedValue = que.Dequeue()) != 100) { iCountErrors++; } //[]TrimToSize then Dequeue then EnQueue iCountTestcases++; que = new Queue(); // Insert 50 items in the Queue for (int i = 0; i < 100; i++) { que.Enqueue(i); } que.TrimToSize(); if (que.Count != 100) { iCountErrors++; } if ((int)(dequeuedValue = que.Dequeue()) != 0) { iCountErrors++; } que.Enqueue(100); if ((int)(dequeuedValue = que.Dequeue()) != 1) { iCountErrors++; Console.WriteLine("Err_51084aheid! wrong value returned Expected={0} Actual={1}", 1, dequeuedValue); } //[] Wrap the queue then dequeue and enqueue iCountTestcases++; que = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { que.Enqueue(i); } // Insert and Remove 75 items in the Queue this should wrap the queue // Where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { que.Enqueue(i + 50); que.Dequeue(); } que.TrimToSize(); if (50 != que.Count) { iCountErrors++; Console.WriteLine("Err_154488ahjeid! Count wrong value returned Expected={0} Actual={1}", 50, que.Count); } if ((int)(dequeuedValue = que.Dequeue()) != 75) { iCountErrors++; Console.WriteLine("Err_410848ajeid! wrong value returned Expected={0} Actual={1}", 50, dequeuedValue); } // Add an item to the Queue que.Enqueue(100); if (50 != que.Count) { iCountErrors++; Console.WriteLine("Err_152180ajekd! Count wrong value returned Expected={0} Actual={1}", 50, que.Count); } if ((int)(dequeuedValue = que.Dequeue()) != 76) { iCountErrors++; Console.WriteLine("Err_5154ejhae! wrong value returned Expected={0} Actual={1}", 51, dequeuedValue); } //[] Wrap the queue then enqueue and dequeue iCountTestcases++; que = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { que.Enqueue(i); } // Insert and Remove 75 items in the Queue this should wrap the queue // Where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { que.Enqueue(i + 50); que.Dequeue(); } que.TrimToSize(); if (50 != que.Count) { iCountErrors++; Console.WriteLine("Err_15418ajioed! Count wrong value returned Expected={0} Actual={1}", 50, que.Count); } // Add an item to the Queue que.Enqueue(100); if ((int)(dequeuedValue = que.Dequeue()) != 75) { iCountErrors++; Console.WriteLine("Err_211508ajoied! wrong value returned Expected={0} Actual={1}", 50, dequeuedValue); } // Add an item to the Queue que.Enqueue(101); if (51 != que.Count) { iCountErrors++; Console.WriteLine("Err_4055ajeid! Count wrong value returned Expected={0} Actual={1}", 51, que.Count); } if ((int)(dequeuedValue = que.Dequeue()) != 76) { iCountErrors++; Console.WriteLine("Err_440815ajkejid! wrong value returned Expected={0} Actual={1}", 51, dequeuedValue); } //[]vanilla SYNCHRONIZED iCountTestcases++; que = new Queue(); que = Queue.Synchronized(que); try { que.TrimToSize(); } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_1689asdfa! unexpected exception thrown," + ex.GetType().Name); } que = new Queue(); que = Queue.Synchronized(que); for (int i = 0; i < 1000; i++) { que.Enqueue(i); } try { que.TrimToSize(); } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_79446jhjk! unexpected exception thrown," + ex.GetType().Name); } que = new Queue(100000); que = Queue.Synchronized(que); try { que.TrimToSize(); } catch (Exception ex) { iCountErrors++; Console.WriteLine("Err_4156hjkj! unexpected exception thrown," + ex.GetType().Name); } /////////////////////////////////////////////////////////////////// /////////////////////////// END TESTS ///////////////////////////// } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(" : Error Err_8888yyy! exc_general==" + exc_general.ToString()); } //// Finish Diagnostics return iCountErrors == 0; } [Fact] public static void ExecuteQueue_TrimToSize() { bool bResult = false; var test = new Queue_TrimToSize(); try { bResult = test.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("Fail! Error Err_main! Uncaught Exception in main(), exc_main==" + exc_main); } Assert.True(bResult); } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ColumnLinkRequest. /// </summary> public partial class ColumnLinkRequest : BaseRequest, IColumnLinkRequest { /// <summary> /// Constructs a new ColumnLinkRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ColumnLinkRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified ColumnLink using POST. /// </summary> /// <param name="columnLinkToCreate">The ColumnLink to create.</param> /// <returns>The created ColumnLink.</returns> public System.Threading.Tasks.Task<ColumnLink> CreateAsync(ColumnLink columnLinkToCreate) { return this.CreateAsync(columnLinkToCreate, CancellationToken.None); } /// <summary> /// Creates the specified ColumnLink using POST. /// </summary> /// <param name="columnLinkToCreate">The ColumnLink to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ColumnLink.</returns> public async System.Threading.Tasks.Task<ColumnLink> CreateAsync(ColumnLink columnLinkToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<ColumnLink>(columnLinkToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified ColumnLink. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified ColumnLink. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<ColumnLink>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified ColumnLink. /// </summary> /// <returns>The ColumnLink.</returns> public System.Threading.Tasks.Task<ColumnLink> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified ColumnLink. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The ColumnLink.</returns> public async System.Threading.Tasks.Task<ColumnLink> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<ColumnLink>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified ColumnLink using PATCH. /// </summary> /// <param name="columnLinkToUpdate">The ColumnLink to update.</param> /// <returns>The updated ColumnLink.</returns> public System.Threading.Tasks.Task<ColumnLink> UpdateAsync(ColumnLink columnLinkToUpdate) { return this.UpdateAsync(columnLinkToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified ColumnLink using PATCH. /// </summary> /// <param name="columnLinkToUpdate">The ColumnLink to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated ColumnLink.</returns> public async System.Threading.Tasks.Task<ColumnLink> UpdateAsync(ColumnLink columnLinkToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<ColumnLink>(columnLinkToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IColumnLinkRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IColumnLinkRequest Expand(Expression<Func<ColumnLink, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IColumnLinkRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IColumnLinkRequest Select(Expression<Func<ColumnLink, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="columnLinkToInitialize">The <see cref="ColumnLink"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(ColumnLink columnLinkToInitialize) { } } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Antlr4.Runtime.Dfa; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Dfa { /// <author>Sam Harwell</author> public sealed class SparseEdgeMap<T> : AbstractEdgeMap<T> where T : class { private const int DefaultMaxSize = 5; private readonly int[] keys; private readonly List<T> values; public SparseEdgeMap(int minIndex, int maxIndex) : this(minIndex, maxIndex, DefaultMaxSize) { } public SparseEdgeMap(int minIndex, int maxIndex, int maxSparseSize) : base(minIndex, maxIndex) { this.keys = new int[maxSparseSize]; this.values = new List<T>(maxSparseSize); } private SparseEdgeMap(Antlr4.Runtime.Dfa.SparseEdgeMap<T> map, int maxSparseSize) : base(map.minIndex, map.maxIndex) { lock (map) { if (maxSparseSize < map.values.Count) { throw new ArgumentException(); } keys = Arrays.CopyOf(map.keys, maxSparseSize); values = new List<T>(maxSparseSize); values.AddRange(map.Values); } } public int[] Keys { get { return keys; } } public IList<T> Values { get { return values; } } public int MaxSparseSize { get { return keys.Length; } } public override int Count { get { return values.Count; } } public override bool IsEmpty { get { return values.Count == 0; } } public override bool ContainsKey(int key) { return this[key] != null; } public override T this[int key] { get { // Special property of this collection: values are only even added to // the end, else a new object is returned from put(). Therefore no lock // is required in this method. int index = System.Array.BinarySearch(keys, 0, Count, key); if (index < 0) { return null; } return values[index]; } } public override AbstractEdgeMap<T> Put(int key, T value) { if (key < minIndex || key > maxIndex) { return this; } if (value == null) { return Remove(key); } lock (this) { int index = System.Array.BinarySearch(keys, 0, Count, key); if (index >= 0) { // replace existing entry values[index] = value; return this; } System.Diagnostics.Debug.Assert(index < 0 && value != null); int insertIndex = -index - 1; if (Count < MaxSparseSize && insertIndex == Count) { // stay sparse and add new entry keys[insertIndex] = key; values.Add(value); return this; } int desiredSize = Count >= MaxSparseSize ? MaxSparseSize * 2 : MaxSparseSize; int space = maxIndex - minIndex + 1; // SparseEdgeMap only uses less memory than ArrayEdgeMap up to half the size of the symbol space if (desiredSize >= space / 2) { ArrayEdgeMap<T> arrayMap = new ArrayEdgeMap<T>(minIndex, maxIndex); arrayMap = ((ArrayEdgeMap<T>)arrayMap.PutAll(this)); arrayMap.Put(key, value); return arrayMap; } else { Antlr4.Runtime.Dfa.SparseEdgeMap<T> resized = new Antlr4.Runtime.Dfa.SparseEdgeMap<T>(this, desiredSize); System.Array.Copy(resized.keys, insertIndex, resized.keys, insertIndex + 1, Count - insertIndex); resized.keys[insertIndex] = key; resized.values.Insert(insertIndex, value); return resized; } } } public override AbstractEdgeMap<T> Remove(int key) { lock (this) { int index = System.Array.BinarySearch(keys, 0, Count, key); if (index < 0) { return this; } Antlr4.Runtime.Dfa.SparseEdgeMap<T> result = new Antlr4.Runtime.Dfa.SparseEdgeMap<T>(this, MaxSparseSize); System.Array.Copy(result.keys, index + 1, result.keys, index, Count - index - 1); result.values.RemoveAt(index); return result; } } public override AbstractEdgeMap<T> Clear() { if (IsEmpty) { return this; } return new EmptyEdgeMap<T>(minIndex, maxIndex); } #if NET45PLUS public override IReadOnlyDictionary<int, T> ToMap() #else public override IDictionary<int, T> ToMap() #endif { if (IsEmpty) { return Sharpen.Collections.EmptyMap<int, T>(); } lock (this) { #if COMPACT IDictionary<int, T> result = new SortedList<int, T>(); #elif PORTABLE && !NET45PLUS IDictionary<int, T> result = new Dictionary<int, T>(); #else IDictionary<int, T> result = new SortedDictionary<int, T>(); #endif for (int i = 0; i < Count; i++) { result[keys[i]] = values[i]; } #if NET45PLUS return new ReadOnlyDictionary<int, T>(result); #else return result; #endif } } } }
using System.Reflection; namespace Tmds.DBus.Protocol; public ref partial struct Reader { public ValueTuple<T1> ReadStruct<T1>() { AlignStruct(); return ValueTuple.Create(Read<T1>()); } private Tuple<T1> ReadStructAsTuple<T1>() { AlignStruct(); return Tuple.Create(Read<T1>()); } sealed class ValueTupleTypeReader<T1> : ITypeReader<ValueTuple<T1>>, ITypeReader<object> where T1 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1> Read(ref Reader reader) { return reader.ReadStruct<T1>(); } } sealed class TupleTypeReader<T1> : ITypeReader<Tuple<T1>>, ITypeReader<object> where T1 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1>(); } } public static void AddValueTupleTypeReader<T1>() where T1 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1>()); } } } public static void AddTupleTypeReader<T1>() where T1 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1) { Type readerType = typeof(ValueTupleTypeReader<>).MakeGenericType(new[] { type1 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1) { Type readerType = typeof(TupleTypeReader<>).MakeGenericType(new[] { type1 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2> ReadStruct<T1, T2>() where T1 : notnull where T2 : notnull { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>()); } private Tuple<T1, T2> ReadStructAsTuple<T1, T2>() where T1 : notnull where T2 : notnull { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>()); } sealed class ValueTupleTypeReader<T1, T2> : ITypeReader<ValueTuple<T1, T2>>, ITypeReader<object> where T1 : notnull where T2 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2> Read(ref Reader reader) { return reader.ReadStruct<T1, T2>(); } } sealed class TupleTypeReader<T1, T2> : ITypeReader<Tuple<T1, T2>>, ITypeReader<object> where T1 : notnull where T2 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2>(); } } public static void AddValueTupleTypeReader<T1, T2>() where T1 : notnull where T2 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2>()); } } } public static void AddTupleTypeReader<T1, T2>() where T1 : notnull where T2 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2) { Type readerType = typeof(ValueTupleTypeReader<,>).MakeGenericType(new[] { type1, type2 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2) { Type readerType = typeof(TupleTypeReader<,>).MakeGenericType(new[] { type1, type2 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3> ReadStruct<T1, T2, T3>() where T1 : notnull where T2 : notnull where T3 : notnull { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>()); } private Tuple<T1, T2, T3> ReadStructAsTuple<T1, T2, T3>() { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>()); } sealed class ValueTupleTypeReader<T1, T2, T3> : ITypeReader<ValueTuple<T1, T2, T3>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3>(); } } sealed class TupleTypeReader<T1, T2, T3> : ITypeReader<Tuple<T1, T2, T3>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3>(); } } public static void AddValueTupleTypeReader<T1, T2, T3>() where T1 : notnull where T2 : notnull where T3 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3>()); } } } public static void AddTupleTypeReader<T1, T2, T3>() where T1 : notnull where T2 : notnull where T3 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3) { Type readerType = typeof(ValueTupleTypeReader<,,>).MakeGenericType(new[] { type1, type2, type3 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3) { Type readerType = typeof(TupleTypeReader<,,>).MakeGenericType(new[] { type1, type2, type3 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4> ReadStruct<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>()); } private Tuple<T1, T2, T3, T4> ReadStructAsTuple<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>()); } sealed class ValueTupleTypeReader<T1, T2, T3, T4> : ITypeReader<ValueTuple<T1, T2, T3, T4>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4>(); } } sealed class TupleTypeReader<T1, T2, T3, T4> : ITypeReader<Tuple<T1, T2, T3, T4>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4) { Type readerType = typeof(ValueTupleTypeReader<,,,>).MakeGenericType(new[] { type1, type2, type3, type4 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4) { Type readerType = typeof(TupleTypeReader<,,,>).MakeGenericType(new[] { type1, type2, type3, type4 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5> ReadStruct<T1, T2, T3, T4, T5>() { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>()); } private Tuple<T1, T2, T3, T4, T5> ReadStructAsTuple<T1, T2, T3, T4, T5>() { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>()); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5> : ITypeReader<Tuple<T1, T2, T3, T4, T5>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5) { Type readerType = typeof(ValueTupleTypeReader<,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5) { Type readerType = typeof(TupleTypeReader<,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type5 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5, T6> ReadStruct<T1, T2, T3, T4, T5, T6>() { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>()); } private Tuple<T1, T2, T3, T4, T5, T6> ReadStructAsTuple<T1, T2, T3, T4, T5, T6>() { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>()); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5, T6> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5, T6>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5, T6> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5, T6>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5, T6> : ITypeReader<Tuple<T1, T2, T3, T4, T5, T6>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5, T6> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5, T6>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5, T6>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5, T6>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5, T6>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5, T6>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6) { Type readerType = typeof(ValueTupleTypeReader<,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6) { Type readerType = typeof(TupleTypeReader<,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5, T6, T7> ReadStruct<T1, T2, T3, T4, T5, T6, T7>() { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>()); } private Tuple<T1, T2, T3, T4, T5, T6, T7> ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7>() { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>()); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5, T6, T7> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5, T6, T7>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5, T6, T7> : ITypeReader<Tuple<T1, T2, T3, T4, T5, T6, T7>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5, T6, T7> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5, T6, T7>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5, T6, T7>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7) { Type readerType = typeof(ValueTupleTypeReader<,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7) { Type readerType = typeof(TupleTypeReader<,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8>() { AlignStruct(); return ValueTuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Read<T8>()); } private Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8>() { AlignStruct(); return Tuple.Create(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Read<T8>()); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8> : ITypeReader<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8) { Type readerType = typeof(ValueTupleTypeReader<,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8) { Type readerType = typeof(TupleTypeReader<,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>() { AlignStruct(); return (Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Read<T8>(), Read<T9>()); } private Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>() { AlignStruct(); return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Tuple.Create(Read<T8>(), Read<T9>())); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9> : ITypeReader<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9) { Type readerType = typeof(ValueTupleTypeReader<,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9) { Type readerType = typeof(TupleTypeReader<,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() { AlignStruct(); return (Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Read<T8>(), Read<T9>(), Read<T10>()); } private Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() { AlignStruct(); return new Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>(Read<T1>(), Read<T2>(), Read<T3>(), Read<T4>(), Read<T5>(), Read<T6>(), Read<T7>(), Tuple.Create(Read<T8>(), Read<T9>(), Read<T10>())); } sealed class ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : ITypeReader<ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> Read(ref Reader reader) { return reader.ReadStruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(); } } sealed class TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : ITypeReader<Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>>, ITypeReader<object> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { object ITypeReader<object>.Read(ref Reader reader) => Read(ref reader); public Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> Read(ref Reader reader) { return reader.ReadStructAsTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(); } } public static void AddValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { lock (_typeReaders) { Type keyType = typeof(ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new ValueTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()); } } } public static void AddTupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>() where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull where T8 : notnull where T9 : notnull where T10 : notnull { lock (_typeReaders) { Type keyType = typeof(Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>); if (!_typeReaders.ContainsKey(keyType)) { _typeReaders.Add(keyType, new TupleTypeReader<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>()); } } } private ITypeReader CreateValueTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9, Type type10) { Type readerType = typeof(ValueTupleTypeReader<,,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9, type10 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } private ITypeReader CreateTupleTypeReader(Type type1, Type type2, Type type3, Type type4, Type type5, Type type6, Type type7, Type type8, Type type9, Type type10) { Type readerType = typeof(TupleTypeReader<,,,,,,,,,>).MakeGenericType(new[] { type1, type2, type3, type4, type5, type6, type7, type8, type9, type10 }); return (ITypeReader)Activator.CreateInstance(readerType)!; } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; using Neo.SmartContract; using Neo.VM.Types; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Array = Neo.VM.Types.Array; using Boolean = Neo.VM.Types.Boolean; using Buffer = Neo.VM.Types.Buffer; namespace Neo.VM { /// <summary> /// A helper class related to NeoVM. /// </summary> public static class Helper { /// <summary> /// Emits the opcodes for creating an array. /// </summary> /// <typeparam name="T">The type of the elements of the array.</typeparam> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="list">The elements of the array.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder CreateArray<T>(this ScriptBuilder builder, IReadOnlyList<T> list = null) { if (list is null || list.Count == 0) return builder.Emit(OpCode.NEWARRAY0); for (int i = list.Count - 1; i >= 0; i--) builder.EmitPush(list[i]); builder.EmitPush(list.Count); return builder.Emit(OpCode.PACK); } /// <summary> /// Emits the opcodes for creating a map. /// </summary> /// <typeparam name="TKey">The type of the key of the map.</typeparam> /// <typeparam name="TValue">The type of the value of the map.</typeparam> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="map">The key/value pairs of the map.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder CreateMap<TKey, TValue>(this ScriptBuilder builder, IEnumerable<KeyValuePair<TKey, TValue>> map = null) { builder.Emit(OpCode.NEWMAP); if (map != null) foreach (var p in map) { builder.Emit(OpCode.DUP); builder.EmitPush(p.Key); builder.EmitPush(p.Value); builder.Emit(OpCode.SETITEM); } return builder; } /// <summary> /// Emits the specified opcodes. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="ops">The opcodes to emit.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder Emit(this ScriptBuilder builder, params OpCode[] ops) { foreach (OpCode op in ops) builder.Emit(op); return builder; } /// <summary> /// Emits the opcodes for calling a contract dynamically. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="scriptHash">The hash of the contract to be called.</param> /// <param name="method">The method to be called in the contract.</param> /// <param name="args">The arguments for calling the contract.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, params object[] args) { return EmitDynamicCall(builder, scriptHash, method, CallFlags.All, args); } /// <summary> /// Emits the opcodes for calling a contract dynamically. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="scriptHash">The hash of the contract to be called.</param> /// <param name="method">The method to be called in the contract.</param> /// <param name="flags">The <see cref="CallFlags"/> for calling the contract.</param> /// <param name="args">The arguments for calling the contract.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitDynamicCall(this ScriptBuilder builder, UInt160 scriptHash, string method, CallFlags flags, params object[] args) { builder.CreateArray(args); builder.EmitPush(flags); builder.EmitPush(method); builder.EmitPush(scriptHash); builder.EmitSysCall(ApplicationEngine.System_Contract_Call); return builder; } /// <summary> /// Emits the opcodes for pushing the specified data onto the stack. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="data">The data to be pushed.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitPush(this ScriptBuilder builder, ISerializable data) { return builder.EmitPush(data.ToArray()); } /// <summary> /// Emits the opcodes for pushing the specified data onto the stack. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="parameter">The data to be pushed.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitPush(this ScriptBuilder builder, ContractParameter parameter) { if (parameter.Value is null) builder.Emit(OpCode.PUSHNULL); else switch (parameter.Type) { case ContractParameterType.Signature: case ContractParameterType.ByteArray: builder.EmitPush((byte[])parameter.Value); break; case ContractParameterType.Boolean: builder.EmitPush((bool)parameter.Value); break; case ContractParameterType.Integer: if (parameter.Value is BigInteger bi) builder.EmitPush(bi); else builder.EmitPush((BigInteger)typeof(BigInteger).GetConstructor(new[] { parameter.Value.GetType() }).Invoke(new[] { parameter.Value })); break; case ContractParameterType.Hash160: builder.EmitPush((UInt160)parameter.Value); break; case ContractParameterType.Hash256: builder.EmitPush((UInt256)parameter.Value); break; case ContractParameterType.PublicKey: builder.EmitPush((ECPoint)parameter.Value); break; case ContractParameterType.String: builder.EmitPush((string)parameter.Value); break; case ContractParameterType.Array: { IList<ContractParameter> parameters = (IList<ContractParameter>)parameter.Value; for (int i = parameters.Count - 1; i >= 0; i--) builder.EmitPush(parameters[i]); builder.EmitPush(parameters.Count); builder.Emit(OpCode.PACK); } break; case ContractParameterType.Map: { var pairs = (IList<KeyValuePair<ContractParameter, ContractParameter>>)parameter.Value; builder.CreateMap(pairs); } break; default: throw new ArgumentException(null, nameof(parameter)); } return builder; } /// <summary> /// Emits the opcodes for pushing the specified data onto the stack. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="obj">The data to be pushed.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitPush(this ScriptBuilder builder, object obj) { switch (obj) { case bool data: builder.EmitPush(data); break; case byte[] data: builder.EmitPush(data); break; case string data: builder.EmitPush(data); break; case BigInteger data: builder.EmitPush(data); break; case ISerializable data: builder.EmitPush(data); break; case sbyte data: builder.EmitPush(data); break; case byte data: builder.EmitPush(data); break; case short data: builder.EmitPush(data); break; case ushort data: builder.EmitPush(data); break; case int data: builder.EmitPush(data); break; case uint data: builder.EmitPush(data); break; case long data: builder.EmitPush(data); break; case ulong data: builder.EmitPush(data); break; case Enum data: builder.EmitPush(BigInteger.Parse(data.ToString("d"))); break; case ContractParameter data: builder.EmitPush(data); break; case null: builder.Emit(OpCode.PUSHNULL); break; default: throw new ArgumentException(null, nameof(obj)); } return builder; } /// <summary> /// Emits the opcodes for invoking an interoperable service. /// </summary> /// <param name="builder">The <see cref="ScriptBuilder"/> to be used.</param> /// <param name="method">The hash of the interoperable service.</param> /// <param name="args">The arguments for calling the interoperable service.</param> /// <returns>The same instance as <paramref name="builder"/>.</returns> public static ScriptBuilder EmitSysCall(this ScriptBuilder builder, uint method, params object[] args) { for (int i = args.Length - 1; i >= 0; i--) EmitPush(builder, args[i]); return builder.EmitSysCall(method); } /// <summary> /// Generates the script for calling a contract dynamically. /// </summary> /// <param name="scriptHash">The hash of the contract to be called.</param> /// <param name="method">The method to be called in the contract.</param> /// <param name="args">The arguments for calling the contract.</param> /// <returns>The generated script.</returns> public static byte[] MakeScript(this UInt160 scriptHash, string method, params object[] args) { using ScriptBuilder sb = new(); sb.EmitDynamicCall(scriptHash, method, args); return sb.ToArray(); } /// <summary> /// Converts the <see cref="StackItem"/> to a JSON object. /// </summary> /// <param name="item">The <see cref="StackItem"/> to convert.</param> /// <returns>The <see cref="StackItem"/> represented by a JSON object.</returns> public static JObject ToJson(this StackItem item) { return ToJson(item, null); } private static JObject ToJson(StackItem item, HashSet<StackItem> context) { JObject json = new(); json["type"] = item.Type; switch (item) { case Array array: context ??= new HashSet<StackItem>(ReferenceEqualityComparer.Instance); if (!context.Add(array)) throw new InvalidOperationException(); json["value"] = new JArray(array.Select(p => ToJson(p, context))); break; case Boolean boolean: json["value"] = boolean.GetBoolean(); break; case Buffer _: case ByteString _: json["value"] = Convert.ToBase64String(item.GetSpan()); break; case Integer integer: json["value"] = integer.GetInteger().ToString(); break; case Map map: context ??= new HashSet<StackItem>(ReferenceEqualityComparer.Instance); if (!context.Add(map)) throw new InvalidOperationException(); json["value"] = new JArray(map.Select(p => { JObject item = new(); item["key"] = ToJson(p.Key, context); item["value"] = ToJson(p.Value, context); return item; })); break; case Pointer pointer: json["value"] = pointer.Position; break; } return json; } /// <summary> /// Converts the <see cref="StackItem"/> to a <see cref="ContractParameter"/>. /// </summary> /// <param name="item">The <see cref="StackItem"/> to convert.</param> /// <returns>The converted <see cref="ContractParameter"/>.</returns> public static ContractParameter ToParameter(this StackItem item) { return ToParameter(item, null); } private static ContractParameter ToParameter(StackItem item, List<(StackItem, ContractParameter)> context) { if (item is null) throw new ArgumentNullException(nameof(item)); ContractParameter parameter = null; switch (item) { case Array array: if (context is null) context = new List<(StackItem, ContractParameter)>(); else (_, parameter) = context.FirstOrDefault(p => ReferenceEquals(p.Item1, item)); if (parameter is null) { parameter = new ContractParameter { Type = ContractParameterType.Array }; context.Add((item, parameter)); parameter.Value = array.Select(p => ToParameter(p, context)).ToList(); } break; case Map map: if (context is null) context = new List<(StackItem, ContractParameter)>(); else (_, parameter) = context.FirstOrDefault(p => ReferenceEquals(p.Item1, item)); if (parameter is null) { parameter = new ContractParameter { Type = ContractParameterType.Map }; context.Add((item, parameter)); parameter.Value = map.Select(p => new KeyValuePair<ContractParameter, ContractParameter>(ToParameter(p.Key, context), ToParameter(p.Value, context))).ToList(); } break; case Boolean _: parameter = new ContractParameter { Type = ContractParameterType.Boolean, Value = item.GetBoolean() }; break; case ByteString array: parameter = new ContractParameter { Type = ContractParameterType.ByteArray, Value = array.GetSpan().ToArray() }; break; case Integer i: parameter = new ContractParameter { Type = ContractParameterType.Integer, Value = i.GetInteger() }; break; case InteropInterface _: parameter = new ContractParameter { Type = ContractParameterType.InteropInterface }; break; case Null _: parameter = new ContractParameter { Type = ContractParameterType.Any }; break; default: throw new ArgumentException($"StackItemType({item.Type}) is not supported to ContractParameter."); } return parameter; } /// <summary> /// Converts the <see cref="ContractParameter"/> to a <see cref="StackItem"/>. /// </summary> /// <param name="parameter">The <see cref="ContractParameter"/> to convert.</param> /// <returns>The converted <see cref="StackItem"/>.</returns> public static StackItem ToStackItem(this ContractParameter parameter) { return ToStackItem(parameter, null); } private static StackItem ToStackItem(ContractParameter parameter, List<(StackItem, ContractParameter)> context) { if (parameter is null) throw new ArgumentNullException(nameof(parameter)); if (parameter.Value is null) return StackItem.Null; StackItem stackItem = null; switch (parameter.Type) { case ContractParameterType.Array: if (context is null) context = new List<(StackItem, ContractParameter)>(); else (stackItem, _) = context.FirstOrDefault(p => ReferenceEquals(p.Item2, parameter)); if (stackItem is null) { stackItem = new Array(((IList<ContractParameter>)parameter.Value).Select(p => ToStackItem(p, context))); context.Add((stackItem, parameter)); } break; case ContractParameterType.Map: if (context is null) context = new List<(StackItem, ContractParameter)>(); else (stackItem, _) = context.FirstOrDefault(p => ReferenceEquals(p.Item2, parameter)); if (stackItem is null) { Map map = new(); foreach (var pair in (IList<KeyValuePair<ContractParameter, ContractParameter>>)parameter.Value) map[(PrimitiveType)ToStackItem(pair.Key, context)] = ToStackItem(pair.Value, context); stackItem = map; context.Add((stackItem, parameter)); } break; case ContractParameterType.Boolean: stackItem = (bool)parameter.Value; break; case ContractParameterType.ByteArray: case ContractParameterType.Signature: stackItem = (byte[])parameter.Value; break; case ContractParameterType.Integer: stackItem = (BigInteger)parameter.Value; break; case ContractParameterType.Hash160: stackItem = ((UInt160)parameter.Value).ToArray(); break; case ContractParameterType.Hash256: stackItem = ((UInt256)parameter.Value).ToArray(); break; case ContractParameterType.PublicKey: stackItem = ((ECPoint)parameter.Value).EncodePoint(true); break; case ContractParameterType.String: stackItem = (string)parameter.Value; break; default: throw new ArgumentException($"ContractParameterType({parameter.Type}) is not supported to StackItem."); } return stackItem; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Commands; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitStringLiteral { public class SplitStringLiteralCommandHandlerTests { private async Task TestWorkerAsync( string inputMarkup, string expectedOutputMarkup, Action callback) { using (var workspace = await TestWorkspace.CreateCSharpAsync(inputMarkup)) { var document = workspace.Documents.Single(); var view = document.GetTextView(); var snapshot = view.TextBuffer.CurrentSnapshot; view.SetSelection(document.SelectedSpans.Single().ToSnapshotSpan(snapshot)); var commandHandler = new SplitStringLiteralCommandHandler(); commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), callback); if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out IList<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); Assert.Equal(expectedSpans.Single().Start, view.Caret.Position.BufferPosition.Position); } } } private Task TestHandledAsync(string inputMarkup, string expectedOutputMarkup) { return TestWorkerAsync( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }); } private async Task TestNotHandledAsync(string inputMarkup) { var notHandled = false; await TestWorkerAsync( inputMarkup, null, callback: () => { notHandled = true; }); Assert.True(notHandled); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingBeforeString() { await TestNotHandledAsync( @"class C { void M() { var v = [||]""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingBeforeInterpolatedString() { await TestNotHandledAsync( @"class C { void M() { var v = [||]$""""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterString_1() { await TestNotHandledAsync( @"class C { void M() { var v = """"[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterString_2() { await TestNotHandledAsync( @"class C { void M() { var v = """" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterString_3() { await TestNotHandledAsync( @"class C { void M() { var v = """"[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterString_4() { await TestNotHandledAsync( @"class C { void M() { var v = """" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterInterpolatedString_1() { await TestNotHandledAsync( @"class C { void M() { var v = $""""[||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterInterpolatedString_2() { await TestNotHandledAsync( @"class C { void M() { var v = $"""" [||]; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterInterpolatedString_3() { await TestNotHandledAsync( @"class C { void M() { var v = $""""[||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingAfterInterpolatedString_4() { await TestNotHandledAsync( @"class C { void M() { var v = $"""" [||] } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingInVerbatimString() { await TestNotHandledAsync( @"class C { void M() { var v = @""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingInInterpolatedVerbatimString() { await TestNotHandledAsync( @"class C { void M() { var v = $@""a[||]b""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestInEmptyString() { await TestHandledAsync( @"class C { void M() { var v = ""[||]""; } }", @"class C { void M() { var v = """" + ""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestInEmptyInterpolatedString() { await TestHandledAsync( @"class C { void M() { var v = $""[||]""; } }", @"class C { void M() { var v = $"""" + $""[||]""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestSimpleString1() { await TestHandledAsync( @"class C { void M() { var v = ""now is [||]the time""; } }", @"class C { void M() { var v = ""now is "" + ""[||]the time""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestInterpolatedString1() { await TestHandledAsync( @"class C { void M() { var v = $""now is [||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is "" + $""[||]the { 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestInterpolatedString2() { await TestHandledAsync( @"class C { void M() { var v = $""now is the [||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the "" + $""[||]{ 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestInterpolatedString3() { await TestHandledAsync( @"class C { void M() { var v = $""now is the { 1 + 2 }[||] time for { 3 + 4 } all good men""; } }", @"class C { void M() { var v = $""now is the { 1 + 2 }"" + $""[||] time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingInInterpolation1() { await TestNotHandledAsync( @"class C { void M() { var v = $""now is the {[||] 1 + 2 } time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestMissingInInterpolation2() { await TestNotHandledAsync( @"class C { void M() { var v = $""now is the { 1 + 2 [||]} time for { 3 + 4 } all good men""; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitStringLiteral)] public async Task TestSelection() { await TestNotHandledAsync( @"class C { void M() { var v = ""now is [|the|] time""; } }"); } } }
// *********************************************************************** // Assembly : OptimizationToolbox // Author : campmatt // Created : 01-28-2021 // // Last Modified By : campmatt // Last Modified On : 01-28-2021 // *********************************************************************** // <copyright file="NelderMead.cs" company="OptimizationToolbox"> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** /************************************************************************* * This file & class is part of the Object-Oriented Optimization * Toolbox (or OOOT) Project * Copyright 2010 Matthew Ira Campbell, PhD. * * OOOT is free software: you can redistribute it and/or modify * it under the terms of the MIT X11 License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OOOT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MIT X11 License for more details. * * * Please find further details and contact information on OOOT * at http://designengrlab.github.io/OOOT/. *************************************************************************/ using System.Collections.Generic; namespace OptimizationToolbox { /// <summary> /// Class NelderMead. /// Implements the <see cref="OptimizationToolbox.abstractOptMethod" /> /// </summary> /// <seealso cref="OptimizationToolbox.abstractOptMethod" /> public class NelderMead : abstractOptMethod { #region Fields /// <summary> /// The chi /// </summary> private readonly double chi = 2; /// <summary> /// The initialize new point addition /// </summary> private readonly double initNewPointAddition = 0.5; /// <summary> /// The initialize new point percentage /// </summary> private readonly double initNewPointPercentage = 0.01; /// <summary> /// The psi /// </summary> private readonly double psi = 0.5; /// <summary> /// The rho /// </summary> private readonly double rho = 1; /// <summary> /// The sigma /// </summary> private readonly double sigma = 0.5; /// <summary> /// The vertices /// </summary> private readonly SortedList<double, double[]> vertices = new SortedList<double, double[]>(new optimizeSort(optimize.minimize)); #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="NelderMead"/> class. /// </summary> public NelderMead() { RequiresObjectiveFunction = true; ConstraintsSolvedWithPenalties = true; InequalitiesConvertedToEqualities = false; RequiresSearchDirectionMethod = false; RequiresLineSearchMethod = false; RequiresAnInitialPoint = true; RequiresConvergenceCriteria = true; RequiresFeasibleStartPoint = false; RequiresDiscreteSpaceDescriptor = false; } /// <summary> /// Initializes a new instance of the <see cref="NelderMead"/> class. /// </summary> /// <param name="rho">The rho.</param> /// <param name="chi">The chi.</param> /// <param name="psi">The psi.</param> /// <param name="sigma">The sigma.</param> /// <param name="initNewPointPercentage">The initialize new point percentage.</param> /// <param name="initNewPointAddition">The initialize new point addition.</param> public NelderMead(double rho, double chi, double psi, double sigma, double initNewPointPercentage = double.NaN, double initNewPointAddition = double.NaN) : this() { this.rho = rho; this.chi = chi; this.psi = psi; this.sigma = sigma; if (!double.IsNaN(initNewPointPercentage)) this.initNewPointPercentage = initNewPointPercentage; if (!double.IsNaN(initNewPointAddition)) this.initNewPointAddition = initNewPointAddition; } #endregion /// <summary> /// Runs the specified optimization method. This includes the details /// of the optimization method. /// </summary> /// <param name="xStar">The x star.</param> /// <returns>System.Double.</returns> protected override double run(out double[] xStar) { vertices.Add(calc_f(x), x); // Creating neighbors in each direction and evaluating them for (var i = 0; i < n; i++) { var y = (double[])x.Clone(); y[i] = (1 + initNewPointPercentage) * y[i] + initNewPointAddition; vertices.Add(calc_f(y), y); } while (notConverged(k, numEvals, vertices.Keys[0], vertices.Values[0], vertices.Values)) { #region Compute the REFLECTION POINT // computing the average for each variable for n variables NOT n+1 var Xm = new double[n]; for (var dim = 0; dim < n; dim++) { double sumX = 0; for (var j = 0; j < n; j++) sumX += vertices.Values[j][dim]; Xm[dim] = sumX / n; } var Xr = CloneVertex(vertices.Values[n]); for (var i = 0; i < n; i++) Xr[i] = (1 + rho) * Xm[i] - rho * Xr[i]; var fXr = calc_f(Xr); SearchIO.output("x_r = " + StarMathLib.StarMath.MakePrintString(Xr), 4); #endregion #region if reflection point is better than best if (fXr < vertices.Keys[0]) { #region Compute the Expansion Point var Xe = CloneVertex(vertices.Values[n]); for (var i = 0; i < n; i++) Xe[i] = (1 + rho * chi) * Xm[i] - rho * chi * Xe[i]; var fXe = calc_f(Xe); #endregion vertices.RemoveAt(n); // remove the worst if (fXe < fXr) { vertices.Add(fXe, Xe); SearchIO.output("expand", 4); } else { vertices.Add(fXr, Xr); SearchIO.output("reflect", 4); } } #endregion #region if reflection point is NOT better than best else { #region but it's better than second worst, still do reflect if (fXr < vertices.Keys[n - 1]) { vertices.RemoveAt(n); // remove the worst vertices.Add(fXr, Xr); SearchIO.output("reflect", 4); } #endregion else { #region if better than worst, do Outside Contraction if (fXr < vertices.Keys[n]) { var Xc = CloneVertex(vertices.Values[n]); for (var i = 0; i < n; i++) Xc[i] = (1 + rho * psi) * Xm[i] - rho * psi * Xc[i]; var fXc = calc_f(Xc); if (fXc <= fXr) { vertices.RemoveAt(n); // remove the worst vertices.Add(fXc, Xc); SearchIO.output("outside constract", 4); } #endregion #region Shrink all others towards best else { var newXs = new List<double[]>(); for (var j = n; j >= 1; j--) { var Xs = CloneVertex(vertices.Values[j]); for (var i = 0; i < n; i++) Xs[i] = vertices.Values[0][i] + sigma * (Xs[i] - vertices.Values[0][i]); newXs.Add(Xs); vertices.RemoveAt(j); } for (int j = 0; j < n; j++) vertices.Add(calc_f(newXs[j]), newXs[j]); SearchIO.output("shrink towards best", 4); } #endregion } else { #region Compute Inside Contraction var Xcc = CloneVertex(vertices.Values[n]); for (var i = 0; i < n; i++) Xcc[i] = (1 - psi) * Xm[i] + psi * Xcc[i]; var fXcc = calc_f(Xcc); if (fXcc < vertices.Keys[n]) { vertices.RemoveAt(n); // remove the worst vertices.Add(fXcc, Xcc); SearchIO.output("inside contract", 4); } #endregion #region Shrink all others towards best and flip over else { var newXs = new List<double[]>(); for (var j = n; j >= 1; j--) { var Xs = CloneVertex(vertices.Values[j]); for (var i = 0; i < n; i++) Xs[i] = vertices.Values[0][i] - sigma * (Xs[i] - vertices.Values[0][i]); newXs.Add(Xs); vertices.RemoveAt(j); } for (int j = 0; j < n; j++) vertices.Add(calc_f(newXs[j]), newXs[j]); SearchIO.output("shrink towards best and flip", 4); } #endregion } } } #endregion k++; SearchIO.output("iter. = " + k, 2); SearchIO.output("Fitness = " + vertices.Keys[0], 2); } // END While Loop xStar = vertices.Values[0]; fStar = vertices.Keys[0]; vertices.Clear(); return fStar; } /// <summary> /// Clones the vertex. /// </summary> /// <param name="vertex">The vertex.</param> /// <returns>System.Double[].</returns> private static double[] CloneVertex(double[] vertex) { return (double[])vertex.Clone(); } } }
using System; using System.Linq; using sd = System.Drawing; using swf = System.Windows.Forms; using Eto.Forms; using System.Runtime.InteropServices; using System.ComponentModel; namespace Eto.WinForms.Forms.Controls { public class EtoTextBox : swf.TextBox { string watermarkText; public string WatermarkText { get { return watermarkText; } set { watermarkText = value; Win32.SendMessage(Handle, Win32.WM.EM_SETCUEBANNER, IntPtr.Zero, watermarkText); } } public event EventHandler<CancelEventArgs> Copying; protected virtual void OnCopying(CancelEventArgs e) { if (Copying != null) Copying(this, e); } public event EventHandler<CancelEventArgs> Cutting; protected virtual void OnCutting(CancelEventArgs e) { if (Cutting != null) Cutting(this, e); } public event EventHandler<CancelEventArgs> Pasting; protected virtual void OnPasting(CancelEventArgs e) { if (Pasting != null) Pasting(this, e); } protected override void WndProc(ref swf.Message m) { var e = new CancelEventArgs(); if (m.Msg == (int)Win32.WM.CUT) OnCutting(e); if (m.Msg == (int)Win32.WM.COPY) OnCopying(e); if (m.Msg == (int)Win32.WM.PASTE) OnPasting(e); if (e.Cancel) return; base.WndProc(ref m); } } public class TextBoxHandler : WindowsControl<EtoTextBox, TextBox, TextBox.ICallback>, TextBox.IHandler { public TextBoxHandler() { Control = new EtoTextBox(); } static Func<char, bool> testIsNonWord = ch => char.IsWhiteSpace(ch) || char.IsPunctuation(ch); public override void AttachEvent(string id) { switch (id) { case TextBox.TextChangingEvent: var clipboard = new Clipboard(); Widget.KeyDown += (sender, e) => { switch (e.KeyData) { case Keys.Delete: case Keys.Backspace: case Keys.Shift | Keys.Delete: case Keys.Shift | Keys.Backspace: var selection = Selection; if (selection.Length() == 0) selection = new Range<int>(e.KeyData == Keys.Delete ? CaretIndex : CaretIndex - 1); if (selection.Start >= 0 && selection.End < Control.TextLength) { var tia = new TextChangingEventArgs(string.Empty, selection); Callback.OnTextChanging(Widget, tia); e.Handled = tia.Cancel; } break; case Keys.Control | Keys.Delete: { // delete next word string text = Text; int start = CaretIndex; int end = start; int length = text.Length; // find end of next word while (end < length && !testIsNonWord(text[end])) end++; while (end < length && testIsNonWord(text[end])) end++; if (end > start) { var tia = new TextChangingEventArgs(string.Empty, new Range<int>(start, end - 1)); Callback.OnTextChanging(Widget, tia); e.Handled = tia.Cancel; } } break; case Keys.Control | Keys.Backspace: { // delete previous word string text = Text; int end = CaretIndex; int start = end; // find start of previous word while (start > 0 && testIsNonWord(text[start - 1])) start--; while (start > 0 && !testIsNonWord(text[start - 1])) start--; if (end > start) { var tia = new TextChangingEventArgs(string.Empty, new Range<int>(start, end - 1)); Callback.OnTextChanging(Widget, tia); e.Handled = tia.Cancel; } } break; } }; Control.Cutting += (sender, e) => { clipboard.Clear(); clipboard.Text = Control.SelectedText; var tia = new TextChangingEventArgs(string.Empty, Selection); Callback.OnTextChanging(Widget, tia); e.Cancel = tia.Cancel; }; Control.Pasting += (sender, e) => { var tia = new TextChangingEventArgs(clipboard.Text, Selection); Callback.OnTextChanging(Widget, tia); e.Cancel = tia.Cancel; }; Widget.TextInput += (sender, e) => { var tia = new TextChangingEventArgs(e.Text, Selection); Callback.OnTextChanging(Widget, tia); e.Cancel = tia.Cancel; }; break; default: base.AttachEvent(id); break; } } public bool ReadOnly { get { return Control.ReadOnly; } set { Control.ReadOnly = value; } } public int MaxLength { get { return Control.MaxLength; } set { Control.MaxLength = value; } } public string PlaceholderText { get { return Control.WatermarkText; } set { Control.WatermarkText = value; } } public void SelectAll() { Control.Focus(); Control.SelectAll(); } static readonly Win32.WM[] intrinsicEvents = { Win32.WM.LBUTTONDOWN, Win32.WM.LBUTTONUP, Win32.WM.LBUTTONDBLCLK, Win32.WM.RBUTTONDOWN, Win32.WM.RBUTTONUP, Win32.WM.RBUTTONDBLCLK }; public override bool ShouldBubbleEvent(swf.Message msg) { return !intrinsicEvents.Contains((Win32.WM)msg.Msg) && base.ShouldBubbleEvent(msg); } public override void SetFilledContent() { base.SetFilledContent(); Control.AutoSize = false; } public int CaretIndex { get { return Control.SelectionStart; } set { Control.SelectionStart = value; Control.SelectionLength = 0; } } public Range<int> Selection { get { return new Range<int>(Control.SelectionStart, Control.SelectionStart + Control.SelectionLength - 1); } set { Control.SelectionStart = value.Start; Control.SelectionLength = value.Length(); } } } }
using System; using System.IO; using System.Runtime.InteropServices; using Comzept.Library.Drawing; namespace Comzept.Library.Drawing.Internal { using PVOID = IntPtr; using FIBITMAP = Int32; using FIMULTIBITMAP = Int32; /* [StructLayout(LayoutKind.Sequential)] public class FreeImageIO { public FI_ReadProc readProc; public FI_WriteProc writeProc; public FI_SeekProc seekProc; public FI_TellProc tellProc; } [StructLayout(LayoutKind.Sequential)] public class FI_Handle { public FileStream stream; } public delegate void FI_ReadProc(IntPtr buffer, uint size, uint count, IntPtr handle); public delegate void FI_WriteProc(IntPtr buffer, uint size, uint count, IntPtr handle); public delegate int FI_SeekProc(IntPtr handle, long offset, int origin); public delegate int FI_TellProc(IntPtr handle); */ internal delegate void FreeImage_OutputMessageFunction(FreeImage.FreeImageFormat format, string msg); internal class FreeImageApi { // Init/Error routines ---------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_Initialise")] public static extern void Initialise(bool loadLocalPluginsOnly); // alias for Americans :) [DllImport("FreeImage.dll", EntryPoint="FreeImage_Initialise")] public static extern void Initialize(bool loadLocalPluginsOnly); [DllImport("FreeImage.dll", EntryPoint="FreeImage_DeInitialise")] public static extern void DeInitialise(); // alias for Americians :) [DllImport("FreeImage.dll", EntryPoint="FreeImage_DeInitialise")] public static extern void DeInitialize(); [DllImport("FreeImage.dll", EntryPoint = "FreeImage_CloseMemory")] public static extern void CloseMemory(IntPtr stream); // Version routines ------------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetVersion")] public static extern string GetVersion(); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetCopyrightMessage")] public static extern string GetCopyrightMessage(); // Message Output routines ------------------------------------ // missing void FreeImage_OutputMessageProc(int fif, // const char *fmt, ...); [DllImport("FreeImage.dll", EntryPoint="FreeImage_SetOutputMessage")] public static extern void SetOutputMessage(FreeImage_OutputMessageFunction omf); // Allocate/Clone/Unload routines ----------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_Allocate")] public static extern FIBITMAP Allocate(int width, int height, int bpp, uint red_mask, uint green_mask, uint blue_mask); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AllocateT")] public static extern FIBITMAP AllocateT(FreeImage.FreeImageType ftype, int width, int height, int bpp, uint red_mask, uint green_mask, uint blue_mask); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Clone")] public static extern FIBITMAP Clone(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Unload")] public static extern void Unload(FIBITMAP dib); // Load/Save routines ----------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_Load")] public static extern FIBITMAP Load(FreeImage.FreeImageFormat format, string filename, int flags); // missing FIBITMAP FreeImage_LoadFromHandle(FreeImage.FreeImageFormat fif, // FreeImageIO *io, fi_handle handle, int flags); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Save")] public static extern bool Save(FreeImage.FreeImageFormat format, FIBITMAP dib, string filename, int flags); // missing BOOL FreeImage_SaveToHandle(FreeImage.FreeImageFormat fif, FIBITMAP *dib, // FreeImageIO *io, fi_handle handle, int flags); // Plugin interface ------------------------------------------- // missing FreeImage.FreeImageFormat FreeImage_RegisterLocalPlugin(FI_InitProc proc_address, // const char *format, const char *description, // const char *extension, const char *regexpr); // // missing FreeImage.FreeImageFormat FreeImage_RegisterExternalPlugin(const char *path, // const char *format, const char *description, // const char *extension, const char *regexpr); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFCount")] public static extern int GetFIFCount(); [DllImport("FreeImage.dll", EntryPoint="FreeImage_SetPluginEnabled")] public static extern int SetPluginEnabled(FreeImage.FreeImageFormat format, bool enabled); [DllImport("FreeImage.dll", EntryPoint="FreeImage_IsPluginEnabled")] public static extern int IsPluginEnabled(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromFormat")] public static extern FreeImage.FreeImageFormat GetFIFFromFormat(string format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromMime")] public static extern FreeImage.FreeImageFormat GetFIFFromMime(string mime); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFormatFromFIF")] public static extern string GetFormatFromFIF(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFExtensionList")] public static extern string GetFIFExtensionList(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFDescription")] public static extern string GetFIFDescription(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFRegExpr")] public static extern string GetFIFRegExpr(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFIFFromFilename")] public static extern FreeImage.FreeImageFormat GetFIFFromFilename([MarshalAs( UnmanagedType.LPStr) ]string filename); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsReading")] public static extern bool FIFSupportsReading(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsWriting")] public static extern bool FIFSupportsWriting(FreeImage.FreeImageFormat format); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsExportBPP")] public static extern bool FIFSupportsExportBPP(FreeImage.FreeImageFormat format, int bpp); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsExportType")] public static extern bool FIFSupportsExportType(FreeImage.FreeImageFormat format, FreeImage.FreeImageType ftype); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FIFSupportsICCProfiles")] public static extern bool FIFSupportsICCProfiles(FreeImage.FreeImageFormat format, FreeImage.FreeImageType ftype); // Multipage interface ---------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_OpenMultiBitmap")] public static extern FIMULTIBITMAP OpenMultiBitmap( FreeImage.FreeImageFormat format, string filename, bool createNew, bool readOnly, bool keepCacheInMemory); [DllImport("FreeImage.dll", EntryPoint="FreeImage_CloseMultiBitmap")] public static extern long CloseMultiBitmap(FIMULTIBITMAP bitmap, int flags); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPageCount")] public static extern int GetPageCount(FIMULTIBITMAP bitmap); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AppendPage")] public static extern void AppendPage(FIMULTIBITMAP bitmap, FIBITMAP data); [DllImport("FreeImage.dll", EntryPoint="FreeImage_InsertPage")] public static extern void InsertPage(FIMULTIBITMAP bitmap, int page, FIBITMAP data); [DllImport("FreeImage.dll", EntryPoint="FreeImage_DeletePage")] public static extern void DeletePage(FIMULTIBITMAP bitmap, int page); [DllImport("FreeImage.dll", EntryPoint="FreeImage_LockPage")] public static extern FIBITMAP LockPage(FIMULTIBITMAP bitmap, int page); [DllImport("FreeImage.dll", EntryPoint="FreeImage_UnlockPage")] public static extern void UnlockPage(FIMULTIBITMAP bitmap, int page, bool changed); [DllImport("FreeImage.dll", EntryPoint="FreeImage_MovePage")] public static extern bool MovePage(FIMULTIBITMAP bitmap, int target, int source); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetLockedPageNumbers")] public static extern bool GetLockedPageNumbers(FIMULTIBITMAP bitmap, IntPtr pages, IntPtr count); // File type request routines --------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetFileType")] public static extern FreeImage.FreeImageFormat GetFileType(string filename, int size); // missing FreeImage.FreeImageFormat FreeImage_GetFileTypeFromHandle(FreeImageIO *io, // fi_handle handle, int size); // Image type request routines -------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetImageType")] public static extern FreeImage.FreeImageType GetImageType(FIBITMAP dib); // Info functions --------------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_IsLittleEndian")] public static extern bool IsLittleEndian(); // Pixel access functions ------------------------------------- [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBits")] public static extern IntPtr GetBits(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetScanLine")] public static extern IntPtr GetScanLine(FIBITMAP dib, int scanline); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPixelIndex")] public static extern bool GetPixelIndex(FIBITMAP dib, uint x, uint y, byte value); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetColorsUsed")] public static extern uint GetColorsUsed(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBPP")] public static extern uint GetBPP(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetWidth")] public static extern uint GetWidth(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetHeight")] public static extern uint GetHeight(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetLine")] public static extern uint GetLine(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPitch")] public static extern uint GetPitch(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDIBSize")] public static extern uint GetDIBSize(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetPalette")] [return: MarshalAs(UnmanagedType.LPStruct)] public static extern RGBQUAD GetPalette(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDotsPerMeterX")] public static extern uint GetDotsPerMeterX(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetDotsPerMeterY")] public static extern uint GetDotsPerMeterY(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetInfoHeader")] [return: MarshalAs(UnmanagedType.LPStruct)] public static extern BITMAPINFOHEADER GetInfoHeader(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetInfo")] public static extern IntPtr GetInfo(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetColorType")] public static extern int GetColorType(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetRedMask")] public static extern uint GetRedMask(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetGreenMask")] public static extern uint GetGreenMask(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetBlueMask")] public static extern uint GetBlueMask(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetTransparencyCount")] public static extern uint GetTransparencyCount(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetTransparencyTable")] public static extern IntPtr GetTransparencyTable(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_SetTransparent")] public static extern void SetTransparent(FIBITMAP dib, bool enabled); [DllImport("FreeImage.dll", EntryPoint="FreeImage_IsTransparent")] public static extern bool IsTransparent(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo8Bits")] public static extern FIBITMAP ConvertTo8Bits(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo16Bits555")] public static extern FIBITMAP ConvertTo16Bits555(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo16Bits565")] public static extern FIBITMAP ConvertTo16Bits565(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo24Bits")] public static extern FIBITMAP ConvertTo24Bits(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertTo32Bits")] public static extern FIBITMAP ConvertTo32Bits(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="ColorQuantize")] public static extern FIBITMAP ColorQuantize(FIBITMAP dib, FreeImage.FreeImageQuantize quantize); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Threshold")] public static extern FIBITMAP Threshold(FIBITMAP dib, byte t); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Dither")] public static extern FIBITMAP Dither(FIBITMAP dib, FreeImage.FreeImageDither algorithm); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertFromRawBits")] public static extern FIBITMAP ConvertFromRawBits(byte[] bits, int width, int height, int pitch, uint bpp, uint redMask, uint greenMask, uint blueMask, bool topDown); [DllImport("FreeImage.dll", EntryPoint="FreeImage_ConvertToRawBits")] public static extern void ConvertToRawBits(IntPtr bits, FIBITMAP dib, int pitch, uint bpp, uint redMask, uint greenMask, uint blueMask, bool topDown); [DllImport("FreeImage.dll", EntryPoint="FreeImage_RotateClassic")] public static extern FIBITMAP RotateClassic(FIBITMAP dib, Double angle); [DllImport("FreeImage.dll", EntryPoint="FreeImage_RotateEx")] public static extern FIBITMAP RotateEx( FIBITMAP dib, Double angle, Double xShift, Double yShift, Double xOrigin, Double yOrigin, bool useMask); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FlipHorizontal")] public static extern bool FlipHorizontal(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_FlipVertical")] public static extern bool FlipVertical(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Rescale")] public static extern FIBITMAP Rescale(FIBITMAP dib, int dst_width, int dst_height, FreeImage.FreeImageFilter filter); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustCurve")] public static extern bool AdjustCurve(FIBITMAP dib, byte[] lut, FreeImage.FreeImageColorChannel channel); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustGamma")] public static extern bool AdjustGamma(FIBITMAP dib, Double gamma); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustBrightness")] public static extern bool AdjustBrightness(FIBITMAP dib, Double percentage); [DllImport("FreeImage.dll", EntryPoint="FreeImage_AdjustContrast")] public static extern bool AdjustContrast(FIBITMAP dib, Double percentage); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Invert")] public static extern bool Invert(FIBITMAP dib); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetHistogram")] public static extern bool GetHistogram(FIBITMAP dib, int histo, FreeImage.FreeImageColorChannel channel); [DllImport("FreeImage.dll", EntryPoint="FreeImage_GetChannel")] public static extern bool GetChannel(FIBITMAP dib, FreeImage.FreeImageColorChannel channel); [DllImport("FreeImage.dll", EntryPoint="FreeImage_SetChannel")] public static extern bool SetChannel(FIBITMAP dib, FIBITMAP dib8, FreeImage.FreeImageColorChannel channel); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Copy")] public static extern FIBITMAP Copy(FIBITMAP dib, int left, int top, int right, int bottom); [DllImport("FreeImage.dll", EntryPoint="FreeImage_Paste")] public static extern bool Paste(FIBITMAP dst, FIBITMAP src, int left, int top, int alpha); [DllImport("FreeImage.dll", EntryPoint="FreeImage_OpenMemory")] public static extern IntPtr OpenMemory(IntPtr data, int size); [DllImport("FreeImage.dll", EntryPoint = "FreeImage_LoadFromMemory")] public static extern int LoadFromMemory(FreeImage.FreeImageFormat format, IntPtr stream, int flags); } }
using System.Diagnostics.Contracts; // ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // SymmetricAlgorithm.cs // namespace System.Security.Cryptography { [System.Runtime.InteropServices.ComVisible(true)] public abstract class SymmetricAlgorithm : IDisposable { protected int BlockSizeValue; protected int FeedbackSizeValue; protected byte[] IVValue; protected byte[] KeyValue; protected KeySizes[] LegalBlockSizesValue; protected KeySizes[] LegalKeySizesValue; protected int KeySizeValue; protected CipherMode ModeValue; protected PaddingMode PaddingValue; // // protected constructors // protected SymmetricAlgorithm() { // Default to cipher block chaining (CipherMode.CBC) and // PKCS-style padding (pad n bytes with value n) ModeValue = CipherMode.CBC; PaddingValue = PaddingMode.PKCS7; } // SymmetricAlgorithm implements IDisposable // To keep mscorlib compatibility with Orcas, CoreCLR's SymmetricAlgorithm has an explicit IDisposable // implementation. Post-Orcas the desktop has an implicit IDispoable implementation. #if FEATURE_CORECLR void IDisposable.Dispose() #else public void Dispose() #endif // FEATURE_CORECLR { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { // Note: we always want to zeroize the sensitive key material if (KeyValue != null) { Array.Clear(KeyValue, 0, KeyValue.Length); KeyValue = null; } if (IVValue != null) { Array.Clear(IVValue, 0, IVValue.Length); IVValue = null; } } } // // public properties // public virtual int BlockSize { get { return BlockSizeValue; } set { int i; int j; for (i=0; i<LegalBlockSizesValue.Length; i++) { // If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0 if (LegalBlockSizesValue[i].SkipSize == 0) { if (LegalBlockSizesValue[i].MinSize == value) { // assume MinSize = MaxSize BlockSizeValue = value; IVValue = null; return; } } else { for (j = LegalBlockSizesValue[i].MinSize; j<=LegalBlockSizesValue[i].MaxSize; j += LegalBlockSizesValue[i].SkipSize) { if (j == value) { if (BlockSizeValue != value) { BlockSizeValue = value; IVValue = null; // Wrong length now } return; } } } } throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidBlockSize")); } } public virtual int FeedbackSize { get { return FeedbackSizeValue; } set { if (value <= 0 || value > BlockSizeValue || (value % 8) != 0) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidFeedbackSize")); FeedbackSizeValue = value; } } public virtual byte[] IV { get { if (IVValue == null) GenerateIV(); return (byte[]) IVValue.Clone(); } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); if (value.Length != BlockSizeValue / 8) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidIVSize")); IVValue = (byte[]) value.Clone(); } } public virtual byte[] Key { get { if (KeyValue == null) GenerateKey(); return (byte[]) KeyValue.Clone(); } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); if (!ValidKeySize(value.Length * 8)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); // must convert bytes to bits KeyValue = (byte[]) value.Clone(); KeySizeValue = value.Length * 8; } } public virtual KeySizes[] LegalBlockSizes { get { return (KeySizes[]) LegalBlockSizesValue.Clone(); } } public virtual KeySizes[] LegalKeySizes { get { return (KeySizes[]) LegalKeySizesValue.Clone(); } } public virtual int KeySize { get { return KeySizeValue; } set { if (!ValidKeySize(value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidKeySize")); KeySizeValue = value; KeyValue = null; } } public virtual CipherMode Mode { get { return ModeValue; } set { if ((value < CipherMode.CBC) || (CipherMode.CFB < value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode")); ModeValue = value; } } public virtual PaddingMode Padding { get { return PaddingValue; } set { if ((value < PaddingMode.None) || (PaddingMode.ISO10126 < value)) throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode")); PaddingValue = value; } } // // public methods // // The following method takes a bit length input and returns whether that length is a valid size // according to LegalKeySizes public bool ValidKeySize(int bitLength) { KeySizes[] validSizes = this.LegalKeySizes; int i,j; if (validSizes == null) return false; for (i=0; i< validSizes.Length; i++) { if (validSizes[i].SkipSize == 0) { if (validSizes[i].MinSize == bitLength) { // assume MinSize = MaxSize return true; } } else { for (j = validSizes[i].MinSize; j<= validSizes[i].MaxSize; j += validSizes[i].SkipSize) { if (j == bitLength) { return true; } } } } return false; } static public SymmetricAlgorithm Create() { #if FULL_AOT_RUNTIME return new System.Security.Cryptography.RijndaelManaged (); #else // use the crypto config system to return an instance of // the default SymmetricAlgorithm on this machine return Create("System.Security.Cryptography.SymmetricAlgorithm"); #endif } static public SymmetricAlgorithm Create(String algName) { return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName); } public virtual ICryptoTransform CreateEncryptor() { return CreateEncryptor(Key, IV); } public abstract ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV); public virtual ICryptoTransform CreateDecryptor() { return CreateDecryptor(Key, IV); } public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV); public abstract void GenerateKey(); public abstract void GenerateIV(); } }
// *********************************************************************** // Assembly : ACBr.Net.DFe.Core // Author : RFTD // Created : 05-04-2016 // // Last Modified By : RFTD // Last Modified On : 05-11-2016 // *********************************************************************** // <copyright file="PrimitiveSerializer.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <summary></summary> // *********************************************************************** using ACBr.Net.Core.Extensions; using ACBr.Net.DFe.Core.Attributes; using ACBr.Net.DFe.Core.Extensions; using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml.Linq; namespace ACBr.Net.DFe.Core.Serializer { internal static class PrimitiveSerializer { #region Serialize /// <summary> /// Serializes a fundamental primitive object (e.g. string, int etc.) into a XElement using options. /// </summary> /// <param name="tag">The name of the primitive to serialize.</param> /// <param name="item">The item.</param> /// <param name="prop">The property.</param> /// <param name="options">Indicates how the output is formatted or serialized.</param> /// <param name="idx"></param> /// <returns>The XElement representation of the primitive.</returns> public static XObject Serialize(DFeBaseAttribute tag, object item, PropertyInfo prop, SerializerOptions options, int idx = -1) { try { var value = prop.GetValueOrIndex(item, idx); var estaVazio = value == null || value.ToString().IsEmpty(); var conteudoProcessado = ProcessValue(ref estaVazio, tag.Tipo, value, tag.Ocorrencia, tag.Min, prop, item); return ProcessContent(tag, conteudoProcessado, estaVazio, options); } catch (Exception ex) { options.AddAlerta(tag.Id, tag.Name, tag.Descricao, ex.ToString()); return null; } } public static XObject Serialize(DFeBaseAttribute tag, object value, SerializerOptions options) { try { var estaVazio = value == null || value.ToString().IsEmpty(); var conteudoProcessado = ProcessValue(ref estaVazio, tag.Tipo, value, tag.Ocorrencia, tag.Min, null, null); return ProcessContent(tag, conteudoProcessado, estaVazio, options); } catch (Exception ex) { options.AddAlerta(tag.Id, tag.Name, tag.Descricao, ex.ToString()); return null; } } public static string ProcessValue(ref bool estaVazio, TipoCampo tipo, object valor, Ocorrencia ocorrencia, int min, PropertyInfo prop, object item) { var conteudoProcessado = string.Empty; if (estaVazio) return conteudoProcessado; // ReSharper disable once SwitchStatementMissingSomeCases switch (tipo) { case TipoCampo.Str: conteudoProcessado = valor.ToString().Trim(); break; case TipoCampo.Dat: case TipoCampo.DatCFe: if (valor is DateTime data) { conteudoProcessado = data.ToString(tipo == TipoCampo.DatCFe ? "yyyyMMdd" : "yyyy-MM-dd"); } else { estaVazio = true; } break; case TipoCampo.Hor: case TipoCampo.HorCFe: if (valor is DateTime hora) { conteudoProcessado = hora.ToString(tipo == TipoCampo.HorCFe ? "HHmmss" : "HH:mm:ss"); } else { estaVazio = true; } break; case TipoCampo.DatHor: if (valor is DateTime dthora) { conteudoProcessado = dthora.ToString("s"); } else { estaVazio = true; } break; case TipoCampo.DatHorTz: switch (valor) { case DateTimeOffset dateTime: conteudoProcessado = dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'sszzz"); break; case DateTime dateTime: conteudoProcessado = dateTime.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'sszzz"); break; default: estaVazio = true; break; } break; case TipoCampo.De2: case TipoCampo.De3: case TipoCampo.De4: case TipoCampo.De6: case TipoCampo.De10: if (valor is decimal vDecimal) { if (ocorrencia == Ocorrencia.MaiorQueZero && vDecimal == 0) { estaVazio = true; } else { // ReSharper disable once SwitchStatementMissingSomeCases switch (tipo) { case TipoCampo.De2: conteudoProcessado = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", vDecimal); break; case TipoCampo.De3: conteudoProcessado = string.Format(CultureInfo.InvariantCulture, "{0:0.000}", vDecimal); break; case TipoCampo.De4: conteudoProcessado = string.Format(CultureInfo.InvariantCulture, "{0:0.0000}", vDecimal); break; case TipoCampo.De6: conteudoProcessado = string.Format(CultureInfo.InvariantCulture, "{0:0.000000}", vDecimal); break; default: conteudoProcessado = string.Format(CultureInfo.InvariantCulture, "{0:0.0000000000}", vDecimal); break; } } } else { estaVazio = true; } break; case TipoCampo.Int: case TipoCampo.Long: switch (valor) { case long vLong when ocorrencia == Ocorrencia.MaiorQueZero && vLong == 0: case int vInt when ocorrencia == Ocorrencia.MaiorQueZero && vInt == 0: estaVazio = true; break; case long _: case int _: conteudoProcessado = valor.ToString(); if (conteudoProcessado.Length < min) conteudoProcessado = conteudoProcessado.ZeroFill(min); break; default: estaVazio = true; break; } break; case TipoCampo.StrNumberFill: conteudoProcessado = valor.ToString(); if (conteudoProcessado.Length < min) { conteudoProcessado = conteudoProcessado.ZeroFill(min); } break; case TipoCampo.StrNumber: conteudoProcessado = valor.ToString().OnlyNumbers(); break; case TipoCampo.Enum: var member = valor.GetType().GetMember(valor.ToString()).FirstOrDefault(); var enumAttribute = member?.GetCustomAttributes(false).OfType<DFeEnumAttribute>().FirstOrDefault(); var enumValue = enumAttribute?.Value; conteudoProcessado = enumValue ?? valor.ToString(); break; case TipoCampo.Custom: var serialize = prop.GetSerializer(item); conteudoProcessado = serialize(); break; default: conteudoProcessado = valor.ToString(); break; } return conteudoProcessado; } private static XObject ProcessContent(DFeBaseAttribute tag, string conteudoProcessado, bool estaVazio, SerializerOptions options) { string alerta; if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio && tag.Min > 0) { alerta = DFeSerializer.ErrMsgVazio; } else { alerta = string.Empty; } if (conteudoProcessado.IsEmpty() && conteudoProcessado.Length < tag.Min && alerta.IsEmpty() && conteudoProcessado.Length > 1) { alerta = DFeSerializer.ErrMsgMenor; } if (!string.IsNullOrEmpty(conteudoProcessado.Trim()) && conteudoProcessado.Length > tag.Max) { alerta = DFeSerializer.ErrMsgMaior; } if (!string.IsNullOrEmpty(alerta.Trim()) && DFeSerializer.ErrMsgVazio.Equals(alerta) && !estaVazio) { alerta += $" [{tag.Name}]"; } options.AddAlerta(tag.Id, tag.Name, tag.Descricao, alerta); if (tag.Ocorrencia == Ocorrencia.Obrigatoria && estaVazio) { XNamespace aw = tag.Namespace ?? string.Empty; return tag is DFeElementAttribute ? (XObject)new XElement(aw + tag.Name, "") : new XAttribute(tag.Name, ""); } if (estaVazio) return null; var elementValue = options.RemoverAcentos ? conteudoProcessado.RemoveAccent() : conteudoProcessado; elementValue = options.RemoverEspacos ? elementValue.Trim() : elementValue; switch (tag) { case DFeAttributeAttribute _: return new XAttribute(tag.Name, elementValue); case DFeDictionaryKeyAttribute keyAtt when keyAtt.AsAttribute: return new XAttribute(keyAtt.Name, elementValue); case DFeElementAttribute eAttribute: XNamespace aw = eAttribute.Namespace ?? string.Empty; if (elementValue.IsCData()) { elementValue = elementValue.RemoveCData(); return new XElement(aw + eAttribute.Name, new XCData(elementValue)); } else { return eAttribute.UseCData ? new XElement(aw + eAttribute.Name, new XCData(elementValue)) : new XElement(aw + eAttribute.Name, elementValue); } default: return new XElement(tag.Name, elementValue); } } #endregion Serialize #region Deserialize /// <summary> /// Deserializes the XElement to the fundamental primitive (e.g. string, int etc.) of a specified type using options. /// </summary> /// <param name="tag">The tag.</param> /// <param name="parentElement">The parent XElement used to deserialize the fundamental primitive.</param> /// <param name="item">The item.</param> /// <param name="prop">The property.</param> /// <param name="options">The options.</param> /// <returns>The deserialized fundamental primitive from the XElement.</returns> public static object Deserialize(DFeBaseAttribute tag, XObject parentElement, object item, PropertyInfo prop) { if (parentElement == null) return null; var element = parentElement as XElement; var value = element?.Value ?? ((XAttribute)parentElement).Value; return GetValue(tag.Tipo, value, item, prop); } public static object GetValue(TipoCampo tipo, string valor, object item, PropertyInfo prop) { if (valor.IsEmpty()) return null; object ret; switch (tipo) { case TipoCampo.Int: ret = valor.ToInt32(); break; case TipoCampo.Long: ret = valor.ToInt64(); break; case TipoCampo.DatHor: ret = valor.ToData(); break; case TipoCampo.DatHorTz: ret = valor.ToDataOffset(); break; case TipoCampo.Dat: case TipoCampo.DatCFe: ret = DateTime.ParseExact(valor, tipo == TipoCampo.DatCFe ? "yyyyMMdd" : "yyyy-MM-dd", CultureInfo.InvariantCulture); break; case TipoCampo.Hor: case TipoCampo.HorCFe: ret = DateTime.ParseExact(valor, tipo == TipoCampo.HorCFe ? "HHmmss" : "HH:mm:ss", CultureInfo.InvariantCulture); break; case TipoCampo.De2: case TipoCampo.De3: case TipoCampo.De4: case TipoCampo.De10: case TipoCampo.De6: var numberFormat = CultureInfo.InvariantCulture.NumberFormat; ret = decimal.Parse(valor, numberFormat); break; case TipoCampo.Enum: var type = prop.PropertyType.IsGenericType ? prop.PropertyType.GetGenericArguments()[0] : prop.PropertyType; object value1 = type.GetMembers().Where(x => x.HasAttribute<DFeEnumAttribute>()) .SingleOrDefault(x => x.GetAttribute<DFeEnumAttribute>().Value == valor)?.Name ?? valor; ret = Enum.Parse(type, value1.ToString()); break; case TipoCampo.Custom: var deserialize = prop.GetDeserializer(item); ret = deserialize(valor); break; default: ret = valor.RemoveCData(); break; } return ret; } #endregion Deserialize } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Common; using Mosa.Compiler.Framework.IR; using System; using System.Collections.Generic; using System.Diagnostics; namespace Mosa.Compiler.Framework { /// <summary> /// Represents a block of instructions with no internal jumps and only one entry and exit. /// </summary> public sealed class BasicBlock { public static readonly int PrologueLabel = -1; public static readonly int StartLabel = 0; public static readonly int EpilogueLabel = Int32.MaxValue; #region Data Fields /// <summary> /// The branch instructions /// </summary> private List<InstructionNode> branchInstructions = new List<InstructionNode>(2); #endregion Data Fields #region Properties /// <summary> /// Gets the first instruction node. /// </summary> public InstructionNode First { get; private set; } /// <summary> /// Gets the last instruction node. /// </summary> public InstructionNode Last { get; private set; } /// <summary> /// Gets the before last instruction node. /// </summary> public InstructionNode BeforeLast { get { return Last.Previous; } } /// <summary> /// Retrieves the label, which uniquely identifies this block. /// </summary> /// <value>The label.</value> public int Label { get; private set; } /// <summary> /// Retrieves the label, which uniquely identifies this block. /// </summary> /// <value>The label.</value> public int Sequence { get; internal set; } /// <summary> /// Returns a list of all Blocks, which are potential branch targets /// of the last instruction in this block. /// </summary> public List<BasicBlock> NextBlocks { get; internal set; } /// <summary> /// Returns a list of all Blocks, which branch to this block. /// </summary> public List<BasicBlock> PreviousBlocks { get; internal set; } /// <summary> /// <True/> if this Block has following blocks /// </summary> public bool HasNextBlocks { get { return NextBlocks.Count > 0; } } /// <summary> /// <True/> if this Block has previous blocks /// </summary> public bool HasPreviousBlocks { get { return PreviousBlocks.Count > 0; } } /// <summary> /// Gets a value indicating whether this instance is prologue. /// </summary> /// <value> /// <c>true</c> if this instance is prologue; otherwise, <c>false</c>. /// </value> public bool IsPrologue { get { return Label == PrologueLabel; } } /// <summary> /// Gets a value indicating whether this instance is epilogue. /// </summary> /// <value> /// <c>true</c> if this instance is epilogue; otherwise, <c>false</c>. /// </value> public bool IsEpilogue { get { return Label == EpilogueLabel; } } #endregion Properties #region Construction internal BasicBlock(int sequence, int label) { NextBlocks = new List<BasicBlock>(2); PreviousBlocks = new List<BasicBlock>(1); Label = label; Sequence = sequence; First = new InstructionNode(IRInstruction.BlockStart); First.Label = label; First.Block = this; Last = new InstructionNode(IRInstruction.BlockEnd); Last.Label = label; Last.Block = this; First.Next = Last; Last.Previous = First; } #endregion Construction #region Methods internal void AddBranchInstruction(InstructionNode node) { if (node.Instruction != null && node.Instruction.IgnoreInstructionBasicBlockTargets) return; if (node.BranchTargets == null || node.BranchTargetsCount == 0) return; Debug.Assert(node.Block != null); // Note: The list only has 1 unless it's a switch statement, so actual performance is very close to O(1) for non-switch statements branchInstructions.AddIfNew(node); var currentBlock = node.Block; foreach (var target in node.BranchTargets) { currentBlock.NextBlocks.AddIfNew(target); target.PreviousBlocks.AddIfNew(currentBlock); } } internal void RemoveBranchInstruction(InstructionNode node) { if (node.BranchTargets == null || node.BranchTargetsCount == 0) return; branchInstructions.Remove(node); var currentBlock = node.Block; // Note: The list only has 1 or 2 entries, so actual performance is very close to O(1) foreach (var target in node.BranchTargets) { if (!FindTarget(target)) { currentBlock.NextBlocks.Remove(target); target.PreviousBlocks.Remove(currentBlock); } } } private bool FindTarget(BasicBlock block) { foreach (var b in branchInstructions) { if (b.BranchTargets.Contains(block)) return true; } return false; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns>The code as a string value.</returns> public override string ToString() { return String.Format("L_{0:X4}", Label); } /// <summary> /// Checks that all instructions are part of the block. /// </summary> public void DebugCheck() { Debug.Assert(First.Block == Last.Block); Debug.Assert(First.Label == Last.Label); var node = First; while (!node.IsBlockEndInstruction) { Debug.Assert(node.Block == this); node = node.Next; Debug.Assert(node != null); } Debug.Assert(node == Last); node = Last; while (!node.IsBlockStartInstruction) { Debug.Assert(node.Block == this); node = node.Previous; Debug.Assert(node != null); } Debug.Assert(node == First); } #endregion Methods } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H11Level111111Child (editable child object).<br/> /// This is a generated base class of <see cref="H11Level111111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H10Level11111"/> collection. /// </remarks> [Serializable] public partial class H11Level111111Child : BusinessBase<H11Level111111Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H11Level111111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="H11Level111111Child"/> object.</returns> internal static H11Level111111Child NewH11Level111111Child() { return DataPortal.CreateChild<H11Level111111Child>(); } /// <summary> /// Factory method. Loads a <see cref="H11Level111111Child"/> object, based on given parameters. /// </summary> /// <param name="cQarentID1">The CQarentID1 parameter of the H11Level111111Child to fetch.</param> /// <returns>A reference to the fetched <see cref="H11Level111111Child"/> object.</returns> internal static H11Level111111Child GetH11Level111111Child(int cQarentID1) { return DataPortal.FetchChild<H11Level111111Child>(cQarentID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H11Level111111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private H11Level111111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H11Level111111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H11Level111111Child"/> object from the database, based on given criteria. /// </summary> /// <param name="cQarentID1">The CQarent ID1.</param> protected void Child_Fetch(int cQarentID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CQarentID1", cQarentID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cQarentID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="H11Level111111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H11Level111111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="H11Level111111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="H11Level111111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteH11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Reflection; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Common.Markup; using Gallio.Common.Normalization; namespace Gallio.Common.Diagnostics { /// <summary> /// Describes an exception in a serializable form. /// </summary> [Serializable] public sealed class ExceptionData : IMarkupStreamWritable, INormalizable<ExceptionData> { private readonly string type; private readonly string message; private readonly StackTraceData stackTrace; private readonly ExceptionData innerException; private readonly PropertySet properties; /// <summary> /// Gets an empty read-only property set that can be used to indicate that /// an exception data object does not contain any properties. /// </summary> public static readonly PropertySet NoProperties = new PropertySet().AsReadOnly(); /// <summary> /// Creates an exception data object from an exception. /// </summary> /// <remarks> /// <para> /// Captures the exception type, message, stack trace and properties from /// the exception object. To filter out specific properties, mark them with /// <see cref="SystemInternalAttribute"/>. /// </para> /// </remarks> /// <param name="exception">The exception.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/> is null.</exception> public ExceptionData(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); type = exception.GetType().FullName; message = ExceptionUtils.SafeGetMessage(exception); stackTrace = new StackTraceData(ExceptionUtils.SafeGetStackTrace(exception)); properties = ExtractExceptionProperties(exception).AsReadOnly(); if (exception.InnerException != null) innerException = new ExceptionData(exception.InnerException); } /// <summary> /// Creates an exception data object. /// </summary> /// <param name="type">The exception type full name.</param> /// <param name="message">The exception message text.</param> /// <param name="stackTrace">The exception stack trace.</param> /// <param name="properties">The exception properties, or <see cref="NoProperties"/> /// if none.</param> /// <param name="innerException">The inner exception data, or null if none.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/>, /// <paramref name="message"/>, <paramref name="properties"/> /// or <paramref name="stackTrace"/> is null.</exception> public ExceptionData(string type, string message, string stackTrace, PropertySet properties, ExceptionData innerException) : this(type, message, new StackTraceData(stackTrace), properties, innerException) { } /// <summary> /// Creates an exception data object. /// </summary> /// <param name="type">The exception type full name.</param> /// <param name="message">The exception message text.</param> /// <param name="stackTrace">The exception stack trace.</param> /// <param name="properties">The exception properties, or <see cref="NoProperties"/> /// if none.</param> /// <param name="innerException">The inner exception data, or null if none.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/>, /// <paramref name="message"/>, <paramref name="properties"/> /// or <paramref name="stackTrace"/> is null.</exception> public ExceptionData(string type, string message, StackTraceData stackTrace, PropertySet properties, ExceptionData innerException) { if (type == null) throw new ArgumentNullException("type"); if (message == null) throw new ArgumentNullException("message"); if (stackTrace == null) throw new ArgumentNullException("stackTrace"); if (properties == null) throw new ArgumentNullException("properties"); this.type = type; this.message = message; this.stackTrace = stackTrace; this.properties = properties.Count == 0 ? NoProperties : properties.AsReadOnly(); this.innerException = innerException; } /// <summary> /// Gets the exception type full name. /// </summary> public string Type { get { return type; } } /// <summary> /// Gets the exception message text. /// </summary> public string Message { get { return message; } } /// <summary> /// Gets the exception stack trace. /// </summary> public StackTraceData StackTrace { get { return stackTrace; } } /// <summary> /// Gets the inner exception data, or null if none. /// </summary> public ExceptionData InnerException { get { return innerException; } } /// <summary> /// Gets the read-only set of formatted exception properties. /// </summary> public PropertySet Properties { get { return properties; } } /// <inheritdoc /> public ExceptionData Normalize() { string normalizedType = NormalizationUtils.NormalizeName(type); string normalizedMessage = NormalizationUtils.NormalizeXmlText(message); StackTraceData normalizedStackTrace = stackTrace.Normalize(); PropertySet normalizedProperties = NormalizationUtils.NormalizeCollection<PropertySet, KeyValuePair<string, string>>(properties, () => new PropertySet(), x => new KeyValuePair<string, string>(NormalizationUtils.NormalizeName(x.Key), NormalizationUtils.NormalizeXmlText(x.Value)), (x, y) => x.Key == y.Key && x.Value == y.Value); ExceptionData normalizedInnerException = innerException != null ? innerException.Normalize() : null; if (ReferenceEquals(type, normalizedType) && ReferenceEquals(message, normalizedMessage) && ReferenceEquals(stackTrace, normalizedStackTrace) && ReferenceEquals(properties, normalizedProperties) && ReferenceEquals(innerException, normalizedInnerException)) return this; return new ExceptionData(normalizedType, normalizedMessage, normalizedStackTrace, normalizedProperties, normalizedInnerException); } /// <summary> /// Formats the exception to a string similar to the one that the .Net framework /// would ordinarily construct. /// </summary> /// <remarks> /// <para> /// The exception will not be terminated by a new line. /// </para> /// </remarks> /// <returns>The formatted exception.</returns> public override string ToString() { return ToString(false); } /// <summary> /// Formats the exception to a string similar to the one that the .Net framework /// would ordinarily construct. /// </summary> /// <remarks> /// <para> /// The exception will not be terminated by a new line. /// </para> /// </remarks> /// <param name="useStandardFormatting">If true, strictly follows the standard .Net /// exception formatting by excluding the display of exception properties.</param> /// <returns>The formatted exception.</returns> public string ToString(bool useStandardFormatting) { StringMarkupDocumentWriter writer = new StringMarkupDocumentWriter(false); WriteTo(writer.Default, useStandardFormatting); return writer.ToString(); } /// <summary> /// Writes the exception in a structured format with markers to distinguish its component elements. /// </summary> /// <remarks> /// <para> /// The exception will not be terminated by a new line. /// </para> /// </remarks> /// <param name="writer">The log stream writer.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="writer"/> is null.</exception> public void WriteTo(MarkupStreamWriter writer) { WriteTo(writer, false); } /// <summary> /// Writes the exception in a structured format with markers to distinguish its component elements. /// </summary> /// <remarks> /// <para> /// The exception will not be terminated by a new line. /// </para> /// </remarks> /// <param name="writer">The log stream writer.</param> /// <param name="useStandardFormatting">If true, strictly follows the standard .Net /// exception formatting by excluding the display of exception properties.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="writer"/> is null.</exception> public void WriteTo(MarkupStreamWriter writer, bool useStandardFormatting) { if (writer == null) throw new ArgumentNullException("writer"); using (writer.BeginMarker(Marker.Exception)) { using (writer.BeginMarker(Marker.ExceptionType)) writer.Write(type); if (message.Length != 0) { writer.Write(@": "); using (writer.BeginMarker(Marker.ExceptionMessage)) writer.Write(message); } if (innerException != null) { writer.Write(@" ---> "); innerException.WriteTo(writer); writer.Write(Environment.NewLine); writer.Write(@" --- "); writer.Write("End of inner exception stack trace"); // todo localize me writer.Write(@" ---"); } if (!useStandardFormatting) { foreach (KeyValuePair<string, string> property in properties) { writer.WriteLine(); using (writer.BeginMarker(Marker.ExceptionPropertyName)) writer.Write(property.Key); writer.Write(@": "); using (writer.BeginMarker(Marker.ExceptionPropertyValue)) writer.Write(property.Value); } } if (!stackTrace.IsEmpty) { writer.WriteLine(); stackTrace.WriteTo(writer); } } } private static PropertySet ExtractExceptionProperties(Exception exception) { PropertySet properties = null; foreach (PropertyInfo propertyInfo in exception.GetType().GetProperties()) { string propertyName = propertyInfo.Name; if (IsBuiltInPropertyName(propertyName)) continue; if (IsIgnoredProperty(propertyInfo)) continue; if (propertyInfo.GetIndexParameters().Length != 0) continue; string propertyValue; try { object obj = propertyInfo.GetValue(exception, null); if (obj == null) continue; propertyValue = obj.ToString(); } catch { continue; } if (properties == null) properties = new PropertySet(); if (! properties.ContainsKey(propertyName)) properties.Add(propertyName, propertyValue); } return properties ?? NoProperties; } private static bool IsBuiltInPropertyName(string propertyName) { switch (propertyName) { case "Data": case "Message": case "InnerException": case "Source": case "StackTrace": case "TargetSite": return true; default: return false; } } private static bool IsIgnoredProperty(PropertyInfo propertyInfo) { return propertyInfo.IsDefined(typeof(SystemInternalAttribute), true); } } }
// Cfg.Net // An Alternative .NET Configuration Handler // Copyright 2015-2018 Dale Newman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Cfg.Net.Contracts; namespace Cfg.Net { internal static class CfgMetadataCache { private static readonly object Locker = new object(); private static readonly Dictionary<Type, Dictionary<string, CfgMetadata>> MetadataCache = new Dictionary<Type, Dictionary<string, CfgMetadata>>(); private static readonly Dictionary<Type, List<string>> PropertyCache = new Dictionary<Type, List<string>>(); private static readonly Dictionary<Type, List<string>> ElementCache = new Dictionary<Type, List<string>>(); private static readonly Dictionary<Type, Dictionary<string, string>> NameCache = new Dictionary<Type, Dictionary<string, string>>(); internal static Dictionary<string, CfgMetadata> GetMetadata(Type type) { if (MetadataCache.TryGetValue(type, out var metadata)) return metadata; lock (Locker) { NameCache[type] = new Dictionary<string, string>(); var keyCache = new List<string>(); var listCache = new List<string>(); #if NETS var propertyInfos = type.GetRuntimeProperties().ToArray(); #else var propertyInfos = type.GetProperties(); #endif metadata = new Dictionary<string, CfgMetadata>(StringComparer.Ordinal); foreach (var propertyInfo in propertyInfos) { if (!propertyInfo.CanRead) continue; if (!propertyInfo.CanWrite) continue; #if NETS var attribute = (CfgAttribute)propertyInfo.GetCustomAttribute(typeof(CfgAttribute), true); #else var attribute = (CfgAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(CfgAttribute), true); #endif if (attribute == null) continue; var key = NormalizeName(type, propertyInfo.Name); var item = new CfgMetadata(propertyInfo, attribute) { TypeDefault = GetDefaultValue(propertyInfo.PropertyType) }; // regex try { if (attribute.RegexIsSet) { #if NETS item.Regex = attribute.ignoreCase ? new Regex(attribute.regex, RegexOptions.IgnoreCase) : new Regex(attribute.regex); #else item.Regex = attribute.ignoreCase ? new Regex(attribute.regex, RegexOptions.Compiled | RegexOptions.IgnoreCase) : new Regex(attribute.regex, RegexOptions.Compiled); #endif } } catch (ArgumentException ex) { item.Errors.Add(CfgEvents.InvalidRegex(key, attribute.regex, ex)); } // check default value for type mismatch if (attribute.ValueIsSet) { if (attribute.value.GetType() != propertyInfo.PropertyType) { var value = attribute.value; if (TryConvertValue(ref value, propertyInfo.PropertyType)) { attribute.value = value; } else { item.TypeMismatch = true; item.Errors.Add(CfgEvents.TypeMismatch(key, value, propertyInfo.PropertyType)); } } } // type safety for value, min value, and max value var defaultValue = attribute.value; if (ResolveType(() => attribute.ValueIsSet, ref defaultValue, key, item)) { attribute.value = defaultValue; } var minValue = attribute.minValue; if (ResolveType(() => attribute.MinValueSet, ref minValue, key, item)) { attribute.minValue = minValue; } var maxValue = attribute.maxValue; if (ResolveType(() => attribute.MaxValueSet, ref maxValue, key, item)) { attribute.maxValue = maxValue; } //foreach (var cp in constructors) { // if (!cp.Any()) { // obj = item.ListActivator(); // break; // } // if (cp.Count() == 1) { // if (cp.First().ParameterType == typeof(int)) { // obj = Activator.CreateInstance(item.ListType, add.Attributes.Count); // break; // } // if (cp.First().ParameterType == typeof(string[])) { // var names = add.Attributes.Select(a => a.Name).ToArray(); // obj = Activator.CreateInstance(item.ListType, new object[] { names }); // break; // } // } //} #if NETS var propertyTypeInfo = propertyInfo.PropertyType.GetTypeInfo(); if (propertyTypeInfo.IsGenericType) { listCache.Add(key); item.ListType = propertyTypeInfo.GenericTypeArguments[0]; var listTypeInfo = item.ListType.GetTypeInfo(); item.ImplementsProperties = typeof(IProperties).GetTypeInfo().IsAssignableFrom(listTypeInfo); item.Constructors = propertyTypeInfo.DeclaredConstructors.Select(c => c.GetParameters()); item.ListActivator = () => Activator.CreateInstance(propertyInfo.PropertyType); if (listTypeInfo.IsSubclassOf(typeof(CfgNode))) { item.Loader = () => (CfgNode)Activator.CreateInstance(item.ListType); } } else { keyCache.Add(key); } #else if (propertyInfo.PropertyType.IsGenericType) { listCache.Add(key); item.ListType = propertyInfo.PropertyType.GetGenericArguments()[0]; item.ImplementsProperties = typeof(IProperties).IsAssignableFrom(item.ListType); item.Constructors = item.ListType.GetConstructors().Select(c => c.GetParameters()); item.ListActivator = () => Activator.CreateInstance(propertyInfo.PropertyType); if (item.ListType.IsSubclassOf(typeof(CfgNode))) { item.Loader = () => (CfgNode)Activator.CreateInstance(item.ListType); } } else { keyCache.Add(key); } #endif if (string.IsNullOrEmpty(attribute.name)) { attribute.name = key; } item.Setter = CfgReflectionHelper.CreateSetter(propertyInfo); item.Getter = CfgReflectionHelper.CreateGetter(propertyInfo); metadata[key] = item; } PropertyCache[type] = keyCache; ElementCache[type] = listCache; MetadataCache[type] = metadata; return metadata; } } private static bool ResolveType(Func<bool> isSet, ref object input, string key, CfgMetadata metadata) { if (!isSet()) return true; var type = metadata.PropertyInfo.PropertyType; if (input.GetType() == type) return true; var value = input; if (TryConvertValue(ref value, type)) { input = value; return true; } metadata.TypeMismatch = true; metadata.Errors.Add(CfgEvents.TypeMismatch(key, value, type)); return false; } private static object GetDefaultValue(Type t) { #if NETS return t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null; #else return t.IsValueType ? Activator.CreateInstance(t) : null; #endif } private static bool TryConvertValue(ref object value, Type conversionType) { try { value = Convert.ChangeType(value, conversionType, null); return true; } catch { return false; } } internal static string NormalizeName(Type type, string name) { lock (Locker) { if (NameCache[type].TryGetValue(name, out var value)) { return value; } var builder = new StringBuilder(); foreach (var character in name.ToCharArray().Where(char.IsLetterOrDigit)) { builder.Append(char.IsUpper(character) ? char.ToLowerInvariant(character) : character); } var result = builder.ToString(); NameCache[type][name] = result; return result; } } public static IEnumerable<string> PropertyNames(Type type) { return PropertyCache.TryGetValue(type, out var names) ? names : new List<string>(); } public static IEnumerable<string> ElementNames(Type type) { return ElementCache.TryGetValue(type, out var names) ? names : new List<string>(); } /// <summary> /// Clone any node that has a parameterless constructor defined. /// </summary> /// <param name="node"></param> /// <returns></returns> internal static T Clone<T>(T node) where T : CfgNode { var clone = Activator.CreateInstance<T>(); clone.Parser = node.Parser; clone.Reader = node.Reader; clone.Serializer = node.Serializer; clone.Customizers = node.Customizers; clone.Type = node.Type; var meta = GetMetadata(typeof(T)); CloneProperties(meta, node, clone); CloneLists(meta, node, clone); return clone; } private static void CloneProperties(Dictionary<string, CfgMetadata> meta, object node, object clone) { foreach (var pair in meta.Where(kv => kv.Value.ListType == null)) { pair.Value.Setter(clone, pair.Value.Getter(node)); } } private static void CloneLists(IDictionary<string, CfgMetadata> meta, object node, object clone) { foreach (var pair in meta.Where(kv => kv.Value.ListType != null)) { var items = (IList)meta[pair.Key].Getter(node); var cloneItems = (IList)Activator.CreateInstance(pair.Value.PropertyInfo.PropertyType); foreach (var item in items) { var metaItem = GetMetadata(item.GetType()); bool isAssignable = false; #if NETS isAssignable = typeof(CfgNode).GetTypeInfo().IsAssignableFrom(pair.Value.ListType.GetTypeInfo()); #else isAssignable = typeof(CfgNode).IsAssignableFrom(pair.Value.ListType); #endif if (!isAssignable) continue; var cloneItem = Activator.CreateInstance(pair.Value.ListType); CloneProperties(metaItem, item, cloneItem); CloneLists(metaItem, item, cloneItem); cloneItems.Add(cloneItem); } meta[pair.Key].Setter(clone, cloneItems); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Collections; using Microsoft.Build.Engine.UnitTests.BackEnd; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using ElementLocation = Microsoft.Build.Construction.ElementLocation; using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using LegacyThreadingData = Microsoft.Build.Execution.LegacyThreadingData; using TargetDotNetFrameworkVersion = Microsoft.Build.Utilities.TargetDotNetFrameworkVersion; using ToolLocationHelper = Microsoft.Build.Utilities.ToolLocationHelper; using Xunit; namespace Microsoft.Build.UnitTests.BackEnd { /// <summary> /// Unit tests for the TaskBuilder component /// </summary> public class TaskBuilder_Tests : ITargetBuilderCallback { #if FEATURE_CODEDOM /// <summary> /// Task definition for a task that outputs items containing null metadata. /// </summary> private static string s_nullMetadataTaskContents = @"using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Collections; using System.Collections.Generic; namespace NullMetadataTask { public class NullMetadataTask : Task { [Output] public ITaskItem[] OutputItems { get; set; } public override bool Execute() { OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(""a"", null); OutputItems[0] = new TaskItem(""foo"", (IDictionary)metadata); return true; } } } "; /// <summary> /// Task definition for task that outputs items in a variety of ways, used to /// test definition of the DefiningProject* metadata for task outputs. /// </summary> private static string s_itemCreationTaskContents = @"using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System.Collections; using System.Collections.Generic; namespace ItemCreationTask { public class ItemCreationTask : Task { public ITaskItem[] InputItemsToPassThrough { get; set; } public ITaskItem[] InputItemsToCopy { get; set; } [Output] public ITaskItem[] PassedThroughOutputItems { get; set; } [Output] public ITaskItem[] CreatedOutputItems { get; set; } [Output] public ITaskItem[] CopiedOutputItems { get; set; } [Output] public string OutputString { get; set; } public override bool Execute() { PassedThroughOutputItems = InputItemsToPassThrough; CopiedOutputItems = new ITaskItem[InputItemsToCopy.Length]; for (int i = 0; i < InputItemsToCopy.Length; i++) { CopiedOutputItems[i] = new TaskItem(InputItemsToCopy[i]); } CreatedOutputItems = new ITaskItem[2]; CreatedOutputItems[0] = new TaskItem(""Foo""); CreatedOutputItems[1] = new TaskItem(""Bar""); OutputString = ""abc;def;ghi""; return true; } } } "; #endif /// <summary> /// The mock component host and logger /// </summary> private MockHost _host; /// <summary> /// The temporary project we use to run the test /// </summary> private ProjectInstance _testProject; /// <summary> /// Prepares the environment for the test. /// </summary> public TaskBuilder_Tests() { _host = new MockHost(); _testProject = CreateTestProject(); } /********************************************************************************* * * OUTPUT PARAMS * *********************************************************************************/ /// <summary> /// Verifies that we do look up the task during execute when the condition is true. /// </summary> [Fact] public void TasksAreDiscoveredWhenTaskConditionTrue() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='1'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("MSB4036"); logger.AssertLogDoesntContain("Made it"); } /// <summary> /// Tests that when the task condition is false, Execute still returns true even though we never loaded /// the task. We verify that we never loaded the task because if we did try, the task load itself would /// have failed, resulting in an error. /// </summary> [Fact] public void TasksNotDiscoveredWhenTaskConditionFalse() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <NonExistantTask Condition=""'1'=='2'""/> <Message Text='Made it'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains("Made it"); } /// <summary> /// Verify when task outputs are overridden the override messages are correctly displayed /// </summary> [Fact] public void OverridePropertiesInCreateProperty() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t'> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='final:[$(LinkSwitches)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t", loggers); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } /// <summary> /// Verify that when a task outputs are inferred the override messages are displayed /// </summary> [Fact] public void OverridePropertiesInInferredCreateProperty() { string[] files = null; try { files = ObjectModelHelpers.GetTempFiles(2, new DateTime(2005, 1, 1)); MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents( @"<Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <i Include='" + files[0] + "'><output>" + files[1] + @"</output></i> </ItemGroup> <ItemGroup> <EmbeddedResource Include='a.resx'> <LogicalName>foo</LogicalName> </EmbeddedResource> <EmbeddedResource Include='b.resx'> <LogicalName>bar</LogicalName> </EmbeddedResource> <EmbeddedResource Include='c.resx'> <LogicalName>barz</LogicalName> </EmbeddedResource> </ItemGroup> <Target Name='t2' DependsOnTargets='t'> <Message Text='final:[$(LinkSwitches)]'/> </Target> <Target Name='t' Inputs='%(i.Identity)' Outputs='%(i.Output)'> <Message Text='start:[Hello]'/> <CreateProperty Value=""@(EmbeddedResource->'/assemblyresource:%(Identity),%(LogicalName)', ' ')"" Condition=""'%(LogicalName)' != '' ""> <Output TaskParameter=""Value"" PropertyName=""LinkSwitches""/> </CreateProperty> <Message Text='end:[hello]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build("t2", loggers); // We should only see messages from the second target, as the first is only inferred logger.AssertLogDoesntContain("start:"); logger.AssertLogDoesntContain("end:"); logger.AssertLogContains(new string[] { "final:[/assemblyresource:c.resx,barz]" }); logger.AssertLogDoesntContain(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("TaskStarted", "CreateProperty")); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:a.resx,foo", "/assemblyresource:b.resx,bar") }); logger.AssertLogContains(new string[] { ResourceUtilities.FormatResourceStringStripCodeAndKeyword("PropertyOutputOverridden", "LinkSwitches", "/assemblyresource:b.resx,bar", "/assemblyresource:c.resx,barz") }); } finally { ObjectModelHelpers.DeleteTempFiles(files); } } /// <summary> /// Tests that tasks batch on outputs correctly. /// </summary> [Fact] public void TaskOutputBatching() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <TaskParameterItem Include=""foo""> <ParameterName>Value</ParameterName> <ParameterName2>Include</ParameterName2> <PropertyName>MetadataProperty</PropertyName> <ItemType>MetadataItem</ItemType> </TaskParameterItem> </ItemGroup> <Target Name='Build'> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""Property1""/> </CreateProperty> <Message Text='Property1=[$(Property1)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName)"" PropertyName=""Property2""/> </CreateProperty> <Message Text='Property2=[$(Property2)]' /> <CreateProperty Value=""@(TaskParameterItem)""> <Output TaskParameter=""Value"" PropertyName=""%(TaskParameterItem.PropertyName)""/> </CreateProperty> <Message Text='MetadataProperty=[$(MetadataProperty)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""TestItem1""/> </CreateItem> <Message Text='TestItem1=[@(TestItem1)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""%(TaskParameterItem.ParameterName2)"" ItemName=""TestItem2""/> </CreateItem> <Message Text='TestItem2=[@(TestItem2)]' /> <CreateItem Include=""@(TaskParameterItem)""> <Output TaskParameter=""Include"" ItemName=""%(TaskParameterItem.ItemType)""/> </CreateItem> <Message Text='MetadataItem=[@(MetadataItem)]' /> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); project.Build(loggers); logger.AssertLogContains("Property1=[foo]"); logger.AssertLogContains("Property2=[foo]"); logger.AssertLogContains("MetadataProperty=[foo]"); logger.AssertLogContains("TestItem1=[foo]"); logger.AssertLogContains("TestItem2=[foo]"); logger.AssertLogContains("MetadataItem=[foo]"); } /// <summary> /// MSbuildLastTaskResult property contains true or false indicating /// the success or failure of the last task. /// </summary> [Fact] public void MSBuildLastTaskResult() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project DefaultTargets='t2' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <Message Text='[start:$(MSBuildLastTaskResult)]'/> <!-- Should be blank --> <Warning Text='warning'/> <Message Text='[0:$(MSBuildLastTaskResult)]'/> <!-- Should be true, only a warning--> <!-- task's Execute returns false --> <Copy SourceFiles='|' DestinationFolder='c:\' ContinueOnError='true' /> <PropertyGroup> <p>$(MSBuildLastTaskResult)</p> </PropertyGroup> <Message Text='[1:$(MSBuildLastTaskResult)]'/> <!-- Should be false: propertygroup did not reset it --> <Message Text='[p:$(p)]'/> <!-- Should be false as stored earlier --> <Message Text='[2:$(MSBuildLastTaskResult)]'/> <!-- Message succeeded, should now be true --> </Target> <Target Name='t2' DependsOnTargets='t'> <Message Text='[3:$(MSBuildLastTaskResult)]'/> <!-- Should still have true --> <!-- check Error task as well --> <Error Text='error' ContinueOnError='true' /> <Message Text='[4:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> <!-- trigger OnError target, ContinueOnError is false --> <Error Text='error2'/> <OnError ExecuteTargets='t3'/> </Target> <Target Name='t3' > <Message Text='[5:$(MSBuildLastTaskResult)]'/> <!-- Should be false --> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); MockLogger logger = new MockLogger(); loggers.Add(logger); project.Build("t2", loggers); logger.AssertLogContains("[start:]"); logger.AssertLogContains("[0:true]"); logger.AssertLogContains("[1:false]"); logger.AssertLogContains("[p:false]"); logger.AssertLogContains("[2:true]"); logger.AssertLogContains("[3:true]"); logger.AssertLogContains("[4:false]"); logger.AssertLogContains("[4:false]"); } /// <summary> /// Verifies that we can add "recursivedir" built-in metadata as target outputs. /// This is to support wildcards in CreateItem. Allowing anything /// else could let the item get corrupt (inconsistent values for Filename and FullPath, for example) /// </summary> [Fact] [Trait("Category", "netcore-osx-failing")] [Trait("Category", "netcore-linux-failing")] [Trait("Category", "mono-osx-failing")] public void TasksCanAddRecursiveDirBuiltInMetadata() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='$(programfiles)\reference assemblies\**\*.dll;'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='@(x)'/> <Message Text='[%(x.RecursiveDir)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogDoesntContain("[]"); logger.AssertLogDoesntContain("MSB4118"); logger.AssertLogDoesntContain("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='RecursiveDir=1'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify CreateItem prevents adding any built-in metadata explicitly, even recursivedir. /// </summary> [Fact] public void OtherBuiltInMetadataErrors2() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <CreateItem Include='Foo' AdditionalMetadata='Extension=1'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.False(result); logger.AssertLogContains("MSB3031"); } /// <summary> /// Verify that properties can be passed in to a task and out as items, despite the /// built-in metadata restrictions. /// </summary> [Fact] public void PropertiesInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>c:\a.ext</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[%(x.Extension)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[.ext]"); } #if FEATURE_CODEDOM /// <summary> /// Verify that properties can be passed in to a task and out as items, despite /// having illegal characters for a file name /// </summary> [Fact] public void IllegalFileCharsInItemsOutOfTask() { MockLogger logger = new MockLogger(); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <Target Name='t'> <PropertyGroup> <p>||illegal||</p> </PropertyGroup> <CreateItem Include='$(p)'> <Output TaskParameter='Include' ItemName='x' /> </CreateItem> <Message Text='[@(x)]'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); bool result = project.Build("t", loggers); Assert.True(result); logger.AssertLogContains("[||illegal||]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnOutputItems() { string customTaskPath = CustomTaskHelper.GetAssemblyForTask(s_nullMetadataTaskContents); string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void NullMetadataOnLegacyOutputItems() { string referenceAssembliesPath = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.VersionLatest); if (String.IsNullOrEmpty(referenceAssembliesPath)) { // fall back to the .NET Framework -- they should always exist there. referenceAssembliesPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest); } string[] referenceAssemblies = new string[] { Path.Combine(referenceAssembliesPath, "System.dll"), Path.Combine(referenceAssembliesPath, "Microsoft.Build.Framework.dll"), Path.Combine(referenceAssembliesPath, "Microsoft.Build.Utilities.v4.0.dll") }; string customTaskPath = CustomTaskHelper.GetAssemblyForTask(s_nullMetadataTaskContents, referenceAssemblies); string projectContents = @"<Project ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`> <UsingTask TaskName=`NullMetadataTask` AssemblyFile=`" + customTaskPath + @"` /> <Target Name=`Build`> <NullMetadataTask> <Output TaskParameter=`OutputItems` ItemName=`Outputs`/> </NullMetadataTask> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents); logger.AssertLogContains("[foo: ]"); } #endif #if FEATURE_CODETASKFACTORY /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] public void NullMetadataOnOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v12` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v12> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v12> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents); logger.AssertLogContains("[foo: ]"); } /// <summary> /// If an item being output from a task has null metadata, we shouldn't crash. /// </summary> [Fact] [Trait("Category", "non-mono-tests")] public void NullMetadataOnLegacyOutputItems_InlineTask() { string projectContents = @" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`NullMetadataTask_v4` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildFrameworkToolsPath)\Microsoft.Build.Tasks.v4.0.dll`> <ParameterGroup> <OutputItems ParameterType=`Microsoft.Build.Framework.ITaskItem[]` Output=`true` /> </ParameterGroup> <Task> <Code> <![CDATA[ OutputItems = new ITaskItem[1]; IDictionary<string, string> metadata = new Dictionary<string, string>(); metadata.Add(`a`, null); OutputItems[0] = new TaskItem(`foo`, (IDictionary)metadata); return true; ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <NullMetadataTask_v4> <Output TaskParameter=`OutputItems` ItemName=`Outputs` /> </NullMetadataTask_v4> <Message Text=`[%(Outputs.Identity): %(Outputs.a)]` Importance=`High` /> </Target> </Project>"; MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess(projectContents); logger.AssertLogContains("[foo: ]"); } #endif #if FEATURE_CODEDOM /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against the current /// version of MSBuild. /// </summary> [Fact] public void ValidateDefiningProjectMetadataOnTaskOutputs() { string customTaskPath = CustomTaskHelper.GetAssemblyForTask(s_itemCreationTaskContents); ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } /// <summary> /// Validates that the defining project metadata is set (or not set) as expected in /// various task output-related operations, using a task built against V4 MSBuild, /// which didn't support the defining project metadata. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ValidateDefiningProjectMetadataOnTaskOutputs_LegacyItems() { string referenceAssembliesPath = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.VersionLatest); if (String.IsNullOrEmpty(referenceAssembliesPath)) { referenceAssembliesPath = ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest); } string[] referenceAssemblies = new string[] { Path.Combine(referenceAssembliesPath, "System.dll"), Path.Combine(referenceAssembliesPath, "Microsoft.Build.Framework.dll"), Path.Combine(referenceAssembliesPath, "Microsoft.Build.Utilities.v4.0.dll") }; string customTaskPath = CustomTaskHelper.GetAssemblyForTask(s_itemCreationTaskContents, referenceAssemblies); ValidateDefiningProjectMetadataOnTaskOutputsHelper(customTaskPath); } #endif #if FEATURE_APARTMENT_STATE /// <summary> /// Tests that putting the RunInSTA attribute on a task causes it to run in the STA thread. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequired() { TestSTATask(true, false, false); } /// <summary> /// Tests an STA task with an exception /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithException() { TestSTATask(true, false, true); } /// <summary> /// Tests an STA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadRequiredWithFailure() { TestSTATask(true, true, false); } /// <summary> /// Tests an MTA task. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequired() { TestSTATask(false, false, false); } /// <summary> /// Tests an MTA task with an exception. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithException() { TestSTATask(false, false, true); } /// <summary> /// Tests an MTA task with failure. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TestSTAThreadNotRequiredWithFailure() { TestSTATask(false, true, false); } #endif #region ITargetBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<ITargetResult[]> ITargetBuilderCallback.LegacyCallTarget(string[] targets, bool continueOnError, ElementLocation referenceLocation) { throw new NotImplementedException(); } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Yield() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.Reacquire() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.EnterMSBuildCallbackState() { } /// <summary> /// Empty impl /// </summary> void IRequestBuilderCallback.ExitMSBuildCallbackState() { } #endregion #region IRequestBuilderCallback Members /// <summary> /// Empty impl /// </summary> Task<BuildResult[]> IRequestBuilderCallback.BuildProjects(string[] projectFiles, PropertyDictionary<ProjectPropertyInstance>[] properties, string[] toolsVersions, string[] targets, bool waitForResults, bool skipNonexistentTargets) { throw new NotImplementedException(); } /// <summary> /// Not implemented. /// </summary> Task IRequestBuilderCallback.BlockOnTargetInProgress(int blockingRequestId, string blockingTarget, BuildResult partialBuildResult) { throw new NotImplementedException(); } #endregion /********************************************************************************* * * Helpers * *********************************************************************************/ #if FEATURE_CODEDOM /// <summary> /// Helper method for validating the setting of defining project metadata on items /// coming from task outputs /// </summary> private void ValidateDefiningProjectMetadataOnTaskOutputsHelper(string customTaskPath) { string projectAPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "a.proj"); string projectBPath = Path.Combine(ObjectModelHelpers.TempProjectDir, "b.proj"); string projectAContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <UsingTask TaskName=`ItemCreationTask` AssemblyFile=`" + customTaskPath + @"` /> <Import Project=`b.proj` /> <Target Name=`Run`> <ItemCreationTask InputItemsToPassThrough=`@(PassThrough)` InputItemsToCopy=`@(Copy)`> <Output TaskParameter=`OutputString` ItemName=`A` /> <Output TaskParameter=`PassedThroughOutputItems` ItemName=`B` /> <Output TaskParameter=`CreatedOutputItems` ItemName=`C` /> <Output TaskParameter=`CopiedOutputItems` ItemName=`D` /> </ItemCreationTask> <Warning Text=`A is wrong: EXPECTED: [a] ACTUAL: [%(A.DefiningProjectName)]` Condition=`'%(A.DefiningProjectName)' != 'a'` /> <Warning Text=`B is wrong: EXPECTED: [a] ACTUAL: [%(B.DefiningProjectName)]` Condition=`'%(B.DefiningProjectName)' != 'a'` /> <Warning Text=`C is wrong: EXPECTED: [a] ACTUAL: [%(C.DefiningProjectName)]` Condition=`'%(C.DefiningProjectName)' != 'a'` /> <Warning Text=`D is wrong: EXPECTED: [a] ACTUAL: [%(D.DefiningProjectName)]` Condition=`'%(D.DefiningProjectName)' != 'a'` /> </Target> </Project> "; string projectBContents = @" <Project xmlns=`msbuildnamespace` ToolsVersion=`msbuilddefaulttoolsversion`> <ItemGroup> <PassThrough Include=`aaa.cs` /> <Copy Include=`bbb.cs` /> </ItemGroup> </Project> "; try { File.WriteAllText(projectAPath, ObjectModelHelpers.CleanupFileContents(projectAContents)); File.WriteAllText(projectBPath, ObjectModelHelpers.CleanupFileContents(projectBContents)); MockLogger logger = ObjectModelHelpers.BuildTempProjectFileExpectSuccess("a.proj"); logger.AssertNoWarnings(); } finally { if (File.Exists(projectAPath)) { File.Delete(projectAPath); } if (File.Exists(projectBPath)) { File.Delete(projectBPath); } } } #endif // FEATURE_CODEDOM #if FEATURE_APARTMENT_STATE /// <summary> /// Executes an STA task test. /// </summary> private void TestSTATask(bool requireSTA, bool failTask, bool throwException) { MockLogger logger = new MockLogger(); logger.AllowTaskCrashes = throwException; string taskAssemblyName = null; Project project = CreateSTATestProject(requireSTA, failTask, throwException, out taskAssemblyName); List<ILogger> loggers = new List<ILogger>(); loggers.Add(logger); BuildParameters parameters = new BuildParameters(); parameters.Loggers = new ILogger[] { logger }; BuildResult result = BuildManager.DefaultBuildManager.Build(parameters, new BuildRequestData(project.CreateProjectInstance(), new string[] { "Foo" })); if (requireSTA) { logger.AssertLogContains("STA"); } else { logger.AssertLogContains("MTA"); } if (throwException) { logger.AssertLogContains("EXCEPTION"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); return; } else { logger.AssertLogDoesntContain("EXCEPTION"); } if (failTask) { logger.AssertLogContains("FAIL"); Assert.Equal(BuildResultCode.Failure, result.OverallResult); } else { logger.AssertLogDoesntContain("FAIL"); } if (!throwException && !failTask) { Assert.Equal(BuildResultCode.Success, result.OverallResult); } } /// <summary> /// Helper to create a project which invokes the STA helper task. /// </summary> private Project CreateSTATestProject(bool requireSTA, bool failTask, bool throwException, out string assemblyToDelete) { assemblyToDelete = GenerateSTATask(requireSTA); string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <UsingTask TaskName='ThreadTask' AssemblyFile='" + assemblyToDelete + @"'/> <Target Name='Foo'> <ThreadTask Fail='" + failTask + @"' ThrowException='" + throwException + @"'/> </Target> </Project>"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); return project; } #endif #if FEATURE_CODEDOM /// <summary> /// Helper to create the STA test task. /// </summary> private string GenerateSTATask(bool requireSTA) { string taskContents = @" using System; using Microsoft.Build.Framework; namespace ClassLibrary2 {" + (requireSTA ? "[RunInSTA]" : String.Empty) + @" public class ThreadTask : ITask { #region ITask Members public IBuildEngine BuildEngine { get; set; } public bool ThrowException { get; set; } public bool Fail { get; set; } public bool Execute() { string message; if (System.Threading.Thread.CurrentThread.GetApartmentState() == System.Threading.ApartmentState.STA) { message = ""STA""; } else { message = ""MTA""; } BuildEngine.LogMessageEvent(new BuildMessageEventArgs(message, """", ""ThreadTask"", MessageImportance.High)); if (ThrowException) { throw new InvalidOperationException(""EXCEPTION""); } if (Fail) { BuildEngine.LogMessageEvent(new BuildMessageEventArgs(""FAIL"", """", ""ThreadTask"", MessageImportance.High)); } return !Fail; } public ITaskHost HostObject { get; set; } #endregion } }"; return CustomTaskHelper.GetAssemblyForTask(taskContents); } #endif /// <summary> /// Creates a test project. /// </summary> /// <returns>The project.</returns> private ProjectInstance CreateTestProject() { string projectFileContents = ObjectModelHelpers.CleanupFileContents(@" <Project ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'> <ItemGroup> <Compile Include='b.cs' /> <Compile Include='c.cs' /> </ItemGroup> <ItemGroup> <Reference Include='System' /> </ItemGroup> <Target Name='Empty' /> <Target Name='Skip' Inputs='testProject.proj' Outputs='testProject.proj' /> <Target Name='Error' > <ErrorTask1 ContinueOnError='True'/> <ErrorTask2 ContinueOnError='False'/> <ErrorTask3 /> <OnError ExecuteTargets='Foo'/> <OnError ExecuteTargets='Bar'/> </Target> <Target Name='Foo' Inputs='foo.cpp' Outputs='foo.o'> <FooTask1/> </Target> <Target Name='Bar'> <BarTask1/> </Target> <Target Name='Baz' DependsOnTargets='Bar'> <BazTask1/> <BazTask2/> </Target> <Target Name='Baz2' DependsOnTargets='Bar;Foo'> <Baz2Task1/> <Baz2Task2/> <Baz2Task3/> </Target> <Target Name='DepSkip' DependsOnTargets='Skip'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> <Target Name='DepError' DependsOnTargets='Foo;Skip;Error'> <DepSkipTask1/> <DepSkipTask2/> <DepSkipTask3/> </Target> </Project> "); IConfigCache cache = (IConfigCache)_host.GetComponent(BuildComponentType.ConfigCache); BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("testfile", new Dictionary<string, string>(), "3.5", new string[0], null), "2.0"); Project project = new Project(XmlReader.Create(new StringReader(projectFileContents))); config.Project = project.CreateProjectInstance(); cache.AddConfiguration(config); return config.Project; } /// <summary> /// The mock component host object. /// </summary> private class MockHost : MockLoggingService, IBuildComponentHost, IBuildComponent { #region IBuildComponentHost Members /// <summary> /// The config cache /// </summary> private IConfigCache _configCache; /// <summary> /// The logging service /// </summary> private ILoggingService _loggingService; /// <summary> /// The results cache /// </summary> private IResultsCache _resultsCache; /// <summary> /// The request builder /// </summary> private IRequestBuilder _requestBuilder; /// <summary> /// The target builder /// </summary> private ITargetBuilder _targetBuilder; /// <summary> /// The build parameters. /// </summary> private BuildParameters _buildParameters; /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> private LegacyThreadingData _legacyThreadingData; private ISdkResolverService _sdkResolverService; /// <summary> /// Constructor /// /// UNDONE: Refactor this, and the other MockHosts, to use a common base implementation. The duplication of the /// logging implementation alone is unfortunate. /// </summary> public MockHost() { _buildParameters = new BuildParameters(); _legacyThreadingData = new LegacyThreadingData(); _configCache = new ConfigCache(); ((IBuildComponent)_configCache).InitializeComponent(this); _loggingService = this; _resultsCache = new ResultsCache(); ((IBuildComponent)_resultsCache).InitializeComponent(this); _requestBuilder = new RequestBuilder(); ((IBuildComponent)_requestBuilder).InitializeComponent(this); _targetBuilder = new TargetBuilder(); ((IBuildComponent)_targetBuilder).InitializeComponent(this); _sdkResolverService = new MockSdkResolverService(); ((IBuildComponent)_sdkResolverService).InitializeComponent(this); } /// <summary> /// Returns the node logging service. We don't distinguish here. /// </summary> public ILoggingService LoggingService { get { return _loggingService; } } /// <summary> /// Retrieves the name of the host. /// </summary> public string Name { get { return "TaskBuilder_Tests.MockHost"; } } /// <summary> /// Returns the build parameters. /// </summary> public BuildParameters BuildParameters { get { return _buildParameters; } } /// <summary> /// Retrieves the LegacyThreadingData associated with a particular component host /// </summary> LegacyThreadingData IBuildComponentHost.LegacyThreadingData { get { return _legacyThreadingData; } } /// <summary> /// Constructs and returns a component of the specified type. /// </summary> /// <param name="type">The type of component to return</param> /// <returns>The component</returns> public IBuildComponent GetComponent(BuildComponentType type) { switch (type) { case BuildComponentType.ConfigCache: return (IBuildComponent)_configCache; case BuildComponentType.LoggingService: return (IBuildComponent)_loggingService; case BuildComponentType.ResultsCache: return (IBuildComponent)_resultsCache; case BuildComponentType.RequestBuilder: return (IBuildComponent)_requestBuilder; case BuildComponentType.TargetBuilder: return (IBuildComponent)_targetBuilder; case BuildComponentType.SdkResolverService: return (IBuildComponent)_sdkResolverService; default: throw new ArgumentException("Unexpected type " + type); } } /// <summary> /// Register a component factory. /// </summary> public void RegisterFactory(BuildComponentType type, BuildComponentFactoryDelegate factory) { } #endregion #region IBuildComponent Members /// <summary> /// Sets the component host /// </summary> /// <param name="host">The component host</param> public void InitializeComponent(IBuildComponentHost host) { throw new NotImplementedException(); } /// <summary> /// Shuts down the component /// </summary> public void ShutdownComponent() { throw new NotImplementedException(); } #endregion } } }
//----------------------------------------------------------------------- // <copyright file="OutputStreamSourceStage.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Dispatch; using Akka.IO; using Akka.Streams.Implementation.Stages; using Akka.Streams.Stage; using Akka.Util; using static Akka.Streams.Implementation.IO.OutputStreamSourceStage; namespace Akka.Streams.Implementation.IO { /// <summary> /// INTERNAL API /// </summary> internal class OutputStreamSourceStage : GraphStageWithMaterializedValue<SourceShape<ByteString>, Stream> { #region internal classes /// <summary> /// TBD /// </summary> internal interface IAdapterToStageMessage { } /// <summary> /// TBD /// </summary> internal class Flush : IAdapterToStageMessage { /// <summary> /// TBD /// </summary> public static readonly Flush Instance = new Flush(); private Flush() { } } /// <summary> /// TBD /// </summary> internal class Close : IAdapterToStageMessage { /// <summary> /// TBD /// </summary> public static readonly Close Instance = new Close(); private Close() { } } /// <summary> /// TBD /// </summary> internal interface IDownstreamStatus { } /// <summary> /// TBD /// </summary> internal class Ok : IDownstreamStatus { /// <summary> /// TBD /// </summary> public static readonly Ok Instance = new Ok(); private Ok() { } } /// <summary> /// TBD /// </summary> internal class Canceled : IDownstreamStatus { /// <summary> /// TBD /// </summary> public static readonly Canceled Instance = new Canceled(); private Canceled() { } } /// <summary> /// TBD /// </summary> internal interface IStageWithCallback { /// <summary> /// TBD /// </summary> /// <param name="msg">TBD</param> /// <returns>TBD</returns> Task WakeUp(IAdapterToStageMessage msg); } private sealed class Logic : GraphStageLogic, IStageWithCallback { private readonly OutputStreamSourceStage _stage; private readonly AtomicReference<IDownstreamStatus> _downstreamStatus; private readonly string _dispatcherId; private readonly Action<Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>> _upstreamCallback; private readonly OnPullRunnable _pullTask; private readonly CancellationTokenSource _cancellation = new CancellationTokenSource(); private BlockingCollection<ByteString> _dataQueue; private TaskCompletionSource<NotUsed> _flush; private TaskCompletionSource<NotUsed> _close; private MessageDispatcher _dispatcher; public Logic(OutputStreamSourceStage stage, BlockingCollection<ByteString> dataQueue, AtomicReference<IDownstreamStatus> downstreamStatus, string dispatcherId) : base(stage.Shape) { _stage = stage; _dataQueue = dataQueue; _downstreamStatus = downstreamStatus; _dispatcherId = dispatcherId; var downstreamCallback = GetAsyncCallback((Either<ByteString, Exception> result) => { if (result.IsLeft) OnPush(result.Value as ByteString); else FailStage(result.Value as Exception); }); _upstreamCallback = GetAsyncCallback<Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>>(OnAsyncMessage); _pullTask = new OnPullRunnable(downstreamCallback, dataQueue, _cancellation.Token); SetHandler(_stage._out, onPull: OnPull, onDownstreamFinish: OnDownstreamFinish); } public override void PreStart() { _dispatcher = ActorMaterializerHelper.Downcast(Materializer).System.Dispatchers.Lookup(_dispatcherId); base.PreStart(); } public override void PostStop() { // interrupt any pending blocking take _cancellation.Cancel(false); base.PostStop(); } private void OnDownstreamFinish() { //assuming there can be no further in messages _downstreamStatus.Value = Canceled.Instance; _dataQueue = null; CompleteStage(); } private sealed class OnPullRunnable : IRunnable { private readonly Action<Either<ByteString, Exception>> _callback; private readonly BlockingCollection<ByteString> _dataQueue; private readonly CancellationToken _cancellationToken; public OnPullRunnable(Action<Either<ByteString, Exception>> callback, BlockingCollection<ByteString> dataQueue, CancellationToken cancellationToken) { _callback = callback; _dataQueue = dataQueue; _cancellationToken = cancellationToken; } public void Run() { try { _callback(new Left<ByteString, Exception>(_dataQueue.Take(_cancellationToken))); } catch (OperationCanceledException) { _callback(new Left<ByteString, Exception>(ByteString.Empty)); } catch (Exception ex) { _callback(new Right<ByteString, Exception>(ex)); } } } private void OnPull() => _dispatcher.Schedule(_pullTask); private void OnPush(ByteString data) { if (_downstreamStatus.Value is Ok) { Push(_stage._out, data); SendResponseIfNeeded(); } } public Task WakeUp(IAdapterToStageMessage msg) { var p = new TaskCompletionSource<NotUsed>(); _upstreamCallback(new Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>>(msg, p)); return p.Task; } private void OnAsyncMessage(Tuple<IAdapterToStageMessage, TaskCompletionSource<NotUsed>> @event) { if (@event.Item1 is Flush) { _flush = @event.Item2; SendResponseIfNeeded(); } else if (@event.Item1 is Close) { _close = @event.Item2; if (_dataQueue.Count == 0) { _downstreamStatus.Value = Canceled.Instance; CompleteStage(); UnblockUpsteam(); } else SendResponseIfNeeded(); } } private void UnblockUpsteam() { if (_flush != null) { _flush.TrySetResult(NotUsed.Instance); _flush = null; return; } if (_close == null) return; _close.TrySetResult(NotUsed.Instance); _close = null; } private void SendResponseIfNeeded() { if (_downstreamStatus.Value is Canceled || _dataQueue.Count == 0) UnblockUpsteam(); } } #endregion private readonly TimeSpan _writeTimeout; private readonly Outlet<ByteString> _out = new Outlet<ByteString>("OutputStreamSource.out"); /// <summary> /// TBD /// </summary> /// <param name="writeTimeout">TBD</param> public OutputStreamSourceStage(TimeSpan writeTimeout) { _writeTimeout = writeTimeout; Shape = new SourceShape<ByteString>(_out); } /// <summary> /// TBD /// </summary> public override SourceShape<ByteString> Shape { get; } /// <summary> /// TBD /// </summary> protected override Attributes InitialAttributes { get; } = DefaultAttributes.OutputStreamSource; /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <exception cref="ArgumentException">TBD</exception> /// <returns>TBD</returns> public override ILogicAndMaterializedValue<Stream> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { // has to be in this order as module depends on shape var maxBuffer = inheritedAttributes.GetAttribute(new Attributes.InputBuffer(16, 16)).Max; if (maxBuffer <= 0) throw new ArgumentException("Buffer size must be greather than 0"); var dataQueue = new BlockingCollection<ByteString>(maxBuffer); var downstreamStatus = new AtomicReference<IDownstreamStatus>(Ok.Instance); var dispatcherId = inheritedAttributes.GetAttribute( DefaultAttributes.IODispatcher.GetAttributeList<ActorAttributes.Dispatcher>().First()).Name; var logic = new Logic(this, dataQueue, downstreamStatus, dispatcherId); return new LogicAndMaterializedValue<Stream>(logic, new OutputStreamAdapter(dataQueue, downstreamStatus, logic, _writeTimeout)); } } /// <summary> /// TBD /// </summary> internal class OutputStreamAdapter : Stream { #region not supported /// <summary> /// TBD /// </summary> /// <param name="offset">TBD</param> /// <param name="origin">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> /// <returns>TBD</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("This stream can only write"); } /// <summary> /// TBD /// </summary> /// <param name="value">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> public override void SetLength(long value) { throw new NotSupportedException("This stream can only write"); } /// <summary> /// TBD /// </summary> /// <param name="buffer">TBD</param> /// <param name="offset">TBD</param> /// <param name="count">TBD</param> /// <exception cref="NotSupportedException">TBD</exception> /// <returns>TBD</returns> public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("This stream can only write"); } /// <summary> /// TBD /// </summary> /// <exception cref="NotSupportedException">TBD</exception> public override long Length { get { throw new NotSupportedException("This stream can only write"); } } /// <summary> /// TBD /// </summary> /// <exception cref="NotSupportedException">TBD</exception> public override long Position { get { throw new NotSupportedException("This stream can only write"); } set { throw new NotSupportedException("This stream can only write"); } } #endregion private static readonly Exception PublisherClosedException = new IOException("Reactive stream is terminated, no writes are possible"); private readonly BlockingCollection<ByteString> _dataQueue; private readonly AtomicReference<IDownstreamStatus> _downstreamStatus; private readonly IStageWithCallback _stageWithCallback; private readonly TimeSpan _writeTimeout; private bool _isActive = true; private bool _isPublisherAlive = true; /// <summary> /// TBD /// </summary> /// <param name="dataQueue">TBD</param> /// <param name="downstreamStatus">TBD</param> /// <param name="stageWithCallback">TBD</param> /// <param name="writeTimeout">TBD</param> public OutputStreamAdapter(BlockingCollection<ByteString> dataQueue, AtomicReference<IDownstreamStatus> downstreamStatus, IStageWithCallback stageWithCallback, TimeSpan writeTimeout) { _dataQueue = dataQueue; _downstreamStatus = downstreamStatus; _stageWithCallback = stageWithCallback; _writeTimeout = writeTimeout; } private void Send(Action sendAction) { if (_isActive) { if (_isPublisherAlive) sendAction(); else throw PublisherClosedException; } else throw new IOException("OutputStream is closed"); } private void SendData(ByteString data) { Send(() => { _dataQueue.Add(data); if (_downstreamStatus.Value is Canceled) { _isPublisherAlive = false; throw PublisherClosedException; } }); } private void SendMessage(IAdapterToStageMessage msg, bool handleCancelled = true) { Send(() => { _stageWithCallback.WakeUp(msg).Wait(_writeTimeout); if (_downstreamStatus.Value is Canceled && handleCancelled) { //Publisher considered to be terminated at earliest convenience to minimize messages sending back and forth _isPublisherAlive = false; throw PublisherClosedException; } }); } /// <summary> /// TBD /// </summary> public override void Flush() => SendMessage(OutputStreamSourceStage.Flush.Instance); /// <summary> /// TBD /// </summary> /// <param name="buffer">TBD</param> /// <param name="offset">TBD</param> /// <param name="count">TBD</param> public override void Write(byte[] buffer, int offset, int count) => SendData(ByteString.Create(buffer, offset, count)); /// <summary> /// TBD /// </summary> /// <param name="disposing">TBD</param> protected override void Dispose(bool disposing) { base.Dispose(disposing); SendMessage(OutputStreamSourceStage.Close.Instance, false); _isActive = false; } /// <summary> /// TBD /// </summary> public override bool CanRead => false; /// <summary> /// TBD /// </summary> public override bool CanSeek => false; /// <summary> /// TBD /// </summary> public override bool CanWrite => true; } }
using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using OpenADK.Library; using OpenADK.Library.us.Common; using OpenADK.Library.us.Student; using NUnit.Framework; using Library.UnitTesting.Framework; using OpenADK.Library.Infra; using OpenADK.Library.us.Reporting; namespace Library.Nunit.US { /// <summary> /// Summary description for SifElementTests. /// </summary> [TestFixture] public class SifElementTests : AdkTest { /// <summary> /// Passing a null SIFDate to an SDO object property still causes the element to be written out. /// For example, calling ReportingPeriod.setBeginReportDate() with a null value will still cause /// the <BeginReportDate> element to be written out. /// </summary> [Test] public void TestSIFDate() { ReportingPeriod period = new ReportingPeriod(); period.BeginReportDate = new DateTime?(); period.EndReportDate = new DateTime?(); period.BeginSubmitDate = new DateTime?(); period.EndSubmitDate = new DateTime?(); period.DueDate = new DateTime?(); Assert.IsNull(period.BeginReportDate, "BeginReportDate contains an empty date element"); Assert.IsNull(period.EndReportDate, "EndReportDate contains an empty date element"); Assert.IsNull(period.BeginSubmitDate, "BeginSubmitDate contains an empty date element"); Assert.IsNull(period.EndSubmitDate, "EndSubmitDate contains an empty date element"); }//end TestSIFDate [Test] public void TestSerializeable() { MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); //************************************************************************ //Serialize / Deserialize Name object ********** Name name = new Name(NameType.LEGAL, "Nahorniak", "Mike"); Name result; formatter.Serialize(ms, name); ms.Seek(0, SeekOrigin.Begin); result = (Name)formatter.Deserialize(ms); Assert.AreEqual(name.FirstName, result.FirstName, "Name.FirstName field did not properly deserialize"); Assert.AreEqual(name.FirstName, result.FirstName, "Name.LastName field did not properly deserialize"); //************************************************************************ //Serialize / Deserialize StudentPersonal object ********** ms.SetLength(0); ms.Position = 0; StudentPersonal sp = new StudentPersonal(); StudentPersonal spResult; formatter.Serialize(ms, sp); ms.Seek(0, SeekOrigin.Begin); spResult = (StudentPersonal)formatter.Deserialize(ms); Assert.AreEqual(sp.Name, spResult.Name, "Deserialized StudentPersonal Name elements do not match"); //************************************************************************ //Serialize / Deserialize SIF_ERROR object ********** ms.SetLength(0); ms.Position = 0; SIF_Error error = new SIF_Error ((int)SifErrorCategoryCode.Generic, SifErrorCodes.GENERIC_GENERIC_ERROR_1, "Could not serialize the SIF_Err object"); SIF_Error result_error; formatter.Serialize(ms, error); ms.Seek(0, SeekOrigin.Begin); result_error = (SIF_Error)formatter.Deserialize(ms); Assert.AreEqual(error.ToString(), result_error.ToString(), "Deserialized SIF_Error match"); ms.Close(); } [Test] public void SharedChildren() { Adk.SifVersion = SifVersion.LATEST; StudentPersonal sp = new StudentPersonal(Adk.MakeGuid(), new Name(NameType.LEGAL, "hello", "world")); // Replace the existing demographics so there is no confusion Demographics d = new Demographics(); sp.Demographics = d; d.SetCountryOfBirth(CountryCode.US); CountriesOfCitizenship countries = new CountriesOfCitizenship(); d.CountriesOfCitizenship = countries; CountriesOfResidency residencies = new CountriesOfResidency(); d.CountriesOfResidency = residencies; countries.AddCountryOfCitizenship(CountryCode.Wrap("UK")); residencies.AddCountryOfResidency(CountryCode.Wrap("AU")); // overwrite the country codes again, just to try to repro the issue d.SetCountryOfBirth(CountryCode.Wrap("AA")); // Should overwrite the existing one //Remove the existing CountryOfCitizenship, add three more, and remove the middle one Assert.IsTrue(countries.Remove(CountryCode.Wrap("UK"))); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB1")); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB2")); countries.AddCountryOfCitizenship(CountryCode.Wrap("BB3")); Assert.IsTrue(countries.Remove(CountryCode.Wrap("BB2"))); // Remove the existing CountryOfResidency, add three more, and remove the first one Assert.IsTrue(residencies.Remove(CountryCode.Wrap("AU"))); residencies.AddCountryOfResidency(CountryCode.Wrap("CC1")); residencies.AddCountryOfResidency(CountryCode.Wrap("CC2")); residencies.AddCountryOfResidency(CountryCode.Wrap("CC3")); Assert.IsTrue(residencies.Remove(CountryCode.Wrap("CC1"))); StudentPersonal sp2 = AdkObjectParseHelper.runParsingTest(sp, SifVersion.LATEST); // The runParsingTest() method will compare the objects after writing them and reading them // back in, but to be completely sure, let's assert the country codes again // NOTE: Due to the .Net Array.Sort algorithm, repeatable elements come out in reverse order. // This doesn't appear to be a problem yet, but may be fixed in a future release. // For now, these tests look for the elements in reverse order Demographics d2 = sp2.Demographics; Assert.AreEqual("AA", d2.CountryOfBirth.ToString(), "Country of Birth"); Country[] citizenships = d2.CountriesOfCitizenship.ToArray(); Assert.AreEqual(2, citizenships.Length, "Should be two CountryOfCitizenships"); Assert.AreEqual("BB1", citizenships[0].TextValue, "First CountryOfCitizenship"); Assert.AreEqual("BB3", citizenships[1].TextValue, "Second CountryOfCitizenship"); // assert Country[] resid = d2.CountriesOfResidency.ToArray(); Assert.AreEqual(2, resid.Length, "Should be two CountryOfResidencys"); Assert.AreEqual("CC2", resid[0].TextValue, "First CountryOfResidencys"); Assert.AreEqual("CC3", resid[1].TextValue, "Second CountryOfResidencys"); } /** * Asserts that the new setArray() method is there and works as expected */ [Test] public void testSetChildren() { StudentPersonal sp = ObjectCreator.CreateStudentPersonal(); Email email1 = new Email(EmailType.PRIMARY, "email@mail.com"); Email email2 = new Email(EmailType.ALT1, "email2@mail.com"); sp.EmailList = new EmailList(); sp.EmailList.SetChildren(CommonDTD.EMAIL, new Email[] { email1, email2 }); EmailList studentEmails = sp.EmailList; Assert.AreEqual(2, studentEmails.ChildCount, "Should be two emails"); studentEmails.SetChildren(CommonDTD.EMAIL, new Email[0]); studentEmails = sp.EmailList; Assert.AreEqual(0, studentEmails.ChildCount, "Should be zero emails after setting empty array"); studentEmails.SetChildren(CommonDTD.EMAIL, new Email[] { email1, email2 }); studentEmails = sp.EmailList; Assert.AreEqual(2, studentEmails.ChildCount, "Should be two emails"); studentEmails.SetChildren(CommonDTD.EMAIL, null); studentEmails = sp.EmailList; Assert.AreEqual(0, studentEmails.ChildCount, "Should be zero emails after setting null"); } /** * Asserts that ADKGen adds a method that takes an array of objects for repeatable elements */ [Test] public void testSetEmails() { StudentPersonal sp = ObjectCreator.CreateStudentPersonal(); Email email1 = new Email(EmailType.PRIMARY, "email@mail.com"); Email email2 = new Email(EmailType.ALT1, "email2@mail.com"); EmailList eList = new EmailList(); eList.AddRange(email1, email2); sp.EmailList = eList; EmailList studentEmails = sp.EmailList; Assert.AreEqual(2, studentEmails.Count, "Should be two emails"); studentEmails.Clear(); Assert.AreEqual(0, studentEmails.Count, "Should be zero emails after clearing"); sp.EmailList = new EmailList(); studentEmails = sp.EmailList; Assert.AreEqual(0, studentEmails.Count, "Should be zero emails after setting empty list"); } /** * Asserts that an object can have the same child object set to it more than once */ [Test] public void testAddChildTwice() { StudentPersonal sp1 = new StudentPersonal(); Email email1 = new Email(EmailType.PRIMARY, "email@mail.com"); EmailList eList = new EmailList(); sp1.EmailList = eList; eList.AddChild(CommonDTD.EMAIL, email1); // We should be able to add the same child twice without getting an exception eList.AddChild(CommonDTD.EMAIL, email1); // Add it again, using the overload eList.AddChild(email1); Email[] studentEmails = sp1.EmailList.ToArray(); Assert.AreEqual(1, studentEmails.Length, "Should be one email"); StudentPersonal sp2 = ObjectCreator.CreateStudentPersonal(); Email email2 = new Email(EmailType.ALT1, "email2@mail.com"); EmailList elist2 = new EmailList(); elist2.Add(email2); sp2.EmailList = elist2; bool exceptionThrown = false; try { eList.AddChild(email2); // should throw here } catch (InvalidOperationException) { exceptionThrown = true; } Assert.IsTrue(exceptionThrown, "IllegalStateException should have been thrown in addChild(SIFElement)"); exceptionThrown = false; try { eList.AddChild(CommonDTD.EMAILLIST, email2); // should throw here } catch (InvalidOperationException) { exceptionThrown = true; } Assert.IsTrue(exceptionThrown, "IllegalStateException should have been thrown in addChild( ElementDef, SIFElement)"); } [Test] public void testIDProperty() { SifElement element = new StudentPersonal(); element.XmlId = "Foo"; Assert.AreEqual("Foo", element.XmlId); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sdb-2009-04-15.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.SimpleDB; using Amazon.SimpleDB.Model; using Amazon.SimpleDB.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class SimpleDBMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("sdb-2009-04-15.normal.json", "sdb.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void BatchDeleteAttributesMarshallTest() { var operation = service_model.FindOperation("BatchDeleteAttributes"); var request = InstantiateClassGenerator.Execute<BatchDeleteAttributesRequest>(); var marshaller = new BatchDeleteAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void BatchPutAttributesMarshallTest() { var operation = service_model.FindOperation("BatchPutAttributes"); var request = InstantiateClassGenerator.Execute<BatchPutAttributesRequest>(); var marshaller = new BatchPutAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void CreateDomainMarshallTest() { var operation = service_model.FindOperation("CreateDomain"); var request = InstantiateClassGenerator.Execute<CreateDomainRequest>(); var marshaller = new CreateDomainRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void DeleteAttributesMarshallTest() { var operation = service_model.FindOperation("DeleteAttributes"); var request = InstantiateClassGenerator.Execute<DeleteAttributesRequest>(); var marshaller = new DeleteAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void DeleteDomainMarshallTest() { var operation = service_model.FindOperation("DeleteDomain"); var request = InstantiateClassGenerator.Execute<DeleteDomainRequest>(); var marshaller = new DeleteDomainRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void DomainMetadataMarshallTest() { var operation = service_model.FindOperation("DomainMetadata"); var request = InstantiateClassGenerator.Execute<DomainMetadataRequest>(); var marshaller = new DomainMetadataRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DomainMetadataResponseUnmarshaller.Instance.Unmarshall(context) as DomainMetadataResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void GetAttributesMarshallTest() { var operation = service_model.FindOperation("GetAttributes"); var request = InstantiateClassGenerator.Execute<GetAttributesRequest>(); var marshaller = new GetAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = GetAttributesResponseUnmarshaller.Instance.Unmarshall(context) as GetAttributesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void ListDomainsMarshallTest() { var operation = service_model.FindOperation("ListDomains"); var request = InstantiateClassGenerator.Execute<ListDomainsRequest>(); var marshaller = new ListDomainsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ListDomainsResponseUnmarshaller.Instance.Unmarshall(context) as ListDomainsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void PutAttributesMarshallTest() { var operation = service_model.FindOperation("PutAttributes"); var request = InstantiateClassGenerator.Execute<PutAttributesRequest>(); var marshaller = new PutAttributesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("SimpleDB")] public void SelectMarshallTest() { var operation = service_model.FindOperation("Select"); var request = InstantiateClassGenerator.Execute<SelectRequest>(); var marshaller = new SelectRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = SelectResponseUnmarshaller.Instance.Unmarshall(context) as SelectResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Collections.Generic; using System.IO; internal sealed class NtfsFileStream : SparseStream { private DirectoryEntry _entry; private File _file; private SparseStream _baseStream; private bool _isDirty; public NtfsFileStream(NtfsFileSystem fileSystem, DirectoryEntry entry, AttributeType attrType, string attrName, FileAccess access) { _entry = entry; _file = fileSystem.GetFile(entry.Reference); _baseStream = _file.OpenStream(attrType, attrName, access); } public override bool CanRead { get { AssertOpen(); return _baseStream.CanRead; } } public override bool CanSeek { get { AssertOpen(); return _baseStream.CanSeek; } } public override bool CanWrite { get { AssertOpen(); return _baseStream.CanWrite; } } public override long Length { get { AssertOpen(); return _baseStream.Length; } } public override long Position { get { AssertOpen(); return _baseStream.Position; } set { AssertOpen(); using (new NtfsTransaction()) { _baseStream.Position = value; } } } public override IEnumerable<StreamExtent> Extents { get { AssertOpen(); return _baseStream.Extents; } } protected override void Dispose(bool disposing) { if (_baseStream == null) { base.Dispose(disposing); return; } using (new NtfsTransaction()) { base.Dispose(disposing); _baseStream.Dispose(); UpdateMetadata(); _baseStream = null; } } public override void Flush() { AssertOpen(); using (new NtfsTransaction()) { _baseStream.Flush(); UpdateMetadata(); } } public override int Read(byte[] buffer, int offset, int count) { AssertOpen(); Utilities.AssertBufferParameters(buffer, offset, count); using (new NtfsTransaction()) { return _baseStream.Read(buffer, offset, count); } } public override long Seek(long offset, SeekOrigin origin) { AssertOpen(); using (new NtfsTransaction()) { return _baseStream.Seek(offset, origin); } } public override void SetLength(long value) { AssertOpen(); using (new NtfsTransaction()) { if (value != Length) { _isDirty = true; _baseStream.SetLength(value); } } } public override void Write(byte[] buffer, int offset, int count) { AssertOpen(); Utilities.AssertBufferParameters(buffer, offset, count); using (new NtfsTransaction()) { _isDirty = true; _baseStream.Write(buffer, offset, count); } } public override void Clear(int count) { AssertOpen(); using (new NtfsTransaction()) { _isDirty = true; _baseStream.Clear(count); } } private void UpdateMetadata() { if (!_file.Context.ReadOnly) { // Update the standard information attribute - so it reflects the actual file state if (_isDirty) { _file.Modified(); } else { _file.Accessed(); } // Update the directory entry used to open the file, so it's accurate _entry.UpdateFrom(_file); // Write attribute changes back to the Master File Table _file.UpdateRecordInMft(); _isDirty = false; } } private void AssertOpen() { if (_baseStream == null) { throw new ObjectDisposedException(_entry.Details.FileName, "Attempt to use closed stream"); } } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Int16 : IComparable, IConvertible, IFormattable, IComparable<Int16>, IEquatable<Int16> { private short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int16) { return m_value - ((Int16)value).m_value; } throw new ArgumentException(SR.Arg_MustBeInt16); } public int CompareTo(Int16 value) { return m_value - value; } public override bool Equals(Object obj) { if (!(obj is Int16)) { return false; } return m_value == ((Int16)obj).m_value; } [NonVersionable] public bool Equals(Int16 obj) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return ((int)((ushort)m_value) | (((int)m_value) << 16)); } public override String ToString() { return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { return ToString(format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { return ToString(format, NumberFormatInfo.GetInstance(provider)); } private String ToString(String format, NumberFormatInfo info) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32(temp, format, info); } return Number.FormatInt32(m_value, format, info); } public static short Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } public static short Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } public static short Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Int16, e); } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || (i > UInt16.MaxValue)) { throw new OverflowException(SR.Overflow_Int16); } return (short)i; } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Int16); return (short)i; } public static bool TryParse(String s, out Int16 result) { if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, out Int16 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Int16 result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } // We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number if ((i < 0) || i > UInt16.MaxValue) { return false; } result = (Int16)i; return true; } if (i < MinValue || i > MaxValue) { return false; } result = (Int16)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return m_value; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindRepository { /// <summary> /// Strongly-typed collection for the Employee class. /// </summary> [Serializable] public partial class EmployeeCollection : RepositoryList<Employee, EmployeeCollection> { public EmployeeCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>EmployeeCollection</returns> public EmployeeCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Employee o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Employees table. /// </summary> [Serializable] public partial class Employee : RepositoryRecord<Employee>, IRecordBase { #region .ctors and Default Settings public Employee() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Employee(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Employees", TableType.Table, DataService.GetInstance("NorthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarEmployeeID = new TableSchema.TableColumn(schema); colvarEmployeeID.ColumnName = "EmployeeID"; colvarEmployeeID.DataType = DbType.Int32; colvarEmployeeID.MaxLength = 0; colvarEmployeeID.AutoIncrement = true; colvarEmployeeID.IsNullable = false; colvarEmployeeID.IsPrimaryKey = true; colvarEmployeeID.IsForeignKey = false; colvarEmployeeID.IsReadOnly = false; colvarEmployeeID.DefaultSetting = @""; colvarEmployeeID.ForeignKeyTableName = ""; schema.Columns.Add(colvarEmployeeID); TableSchema.TableColumn colvarLastName = new TableSchema.TableColumn(schema); colvarLastName.ColumnName = "LastName"; colvarLastName.DataType = DbType.String; colvarLastName.MaxLength = 20; colvarLastName.AutoIncrement = false; colvarLastName.IsNullable = false; colvarLastName.IsPrimaryKey = false; colvarLastName.IsForeignKey = false; colvarLastName.IsReadOnly = false; colvarLastName.DefaultSetting = @""; colvarLastName.ForeignKeyTableName = ""; schema.Columns.Add(colvarLastName); TableSchema.TableColumn colvarFirstName = new TableSchema.TableColumn(schema); colvarFirstName.ColumnName = "FirstName"; colvarFirstName.DataType = DbType.String; colvarFirstName.MaxLength = 10; colvarFirstName.AutoIncrement = false; colvarFirstName.IsNullable = false; colvarFirstName.IsPrimaryKey = false; colvarFirstName.IsForeignKey = false; colvarFirstName.IsReadOnly = false; colvarFirstName.DefaultSetting = @""; colvarFirstName.ForeignKeyTableName = ""; schema.Columns.Add(colvarFirstName); TableSchema.TableColumn colvarTitle = new TableSchema.TableColumn(schema); colvarTitle.ColumnName = "Title"; colvarTitle.DataType = DbType.String; colvarTitle.MaxLength = 30; colvarTitle.AutoIncrement = false; colvarTitle.IsNullable = true; colvarTitle.IsPrimaryKey = false; colvarTitle.IsForeignKey = false; colvarTitle.IsReadOnly = false; colvarTitle.DefaultSetting = @""; colvarTitle.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitle); TableSchema.TableColumn colvarTitleOfCourtesy = new TableSchema.TableColumn(schema); colvarTitleOfCourtesy.ColumnName = "TitleOfCourtesy"; colvarTitleOfCourtesy.DataType = DbType.String; colvarTitleOfCourtesy.MaxLength = 25; colvarTitleOfCourtesy.AutoIncrement = false; colvarTitleOfCourtesy.IsNullable = true; colvarTitleOfCourtesy.IsPrimaryKey = false; colvarTitleOfCourtesy.IsForeignKey = false; colvarTitleOfCourtesy.IsReadOnly = false; colvarTitleOfCourtesy.DefaultSetting = @""; colvarTitleOfCourtesy.ForeignKeyTableName = ""; schema.Columns.Add(colvarTitleOfCourtesy); TableSchema.TableColumn colvarBirthDate = new TableSchema.TableColumn(schema); colvarBirthDate.ColumnName = "BirthDate"; colvarBirthDate.DataType = DbType.DateTime; colvarBirthDate.MaxLength = 0; colvarBirthDate.AutoIncrement = false; colvarBirthDate.IsNullable = true; colvarBirthDate.IsPrimaryKey = false; colvarBirthDate.IsForeignKey = false; colvarBirthDate.IsReadOnly = false; colvarBirthDate.DefaultSetting = @""; colvarBirthDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarBirthDate); TableSchema.TableColumn colvarHireDate = new TableSchema.TableColumn(schema); colvarHireDate.ColumnName = "HireDate"; colvarHireDate.DataType = DbType.DateTime; colvarHireDate.MaxLength = 0; colvarHireDate.AutoIncrement = false; colvarHireDate.IsNullable = true; colvarHireDate.IsPrimaryKey = false; colvarHireDate.IsForeignKey = false; colvarHireDate.IsReadOnly = false; colvarHireDate.DefaultSetting = @""; colvarHireDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarHireDate); TableSchema.TableColumn colvarAddress = new TableSchema.TableColumn(schema); colvarAddress.ColumnName = "Address"; colvarAddress.DataType = DbType.String; colvarAddress.MaxLength = 60; colvarAddress.AutoIncrement = false; colvarAddress.IsNullable = true; colvarAddress.IsPrimaryKey = false; colvarAddress.IsForeignKey = false; colvarAddress.IsReadOnly = false; colvarAddress.DefaultSetting = @""; colvarAddress.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddress); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; colvarCity.DefaultSetting = @""; colvarCity.ForeignKeyTableName = ""; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarRegion = new TableSchema.TableColumn(schema); colvarRegion.ColumnName = "Region"; colvarRegion.DataType = DbType.String; colvarRegion.MaxLength = 15; colvarRegion.AutoIncrement = false; colvarRegion.IsNullable = true; colvarRegion.IsPrimaryKey = false; colvarRegion.IsForeignKey = false; colvarRegion.IsReadOnly = false; colvarRegion.DefaultSetting = @""; colvarRegion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRegion); TableSchema.TableColumn colvarPostalCode = new TableSchema.TableColumn(schema); colvarPostalCode.ColumnName = "PostalCode"; colvarPostalCode.DataType = DbType.String; colvarPostalCode.MaxLength = 10; colvarPostalCode.AutoIncrement = false; colvarPostalCode.IsNullable = true; colvarPostalCode.IsPrimaryKey = false; colvarPostalCode.IsForeignKey = false; colvarPostalCode.IsReadOnly = false; colvarPostalCode.DefaultSetting = @""; colvarPostalCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarPostalCode); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; colvarCountry.DefaultSetting = @""; colvarCountry.ForeignKeyTableName = ""; schema.Columns.Add(colvarCountry); TableSchema.TableColumn colvarHomePhone = new TableSchema.TableColumn(schema); colvarHomePhone.ColumnName = "HomePhone"; colvarHomePhone.DataType = DbType.String; colvarHomePhone.MaxLength = 24; colvarHomePhone.AutoIncrement = false; colvarHomePhone.IsNullable = true; colvarHomePhone.IsPrimaryKey = false; colvarHomePhone.IsForeignKey = false; colvarHomePhone.IsReadOnly = false; colvarHomePhone.DefaultSetting = @""; colvarHomePhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarHomePhone); TableSchema.TableColumn colvarExtension = new TableSchema.TableColumn(schema); colvarExtension.ColumnName = "Extension"; colvarExtension.DataType = DbType.String; colvarExtension.MaxLength = 4; colvarExtension.AutoIncrement = false; colvarExtension.IsNullable = true; colvarExtension.IsPrimaryKey = false; colvarExtension.IsForeignKey = false; colvarExtension.IsReadOnly = false; colvarExtension.DefaultSetting = @""; colvarExtension.ForeignKeyTableName = ""; schema.Columns.Add(colvarExtension); TableSchema.TableColumn colvarPhoto = new TableSchema.TableColumn(schema); colvarPhoto.ColumnName = "Photo"; colvarPhoto.DataType = DbType.Binary; colvarPhoto.MaxLength = 2147483647; colvarPhoto.AutoIncrement = false; colvarPhoto.IsNullable = true; colvarPhoto.IsPrimaryKey = false; colvarPhoto.IsForeignKey = false; colvarPhoto.IsReadOnly = false; colvarPhoto.DefaultSetting = @""; colvarPhoto.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhoto); TableSchema.TableColumn colvarNotes = new TableSchema.TableColumn(schema); colvarNotes.ColumnName = "Notes"; colvarNotes.DataType = DbType.String; colvarNotes.MaxLength = 1073741823; colvarNotes.AutoIncrement = false; colvarNotes.IsNullable = true; colvarNotes.IsPrimaryKey = false; colvarNotes.IsForeignKey = false; colvarNotes.IsReadOnly = false; colvarNotes.DefaultSetting = @""; colvarNotes.ForeignKeyTableName = ""; schema.Columns.Add(colvarNotes); TableSchema.TableColumn colvarReportsTo = new TableSchema.TableColumn(schema); colvarReportsTo.ColumnName = "ReportsTo"; colvarReportsTo.DataType = DbType.Int32; colvarReportsTo.MaxLength = 0; colvarReportsTo.AutoIncrement = false; colvarReportsTo.IsNullable = true; colvarReportsTo.IsPrimaryKey = false; colvarReportsTo.IsForeignKey = true; colvarReportsTo.IsReadOnly = false; colvarReportsTo.DefaultSetting = @""; colvarReportsTo.ForeignKeyTableName = "Employees"; schema.Columns.Add(colvarReportsTo); TableSchema.TableColumn colvarPhotoPath = new TableSchema.TableColumn(schema); colvarPhotoPath.ColumnName = "PhotoPath"; colvarPhotoPath.DataType = DbType.String; colvarPhotoPath.MaxLength = 255; colvarPhotoPath.AutoIncrement = false; colvarPhotoPath.IsNullable = true; colvarPhotoPath.IsPrimaryKey = false; colvarPhotoPath.IsForeignKey = false; colvarPhotoPath.IsReadOnly = false; colvarPhotoPath.DefaultSetting = @""; colvarPhotoPath.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhotoPath); TableSchema.TableColumn colvarDeleted = new TableSchema.TableColumn(schema); colvarDeleted.ColumnName = "Deleted"; colvarDeleted.DataType = DbType.Boolean; colvarDeleted.MaxLength = 0; colvarDeleted.AutoIncrement = false; colvarDeleted.IsNullable = false; colvarDeleted.IsPrimaryKey = false; colvarDeleted.IsForeignKey = false; colvarDeleted.IsReadOnly = false; colvarDeleted.DefaultSetting = @"((0))"; colvarDeleted.ForeignKeyTableName = ""; schema.Columns.Add(colvarDeleted); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindRepository"].AddSchema("Employees",schema); } } #endregion #region Props [XmlAttribute("EmployeeID")] [Bindable(true)] public int EmployeeID { get { return GetColumnValue<int>(Columns.EmployeeID); } set { SetColumnValue(Columns.EmployeeID, value); } } [XmlAttribute("LastName")] [Bindable(true)] public string LastName { get { return GetColumnValue<string>(Columns.LastName); } set { SetColumnValue(Columns.LastName, value); } } [XmlAttribute("FirstName")] [Bindable(true)] public string FirstName { get { return GetColumnValue<string>(Columns.FirstName); } set { SetColumnValue(Columns.FirstName, value); } } [XmlAttribute("Title")] [Bindable(true)] public string Title { get { return GetColumnValue<string>(Columns.Title); } set { SetColumnValue(Columns.Title, value); } } [XmlAttribute("TitleOfCourtesy")] [Bindable(true)] public string TitleOfCourtesy { get { return GetColumnValue<string>(Columns.TitleOfCourtesy); } set { SetColumnValue(Columns.TitleOfCourtesy, value); } } [XmlAttribute("BirthDate")] [Bindable(true)] public DateTime? BirthDate { get { return GetColumnValue<DateTime?>(Columns.BirthDate); } set { SetColumnValue(Columns.BirthDate, value); } } [XmlAttribute("HireDate")] [Bindable(true)] public DateTime? HireDate { get { return GetColumnValue<DateTime?>(Columns.HireDate); } set { SetColumnValue(Columns.HireDate, value); } } [XmlAttribute("Address")] [Bindable(true)] public string Address { get { return GetColumnValue<string>(Columns.Address); } set { SetColumnValue(Columns.Address, value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>(Columns.City); } set { SetColumnValue(Columns.City, value); } } [XmlAttribute("Region")] [Bindable(true)] public string Region { get { return GetColumnValue<string>(Columns.Region); } set { SetColumnValue(Columns.Region, value); } } [XmlAttribute("PostalCode")] [Bindable(true)] public string PostalCode { get { return GetColumnValue<string>(Columns.PostalCode); } set { SetColumnValue(Columns.PostalCode, value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>(Columns.Country); } set { SetColumnValue(Columns.Country, value); } } [XmlAttribute("HomePhone")] [Bindable(true)] public string HomePhone { get { return GetColumnValue<string>(Columns.HomePhone); } set { SetColumnValue(Columns.HomePhone, value); } } [XmlAttribute("Extension")] [Bindable(true)] public string Extension { get { return GetColumnValue<string>(Columns.Extension); } set { SetColumnValue(Columns.Extension, value); } } [XmlAttribute("Photo")] [Bindable(true)] public byte[] Photo { get { return GetColumnValue<byte[]>(Columns.Photo); } set { SetColumnValue(Columns.Photo, value); } } [XmlAttribute("Notes")] [Bindable(true)] public string Notes { get { return GetColumnValue<string>(Columns.Notes); } set { SetColumnValue(Columns.Notes, value); } } [XmlAttribute("ReportsTo")] [Bindable(true)] public int? ReportsTo { get { return GetColumnValue<int?>(Columns.ReportsTo); } set { SetColumnValue(Columns.ReportsTo, value); } } [XmlAttribute("PhotoPath")] [Bindable(true)] public string PhotoPath { get { return GetColumnValue<string>(Columns.PhotoPath); } set { SetColumnValue(Columns.PhotoPath, value); } } [XmlAttribute("Deleted")] [Bindable(true)] public bool Deleted { get { return GetColumnValue<bool>(Columns.Deleted); } set { SetColumnValue(Columns.Deleted, value); } } #endregion //no foreign key tables defined (1) //no ManyToMany tables defined (1) #region Typed Columns public static TableSchema.TableColumn EmployeeIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn LastNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn FirstNameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn TitleColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn TitleOfCourtesyColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn BirthDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn HireDateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn AddressColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn CityColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn RegionColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn PostalCodeColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn CountryColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn HomePhoneColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ExtensionColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn PhotoColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn NotesColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn ReportsToColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn PhotoPathColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn DeletedColumn { get { return Schema.Columns[18]; } } #endregion #region Columns Struct public struct Columns { public static string EmployeeID = @"EmployeeID"; public static string LastName = @"LastName"; public static string FirstName = @"FirstName"; public static string Title = @"Title"; public static string TitleOfCourtesy = @"TitleOfCourtesy"; public static string BirthDate = @"BirthDate"; public static string HireDate = @"HireDate"; public static string Address = @"Address"; public static string City = @"City"; public static string Region = @"Region"; public static string PostalCode = @"PostalCode"; public static string Country = @"Country"; public static string HomePhone = @"HomePhone"; public static string Extension = @"Extension"; public static string Photo = @"Photo"; public static string Notes = @"Notes"; public static string ReportsTo = @"ReportsTo"; public static string PhotoPath = @"PhotoPath"; public static string Deleted = @"Deleted"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; namespace System { public static class Console { private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields private static TextReader _in; private static TextWriter _out, _error; private static ConsoleCancelEventHandler _cancelCallbacks; private static ConsolePal.ControlCHandlerRegistrar _registrar; internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class { lock (InternalSyncObject) { T result = Volatile.Read(ref field); if (result == null) { result = initializer(); Volatile.Write(ref field, result); } return result; } } public static TextReader In { get { return Volatile.Read(ref _in) ?? EnsureInitialized(ref _in, () => { return ConsolePal.GetOrCreateReader(); }); } } public static ConsoleKeyInfo ReadKey() { return ConsolePal.ReadKey(false); } public static ConsoleKeyInfo ReadKey(bool intercept) { return ConsolePal.ReadKey(intercept); } public static TextWriter Out { get { return Volatile.Read(ref _out) ?? EnsureInitialized(ref _out, () => CreateOutputWriter(OpenStandardOutput())); } } public static TextWriter Error { get { return Volatile.Read(ref _error) ?? EnsureInitialized(ref _error, () => CreateOutputWriter(OpenStandardError())); } } private static TextWriter CreateOutputWriter(Stream outputStream) { return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ? StreamWriter.Null : new StreamWriter( stream: outputStream, encoding: ConsolePal.OutputEncoding, bufferSize: DefaultConsoleBufferSize, leaveOpen: true) { AutoFlush = true }); } private static StrongBox<bool> _isStdInRedirected; private static StrongBox<bool> _isStdOutRedirected; private static StrongBox<bool> _isStdErrRedirected; public static bool IsInputRedirected { get { StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ?? EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore())); return redirected.Value; } } public static bool IsOutputRedirected { get { StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ?? EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore())); return redirected.Value; } } public static bool IsErrorRedirected { get { StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ?? EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore())); return redirected.Value; } } public static ConsoleColor BackgroundColor { get { return ConsolePal.BackgroundColor; } set { ConsolePal.BackgroundColor = value; } } public static ConsoleColor ForegroundColor { get { return ConsolePal.ForegroundColor; } set { ConsolePal.ForegroundColor = value; } } public static void ResetColor() { ConsolePal.ResetColor(); } public static int WindowWidth { get { return ConsolePal.WindowWidth; } set { ConsolePal.WindowWidth = value; } } public static bool CursorVisible { get { return ConsolePal.CursorVisible; } set { ConsolePal.CursorVisible = value; } } public static event ConsoleCancelEventHandler CancelKeyPress { add { lock (InternalSyncObject) { _cancelCallbacks += value; // If we haven't registered our control-C handler, do it. if (_registrar == null) { _registrar = new ConsolePal.ControlCHandlerRegistrar(); _registrar.Register(); } } } remove { lock (InternalSyncObject) { _cancelCallbacks -= value; if (_registrar != null && _cancelCallbacks == null) { _registrar.Unregister(); _registrar = null; } } } } public static Stream OpenStandardInput() { return ConsolePal.OpenStandardInput(); } public static Stream OpenStandardOutput() { return ConsolePal.OpenStandardOutput(); } public static Stream OpenStandardError() { return ConsolePal.OpenStandardError(); } public static void SetIn(TextReader newIn) { CheckNonNull(newIn, "newIn"); newIn = SyncTextReader.GetSynchronizedTextReader(newIn); lock (InternalSyncObject) { _in = newIn; } } public static void SetOut(TextWriter newOut) { CheckNonNull(newOut, "newOut"); newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut); lock (InternalSyncObject) { _out = newOut; } } public static void SetError(TextWriter newError) { CheckNonNull(newError, "newError"); newError = SyncTextWriter.GetSynchronizedTextWriter(newError); lock (InternalSyncObject) { _error = newError; } } private static void CheckNonNull(object obj, string paramName) { if (obj == null) throw new ArgumentNullException(paramName); } // // Give a hint to the code generator to not inline the common console methods. The console methods are // not performance critical. It is unnecessary code bloat to have them inlined. // // Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out // the inlined console writelines from them. // [MethodImplAttribute(MethodImplOptions.NoInlining)] public static int Read() { return In.Read(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static String ReadLine() { return In.ReadLine(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine() { Out.WriteLine(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(bool value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(char value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(char[] buffer) { Out.WriteLine(buffer); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(char[] buffer, int index, int count) { Out.WriteLine(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(decimal value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(double value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(float value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(int value) { Out.WriteLine(value); } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(uint value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(long value) { Out.WriteLine(value); } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(ulong value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(Object value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(String value) { Out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(String format, Object arg0) { Out.WriteLine(format, arg0); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(String format, Object arg0, Object arg1) { Out.WriteLine(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(String format, Object arg0, Object arg1, Object arg2) { Out.WriteLine(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void WriteLine(String format, params Object[] arg) { if (arg == null) // avoid ArgumentNullException from String.Format Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg); else Out.WriteLine(format, arg); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(String format, Object arg0) { Out.Write(format, arg0); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(String format, Object arg0, Object arg1) { Out.Write(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(String format, Object arg0, Object arg1, Object arg2) { Out.Write(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(String format, params Object[] arg) { if (arg == null) // avoid ArgumentNullException from String.Format Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg); else Out.Write(format, arg); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(bool value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(char value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(char[] buffer) { Out.Write(buffer); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(char[] buffer, int index, int count) { Out.Write(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(double value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(decimal value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(float value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(int value) { Out.Write(value); } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(uint value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(long value) { Out.Write(value); } [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(ulong value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(Object value) { Out.Write(value); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void Write(String value) { Out.Write(value); } private sealed class ControlCDelegateData { private readonly ConsoleSpecialKey _controlKey; private readonly ConsoleCancelEventHandler _cancelCallbacks; internal bool Cancel; internal bool DelegateStarted; internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks) { _controlKey = controlKey; _cancelCallbacks = cancelCallbacks; } // This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so // the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task // to start). internal void HandleBreakEvent() { DelegateStarted = true; var args = new ConsoleCancelEventArgs(_controlKey); _cancelCallbacks(null, args); Cancel = args.Cancel; } } internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey) { // The thread that this gets called back on has a very small stack on some systems. There is // not enough space to handle a managed exception being caught and thrown. So, run a task // on the threadpool for the actual event callback. // To avoid the race condition between remove handler and raising the event ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks; if (cancelCallbacks == null) { return false; } var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks); Task callBackTask = Task.Factory.StartNew( d => ((ControlCDelegateData)d).HandleBreakEvent(), delegateData, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Block until the delegate is done. We need to be robust in the face of the task not executing // but we also want to get control back immediately after it is done and we don't want to give the // handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a // timout and a second time without if we are sure that the handler actually started. TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds callBackTask.Wait(controlCWaitTime); if (!delegateData.DelegateStarted) { Debug.Assert(false, "The task to execute the handler did not start within 30 seconds."); return false; } callBackTask.Wait(); return delegateData.Cancel; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.Framework { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using ICSharpCode.SharpZipLib.Zip.Compression.Streams.Interactive; using Platform.IO; using Platform.Text; using Platform.VirtualFileSystem.Network.Client; using Platform.VirtualFileSystem.Network.Text.Protocol; namespace Platform.VirtualFileSystem.Network.Text { public partial class TextNetworkFileSystemClient : AbstractNetworkFileSystemClient { public static readonly int DefaultTryCount = 4; public static readonly int DefaultPort = TextNetworkProtocol.DefaultPort; protected override Stream WriteStream { get { if (this.writeStream == null) { this.writeStream = base.WriteStream; } return this.writeStream; } set { if (value != this.writeStream) { this.writeStream = new MeteringStream(value); this.writer = new StreamWriter(this.writeStream); } } } private Stream writeStream; private TextWriter writer; public class DeterministicBinaryReadContext : IDisposable { private bool acquired = false; private TextNetworkFileSystemClient client; internal DeterministicBinaryReadContext(TextNetworkFileSystemClient client) { this.acquired = false; this.client = client; } internal void Aquire() { lock (this) { if (this.acquired) { throw new InvalidOperationException(); } this.acquired = true; this.client.readStream.ChunkingEnabled = false; } System.Threading.Monitor.Enter(this.client.SyncLock); } internal void Release() { lock (this) { if (!this.acquired) { throw new InvalidOperationException(); } this.acquired = false; this.client.readStream.ChunkingEnabled = true; } System.Threading.Monitor.Exit(this.client.SyncLock); } public void Dispose() { Release(); } } private DeterministicBinaryReadContext binaryReadContext; public virtual DeterministicBinaryReadContext AquireBinaryReadContext() { this.binaryReadContext.Aquire(); return this.binaryReadContext; } protected override Stream ReadStream { get { if (this.readStream == null) { this.ReadStream = base.ReadStream; } return this.readStream; } set { if (value != this.readStream) { this.readStream = new ChunkingStream(value, 1024 * 512, Encoding.ASCII.GetBytes("\n")); this.reader = new StreamReader(this.readStream); } } } private TextReader reader; private ChunkingStream readStream; protected virtual TextReader Reader { get { return this.reader; } } protected virtual TextWriter Writer { get { return this.writer; } } public override void Disconnect() { try { Writer.Flush(); base.Disconnect(); } catch (IOException) { } catch (ObjectDisposedException) { } } ~TextNetworkFileSystemClient() { ActionUtils.IgnoreExceptions(this.Disconnect); } public TextNetworkFileSystemClient(string address) : base(address, DefaultPort) { Initialize(); } public TextNetworkFileSystemClient(string address, int port) : base(address, port) { Initialize(); } public TextNetworkFileSystemClient(IPAddress serverAddress) : this(serverAddress, TextNetworkProtocol.DefaultPort) { } public TextNetworkFileSystemClient(IPAddress serverAddress, int port) : this(new IPEndPoint(serverAddress, port)) { } public TextNetworkFileSystemClient(IPEndPoint serverEndPoint) : base(serverEndPoint) { Initialize(); } private void Initialize() { this.binaryReadContext = new DeterministicBinaryReadContext(this); } public override void Connect() { this.TcpClient.ReceiveBufferSize = 256 * 1024; this.TcpClient.ReceiveTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; this.TcpClient.SendTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds; base.Connect(); this.ReadStream = base.ReadStream; this.WriteStream = base.WriteStream; ReadWelcomeText(); //NegotiateEncryption(); Login(); } public virtual void Login() { using (this.AcquireCommandContext()) { SendCommand(DefaultTryCount, "login"); } } public virtual void ReadReady() { Exception e = null; while (true) { var line = ReadNextLine(); if (line.StartsWith(ResponseCodes.READY)) { break; } else if (line.StartsWith(ResponseCodes.ERROR)) { e = ParseResponse(line).GetErrorException() ?? e; } } if (e != null) { throw e; } } public virtual void ReadWelcomeText(TextWriter welcomeTextWriter) { for (;;) { var line = this.reader.ReadLine(); if (line.StartsWith(ResponseCodes.READY, StringComparison.CurrentCultureIgnoreCase)) { break; } //WriteTextBlock(line); } } public virtual string ReadWelcomeText() { var builder = new StringBuilder(64); ReadWelcomeText(new StringWriter(builder)); return builder.ToString(); } private string lastLineRead; protected virtual string ReadNextLine() { lock (this) { string s; for (;;) { s = this.reader.ReadLine(); if (s == null) { throw new IOException(); } if (s.Trim(' ', '\r', '\n').Length > 0) { break; } } return this.lastLineRead = s; } } public virtual CommandResponse ReadResponse() { return ParseResponse(ReadNextLine()); } public virtual CommandResponse ParseResponse(string line) { lock (this.SyncLock) { int x; string s; string responseType; string responseTupleString; CommandResponse retval; s = line; x = s.IndexOf(' '); if (x < 0) { responseType = s; responseTupleString = ""; } else { responseType = s.Substring(0, x); responseTupleString = s.Substring(x + 1); } if (responseType.EqualsIgnoreCase(ResponseCodes.OK) || responseType.EqualsIgnoreCase(ResponseCodes.ERROR)) { retval = new CommandResponse(responseType, responseTupleString); } else { throw new RemoteVirtualFileSystemException(ErrorCodes.UNEXPECTED); } return retval; } } public virtual CommandResponse SendCommand(int trycount, string command) { return SendCommand(trycount, command, new object[0]); } public virtual CommandResponse SendCommand(int trycount, string format, params object[] args) { lock (this.SyncLock) { var tries = trycount; var delay = TimeSpan.Zero; for (var i = 0; i < tries; i++) { try { SendCommandWithoutResponse(format, args); return ReadResponse(); } catch (IOException) { if (i != tries - 1) { System.Threading.Thread.Sleep(delay); if (delay == TimeSpan.Zero) { delay = TimeSpan.FromMilliseconds(50); } else { delay = TimeSpan.FromMilliseconds(delay.TotalMilliseconds * 2); } if (delay > TimeSpan.FromSeconds(5)) { delay = TimeSpan.FromSeconds(5); } Reconnect(); continue; } else { throw; } } catch { } } throw new ApplicationException("Unreachable state"); } } public virtual void SendCommandWithoutResponse(string command) { WriteTextBlock(command); } public virtual void SendCommandWithoutResponse(string format, params object[] args) { WriteTextBlock(format, args); } public virtual void WriteTextBlock(string block) { this.writer.Write(block); this.writer.Write("\r\n"); this.writer.Flush(); } public virtual void WriteTextBlock(string format, params object[] args) { string s; s = String.Format(format, args); this.writer.Write(String.Format(format, args)); this.writer.Write("\r\n"); this.writer.Flush(); } #region CommandContext protected class CommandContext : IDisposable { private readonly bool readReady; private readonly TextNetworkFileSystemClient client; internal CommandContext(TextNetworkFileSystemClient client, bool readReady, bool aquire) { this.client = client; this.readReady = readReady; if (aquire) { Aquire(); } } public virtual void Aquire() { System.Threading.Monitor.Enter(this.client); } public virtual void Dispose() { try { if (this.readReady) { try { this.client.ReadReady(); } catch (TextNetworkProtocolException) { this.client.connected = false; throw; } catch (IOException) { this.client.connected = false; } } } finally { System.Threading.Monitor.Exit(this.client); } } } protected virtual CommandContext AcquireCommandContext() { return this.AcquireCommandContext(true); } protected virtual CommandContext AcquireCommandContext(bool readReadyAtEnd) { return new CommandContext(this, readReadyAtEnd, true); } #endregion public virtual void NegotiateEncryption() { using (this.AcquireCommandContext()) { var response = this.SendCommand(DefaultTryCount, "ADHOCENCRYPTION -w -compress"); response.ProcessError(); this.ReadStream = new InteractiveInflaterInputStream(base.ReadStream, new Inflater(true), 1024 * 256); this.WriteStream = new InteractiveDeflaterOutputStream(base.WriteStream, new Deflater(Deflater.BEST_COMPRESSION, true), 512); WriteTextBlock(ResponseCodes.READY); } } public override bool Connected { get { return this.connected ?? base.Connected; } } private bool? connected; public override void Delete(string uri, NodeType nodeType, bool recursive) { using (this.AcquireCommandContext()) { try { SendCommand(DefaultTryCount, "delete -t={0} {1} \"{2}\"", TextNetworkProtocol.GetNodeTypeName(nodeType), recursive ? "-r" : "", uri).ProcessError(); } catch (Exception) { this.connected = false; throw; } } } public override void Create(string uri, NodeType nodeType, bool createParent) { using (this.AcquireCommandContext()) { try { SendCommand(DefaultTryCount, "create -t={0} {1} \"{2}\"", TextNetworkProtocol.GetNodeTypeName(nodeType), createParent && nodeType.IsLikeDirectory ? "-p" : "", uri).ProcessError(); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } } public override void Move(string srcUri, string desUri, NodeType nodeType, bool overwrite) { using (this.AcquireCommandContext()) { try { SendCommand(DefaultTryCount, "move -t={0} -o={1} \"{2}\" \"{3}\"", TextNetworkProtocol.GetNodeTypeName(nodeType), overwrite, srcUri, desUri).ProcessError(); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } } public override void Copy(string srcUri, string desUri, NodeType nodeType, bool overwrite) { using (this.AcquireCommandContext()) { try { SendCommand(DefaultTryCount, "copy -t={0} -o={1} \"{2}\" \"{3}\"", TextNetworkProtocol.GetNodeTypeName(nodeType), overwrite, srcUri, desUri).ProcessError(); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } } public override IEnumerable<Pair<string, NodeType>> List(string uri, string regex) { Predicate<string> acceptName = null; using (this.AcquireCommandContext(false)) { try { try { if (!String.IsNullOrEmpty(regex)) { SendCommand(DefaultTryCount, @"list -regex=""{0}"" ""{1}""", TextConversion.ToEscapedHexString(regex), uri).ProcessError(); } else { SendCommand(DefaultTryCount, @"list ""{0}""", uri).ProcessError(); acceptName = PredicateUtils.NewRegex(regex); } } catch { ReadReady(); throw; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } for (; ; ) { string line; NodeType currentNodeType; Pair<string, string> currentFile; try { line = TextConversion.FromEscapedHexString(ReadNextLine()); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } if (line.EqualsIgnoreCase(ResponseCodes.READY)) { break; } currentFile = line.SplitAroundFirstCharFromLeft(':'); currentFile.Right = TextConversion.FromEscapedHexString(currentFile.Right); currentNodeType = TextNetworkProtocol.GetNodeType(currentFile.Left); if (currentNodeType == null || currentFile.Right.Length == 0) { continue; } if (acceptName != null) { if (acceptName(currentFile.Right)) { yield return new Pair<string, NodeType>(currentFile.Right, currentNodeType); } } else { yield return new Pair<string, NodeType>(currentFile.Right, currentNodeType); } } } } #region ListAttributes public override IEnumerable<NetworkFileSystemEntry> ListAttributes(string uri, string regex) { Predicate<string> acceptName = null; using (this.AcquireCommandContext(false)) { try { try { if (!String.IsNullOrEmpty(regex)) { try { SendCommand(DefaultTryCount, @"list -a -regex=""{0}"" ""{1}""", TextConversion.ToEscapedHexString(regex), uri).ProcessError(); } catch (TextNetworkProtocolErrorResponseException) { ReadReady(); SendCommand(DefaultTryCount, @"list -a ""{1}""", regex, uri).ProcessError(); acceptName = PredicateUtils.NewRegex(regex); } } else { SendCommand(DefaultTryCount, @"list -a ""{0}""", uri).ProcessError(); } } catch { ReadReady(); throw; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } var enumerator = TextNetworkProtocol.ReadEntries(this.ReadNextLine).GetEnumerator(); try { for (; ; ) { try { if (!enumerator.MoveNext()) { break; } } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } if (enumerator.Current.Right != null) { CommandResponse response; response = ParseResponse(enumerator.Current.Right); response.ProcessError(); } if (acceptName != null) { if (acceptName(enumerator.Current.Left.Name)) { yield return enumerator.Current.Left; } } else { yield return enumerator.Current.Left; } } } finally { enumerator.Dispose(); } } } public override void CreateHardLink(string srcUri, string desUri, bool overwrite) { using (this.AcquireCommandContext()) { try { this.SendCommand(DefaultTryCount, "createhardlink -o={0} \"{1}\" \"{2}\"", overwrite.ToString(), srcUri, desUri).ProcessError(); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } } #endregion public override Stream OpenRandomAccessStream(string uri, FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { long length; CommandResponse response; using (this.AcquireCommandContext()) { try { response = SendCommand ( DefaultTryCount, "randomaccess -mode=\"{0}\" -share=\"{1}\" -access=\"{2}\" \"{3}\"", fileMode, fileShare, fileAccess, uri ); response.ProcessError(); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } var canseek = Convert.ToBoolean(response.ResponseTuples["canseek"]); if (canseek) { length = Convert.ToInt64(response.ResponseTuples["length"]); } else { length = -1; } return new TextRandomAccessNetworkFileSystemStream(this, fileAccess, fileShare, canseek, length); } #region BufferedFileSystemNetworkStream private class BufferedFileSystemNetworkStream : StreamWrapper, IStreamWithEvents { public TextRandomAccessNetworkFileSystemStream NetworkFileSystemStream { get { return m_NetworkFileSystemStream; } } private TextRandomAccessNetworkFileSystemStream m_NetworkFileSystemStream; public BufferedFileSystemNetworkStream(TextRandomAccessNetworkFileSystemStream stream, int bufferSize) : base(new BufferedStream(stream, bufferSize)) { m_NetworkFileSystemStream = stream; m_NetworkFileSystemStream.AfterClose += delegate(object sender, EventArgs eventArgs) { OnAfterClose(eventArgs); }; m_NetworkFileSystemStream.BeforeClose += delegate(object sender, EventArgs eventArgs) { OnBeforeClose(eventArgs); }; } #region IStreamWithEvents Members public virtual event EventHandler AfterClose; public virtual void OnAfterClose(EventArgs eventArgs) { if (AfterClose != null) { AfterClose(this, eventArgs); } } public virtual event EventHandler BeforeClose; public virtual void OnBeforeClose(EventArgs eventArgs) { if (BeforeClose != null) { BeforeClose(this, eventArgs); } } #endregion } #endregion public override HashValue ComputeHash(string uri, NodeType nodeType, string algorithm, bool recursive, long offset, long length, IEnumerable<string> fileAttributes, IEnumerable<string> dirAttributes) { StringBuilder dirAttributesString = null; StringBuilder fileAttributesString = null; using (this.AcquireCommandContext()) { try { if (dirAttributes != null) { dirAttributesString = new StringBuilder(); foreach (string s in dirAttributes) { dirAttributesString.Append(s); dirAttributesString.Append(','); } if (dirAttributesString.Length > 0) { dirAttributesString.Length--; } else { dirAttributesString = null; } } if (fileAttributes != null) { fileAttributesString = new StringBuilder(); foreach (string s in fileAttributes) { fileAttributesString.Append(s); fileAttributesString.Append(','); } if (fileAttributesString.Length > 0) { fileAttributesString.Length--; } else { fileAttributesString = null; } } StringBuilder commandText = new StringBuilder(128); commandText.Append("computehash -hex"); commandText.Append(" -t=\"").Append(TextNetworkProtocol.GetNodeTypeName(nodeType)).Append('\"'); if (offset != 0) { commandText.Append(" -o=\"").Append(offset).Append('\"'); } if (recursive) { commandText.Append(" -r"); } if (length != -1) { commandText.Append(" -l=\"").Append(length).Append('\"'); } if (algorithm != "md5") { commandText.Append(" -a=\"").Append(algorithm).Append('\"'); } if (fileAttributesString != null) { commandText.Append(" -fileattribs=\"").Append(fileAttributesString).Append('\"'); } if (dirAttributesString != null) { commandText.Append(" -dirattribs=\"").Append(dirAttributesString).Append('\"'); } commandText.Append(" \"").Append(uri).Append('\"'); var response = SendCommand(DefaultTryCount, commandText.ToString()).ProcessError(); return new HashValue ( TextConversion.FromHexString(response.ResponseTuples["hash"]), algorithm, 0, length ); } catch (TextNetworkProtocolException) { this.connected = false; throw; } catch (IOException) { this.connected = false; throw; } } } public override HashValue ComputeHash(Stream stream, string algorithm, long offset, long length) { var networkStream = (TextRandomAccessNetworkFileSystemStream)stream; return networkStream.ComputeHash(algorithm, offset, length); } public override IEnumerable<Pair<string,object>> GetAttributes(string uri, NodeType nodeType) { using (this.AcquireCommandContext(false)) { var lastReadLine = new ValueBox<string>(this.lastLineRead); try { this.SendCommand(DefaultTryCount, @"getattributes -t={0} ""{1}""", TextNetworkProtocol.GetNodeTypeName(nodeType), uri).ProcessError(); } catch { ReadReady(); throw; } foreach (var attribute in TextNetworkProtocol.ReadAttributes(this.ReadNextLine, lastReadLine)) { yield return attribute; } } } public override void SetAttributes(string uri, NodeType nodeType, IEnumerable<Pair<string, object>> attributes) { using (this.AcquireCommandContext()) { var attributesList = attributes.Where(x => !x.Left.EqualsIgnoreCase("length") && !x.Left.EqualsIgnoreCase("exists")).ToList(); SendCommandWithoutResponse(@"setattributes -t={0} ""{1}""", TextNetworkProtocol.GetNodeTypeName(nodeType), uri); ReadResponse().ProcessError(); try { foreach (var attribute in attributesList) { WriteTextBlock(@"{0}=""{1}:{2}""", attribute.Name, ProtocolTypes.GetTypeName(attribute.Value.GetType()), ProtocolTypes.ToEscapedString(attribute.Value)); } } finally { WriteTextBlock(ResponseCodes.READY); } ReadResponse().ProcessError(); } } public override TimeSpan Ping() { using (this.AcquireCommandContext()) { var start = DateTime.Now; this.SendCommand(DefaultTryCount, "noop").ProcessError(); return DateTime.Now - start; } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace Apache.Geode.Client.Tests { using Apache.Geode.Client; /// <summary> /// User class for testing the put functionality for object. /// </summary> public class Portfolio : IGeodeSerializable { #region Private members and methods private int m_id; private string m_pkid; private Position m_position1; private Position m_position2; private Dictionary<Object, Object> m_positions; private string m_type; private string m_status; private string[] m_names; private byte[] m_newVal; private DateTime m_creationDate; private byte[] m_arrayZeroSize; private byte[] m_arrayNull; private static string[] m_secIds = { "SUN", "IBM", "YHOO", "GOOG", "MSFT", "AOL", "APPL", "ORCL", "SAP", "DELL" }; private UInt32 GetObjectSize(IGeodeSerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public int ID { get { return m_id; } } public string Pkid { get { return m_pkid; } } public Position P1 { get { return m_position1; } } public Position P2 { get { return m_position2; } } public IDictionary<Object, Object> Positions { get { return m_positions; } } public string Status { get { return m_status; } } public bool IsActive { get { return (m_status == "active"); } } public byte[] NewVal { get { return m_newVal; } } public byte[] ArrayNull { get { return m_arrayNull; } } public byte[] ArrayZeroSize { get { return m_arrayZeroSize; } } public DateTime CreationDate { get { return m_creationDate; } } public string Type { get { return m_type; } } public static string[] SecIds { get { return m_secIds; } } public override string ToString() { string portStr = string.Format("Portfolio [ID={0} status={1} " + "type={2} pkid={3}]", m_id, m_status, m_type, m_pkid); portStr += string.Format("{0}\tP1: {1}", Environment.NewLine, m_position1); portStr += string.Format("{0}\tP2: {1}", Environment.NewLine, m_position2); portStr += string.Format("{0}Creation Date: {1}", Environment.NewLine, m_creationDate); return portStr; } #endregion #region Constructors public Portfolio() { m_id = 0; m_pkid = null; m_type = null; m_status = null; m_newVal = null; m_creationDate = DateTime.MinValue; } public Portfolio(int id) : this(id, 0) { } public Portfolio(int id, int size) : this(id, size, null) { } public Portfolio(int id, int size, string[] names) { m_names = names; m_id = id; m_pkid = id.ToString(); m_status = (id % 2 == 0) ? "active" : "inactive"; m_type = "type" + (id % 3); int numSecIds = m_secIds.Length; m_position1 = new Position(m_secIds[Position.Count % numSecIds], Position.Count * 1000); if (id % 2 != 0) { m_position2 = new Position(m_secIds[Position.Count % numSecIds], Position.Count * 1000); } else { m_position2 = null; } m_positions = new Dictionary<Object, Object>(); m_positions[(m_secIds[Position.Count % numSecIds])] = m_position1; if (size > 0) { m_newVal = new byte[size]; for (int index = 0; index < size; index++) { m_newVal[index] = (byte)'B'; } } m_creationDate = DateTime.Now; m_arrayNull = null; m_arrayZeroSize = new byte[0]; } #endregion #region IGeodeSerializable Members public void FromData(DataInput input) { m_id = input.ReadInt32(); m_pkid = input.ReadUTF(); m_position1 = (Position)input.ReadObject(); m_position2 = (Position)input.ReadObject(); m_positions = new Dictionary<object,object>(); input.ReadDictionary((System.Collections.IDictionary)m_positions); m_type = input.ReadUTF(); m_status = input.ReadUTF(); m_names = (string[])(object)input.ReadObject(); m_newVal = input.ReadBytes(); //m_creationDate = (System.DateTime)input.ReadGenericObject(); m_creationDate = input.ReadDate(); m_arrayNull = input.ReadBytes(); m_arrayZeroSize = input.ReadBytes(); } public void ToData(DataOutput output) { output.WriteInt32(m_id); output.WriteUTF(m_pkid); output.WriteObject(m_position1); output.WriteObject(m_position2); output.WriteDictionary((System.Collections.IDictionary)m_positions); output.WriteUTF(m_type); output.WriteUTF(m_status); output.WriteObject(m_names); output.WriteBytes(m_newVal); //output.WriteObject((IGeodeSerializable)(object)m_creationDate); // VJR: TODO //output.WriteObject(CacheableDate.Create(m_creationDate)); output.WriteDate(m_creationDate); output.WriteBytes(m_arrayNull); output.WriteBytes(m_arrayZeroSize); } public UInt32 ObjectSize { get { UInt32 objectSize = 0; objectSize += (UInt32)sizeof(Int32); objectSize += (UInt32)(m_pkid.Length * sizeof(char)); objectSize += GetObjectSize(m_position1); objectSize += GetObjectSize(m_position2); objectSize += (UInt32)(m_type.Length * sizeof(char)); objectSize += (UInt32)(m_status == null ? 0 : sizeof(char) * m_status.Length); objectSize += (uint)m_names.Length;//TODO:need to calculate properly objectSize += (UInt32)(m_newVal == null ? 0 : sizeof(byte) * m_newVal.Length); objectSize += 8; //TODO:need to calculate properly for m_creationDate.; objectSize += (UInt32)(m_arrayZeroSize == null ? 0 : sizeof(byte) * m_arrayZeroSize.Length); objectSize += (UInt32)(m_arrayNull == null ? 0 : sizeof(byte) * m_arrayNull.Length); return objectSize; } } public UInt32 ClassId { get { return 0x08; } } #endregion public static IGeodeSerializable CreateDeserializable() { return new Portfolio(); } } }
//----------------------------------------------------------------------- // <copyright file="UndoableBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://www.lhotka.net/cslanet/ // </copyright> // <summary>Implements n-level undo capabilities as</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Reflection; using System.IO; using System.ComponentModel; using Csla.Properties; using Csla.Reflection; using Csla.Serialization.Mobile; using Csla.Serialization; using System.Linq; namespace Csla.Core { /// <summary> /// Implements n-level undo capabilities as /// described in Chapters 2 and 3. /// </summary> [Serializable()] public abstract class UndoableBase : Csla.Core.BindableBase, Csla.Core.IUndoableObject { // keep a stack of object state values. [NotUndoable()] private Stack<byte[]> _stateStack = new Stack<byte[]>(); [NotUndoable] private bool _bindingEdit; /// <summary> /// Creates an instance of the object. /// </summary> protected UndoableBase() { } /// <summary> /// Gets or sets a value indicating whether n-level undo /// was invoked through IEditableObject. FOR INTERNAL /// CSLA .NET USE ONLY! /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected bool BindingEdit { get { return _bindingEdit; } set { _bindingEdit = value; } } int IUndoableObject.EditLevel { get { return EditLevel; } } /// <summary> /// Returns the current edit level of the object. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected int EditLevel { get { return _stateStack.Count; } } void IUndoableObject.CopyState(int parentEditLevel, bool parentBindingEdit) { if (!parentBindingEdit) CopyState(parentEditLevel); } void IUndoableObject.UndoChanges(int parentEditLevel, bool parentBindingEdit) { if (!parentBindingEdit) UndoChanges(parentEditLevel); } void IUndoableObject.AcceptChanges(int parentEditLevel, bool parentBindingEdit) { if (!parentBindingEdit) AcceptChanges(parentEditLevel); } /// <summary> /// This method is invoked before the CopyState /// operation begins. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void CopyingState() { } /// <summary> /// This method is invoked after the CopyState /// operation is complete. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void CopyStateComplete() { } /// <summary> /// Copies the state of the object and places the copy /// onto the state stack. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected internal void CopyState(int parentEditLevel) { CopyingState(); Type currentType = this.GetType(); var state = new MobileDictionary<string, object>(); if (this.EditLevel + 1 > parentEditLevel) throw new UndoException(string.Format(Resources.EditLevelMismatchException, "CopyState"), this.GetType().Name, null, this.EditLevel, parentEditLevel - 1); do { var currentTypeName = currentType.FullName; // get the list of fields in this type List<DynamicMemberHandle> handlers = UndoableHandler.GetCachedFieldHandlers(currentType); foreach (var h in handlers) { var value = h.DynamicMemberGet(this); var fieldName = GetFieldName(currentTypeName, h.MemberName); if (typeof(IUndoableObject).IsAssignableFrom(h.MemberType)) { if (value == null) { // variable has no value - store that fact state.Add(fieldName, null); } else { // this is a child object, cascade the call ((IUndoableObject)value).CopyState(this.EditLevel + 1, BindingEdit); } } else if (value is IMobileObject) { // this is a mobile object, store the serialized value using (MemoryStream buffer = new MemoryStream()) { var formatter = SerializationFormatterFactory.GetFormatter(); formatter.Serialize(buffer, value); state.Add(fieldName, buffer.ToArray()); } } else { // this is a normal field, simply trap the value state.Add(fieldName, value); } } currentType = currentType.BaseType; } while (currentType != typeof(UndoableBase)); // serialize the state and stack it using (MemoryStream buffer = new MemoryStream()) { var formatter = SerializationFormatterFactory.GetFormatter(); formatter.Serialize(buffer, state); _stateStack.Push(buffer.ToArray()); } CopyStateComplete(); } /// <summary> /// This method is invoked before the UndoChanges /// operation begins. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void UndoChangesComplete() { } /// <summary> /// This method is invoked after the UndoChanges /// operation is complete. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void UndoingChanges() { } /// <summary> /// Restores the object's state to the most recently /// copied values from the state stack. /// </summary> /// <remarks> /// Restores the state of the object to its /// previous value by taking the data out of /// the stack and restoring it into the fields /// of the object. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] protected internal void UndoChanges(int parentEditLevel) { UndoingChanges(); // if we are a child object we might be asked to // undo below the level of stacked states, // so just do nothing in that case if (EditLevel > 0) { if (this.EditLevel - 1 != parentEditLevel) throw new UndoException(string.Format(Resources.EditLevelMismatchException, "UndoChanges"), this.GetType().Name, null, this.EditLevel, parentEditLevel + 1); MobileDictionary<string, object> state; using (MemoryStream buffer = new MemoryStream(_stateStack.Pop())) { buffer.Position = 0; var formatter = SerializationFormatterFactory.GetFormatter(); state = (MobileDictionary<string, object>)formatter.Deserialize(buffer); } Type currentType = this.GetType(); do { var currentTypeName = currentType.FullName; // get the list of fields in this type List<DynamicMemberHandle> handlers = UndoableHandler.GetCachedFieldHandlers(currentType); foreach (var h in handlers) { // the field is undoable, so restore its value var value = h.DynamicMemberGet(this); var fieldName = GetFieldName(currentTypeName, h.MemberName); if (typeof(IUndoableObject).IsAssignableFrom(h.MemberType)) { // this is a child object // see if the previous value was empty //if (state.Contains(h.MemberName)) if (state.Contains(fieldName)) { // previous value was empty - restore to empty h.DynamicMemberSet(this, null); } else { // make sure the variable has a value if (value != null) { // this is a child object, cascade the call. ((IUndoableObject)value).UndoChanges(this.EditLevel, BindingEdit); } } } else if (value is IMobileObject && state[fieldName] != null) { // this is a mobile object, deserialize the value using (MemoryStream buffer = new MemoryStream((byte[])state[fieldName])) { buffer.Position = 0; var formatter = SerializationFormatterFactory.GetFormatter(); var obj = formatter.Deserialize(buffer); h.DynamicMemberSet(this, obj); } } else { // this is a regular field, restore its value h.DynamicMemberSet(this, state[fieldName]); } } currentType = currentType.BaseType; } while (currentType != typeof(UndoableBase)); } UndoChangesComplete(); } /// <summary> /// This method is invoked before the AcceptChanges /// operation begins. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AcceptingChanges() { } /// <summary> /// This method is invoked after the AcceptChanges /// operation is complete. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AcceptChangesComplete() { } /// <summary> /// Accepts any changes made to the object since the last /// state copy was made. /// </summary> /// <remarks> /// The most recent state copy is removed from the state /// stack and discarded, thus committing any changes made /// to the object's state. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] protected internal void AcceptChanges(int parentEditLevel) { AcceptingChanges(); if (this.EditLevel - 1 != parentEditLevel) throw new UndoException(string.Format(Resources.EditLevelMismatchException, "AcceptChanges"), this.GetType().Name, null, this.EditLevel, parentEditLevel + 1); if (EditLevel > 0) { _stateStack.Pop(); Type currentType = this.GetType(); do { // get the list of fields in this type List<DynamicMemberHandle> handlers = UndoableHandler.GetCachedFieldHandlers(currentType); foreach (var h in handlers) { // the field is undoable so see if it is a child object if (typeof(Csla.Core.IUndoableObject).IsAssignableFrom(h.MemberType)) { object value = h.DynamicMemberGet(this); // make sure the variable has a value if (value != null) { // it is a child object so cascade the call ((Core.IUndoableObject)value).AcceptChanges(this.EditLevel, BindingEdit); } } } currentType = currentType.BaseType; } while (currentType != typeof(UndoableBase)); } AcceptChangesComplete(); } /// <summary> /// Returns the full name of a field, including /// the containing type name. /// </summary> /// <param name="typeName">Name of the containing type.</param> /// <param name="memberName">Name of the member (field).</param> private static string GetFieldName(string typeName, string memberName) { return typeName + "." + memberName; } #region Helper Functions private static bool NotUndoableField(FieldInfo field) { return Attribute.IsDefined(field, typeof(NotUndoableAttribute)); } private static string GetFieldName(FieldInfo field) { return field.DeclaringType.FullName + "!" + field.Name; } #endregion #region Reset child edit level internal static void ResetChildEditLevel(IUndoableObject child, int parentEditLevel, bool bindingEdit) { int targetLevel = parentEditLevel; if (bindingEdit && targetLevel > 0 && !(child is FieldManager.FieldDataManager)) targetLevel--; // if item's edit level is too high, // reduce it to match list while (child.EditLevel > targetLevel) child.AcceptChanges(targetLevel, false); // if item's edit level is too low, // increase it to match list while (child.EditLevel < targetLevel) child.CopyState(targetLevel, false); } #endregion #region MobileObject overrides /// <summary> /// Override this method to insert your field values /// into the MobileFormatter serialzation stream. /// </summary> /// <param name="info"> /// Object containing the data to serialize. /// </param> /// <param name="mode"> /// The StateMode indicating why this method was invoked. /// </param> protected override void OnGetState(SerializationInfo info, StateMode mode) { if (mode != StateMode.Undo) { info.AddValue("_bindingEdit", _bindingEdit); if (_stateStack.Count > 0) { var stackArray = _stateStack.ToArray(); info.AddValue("_stateStack", stackArray); } } base.OnGetState(info, mode); } /// <summary> /// Override this method to retrieve your field values /// from the MobileFormatter serialzation stream. /// </summary> /// <param name="info"> /// Object containing the data to serialize. /// </param> /// <param name="mode"> /// The StateMode indicating why this method was invoked. /// </param> protected override void OnSetState(SerializationInfo info, StateMode mode) { if (mode != StateMode.Undo) { _bindingEdit = info.GetValue<bool>("_bindingEdit"); if (info.Values.ContainsKey("_stateStack")) { var stackArray = info.GetValue<byte[][]>("_stateStack"); _stateStack.Clear(); foreach (var item in stackArray.Reverse()) _stateStack.Push(item); } } base.OnSetState(info, mode); } #endregion } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { internal class SocketManager { private readonly LRU<IPEndPoint, Socket> cache; private const int MAX_SOCKETS = 200; internal SocketManager(IMessagingConfiguration config) { cache = new LRU<IPEndPoint, Socket>(MAX_SOCKETS, config.MaxSocketAge, SendingSocketCreator); cache.RaiseFlushEvent += FlushHandler; } /// <summary> /// Creates a socket bound to an address for use accepting connections. /// This is for use by client gateways and other acceptors. /// </summary> /// <param name="address">The address to bind to.</param> /// <returns>The new socket, appropriately bound.</returns> internal static Socket GetAcceptingSocketForEndpoint(IPEndPoint address) { var s = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { // Prep the socket so it will reset on close s.LingerState = new LingerOption(true, 0); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // And bind it to the address s.Bind(address); } catch (Exception) { CloseSocket(s); throw; } return s; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal bool CheckSendingSocket(IPEndPoint target) { return cache.ContainsKey(target); } internal Socket GetSendingSocket(IPEndPoint target) { return cache.Get(target); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private Socket SendingSocketCreator(IPEndPoint target) { var s = new Socket(target.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { s.Connect(target); // Prep the socket so it will reset on close and won't Nagle s.LingerState = new LingerOption(true, 0); s.NoDelay = true; WriteConnectionPreemble(s, Constants.SiloDirectConnectionId); // Identifies this client as a direct silo-to-silo socket // Start an asynch receive off of the socket to detect closure var receiveAsyncEventArgs = new SocketAsyncEventArgs { BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[4]) }, UserToken = new Tuple<Socket, IPEndPoint, SocketManager>(s, target, this) }; receiveAsyncEventArgs.Completed += ReceiveCallback; bool receiveCompleted = s.ReceiveAsync(receiveAsyncEventArgs); NetworkingStatisticsGroup.OnOpenedSendingSocket(); if (!receiveCompleted) { ReceiveCallback(this, receiveAsyncEventArgs); } } catch (Exception) { try { s.Dispose(); } catch (Exception) { // ignore } throw; } return s; } internal static void WriteConnectionPreemble(Socket socket, GrainId grainId) { int size = 0; byte[] grainIdByteArray = null; if (grainId != null) { grainIdByteArray = grainId.ToByteArray(); size += grainIdByteArray.Length; } ByteArrayBuilder sizeArray = new ByteArrayBuilder(); sizeArray.Append(size); socket.Send(sizeArray.ToBytes()); // The size of the data that is coming next. //socket.Send(guid.ToByteArray()); // The guid of client/silo id if (grainId != null) { // No need to send in a loop. // From MSDN: If you are using a connection-oriented protocol, Send will block until all of the bytes in the buffer are sent, // unless a time-out was set by using Socket.SendTimeout. // If the time-out value was exceeded, the Send call will throw a SocketException. socket.Send(grainIdByteArray); // The grainId of the client } } // We start an asynch receive, with this callback, off of every send socket. // Since we should never see data coming in on these sockets, having the receive complete means that // the socket is in an unknown state and we should close it and try again. private static void ReceiveCallback(object sender, SocketAsyncEventArgs socketAsyncEventArgs) { var t = socketAsyncEventArgs.UserToken as Tuple<Socket, IPEndPoint, SocketManager>; try { t?.Item3.InvalidateEntry(t.Item2); } catch (Exception ex) { LogManager.GetLogger("SocketManager", LoggerType.Runtime).Error(ErrorCode.Messaging_Socket_ReceiveError, $"ReceiveCallback: {t?.Item2}", ex); } finally { socketAsyncEventArgs.Dispose(); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "s")] internal void ReturnSendingSocket(Socket s) { // Do nothing -- the socket will get cleaned up when it gets flushed from the cache } private static void FlushHandler(Object sender, LRU<IPEndPoint, Socket>.FlushEventArgs args) { if (args.Value == null) return; CloseSocket(args.Value); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal void InvalidateEntry(IPEndPoint target) { Socket socket; if (!cache.RemoveKey(target, out socket)) return; CloseSocket(socket); NetworkingStatisticsGroup.OnClosedSendingSocket(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // Note that this method assumes that there are no other threads accessing this object while this method runs. // Since this is true for the MessageCenter's use of this object, we don't lock around all calls to avoid the overhead. internal void Stop() { // Clear() on an LRU<> calls the flush handler on every item, so no need to manually close the sockets. cache.Clear(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] internal static void CloseSocket(Socket s) { if (s == null) { return; } try { s.Shutdown(SocketShutdown.Both); } catch (ObjectDisposedException) { // Socket is already closed -- we're done here return; } catch (Exception) { // Ignore } try { s.Disconnect(false); } catch (Exception) { // Ignore } try { s.Dispose(); } catch (Exception) { // Ignore } } } }
//========================================================================================== // // OpenNETCF.Windows.Forms.Context // Copyright (c) 2003, OpenNETCF.org // // This library is free software; you can redistribute it and/or modify it under // the terms of the OpenNETCF.org Shared Source License. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License // for more details. // // You should have received a copy of the OpenNETCF.org Shared Source License // along with this library; if not, email licensing@opennetcf.org to request a copy. // // If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please // email licensing@opennetcf.org. // // For general enquiries, email enquiries@opennetcf.org or visit our website at: // http://www.opennetcf.org // // !!! A HUGE thank-you goes out to Casey Chesnut for supplying this class library !!! // !!! You can contact Casey at http://www.brains-n-brawn.com !!! // //========================================================================================== using System; using System.Text; namespace FlickrNet.Security.Cryptography.NativeMethods { internal class Context { //static constructor static Context() { FindWoteInfo(); } private static void FindWoteInfo() { try { ProviderInfo [] pia = Prov.EnumProviders(); isCryptoApi = true; foreach(ProviderInfo pi in pia) { if(pi.name == ProvName.MS_ENHANCED_PROV) isEnhanced = true; if(pi.type == ProvType.DSS_DH) isDsa = true; } if(isEnhanced == false) provName = ProvName.MS_DEF_PROV; //dont default to enhanced anymore } catch(MissingMethodException) //mme { //dll or method is missing //properties default to false; } //all other exceptions bubble up } private static bool isCryptoApi = false; public static bool IsCryptoApi { get { return isCryptoApi; } } private static bool isEnhanced = false; public static bool IsEnhanced { get { return isEnhanced; } } private static bool isDsa = false; public static bool IsDsa { get { return isDsa; } } private static IntPtr prov = IntPtr.Zero; public static IntPtr Provider { get{return prov;} set{prov=value;} } private static ProvType provType = ProvType.RSA_FULL; public static ProvType ProviderType { get{return provType;} set{provType=value;} } private static string provName = ProvName.MS_ENHANCED_PROV; public static string ProviderName { get{return provName;} set{provName=value;} } private static string container = "bNbContainer"; public static string KeyContainer { get{return container;} set{container=value;} } public static void ResetKeySet() { IntPtr prov = AcquireContext(container, provName, provType, ContextFlag.DELETEKEYSET); Context.ReleaseContext(prov); prov = AcquireContext(container, provName, provType, ContextFlag.NEWKEYSET); Context.ReleaseContext(prov); } /// <summary> /// MissingMethodException. call AcquireContext instead /// </summary> public static IntPtr CpAcquireContext(string container, ContextFlag flag) { IntPtr prov; StringBuilder sb = new StringBuilder(container); byte[] vTable = new byte[0]; //VTableProvStruc with callbacks bool retVal = Crypto.CPAcquireContext(out prov, sb, (uint) flag, vTable); ErrCode ec = Error.HandleRetVal(retVal); return prov; } public static IntPtr AcquireContext() { return AcquireContext(container, provName, provType, ContextFlag.NONE); } public static IntPtr AcquireContext(string container) { return AcquireContext(container, provName, provType, ContextFlag.NONE); } public static IntPtr AcquireContext(ProvType provType) { return AcquireContext(null, null, provType, ContextFlag.NONE); } public static IntPtr AcquireContext(string provName, ProvType provType) { return AcquireContext(null, provName, provType, ContextFlag.NONE); } public static IntPtr AcquireContext(string provName, ProvType provType, ContextFlag conFlag) { return AcquireContext(null, provName, provType, conFlag); } public static IntPtr AcquireContext(string conName, string provName, ProvType provType) { return AcquireContext(conName, provName, provType, ContextFlag.NONE); } public static IntPtr AcquireContext(string conName, string provName, ProvType provType, ContextFlag conFlag) { IntPtr hProv; bool retVal = Crypto.CryptAcquireContext(out hProv, conName, provName, (uint) provType, (uint) conFlag); ErrCode ec = Error.HandleRetVal(retVal, ErrCode.NTE_BAD_KEYSET); if(ec == ErrCode.NTE_BAD_KEYSET) //try creating a new key container { retVal = Crypto.CryptAcquireContext(out hProv, conName, provName, (uint) provType, (uint) ContextFlag.NEWKEYSET); ec = Error.HandleRetVal(retVal); } if(hProv == IntPtr.Zero) throw new Exception("bNb.Sec: " + ec.ToString()); return hProv; } public static void ReleaseContext(IntPtr prov) { uint reserved = 0; if(prov != IntPtr.Zero) { bool retVal = Crypto.CryptReleaseContext(prov, reserved); ErrCode ec = Error.HandleRetVal(retVal); //dont exception } } /// <summary> /// INVALID_PARAMETER. no need to ever call this /// </summary> public static void ContextAddRef(IntPtr prov) { uint reserved = 0; uint flags = 0; bool retVal = Crypto.CryptContextAddRef(prov, ref reserved, flags); ErrCode ec = Error.HandleRetVal(retVal); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public class RegistrationBuilderAttributedOverrideUnitTests { public interface IContractA { } public interface IContractB { } public class AB : IContractA, IContractB { } private static class ContractNames { public const string ContractX = "X"; public const string ContractY = "Y"; } private static class MetadataKeys { public const string MetadataKeyP = "P"; public const string MetadataKeyQ = "Q"; } private static class MetadataValues { public const string MetadataValueN = "N"; public const string MetadataValueO = "O"; } // Flattened so that we can be sure nothing funky is going on in the base type private static void AssertHasDeclaredAttributesUnderConvention<TSource>(RegistrationBuilder convention) { AssertHasAttributesUnderConvention<TSource>(convention, typeof(TSource).GetCustomAttributes(true)); } private static void AssertHasAttributesUnderConvention<TSource>(RegistrationBuilder convention, IEnumerable<object> expected) { TypeInfo mapped = convention.MapType(typeof(TSource).GetTypeInfo()); var applied = mapped.GetCustomAttributes(true); // Was: CollectionAssert.AreEquivalent(expected, applied) - output is not much good. AssertEquivalentAttributes(expected, applied); } private static PropertyInfo GetPropertyFromAccessor<T>(Expression<Func<T, object>> property) { return (PropertyInfo)((MemberExpression)property.Body).Member; } private static void AssertHasDeclaredAttributesUnderConvention<TSource>(Expression<Func<TSource, object>> property, RegistrationBuilder convention) { PropertyInfo pi = GetPropertyFromAccessor(property); AssertHasAttributesUnderConvention<TSource>(property, convention, pi.GetCustomAttributes(true)); } private static void AssertHasAttributesUnderConvention<TSource>(Expression<Func<TSource, object>> property, RegistrationBuilder convention, IEnumerable<object> expected) { TypeInfo mapped = convention.MapType(typeof(TSource).GetTypeInfo()); PropertyInfo pi = GetPropertyFromAccessor(property); var applied = mapped.GetProperty(pi.Name).GetCustomAttributes(true); // Was: CollectionAssert.AreEquivalent(expected, applied) - output is not much good. AssertEquivalentAttributes(expected, applied); } private static void AssertEquivalentAttributes(IEnumerable<object> expected, IEnumerable<object> applied) { var expectedRemaining = expected.ToList(); var unexpected = new List<object>(); foreach (var appl in applied) { var matching = expectedRemaining.FirstOrDefault(e => object.Equals(e, appl)); if (matching == null) { unexpected.Add(appl); } else { expectedRemaining.Remove(matching); } } var failures = new List<string>(); if (expectedRemaining.Any()) { failures.Add("Expected attributes: " + string.Join(", ", expectedRemaining)); } if (unexpected.Any()) { failures.Add("Did not expect attributes: " + string.Join(", ", unexpected)); } Assert.Empty(failures); } // This set of tests is for exports at the class declaration level private static RegistrationBuilder ConfigureExportInterfaceConvention<TPart>() { var convention = new RegistrationBuilder(); convention.ForType<TPart>() .Export(eb => eb.AsContractType<IContractA>() .AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN)); return convention; } private static object[] ExportInterfaceConventionAttributes = new object[] { new ExportAttribute(typeof(IContractA)), new ExportMetadataAttribute(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN) }; public class NoClassDeclarationOverrides : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_NoOverrides_ConventionApplied() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<NoClassDeclarationOverrides>(); AssertHasAttributesUnderConvention<NoClassDeclarationOverrides>(convention, ExportInterfaceConventionAttributes); } [Export(typeof(IContractB))] public class ExportContractBClassDeclarationOverride : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_ExportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<ExportContractBClassDeclarationOverride>(); AssertHasDeclaredAttributesUnderConvention<ExportContractBClassDeclarationOverride>(convention); } [ExportMetadata(MetadataKeys.MetadataKeyQ, MetadataValues.MetadataValueO)] public class ExportJustMetadataOverride : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_JustMetadataOverride_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<ExportJustMetadataOverride>(); AssertHasDeclaredAttributesUnderConvention<ExportJustMetadataOverride>(convention); } [InheritedExport(typeof(IContractA))] public class InheritedExportContractAClassDeclarationOverride : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_InheritedExportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<InheritedExportContractAClassDeclarationOverride>(); AssertHasDeclaredAttributesUnderConvention<InheritedExportContractAClassDeclarationOverride>(convention); } [InheritedExport(typeof(IContractA))] public class BaseWithInheritedExport { } public class InheritedExportOnBaseClassDeclaration : BaseWithInheritedExport, IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_InheritedExportOnBaseClassDeclaration_ConventionApplied() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<InheritedExportOnBaseClassDeclaration>(); AssertHasAttributesUnderConvention<InheritedExportOnBaseClassDeclaration>(convention, ExportInterfaceConventionAttributes.Concat(new object[] { new InheritedExportAttribute(typeof(IContractA)) })); } public class CustomExportAttribute : ExportAttribute { } [CustomExport] public class CustomExportClassDeclarationOverride : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_CustomExportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<CustomExportClassDeclarationOverride>(); AssertHasDeclaredAttributesUnderConvention<CustomExportClassDeclarationOverride>(convention); } [MetadataAttribute] public class CustomMetadataAttribute : Attribute { public string Z { get { return "Z"; } } } [CustomMetadata] public class CustomMetadataClassDeclarationOverride : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_CustomMetadataAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<CustomMetadataClassDeclarationOverride>(); AssertHasDeclaredAttributesUnderConvention<CustomMetadataClassDeclarationOverride>(convention); } [PartCreationPolicy(CreationPolicy.NonShared), PartMetadata(MetadataKeys.MetadataKeyQ, MetadataValues.MetadataValueO), PartNotDiscoverable] public class NonExportClassDeclarationAttributes : IContractA, IContractB { } [Fact] public void ExportInterfaceConvention_NonExportClassDeclarationAttributes_ConventionApplied() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<NonExportClassDeclarationAttributes>(); var unionOfConventionAndDeclared = typeof(NonExportClassDeclarationAttributes) .GetCustomAttributes(true) .Concat(ExportInterfaceConventionAttributes) .ToArray(); AssertHasAttributesUnderConvention<NonExportClassDeclarationAttributes>(convention, unionOfConventionAndDeclared); } public class ExportAtProperty { [Export] public IContractA A { get; set; } } [Fact] public void ExportInterfacesConvention_UnrelatedExportOnProperty_ConventionApplied() { RegistrationBuilder convention = ConfigureExportInterfaceConvention<ExportAtProperty>(); AssertHasAttributesUnderConvention<ExportAtProperty>(convention, ExportInterfaceConventionAttributes); } // This set of tests is for exports at the property level private static RegistrationBuilder ConfigureExportPropertyConvention<TPart>(Expression<Func<TPart, object>> property) { var convention = new RegistrationBuilder(); convention.ForType<TPart>() .ExportProperty(property, eb => eb.AsContractType<IContractA>() .AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN)); return convention; } private static object[] ExportPropertyConventionAttributes = new object[] { new ExportAttribute(typeof(IContractA)), new ExportMetadataAttribute(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN) }; public class NoPropertyDeclarationOverrides { public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_NoOverrides_ConventionApplied() { RegistrationBuilder convention = ConfigureExportPropertyConvention<NoPropertyDeclarationOverrides>(t => t.AB); AssertHasAttributesUnderConvention<NoPropertyDeclarationOverrides>(t => t.AB, convention, ExportPropertyConventionAttributes); } public class ExportContractBPropertyDeclarationOverride { [Export(typeof(IContractB))] public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_ExportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportPropertyConvention<ExportContractBPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<ExportContractBPropertyDeclarationOverride>(t => t.AB, convention); } public class ExportJustMetadataPropertyDeclarationOverride { [ExportMetadata(MetadataKeys.MetadataKeyQ, MetadataValues.MetadataValueO)] public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_JustMetadataOverride_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportPropertyConvention<ExportJustMetadataPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<ExportJustMetadataPropertyDeclarationOverride>(t => t.AB, convention); } public class CustomExportPropertyDeclarationOverride { [CustomExport] public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_CustomExportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportPropertyConvention<CustomExportPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<CustomExportPropertyDeclarationOverride>(t => t.AB, convention); } public class CustomMetadataPropertyDeclarationOverride { [CustomMetadata] public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_CustomMetadataAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureExportPropertyConvention<CustomMetadataPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<CustomMetadataPropertyDeclarationOverride>(t => t.AB, convention); } public class NonExportPropertyDeclarationAttributes { [Import, ImportMany] public AB AB { get; set; } } [Fact] public void ExportPropertyConvention_NonExportPropertyDeclarationAttributes_ConventionApplied() { RegistrationBuilder convention = ConfigureExportPropertyConvention<NonExportPropertyDeclarationAttributes>(t => t.AB); var unionOfConventionAndDeclared = typeof(NonExportPropertyDeclarationAttributes) .GetProperty("AB") .GetCustomAttributes(true) .Concat(ExportPropertyConventionAttributes) .ToArray(); AssertHasAttributesUnderConvention<NonExportPropertyDeclarationAttributes>(t => t.AB, convention, unionOfConventionAndDeclared); } // This set of tests is for imports at the property level private static RegistrationBuilder ConfigureImportPropertyConvention<TPart>(Expression<Func<TPart, object>> property) { var convention = new RegistrationBuilder(); convention.ForType<TPart>() .ImportProperty(property, ib => ib.AsMany(false).AsContractName(ContractNames.ContractX).AsContractType<AB>()); return convention; } private static object[] ImportPropertyConventionAttributes = new object[] { new ImportAttribute(ContractNames.ContractX, typeof(AB)) }; [Fact] public void ImportPropertyConvention_NoOverrides_ConventionApplied() { RegistrationBuilder convention = ConfigureImportPropertyConvention<NoPropertyDeclarationOverrides>(t => t.AB); AssertHasAttributesUnderConvention<NoPropertyDeclarationOverrides>(t => t.AB, convention, ImportPropertyConventionAttributes); } public class ImportContractYPropertyDeclarationOverride { [Import(ContractNames.ContractY)] public AB AB { get; set; } } [Fact] public void ImportPropertyConvention_ImportAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureImportPropertyConvention<ImportContractYPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<ImportContractYPropertyDeclarationOverride>(t => t.AB, convention); } public class ImportManyPropertyDeclarationOverride { [ImportMany] public AB[] AB { get; set; } } [Fact] public void ImportPropertyConvention_ImportManyAttribute_ConventionIgnored() { RegistrationBuilder convention = ConfigureImportPropertyConvention<ImportManyPropertyDeclarationOverride>(t => t.AB); AssertHasDeclaredAttributesUnderConvention<ImportManyPropertyDeclarationOverride>(t => t.AB, convention); } public class NonImportPropertyDeclarationAttributes { [Export, ExportMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN)] public AB AB { get; set; } } [Fact] public void ImportPropertyConvention_NonImportPropertyDeclarationAttributes_ConventionApplied() { RegistrationBuilder convention = ConfigureImportPropertyConvention<NonImportPropertyDeclarationAttributes>(t => t.AB); var unionOfConventionAndDeclared = typeof(NonImportPropertyDeclarationAttributes) .GetProperty("AB") .GetCustomAttributes(true) .Concat(ImportPropertyConventionAttributes) .ToArray(); AssertHasAttributesUnderConvention<NonImportPropertyDeclarationAttributes>(t => t.AB, convention, unionOfConventionAndDeclared); } // The following test is for importing constructors private class TwoConstructorsWithOverride { [ImportingConstructor] public TwoConstructorsWithOverride(IContractA a) { } public TwoConstructorsWithOverride(IContractA a, IContractB b) { } } [Fact] public void ConstructorConvention_OverrideOnDeclaration_ConventionIgnored() { var rb = new RegistrationBuilder(); rb.ForType<TwoConstructorsWithOverride>() .SelectConstructor(pi => new TwoConstructorsWithOverride(pi.Import<IContractA>(), pi.Import<IContractB>())); TypeInfo mapped = rb.MapType(typeof(TwoConstructorsWithOverride).GetTypeInfo()); ConstructorInfo conventional = mapped.GetConstructor(new[] { rb.MapType(typeof(IContractA).GetTypeInfo()), rb.MapType(typeof(IContractB).GetTypeInfo()) }); var conventionalAttrs = conventional.GetCustomAttributes(true); Assert.False(conventionalAttrs.Any()); ConstructorInfo overridden = mapped.GetConstructor(new[] { rb.MapType(typeof(IContractA).GetTypeInfo()) }); var overriddenAttr = overridden.GetCustomAttributes(true).Single(); Assert.Equal(new ImportingConstructorAttribute(), overriddenAttr); } // Tests follow for constructor parameters private static RegistrationBuilder ConfigureImportConstructorParameterConvention<TPart>() { var convention = new RegistrationBuilder(); convention.ForType<TPart>() .SelectConstructor(cis => cis.Single(), (ci, ib) => ib.AsMany(false).AsContractName(ContractNames.ContractX).AsContractType<IContractA>()); return convention; } private static object[] ImportParameterConventionAttributes = new object[] { new ImportAttribute(ContractNames.ContractX, typeof(IContractA)) }; private class NoConstructorParameterOverrides { public NoConstructorParameterOverrides(IContractA a) { } } [Fact] public void ConstructorParameterConvention_NoOverride_ConventionApplied() { RegistrationBuilder convention = ConfigureImportConstructorParameterConvention<NoConstructorParameterOverrides>(); TypeInfo mapped = convention.MapType(typeof(NoConstructorParameterOverrides).GetTypeInfo()); ParameterInfo pi = mapped.GetConstructors().Single().GetParameters().Single(); var actual = pi.GetCustomAttributes(true); AssertEquivalentAttributes(ImportParameterConventionAttributes, actual); } private class ConstructorParameterImportContractX { public ConstructorParameterImportContractX([Import(ContractNames.ContractX)] IContractA a) { } } [Fact] public void ConstructorParameterConvention_ImportOnDeclaration_ConventionIgnored() { RegistrationBuilder convention = ConfigureImportConstructorParameterConvention<ConstructorParameterImportContractX>(); TypeInfo mapped = convention.MapType(typeof(ConstructorParameterImportContractX).GetTypeInfo()); ParameterInfo pi = mapped.GetConstructors().Single().GetParameters().Single(); var actual = pi.GetCustomAttributes(true); AssertEquivalentAttributes(new object[] { new ImportAttribute(ContractNames.ContractX) }, actual); } // Tests for creation policy private static RegistrationBuilder ConfigureCreationPolicyConvention<T>() { var convention = new RegistrationBuilder(); convention.ForType<T>().SetCreationPolicy(CreationPolicy.NonShared); return convention; } private static readonly IEnumerable<object> CreationPolicyConventionAttributes = new[] { new PartCreationPolicyAttribute(CreationPolicy.NonShared) }; private class NoCreationPolicyDeclared { } [Fact] public void CreationPolicyConvention_NoCreationPolicyDeclared_ConventionApplied() { RegistrationBuilder convention = ConfigureCreationPolicyConvention<NoCreationPolicyDeclared>(); AssertHasAttributesUnderConvention<NoCreationPolicyDeclared>(convention, CreationPolicyConventionAttributes); } [PartCreationPolicy(CreationPolicy.Shared)] private class SetCreationPolicy { } [Fact] public void CreationPolicyConvention_CreationPolicyDeclared_ConventionIgnored() { RegistrationBuilder convention = ConfigureCreationPolicyConvention<SetCreationPolicy>(); AssertHasDeclaredAttributesUnderConvention<SetCreationPolicy>(convention); } [Export] private class UnrelatedToCreationPolicy { } [Fact] public void CreationPolicyConvention_UnrelatedAttributesDeclared_ConventionApplied() { RegistrationBuilder convention = ConfigureCreationPolicyConvention<UnrelatedToCreationPolicy>(); AssertHasAttributesUnderConvention<UnrelatedToCreationPolicy>(convention, CreationPolicyConventionAttributes.Concat(typeof(UnrelatedToCreationPolicy).GetCustomAttributes(true))); } // Tests for part discoverability [PartNotDiscoverable] private class NotDiscoverablePart { } [Fact] public void AnyConvention_NotDiscoverablePart_ConventionApplied() { var convention = new RegistrationBuilder(); convention.ForType<NotDiscoverablePart>().Export(); AssertHasAttributesUnderConvention<NotDiscoverablePart>(convention, new object[] { new PartNotDiscoverableAttribute(), new ExportAttribute() }); } // Tests for part metadata private static RegistrationBuilder ConfigurePartMetadataConvention<T>() { var convention = new RegistrationBuilder(); convention.ForType<T>().AddMetadata(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN); return convention; } private static readonly IEnumerable<object> PartMetadataConventionAttributes = new object[] { new PartMetadataAttribute(MetadataKeys.MetadataKeyP, MetadataValues.MetadataValueN) }; private class NoDeclaredPartMetadata { } [Fact] public void PartMetadataConvention_NoDeclaredMetadata_ConventionApplied() { RegistrationBuilder convention = ConfigurePartMetadataConvention<NoDeclaredPartMetadata>(); AssertHasAttributesUnderConvention<NoDeclaredPartMetadata>(convention, PartMetadataConventionAttributes); } [PartMetadata(MetadataKeys.MetadataKeyQ, MetadataValues.MetadataValueO)] private class PartMetadataQO { } [Fact] public void PartMetadataConvention_DeclaredQO_ConventionIgnored() { RegistrationBuilder convention = ConfigurePartMetadataConvention<PartMetadataQO>(); AssertHasDeclaredAttributesUnderConvention<PartMetadataQO>(convention); } [PartCreationPolicy(CreationPolicy.NonShared), Export] private class PartMetadataUnrelatedAttributes { } [Fact] public void PartMetadataConvention_UnrelatedDeclaredAttributes_ConventionApplied() { RegistrationBuilder convention = ConfigurePartMetadataConvention<PartMetadataUnrelatedAttributes>(); AssertHasAttributesUnderConvention<PartMetadataUnrelatedAttributes>(convention, PartMetadataConventionAttributes.Concat(typeof(PartMetadataUnrelatedAttributes).GetCustomAttributes(true))); } private interface IFoo { } [Export] private class ExportInterfacesExportOverride : IFoo { } private class ExportInterfacesExportConventionApplied : IFoo { } [Export(typeof(IFoo))] public class ExportInterfacesExportConvention : IFoo { } private static RegistrationBuilder ConfigureExportInterfacesConvention<T>() { var convention = new RegistrationBuilder(); convention.ForType<T>().ExportInterfaces((t) => true); return convention; } [Fact] public void ConfigureExportInterfaces_ExportInterfaces_Overridden() { RegistrationBuilder convention = ConfigureExportInterfacesConvention<ExportInterfacesExportOverride>(); AssertHasAttributesUnderConvention<ExportInterfacesExportOverride>(convention, typeof(ExportInterfacesExportOverride).GetCustomAttributes(true)); } [Fact] public void ConfigureExportInterfaces_ExportInterfaces_ConventionApplied() { RegistrationBuilder convention = ConfigureExportInterfacesConvention<ExportInterfacesExportConventionApplied>(); AssertHasAttributesUnderConvention<ExportInterfacesExportConventionApplied>(convention, typeof(ExportInterfacesExportConvention).GetCustomAttributes(true)); } // Tests for chained RCs private class ConventionTarget { } [Fact] public void ConventionsInInnerAndOuterRCs_InnerRCTakesPrecendence() { var innerConvention = new RegistrationBuilder(); innerConvention.ForType<ConventionTarget>().Export(eb => eb.AsContractName(ContractNames.ContractX)); TypeInfo innerType = innerConvention.MapType(typeof(ConventionTarget).GetTypeInfo()); var outerConvention = new RegistrationBuilder(); outerConvention.ForType<ConventionTarget>().Export(eb => eb.AsContractName(ContractNames.ContractY)); TypeInfo outerType = outerConvention.MapType(innerType/*.GetTypeInfo()*/); ExportAttribute export = outerType.GetCustomAttributes(false).OfType<ExportAttribute>().Single(); Assert.Equal(ContractNames.ContractX, export.ContractName); } } }
/* ** Copyright (c) Microsoft. All rights reserved. ** Licensed under the MIT license. ** See LICENSE file in the project root for full license information. ** ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /******************** ** IDEA Encryption ** ********************* ** IDEA - International Data Encryption Algorithm. ** Based on code presented in Applied Cryptography by Bruce Schneier. ** Which was based on code developed by Xuejia Lai and James L. Massey. ** Other modifications made by Colin Plumb. ** */ /*********** ** DoIDEA ** ************ ** Perform IDEA encryption. Note that we time encryption & decryption ** time as being a single loop. */ using System; public class IDEAEncryption : IDEAStruct { public override string Name() { return "IDEA"; } public override double Run() { int i; char[] Z = new char[global.KEYLEN]; char[] DK = new char[global.KEYLEN]; char[] userkey = new char[8]; long accumtime; double iterations; byte[] plain1; /* First plaintext buffer */ byte[] crypt1; /* Encryption buffer */ byte[] plain2; /* Second plaintext buffer */ /* ** Re-init random-number generator. */ ByteMark.randnum(3); /* ** Build an encryption/decryption key */ for (i = 0; i < 8; i++) userkey[i] = (char)(ByteMark.abs_randwc(60000) & 0xFFFF); for (i = 0; i < global.KEYLEN; i++) Z[i] = (char)0; /* ** Compute encryption/decryption subkeys */ en_key_idea(userkey, Z); de_key_idea(Z, DK); /* ** Allocate memory for buffers. We'll make 3, called plain1, ** crypt1, and plain2. It works like this: ** plain1 >>encrypt>> crypt1 >>decrypt>> plain2. ** So, plain1 and plain2 should match. ** Also, fill up plain1 with sample text. */ plain1 = new byte[this.arraysize]; crypt1 = new byte[this.arraysize]; plain2 = new byte[this.arraysize]; /* ** Note that we build the "plaintext" by simply loading ** the array up with random numbers. */ for (i = 0; i < this.arraysize; i++) plain1[i] = (byte)(ByteMark.abs_randwc(255) & 0xFF); /* ** See if we need to perform self adjustment loop. */ if (this.adjust == 0) { /* ** Do self-adjustment. This involves initializing the ** # of loops and increasing the loop count until we ** get a number of loops that we can use. */ for (this.loops = 100; this.loops < global.MAXIDEALOOPS; this.loops += 10) if (DoIDEAIteration(plain1, crypt1, plain2, this.arraysize, this.loops, Z, DK) > global.min_ticks) break; } /* ** All's well if we get here. Do the test. */ accumtime = 0; iterations = (double)0.0; do { accumtime += DoIDEAIteration(plain1, crypt1, plain2, this.arraysize, this.loops, Z, DK); iterations += (double)this.loops; } while (ByteMark.TicksToSecs(accumtime) < this.request_secs); /* ** Clean up, calculate results, and go home. Be sure to ** show that we don't have to rerun adjustment code. */ if (this.adjust == 0) this.adjust = 1; return (iterations / ByteMark.TicksToFracSecs(accumtime)); } /******************** ** DoIDEAIteration ** ********************* ** Execute a single iteration of the IDEA encryption algorithm. ** Actually, a single iteration is one encryption and one ** decryption. */ private static long DoIDEAIteration(byte[] plain1, byte[] crypt1, byte[] plain2, int arraysize, int nloops, char[] Z, char[] DK) { int i; int j; long elapsed; /* ** Start the stopwatch. */ elapsed = ByteMark.StartStopwatch(); /* ** Do everything for nloops. */ for (i = 0; i < nloops; i++) { for (j = 0; j < arraysize; j += 8) cipher_idea(plain1, crypt1, j, Z); /* Encrypt */ for (j = 0; j < arraysize; j += 8) cipher_idea(crypt1, plain2, j, DK); /* Decrypt */ } // Validate output for (j = 0; j < arraysize; j++) if (plain1[j] != plain2[j]) { string error = String.Format("IDEA: error at index {0} ({1} <> {2})!", j, (int)plain1[j], (int)plain2[j]); throw new Exception(error); } /* ** Get elapsed time. */ return (ByteMark.StopStopwatch(elapsed)); } /******** ** mul ** ********* ** Performs multiplication, modulo (2**16)+1. This code is structured ** on the assumption that untaken branches are cheaper than taken ** branches, and that the compiler doesn't schedule branches. */ private static char mul(char a, char b) { int p; if (a != 0) { if (b != 0) { p = unchecked((int)(a * b)); b = low16(p); a = unchecked((char)(p >> 16)); return unchecked((char)(b - a + (b < a ? 1 : 0))); } else return unchecked((char)(1 - a)); } else return unchecked((char)(1 - b)); } /******** ** inv ** ********* ** Compute multiplicative inverse of x, modulo (2**16)+1 ** using Euclid's GCD algorithm. It is unrolled twice ** to avoid swapping the meaning of the registers. And ** some subtracts are changed to adds. */ private static char inv(char x) { char t0, t1; char q, y; if (x <= 1) return (x); /* 0 and 1 are self-inverse */ t1 = (char)(0x10001 / x); y = (char)(0x10001 % x); if (y == 1) return (low16(1 - t1)); t0 = (char)1; do { q = (char)(x / y); x = (char)(x % y); t0 += (char)(q * t1); if (x == 1) return (t0); q = (char)(y / x); y = (char)(y % x); t1 += (char)(q * t0); } while (y != 1); return (low16(1 - t1)); } /**************** ** en_key_idea ** ***************** ** Compute IDEA encryption subkeys Z */ private static void en_key_idea(char[] userkey, char[] Z) { int i, j; // NOTE: The temp variables (tmp,idx) were not in original C code. // It may affect numbers a bit. int tmp = 0; int idx = 0; /* ** shifts */ for (j = 0; j < 8; j++) Z[j + idx] = userkey[tmp++]; for (i = 0; j < global.KEYLEN; j++) { i++; Z[i + 7 + idx] = unchecked((char)((Z[(i & 7) + idx] << 9) | (Z[((i + 1) & 7) + idx] >> 7))); idx += (i & 8); i &= 7; } return; } /**************** ** de_key_idea ** ***************** ** Compute IDEA decryption subkeys DK from encryption ** subkeys Z. */ private static void de_key_idea(char[] Z, char[] DK) { char[] TT = new char[global.KEYLEN]; int j; char t1, t2, t3; short p = (short)global.KEYLEN; // NOTE: Another local variable was needed here but was not in original C. // May affect benchmark numbers. int tmpZ = 0; t1 = inv(Z[tmpZ++]); t2 = unchecked((char)(-Z[tmpZ++])); t3 = unchecked((char)(-Z[tmpZ++])); TT[--p] = inv(Z[tmpZ++]); TT[--p] = t3; TT[--p] = t2; TT[--p] = t1; for (j = 1; j < global.ROUNDS; j++) { t1 = Z[tmpZ++]; TT[--p] = Z[tmpZ++]; TT[--p] = t1; t1 = inv(Z[tmpZ++]); t2 = unchecked((char)(-Z[tmpZ++])); t3 = unchecked((char)(-Z[tmpZ++])); TT[--p] = inv(Z[tmpZ++]); TT[--p] = t2; TT[--p] = t3; TT[--p] = t1; } t1 = Z[tmpZ++]; TT[--p] = Z[tmpZ++]; TT[--p] = t1; t1 = inv(Z[tmpZ++]); t2 = unchecked((char)(-Z[tmpZ++])); t3 = unchecked((char)(-Z[tmpZ++])); TT[--p] = inv(Z[tmpZ++]); TT[--p] = t3; TT[--p] = t2; TT[--p] = t1; /* ** Copy and destroy temp copy */ for (j = 0, p = 0; j < global.KEYLEN; j++) { DK[j] = TT[p]; TT[p++] = (char)0; } return; } /* ** MUL(x,y) ** This #define creates a macro that computes x=x*y modulo 0x10001. ** Requires temps t16 and t32. Also requires y to be strictly 16 ** bits. Here, I am using the simplest form. May not be the ** fastest. -- RG */ /* #define MUL(x,y) (x=mul(low16(x),y)) */ /**************** ** cipher_idea ** ***************** ** IDEA encryption/decryption algorithm. */ // NOTE: args in and out were renamed because in/out are reserved words // in cool. private static void cipher_idea(byte[] xin, byte[] xout, int offset, char[] Z) { char x1, x2, x3, x4, t1, t2; int r = global.ROUNDS; // NOTE: More local variables (AND AN ARG) were required by this // function. The original C code did not need/have these. int offset2 = offset; int idx = 0; // NOTE: Because of big endian (and lack of pointers) I had to // force two bytes into the chars instead of how original // c code did it. unchecked { x1 = (char)((xin[offset]) | (xin[offset + 1] << 8)); x2 = (char)((xin[offset + 2]) | (xin[offset + 3] << 8)); x3 = (char)((xin[offset + 4]) | (xin[offset + 5] << 8)); x4 = (char)((xin[offset + 6]) | (xin[offset + 7] << 8)); do { MUL(ref x1, Z[idx++]); x2 += Z[idx++]; x3 += Z[idx++]; MUL(ref x4, Z[idx++]); t2 = (char)(x1 ^ x3); MUL(ref t2, Z[idx++]); t1 = (char)(t2 + (x2 ^ x4)); MUL(ref t1, Z[idx++]); t2 = (char)(t1 + t2); x1 ^= t1; x4 ^= t2; t2 ^= x2; x2 = (char)(x3 ^ t1); x3 = t2; } while ((--r) != 0); MUL(ref x1, Z[idx++]); xout[offset2] = (byte)(x1 & 0x00ff); xout[offset2 + 1] = (byte)((x1 >> 8) & 0x00ff); xout[offset2 + 2] = (byte)((x3 + Z[idx]) & 0x00ff); xout[offset2 + 3] = (byte)(((x3 + Z[idx++]) >> 8) & 0x00ff); xout[offset2 + 4] = (byte)((x2 + Z[idx]) & 0x00ff); xout[offset2 + 5] = (byte)(((x2 + Z[idx++]) >> 8) & 0x00ff); MUL(ref x4, Z[idx]); xout[offset2 + 6] = (byte)(x4 & 0x00ff); xout[offset2 + 7] = (byte)((x4 >> 8) & 0x00ff); } return; } // These were macros in the original C code /* #define low16(x) ((x) & 0x0FFFF) */ private static char low16(int x) { return (char)((x) & 0x0FFFF); } /* #define MUL(x,y) (x=mul(low16(x),y)) */ private static void MUL(ref char x, char y) { x = mul(low16(x), y); } }
namespace UnitTest { using System; using System.Text; using Bond; using Bond.Protocols; using Bond.IO; internal static class Random { static readonly System.Random random; static Random() { var seed = (int)DateTime.Now.ToBinary(); random = new System.Random(seed); System.Diagnostics.Trace.TraceInformation("Random seed {0}", seed); } public static T Init<T>() { return Deserialize<T>.From(new RandomReader(random)); } public static T Init<T>(IFactory factory) { return new Deserializer<RandomReader>(typeof(T), factory) .Deserialize<T>(new RandomReader(random)); } public static T Init<T>(Factory factory) { return new Deserializer<RandomReader>(typeof(T), factory) .Deserialize<T>(new RandomReader(random)); } } internal class RandomReader : IClonableUntaggedProtocolReader, ICloneable<RandomReader> { readonly System.Random random; const int MaxStringLength = 50; const int MaxContainerLength = 5; const int MaxContainerDepth = 5; int level; public RandomReader(System.Random random) { this.random = random; } RandomReader ICloneable<RandomReader>.Clone() { return this; } IClonableUntaggedProtocolReader ICloneable<IClonableUntaggedProtocolReader>.Clone() { return this; } public bool ReadFieldOmitted() { return false; } public int ReadContainerBegin() { if (++level == MaxContainerDepth) return 0; return random.Next(MaxContainerLength); } public void ReadContainerEnd() { --level; } public sbyte ReadInt8() { return (sbyte)random.Next(sbyte.MinValue, sbyte.MaxValue); } public void SkipInt8() { } public short ReadInt16() { return (short)random.Next(short.MinValue, short.MaxValue); } public void SkipInt16() { } public int ReadInt32() { return random.Next(int.MinValue, int.MaxValue); } public void SkipInt32() { } public long ReadInt64() { return BitConverter.ToInt64(GetRandomBytes(sizeof(long)), 0); } public void SkipInt64() { } public byte ReadUInt8() { return (byte)random.Next(byte.MinValue, byte.MaxValue); } public void SkipUInt8() { } public ushort ReadUInt16() { return (ushort)random.Next(ushort.MinValue, ushort.MaxValue); } public void SkipUInt16() { } public uint ReadUInt32() { return (uint)random.Next(); } public void SkipUInt32() { } public ulong ReadUInt64() { return (ulong)random.Next(); } public void SkipUInt64() { } public float ReadFloat() { return 3.14159F * random.Next(-100, 100); } public void SkipFloat() { } public double ReadDouble() { return ReadFloat(); } public void SkipDouble() { } public ArraySegment<byte> ReadBytes(int count) { return new ArraySegment<byte>(GetRandomBytes(count)); } public void SkipBytes(int count) { } public bool ReadBool() { return random.Next(0, 2) == 1; } public void SkipBool() { } public string ReadString() { var length = random.Next(MaxStringLength); var builder = new StringBuilder(length); for (var i = 0; i < length; i++) { builder.Append((char)(random.Next(32, 126))); } return builder.ToString(); } public void SkipString() { } public string ReadWString() { return ReadString(); } public void SkipWString() { } byte[] GetRandomBytes(int length) { var array = new byte[length]; random.NextBytes(array); return array; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.Providers { /// <summary> /// Providers configuration and loading error semantics: /// 1) We will only load the providers that were specified in the config. /// If a provider is not specified in the config, we will not attempt to load it. /// Specificaly, it means both storage and streaming providers are loaded only if configured. /// 2) If a provider is specified in the config, but was not loaded (no type found, or constructor failed, or Init failed), the silo will fail to start. /// /// Loading providers workflow and error handling implementation: /// 1) Load ProviderCategoryConfiguration. /// a) If CategoryConfiguration not found - it is not an error, continue. /// 2) Go over all assemblies and load all found providers and instantiate them via ProviderTypeManager. /// a) If a certain found provider type failed to get instantiated, it is not an error, continue. /// 3) Validate all providers were loaded: go over all provider config and check that we could indeed load and instantiate all of them. /// a) If failed to load or instantiate at least one configured provider, fail the silo start. /// 4) InitProviders: call Init on all loaded providers. /// a) Failure to init a provider wil result in silo failing to start. /// </summary> /// <typeparam name="TProvider"></typeparam> internal class ProviderLoader<TProvider> where TProvider : IProvider { private readonly Dictionary<string, TProvider> providers; private IDictionary<string, IProviderConfiguration> providerConfigs; private readonly TraceLogger logger; public ProviderLoader() { logger = TraceLogger.GetLogger("ProviderLoader/" + typeof(TProvider).Name, TraceLogger.LoggerType.Runtime); providers = new Dictionary<string, TProvider>(); } public void LoadProviders(IDictionary<string, IProviderConfiguration> configs, IProviderManager providerManager) { providerConfigs = configs ?? new Dictionary<string, IProviderConfiguration>(); foreach (IProviderConfiguration providerConfig in providerConfigs.Values) ((ProviderConfiguration)providerConfig).SetProviderManager(providerManager); // Load providers ProviderTypeLoader.AddProviderTypeManager(t => typeof(TProvider).IsAssignableFrom(t), RegisterProviderType); ValidateProviders(); } private void ValidateProviders() { foreach (IProviderConfiguration providerConfig in providerConfigs.Values) { TProvider provider; ProviderConfiguration fullConfig = (ProviderConfiguration) providerConfig; if (providers.TryGetValue(providerConfig.Name, out provider)) { logger.Verbose(ErrorCode.Provider_ProviderLoadedOk, "Provider of type {0} name {1} located ok.", fullConfig.Type, fullConfig.Name); continue; } string msg = string.Format("Provider of type {0} name {1} was not loaded." + "Please check that you deployed the assembly in which the provider class is defined to the execution folder.", fullConfig.Type, fullConfig.Name); logger.Error(ErrorCode.Provider_ConfiguredProviderNotLoaded, msg); throw new OrleansException(msg); } } public async Task InitProviders(IProviderRuntime providerRuntime) { Dictionary<string, TProvider> copy; lock (providers) { copy = providers.ToDictionary(p => p.Key, p => p.Value); } foreach (var provider in copy) { string name = provider.Key; try { await provider.Value.Init(provider.Key, providerRuntime, providerConfigs[name]); } catch (Exception exc) { logger.Error(ErrorCode.Provider_ErrorFromInit, string.Format("Exception initializing provider Name={0} Type={1}", name, provider), exc); throw; } } } // used only for testing internal void AddProvider(string name, TProvider provider, IProviderConfiguration config) { lock (providers) { providers.Add(name, provider); } } internal int GetNumLoadedProviders() { lock (providers) { return providers.Count; } } public TProvider GetProvider(string name, bool caseInsensitive = false) { TProvider provider; if (!TryGetProvider(name, out provider, caseInsensitive)) { throw new KeyNotFoundException(string.Format("Cannot find provider of type {0} with Name={1}", typeof(TProvider).FullName, name)); } return provider; } public bool TryGetProvider(string name, out TProvider provider, bool caseInsensitive = false) { lock (providers) { if (providers.TryGetValue(name, out provider)) return provider != null; if (!caseInsensitive) return provider != null; // Try all lower case if (!providers.TryGetValue(name.ToLowerInvariant(), out provider)) { // Try all upper case providers.TryGetValue(name.ToUpperInvariant(), out provider); } } return provider != null; } public IList<TProvider> GetProviders() { lock (providers) { return providers.Values.ToList(); } } public TProvider GetDefaultProvider(string defaultProviderName) { lock (providers) { TProvider provider; // Use provider named "Default" if present if (!providers.TryGetValue(defaultProviderName, out provider)) { // Otherwise, if there is only a single provider listed, use that if (providers.Count == 1) provider = providers.First().Value; } if (provider != null) return provider; string errMsg = "Cannot find default provider for " + typeof(TProvider); logger.Error(ErrorCode.Provider_NoDefaultProvider, errMsg); throw new InvalidOperationException(errMsg); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void RegisterProviderType(Type t) { // First, figure out the provider type name var typeName = TypeUtils.GetFullName(t); // Now see if we have any config entries for that type // If there's no config entry, then we don't load the type Type[] constructorBindingTypes = new[] { typeof(string), typeof(XmlElement) }; foreach (var entry in providerConfigs.Values) { var fullConfig = (ProviderConfiguration) entry; if (fullConfig.Type != typeName) continue; // Found one! Now look for an appropriate constructor; try TProvider(string, Dictionary<string,string>) first var constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorBindingTypes, null); var parms = new object[] { typeName, entry.Properties }; if (constructor == null) { // See if there's a default constructor to use, if there's no two-parameter constructor constructor = t.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); parms = new object[0]; } if (constructor == null) continue; TProvider instance; try { instance = (TProvider)constructor.Invoke(parms); } catch (Exception ex) { logger.Warn(ErrorCode.Provider_InstanceConstructionError1, "Error constructing an instance of a " + typeName + " provider using type " + t.Name + " for provider with name " + fullConfig.Name, ex); return; } lock (providers) { providers[fullConfig.Name] = instance; } logger.Info(ErrorCode.Provider_Loaded, "Loaded provider of type {0} Name={1}", typeName, fullConfig.Name); } } } }
using UnityEngine; using System.Collections; using System; namespace Lockstep { [Serializable] public struct Vector2d : ICommandData { [FixedNumber] public long x; [FixedNumber] public long y; #region Constructors public Vector2d(long xFixed, long yFixed) { this.x = xFixed; this.y = yFixed; } public Vector2d(int xInt, int yInt) { this.x = xInt << FixedMath.SHIFT_AMOUNT; this.y = yInt << FixedMath.SHIFT_AMOUNT; } public Vector2d(Vector2 vec2) { this.x = FixedMath.Create(vec2.x); this.y = FixedMath.Create(vec2.y); } public Vector2d(float xFloat, float yFloat) { this.x = FixedMath.Create(xFloat); this.y = FixedMath.Create(yFloat); } public Vector2d(double xDoub, double yDoub) { this.x = FixedMath.Create(xDoub); this.y = FixedMath.Create(yDoub); } public Vector2d(Vector3 vec) { this.x = FixedMath.Create(vec.x); this.y = FixedMath.Create(vec.z); } #endregion #region Local Math public void Subtract(ref Vector2d other) { this.x -= other.x; this.y -= other.y; } public void Add(ref Vector2d other) { this.x += other.x; this.y += other.y; } /// <summary> /// This vector's square magnitude. /// </summary> /// <returns>The magnitude.</returns> public long SqrMagnitude() { return (this.x * this.x + this.y * this.y) >> FixedMath.SHIFT_AMOUNT; } /// <summary> /// This vector's magnitude. /// </summary> public long Magnitude() { temp1 = (this.x * this.x + this.y * this.y); if (temp1 == 0) return 0; temp1 >>= FixedMath.SHIFT_AMOUNT; return FixedMath.Sqrt(temp1); } public long FastMagnitude() { return this.x * this.x + this.y * this.y; } /// <summary> /// Normalize this vector. /// </summary> public void Normalize() { tempMag = this.Magnitude(); if (tempMag == 0) { return; } else if (tempMag == FixedMath.One) { return; } this.x = (this.x << FixedMath.SHIFT_AMOUNT) / tempMag; this.y = (this.y << FixedMath.SHIFT_AMOUNT) / tempMag; } public void Normalize(out long mag) { mag = this.Magnitude(); if (mag == 0) { return; } else if (mag == FixedMath.One) { return; } this.x = (this.x << FixedMath.SHIFT_AMOUNT) / mag; this.y = (this.y << FixedMath.SHIFT_AMOUNT) / mag; } public void FastNormalize() { //Blazing fast normalization when accuracy isn't needed tempMag = x > y ? x + y / 2 : x / 2 + y; const long errorFactor = 1000 * FixedMath.One / 1118; this.x = ((this.x << FixedMath.SHIFT_AMOUNT) / tempMag) * errorFactor >> FixedMath.SHIFT_AMOUNT; this.y = ((this.y << FixedMath.SHIFT_AMOUNT) / tempMag) * errorFactor >> FixedMath.SHIFT_AMOUNT; } public void Lerp(Vector2d target, long amount) { Lerp(target.x, target.y, amount); } /// <summary> /// Lerp this vector to target by amount. /// </summary> /// <param name="target">target.</param> /// <param name="amount">amount.</param> public void Lerp(long targetx, long targety, long amount) { if (amount >= FixedMath.One) { this.x = targetx; this.y = targety; return; } else if (amount <= 0) { return; } this.x = (targetx * amount + this.x * (FixedMath.One - amount)) >> FixedMath.SHIFT_AMOUNT; this.y = (targety * amount + this.y * (FixedMath.One - amount)) >> FixedMath.SHIFT_AMOUNT; } public Vector2d Lerped(Vector2d target, long amount) { Vector2d vec = this; vec.Lerp(target.x, target.y, amount); return vec; } public void Rotate(long cos, long sin) { temp1 = (this.x * cos + this.y * sin) >> FixedMath.SHIFT_AMOUNT; this.y = (this.x * -sin + this.y * cos) >> FixedMath.SHIFT_AMOUNT; this.x = temp1; } public Vector2d Rotated(long cos, long sin) { Vector2d vec = this; vec.Rotate(cos, sin); return vec; } public Vector2d Rotated(Vector2d rotation) { return Rotated(rotation.x, rotation.y); } public void RotateInverse(long cos, long sin) { Rotate(cos, -sin); } public void RotateRight() { temp1 = this.x; this.x = this.y; this.y = -temp1; } static Vector2d retVec = Vector2d.zero; public Vector2d rotatedRight { get { retVec.x = y; retVec.y = -x; return retVec; } } public Vector2d rotatedLeft { get { retVec.x = -y; retVec.y = x; return retVec; } } public void Reflect(long axisX, long axisY) { temp3 = this.Dot(axisX, axisY); temp1 = (axisX * temp3) >> FixedMath.SHIFT_AMOUNT; temp2 = (axisY * temp3) >> FixedMath.SHIFT_AMOUNT; this.x = temp1 + temp1 - this.x; this.y = temp2 + temp2 - this.y; } public void Reflect(long axisX, long axisY, long projection) { temp1 = (axisX * projection) >> FixedMath.SHIFT_AMOUNT; temp2 = (axisY * projection) >> FixedMath.SHIFT_AMOUNT; this.x = temp1 + temp1 - this.x; this.y = temp2 + temp2 - this.y; } public Vector2d Reflected(long axisX, long axisY) { Vector2d vec = this; vec.Reflect(axisX, axisY); return vec; } public long Dot(long otherX, long otherY) { return (this.x * otherX + this.y * otherY) >> FixedMath.SHIFT_AMOUNT; } public long Dot(Vector2d other) { return this.Dot(other.x, other.y); } public long Cross(long otherX, long otherY) { return (this.x * otherY - this.y * otherX) >> FixedMath.SHIFT_AMOUNT; } public long Cross(Vector2d vec) { return Cross(vec.x, vec.y); } static long temp1; static long temp2; static long temp3; static long tempMag; public long Distance(long otherX, long otherY) { temp1 = this.x - otherX; temp1 *= temp1; temp2 = this.y - otherY; temp2 *= temp2; return (FixedMath.Sqrt((temp1 + temp2) >> FixedMath.SHIFT_AMOUNT)); } public long Distance(Vector2d other) { return Distance(other.x, other.y); } public long SqrDistance(long otherX, long otherY) { temp1 = this.x - otherX; temp1 *= temp1; temp2 = this.y - otherY; temp2 *= temp2; return ((temp1 + temp2) >> FixedMath.SHIFT_AMOUNT); } /// <summary> /// Returns a value that is greater if the distance is greater. /// </summary> /// <returns>The FastDistance.</returns> public long FastDistance(long otherX, long otherY) { temp1 = this.x - otherX; temp1 *= temp1; temp2 = this.y - otherY; temp2 *= temp2; return (temp1 + temp2); } public bool NotZero() { return x.MoreThanEpsilon() || y.MoreThanEpsilon(); } #endregion #region Static Math public static readonly Vector2d defaultRotation = new Vector2d(1,0); public static readonly Vector2d up = new Vector2d(0, 1); public static readonly Vector2d right = new Vector2d(1, 0); public static readonly Vector2d down = new Vector2d(0, -1); public static readonly Vector2d left = new Vector2d(-1, 0); public static readonly Vector2d one = new Vector2d(1, 1); public static readonly Vector2d negative = new Vector2d(-1, -1); public static readonly Vector2d zero = new Vector2d(0, 0); public static readonly Vector2d radian0 = new Vector2d(1, 0); public static readonly Vector2d radian1 = new Vector2d(0, 1); public static readonly Vector2d radian2 = new Vector2d(-1, 0); public static readonly Vector2d radian3 = new Vector2d(0, -1); public static long Dot(long v1x, long v1y, long v2x, long v2y) { return (v1x * v2x + v1y * v2y) >> FixedMath.SHIFT_AMOUNT; } public static long Cross(long v1x, long v1y, long v2x, long v2y) { return (v1x * v2y - v1y * v2x) >> FixedMath.SHIFT_AMOUNT; } /// <summary> /// Note: Not deterministic. Use only for serialization and sending in Commands. /// </summary> /// <returns>The from angle.</returns> /// <param name="angle">Angle.</param> public static Vector2d CreateRotation(double angle) { return new Vector2d(Math.Cos(angle), Math.Sin(angle)); } public static Vector2d CreateRotation(float angle) { return CreateRotation((double)angle); } /// <summary> /// Deterministic! /// </summary> /// <returns>The rotation.</returns> /// <param name="angle">Angle.</param> public static Vector2d CreateRotation(long angle) { return new Vector2d(FixedMath.Trig.Cos(angle), FixedMath.Trig.Sin(angle)); } public Vector2d ToDirection() { return new Vector2d(y, x); } public Vector2d ToRotation() { return new Vector2d(y, x); } #endregion #region Convert public override string ToString() { return ( "(" + Math.Round(FixedMath.ToDouble(this.x), 2, MidpointRounding.AwayFromZero).ToString() + ", " + Math.Round(FixedMath.ToDouble(this.y), 2, MidpointRounding.AwayFromZero) + ")" ); } public Vector2 ToVector2() { return new Vector2( (float)FixedMath.ToDouble(this.x), (float)FixedMath.ToDouble(this.y) ); } public Vector3d ToVector3d(long z = 0) { return new Vector3d(x, y, z); } public Vector3 ToVector3(float z = 0f) { return new Vector3((float)FixedMath.ToDouble(this.x), z, (float)FixedMath.ToDouble(this.y)); } #endregion public override bool Equals(object obj) { if (obj is Vector2d) { return (Vector2d)obj == this; } return false; } #region Operators public static Vector2d operator +(Vector2d v1, Vector2d v2) { return new Vector2d(v1.x + v2.x, v1.y + v2.y); } public static Vector2d operator -(Vector2d v1, Vector2d v2) { return new Vector2d(v1.x - v2.x, v1.y - v2.y); } public static Vector2d operator *(Vector2d v1, long mag) { return new Vector2d((v1.x * mag) >> FixedMath.SHIFT_AMOUNT, (v1.y * mag) >> FixedMath.SHIFT_AMOUNT); } public static Vector2d operator *(Vector2d v1, int mag) { return new Vector2d((v1.x * mag), (v1.y * mag)); } public static Vector2d operator /(Vector2d v1, long div) { return new Vector2d(((v1.x << FixedMath.SHIFT_AMOUNT) / div), (v1.y << FixedMath.SHIFT_AMOUNT) / div); } public static Vector2d operator /(Vector2d v1, int div) { return new Vector2d((v1.x / div), v1.y / div); } public static Vector2d operator >>(Vector2d v1, int shift) { return new Vector2d(v1.x >> shift, v1.y >> shift); } public static bool operator ==(Vector2d v1, Vector2d v2) { return v1.x == v2.x && v1.y == v2.y; } public static bool operator !=(Vector2d v1, Vector2d v2) { return v1.x != v2.x || v1.y != v2.y; } #endregion public long GetLongHashCode() { return x * 31 + y * 7; } public int GetStateHash() { return (int)(GetLongHashCode() % int.MaxValue); } public override int GetHashCode() { return this.GetStateHash(); } public void Write(Writer writer) { writer.Write(this.x); writer.Write(this.y); } public void Read(Reader reader) { this.x = reader.ReadLong(); this.y = reader.ReadLong(); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.EnterpriseServer; using System.Xml; using System.Collections.Generic; using WebsitePanel.WebPortal; namespace WebsitePanel.Portal.UserControls { public class OrganizationMenuControl : WebsitePanelModuleBase { virtual public int PackageId { get { return PanelSecurity.PackageId; } set { } } virtual public int ItemID { get { return PanelRequest.ItemID; } set { } } private PackageContext cntx = null; virtual public PackageContext Cntx { get { if (cntx == null) cntx = PackagesHelper.GetCachedPackageContext(PackageId); return cntx; } } public bool ShortMenu = false; public bool ShowImg = false; public MenuItem OrganizationMenuRoot = null; public MenuItem ExchangeMenuRoot = null; public bool PutBlackBerryInExchange = false; public void BindMenu(MenuItemCollection items) { if ((PackageId <= 0) || (ItemID <= 0)) return; //Organization menu group; if (Cntx.Groups.ContainsKey(ResourceGroups.HostedOrganizations)) PrepareOrganizationMenuRoot(items); //Exchange menu group; if (Cntx.Groups.ContainsKey(ResourceGroups.Exchange)) PrepareExchangeMenuRoot(items); //BlackBerry Menu if (Cntx.Groups.ContainsKey(ResourceGroups.BlackBerry)) PrepareBlackBerryMenuRoot(items); //SharePoint menu group; if (Cntx.Groups.ContainsKey(ResourceGroups.SharepointFoundationServer)) PrepareSharePointMenuRoot(items); if (Cntx.Groups.ContainsKey(ResourceGroups.SharepointEnterpriseServer)) PrepareSharePointEnterpriseMenuRoot(items); //CRM Menu if (Cntx.Groups.ContainsKey(ResourceGroups.HostedCRM2013)) PrepareCRM2013MenuRoot(items); else if (Cntx.Groups.ContainsKey(ResourceGroups.HostedCRM)) PrepareCRMMenuRoot(items); //OCS Menu if (Cntx.Groups.ContainsKey(ResourceGroups.OCS)) PrepareOCSMenuRoot(items); //Lync Menu if (Cntx.Groups.ContainsKey(ResourceGroups.Lync)) PrepareLyncMenuRoot(items); //EnterpriseStorage Menu if (Cntx.Groups.ContainsKey(ResourceGroups.EnterpriseStorage)) PrepareEnterpriseStorageMenuRoot(items); //Remote Desktop Services Menu if (Cntx.Groups.ContainsKey(ResourceGroups.RDS)) PrepareRDSMenuRoot(items); } private void PrepareOrganizationMenuRoot(MenuItemCollection items) { bool hideItems = false; UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId); if (user != null) { if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, Cntx))) hideItems = true; } if (!hideItems) { if (ShortMenu) { PrepareOrganizationMenu(items); } else { MenuItem item; if (OrganizationMenuRoot != null) item = OrganizationMenuRoot; else item = new MenuItem(GetLocalizedString("Text.OrganizationGroup"), "", "", null); item.Selectable = false; PrepareOrganizationMenu(item.ChildItems); if ((item.ChildItems.Count > 0) && (OrganizationMenuRoot == null)) { items.Add(item); } OrganizationMenuRoot = item; } } } private void PrepareOrganizationMenu(MenuItemCollection items) { if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, Cntx) == false) { if (Utils.CheckQouta(Quotas.ORGANIZATION_DOMAINS, Cntx)) items.Add(CreateMenuItem("DomainNames", "org_domains")); } if (Utils.CheckQouta(Quotas.ORGANIZATION_USERS, Cntx)) items.Add(CreateMenuItem("Users", "users", @"Icons/user_48.png")); if (Utils.CheckQouta(Quotas.ORGANIZATION_DELETED_USERS, Cntx)) items.Add(CreateMenuItem("DeletedUsers", "deleted_users", @"Icons/deleted_user_48.png")); if (Utils.CheckQouta(Quotas.ORGANIZATION_SECURITYGROUPS, Cntx)) items.Add(CreateMenuItem("SecurityGroups", "secur_groups", @"Icons/group_48.png")); items.Add(CreateMenuItem("PasswordPolicy", "organization_settings_password_settings", @"Icons/user_48.png")); } private void PrepareExchangeMenuRoot(MenuItemCollection items) { bool hideItems = false; UserInfo user = UsersHelper.GetUser(PanelSecurity.EffectiveUserId); if (user != null) { if ((user.Role == UserRole.User) & (Utils.CheckQouta(Quotas.EXCHANGE2007_ISCONSUMER, Cntx))) hideItems = true; } if (ShortMenu) { PrepareExchangeMenu(items, hideItems); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.ExchangeGroup"), "", "", null); item.Selectable = false; PrepareExchangeMenu(item.ChildItems, hideItems); if (item.ChildItems.Count > 0) { items.Add(item); } ExchangeMenuRoot = item; } } private void PrepareExchangeMenu(MenuItemCollection exchangeItems, bool hideItems) { if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, Cntx)) exchangeItems.Add(CreateMenuItem("Mailboxes", "mailboxes", @"Icons/mailboxes_48.png")); if (Utils.CheckQouta(Quotas.EXCHANGE2007_CONTACTS, Cntx)) exchangeItems.Add(CreateMenuItem("Contacts", "contacts", @"Icons/exchange_contacts_48.png")); if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISTRIBUTIONLISTS, Cntx)) exchangeItems.Add(CreateMenuItem("DistributionLists", "dlists", @"Icons/exchange_dlists_48.png")); //if (ShortMenu) return; if (Utils.CheckQouta(Quotas.EXCHANGE2007_PUBLICFOLDERS, Cntx)) exchangeItems.Add(CreateMenuItem("PublicFolders", "public_folders", @"Icons/public_folders_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2007_ACTIVESYNCALLOWED, Cntx)) exchangeItems.Add(CreateMenuItem("ActiveSyncPolicy", "activesync_policy", @"Icons/activesync_policy_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, Cntx)) exchangeItems.Add(CreateMenuItem("MailboxPlans", "mailboxplans", @"Icons/mailboxplans_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, Cntx)) exchangeItems.Add(CreateMenuItem("RetentionPolicy", "retentionpolicy", @"Icons/retentionpolicy_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2013_ALLOWRETENTIONPOLICY, Cntx)) exchangeItems.Add(CreateMenuItem("RetentionPolicyTag", "retentionpolicytag", @"Icons/retentionpolicytag_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, Cntx)) exchangeItems.Add(CreateMenuItem("ExchangeDomainNames", "domains", @"Icons/domains_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2007_MAILBOXES, Cntx)) exchangeItems.Add(CreateMenuItem("StorageUsage", "storage_usage", @"Icons/storage_usages_48.png")); if (!hideItems) if (Utils.CheckQouta(Quotas.EXCHANGE2007_DISCLAIMERSALLOWED, Cntx)) exchangeItems.Add(CreateMenuItem("Disclaimers", "disclaimers", @"Icons/disclaimers_48.png")); } private void PrepareCRMMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareCRMMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.CRMGroup"), "", "", null); item.Selectable = false; PrepareCRMMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareCRMMenu(MenuItemCollection crmItems) { crmItems.Add(CreateMenuItem("CRMOrganization", "CRMOrganizationDetails", @"Icons/crm_orgs_48.png")); crmItems.Add(CreateMenuItem("CRMUsers", "CRMUsers", @"Icons/crm_users_48.png")); //if (ShortMenu) return; crmItems.Add(CreateMenuItem("StorageLimits", "crm_storage_settings", @"Icons/crm_storage_settings_48.png")); } private void PrepareCRM2013MenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareCRM2013Menu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.CRM2013Group"), "", "", null); item.Selectable = false; PrepareCRM2013Menu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareCRM2013Menu(MenuItemCollection crmItems) { crmItems.Add(CreateMenuItem("CRMOrganization", "CRMOrganizationDetails", @"Icons/crm_orgs_48.png")); crmItems.Add(CreateMenuItem("CRMUsers", "CRMUsers", @"Icons/crm_users_48.png")); //if (ShortMenu) return; crmItems.Add(CreateMenuItem("StorageLimits", "crm_storage_settings", @"Icons/crm_storage_settings_48.png")); } private void PrepareBlackBerryMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareBlackBerryMenu(items); } else { MenuItem item; bool additem = true; if (PutBlackBerryInExchange && (ExchangeMenuRoot != null)) { item = ExchangeMenuRoot; additem = false; } else item = new MenuItem(GetLocalizedString("Text.BlackBerryGroup"), "", "", null); item.Selectable = false; PrepareBlackBerryMenu(item.ChildItems); additem = additem && (item.ChildItems.Count > 0); if (additem) { items.Add(item); } } } private void PrepareBlackBerryMenu(MenuItemCollection bbItems) { bbItems.Add(CreateMenuItem("BlackBerryUsers", "blackberry_users", @"Icons/blackberry_users_48.png")); } private void PrepareSharePointMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareSharePointMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.SharePointFoundationServerGroup"), "", "", null); item.Selectable = false; PrepareSharePointMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareSharePointMenu(MenuItemCollection spItems) { spItems.Add(CreateMenuItem("SiteCollections", "sharepoint_sitecollections", @"Icons/sharepoint_sitecollections_48.png")); spItems.Add(CreateMenuItem("StorageUsage", "sharepoint_storage_usage", @"Icons/sharepoint_storage_usage_48.png")); spItems.Add(CreateMenuItem("StorageLimits", "sharepoint_storage_settings", @"Icons/sharepoint_storage_settings_48.png")); } private void PrepareSharePointEnterpriseMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareSharePointEnterpriseMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.SharePointEnterpriseServerGroup"), "", "", null); item.Selectable = false; PrepareSharePointEnterpriseMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareSharePointEnterpriseMenu(MenuItemCollection spItems) { spItems.Add(CreateMenuItem("SiteCollections", "sharepoint_enterprise_sitecollections", @"Icons/sharepoint_sitecollections_48.png")); spItems.Add(CreateMenuItem("StorageUsage", "sharepoint_enterprise_storage_usage", @"Icons/sharepoint_storage_usage_48.png")); spItems.Add(CreateMenuItem("StorageLimits", "sharepoint_enterprise_storage_settings", @"Icons/sharepoint_storage_settings_48.png")); } private void PrepareOCSMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareOCSMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.OCSGroup"), "", "", null); item.Selectable = false; PrepareOCSMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareOCSMenu(MenuItemCollection osItems) { osItems.Add(CreateMenuItem("OCSUsers", "ocs_users")); } private void PrepareLyncMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareLyncMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.LyncGroup"), "", "", null); item.Selectable = false; PrepareLyncMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareLyncMenu(MenuItemCollection lyncItems) { lyncItems.Add(CreateMenuItem("LyncUsers", "lync_users", @"Icons/lync_users_48.png")); //if (ShortMenu) return; lyncItems.Add(CreateMenuItem("LyncUserPlans", "lync_userplans", @"Icons/lync_userplans_48.png")); if (Utils.CheckQouta(Quotas.LYNC_FEDERATION, Cntx)) lyncItems.Add(CreateMenuItem("LyncFederationDomains", "lync_federationdomains", @"Icons/lync_federationdomains_48.png")); if (Utils.CheckQouta(Quotas.LYNC_PHONE, Cntx)) lyncItems.Add(CreateMenuItem("LyncPhoneNumbers", "lync_phonenumbers", @"Icons/lync_phonenumbers_48.png")); } private void PrepareEnterpriseStorageMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareEnterpriseStorageMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.EnterpriseStorageGroup"), "", "", null); item.Selectable = false; PrepareEnterpriseStorageMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareEnterpriseStorageMenu(MenuItemCollection enterpriseStorageItems) { enterpriseStorageItems.Add(CreateMenuItem("EnterpriseStorageFolders", "enterprisestorage_folders", @"Icons/enterprisestorage_folders_48.png")); if (Utils.CheckQouta(Quotas.ENTERPRICESTORAGE_DRIVEMAPS, Cntx)) { enterpriseStorageItems.Add(CreateMenuItem("EnterpriseStorageDriveMaps", "enterprisestorage_drive_maps", @"Icons/enterprisestorage_drive_maps_48.png")); } } private void PrepareRDSMenuRoot(MenuItemCollection items) { if (ShortMenu) { PrepareRDSMenu(items); } else { MenuItem item = new MenuItem(GetLocalizedString("Text.RDSGroup"), "", "", null); item.Selectable = false; PrepareRDSMenu(item.ChildItems); if (item.ChildItems.Count > 0) { items.Add(item); } } } private void PrepareRDSMenu(MenuItemCollection rdsItems) { rdsItems.Add(CreateMenuItem("RDSCollections", "rds_collections", null)); if (Utils.CheckQouta(Quotas.RDS_SERVERS, Cntx) && (PanelSecurity.LoggedUser.Role != UserRole.User)) { rdsItems.Add(CreateMenuItem("RDSServers", "rds_servers", null)); } } private MenuItem CreateMenuItem(string text, string key) { return CreateMenuItem(text, key, null); } virtual protected MenuItem CreateMenuItem(string text, string key, string img) { MenuItem item = new MenuItem(); item.Text = GetLocalizedString("Text." + text); item.NavigateUrl = PortalUtils.EditUrl("ItemID", ItemID.ToString(), key, "SpaceID=" + PackageId); if (ShowImg) { if (img==null) item.ImageUrl = PortalUtils.GetThemedIcon("Icons/tool_48.png"); else item.ImageUrl = PortalUtils.GetThemedIcon(img); } return item; } } }
using System; using System.Collections.Generic; using Northwind.Common.DataModel; using NUnit.Framework; using ServiceStack.Common.Tests.Models; using ServiceStack.DataAnnotations; using ServiceStack.Text; namespace ServiceStack.OrmLite.FirebirdTests { [TestFixture] public class OrmLiteInsertTests : OrmLiteTestBase { [Test] public void Can_insert_into_ModelWithFieldsOfDifferentTypes_table() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { dbConn.CreateTable<ModelWithFieldsOfDifferentTypes>(true); var row = ModelWithFieldsOfDifferentTypes.Create(1); dbConn.Insert(row); } } [Test] public void Can_insert_and_select_from_ModelWithFieldsOfDifferentTypes_table() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { dbConn.CreateTable<ModelWithFieldsOfDifferentTypes>(true); var row = ModelWithFieldsOfDifferentTypes.Create(1); dbConn.Insert(row); var rows = dbConn.Select<ModelWithFieldsOfDifferentTypes>(); Assert.That(rows, Has.Count.EqualTo(1)); ModelWithFieldsOfDifferentTypes.AssertIsEqual(rows[0], row); } } [Test] public void Can_insert_and_select_from_ModelWithFieldsOfNullableTypes_table() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { dbConn.CreateTable<ModelWithFieldsOfNullableTypes>(true); var row = ModelWithFieldsOfNullableTypes.Create(1); dbConn.Insert(row); var rows = dbConn.Select<ModelWithFieldsOfNullableTypes>(); Assert.That(rows, Has.Count.EqualTo(1)); ModelWithFieldsOfNullableTypes.AssertIsEqual(rows[0], row); } } [Test] public void Can_insert_and_select_from_ModelWithFieldsOfDifferentAndNullableTypes_table_default_GUID() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) Can_insert_and_select_from_ModelWithFieldsOfDifferentAndNullableTypes_table_impl(dbConn); } [Test] public void Can_insert_and_select_from_ModelWithFieldsOfDifferentAndNullableTypes_table_compact_GUID() { Firebird.FirebirdOrmLiteDialectProvider dialect = new Firebird.FirebirdOrmLiteDialectProvider(true); OrmLiteConnectionFactory factory = new OrmLiteConnectionFactory(ConnectionString, dialect); using (var db = factory.CreateDbConnection()) { db.Open(); using (var dbConn = db.CreateCommand()) { Can_insert_and_select_from_ModelWithFieldsOfDifferentAndNullableTypes_table_impl(dbConn); } } } private void Can_insert_and_select_from_ModelWithFieldsOfDifferentAndNullableTypes_table_impl(System.Data.IDbCommand dbConn) { { dbConn.CreateTable<ModelWithFieldsOfDifferentAndNullableTypes>(true); var row = ModelWithFieldsOfDifferentAndNullableTypes.Create(1); Console.WriteLine(OrmLiteConfig.DialectProvider.ToInsertRowStatement(row, null)); dbConn.Insert(row); var rows = dbConn.Select<ModelWithFieldsOfDifferentAndNullableTypes>(); Assert.That(rows, Has.Count.EqualTo(1)); ModelWithFieldsOfDifferentAndNullableTypes.AssertIsEqual(rows[0], row); } } [Test] public void Can_insert_table_with_null_fields() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { dbConn.CreateTable<ModelWithIdAndName>(true); dbConn.DeleteAll<ModelWithIdAndName>(); var row = ModelWithIdAndName.Create(0); row.Name = null; dbConn.Insert(row); var rows = dbConn.Select<ModelWithIdAndName>(); Assert.That(rows, Has.Count.EqualTo(1)); ModelWithIdAndName.AssertIsEqual(rows[0], row); } } [Test] public void Can_retrieve_LastInsertId_from_inserted_table() { using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<ModelWithIdAndName>(true); var row1 = ModelWithIdAndName.Create(5); var row2 = ModelWithIdAndName.Create(6); dbCmd.Insert(row1); var row1LastInsertId = dbCmd.GetLastInsertId(); dbCmd.Insert(row2); var row2LastInsertId = dbCmd.GetLastInsertId(); var insertedRow1 = dbCmd.GetById<ModelWithIdAndName>(row1LastInsertId); var insertedRow2 = dbCmd.GetById<ModelWithIdAndName>(row2LastInsertId); Assert.That(insertedRow1.Name, Is.EqualTo(row1.Name)); Assert.That(insertedRow2.Name, Is.EqualTo(row2.Name)); } } [Test] public void Can_insert_TaskQueue_table() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { dbConn.CreateTable<TaskQueue>(true); var row = TaskQueue.Create(1); dbConn.Insert(row); var rows = dbConn.Select<TaskQueue>(); Assert.That(rows, Has.Count.EqualTo(1)); //Update the auto-increment id row.Id = rows[0].Id; TaskQueue.AssertIsEqual(rows[0], row); } } [Test] public void Can_insert_table_with_blobs() { using (var db = ConnectionString.OpenDbConnection()) using (var dbConn = db.CreateCommand()) { var dsl= OrmLiteConfig.DialectProvider.DefaultStringLength; OrmLiteConfig.DialectProvider.DefaultStringLength=1024; dbConn.CreateTable<OrderBlob>(true); OrmLiteConfig.DialectProvider.DefaultStringLength=dsl; var row = OrderBlob.Create(1); dbConn.Insert(row); var rows = dbConn.Select<OrderBlob>(); Assert.That(rows, Has.Count.EqualTo(1)); var newRow = rows[0]; Assert.That(newRow.Id, Is.EqualTo(row.Id)); Assert.That(newRow.Customer.Id, Is.EqualTo(row.Customer.Id)); Assert.That(newRow.Employee.Id, Is.EqualTo(row.Employee.Id)); Assert.That(newRow.IntIds, Is.EquivalentTo(row.IntIds)); Assert.That(newRow.CharMap, Is.EquivalentTo(row.CharMap)); Assert.That(newRow.OrderDetails.Count, Is.EqualTo(row.OrderDetails.Count)); Assert.That(newRow.OrderDetails[0].ProductId, Is.EqualTo(row.OrderDetails[0].ProductId)); Assert.That(newRow.OrderDetails[1].ProductId, Is.EqualTo(row.OrderDetails[1].ProductId)); Assert.That(newRow.OrderDetails[2].ProductId, Is.EqualTo(row.OrderDetails[2].ProductId)); } } public class UserAuth { public UserAuth() { this.Roles = new List<string>(); this.Permissions = new List<string>(); } [AutoIncrement] public virtual int Id { get; set; } public virtual string UserName { get; set; } public virtual string Email { get; set; } public virtual string PrimaryEmail { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public virtual string DisplayName { get; set; } public virtual string Salt { get; set; } public virtual string PasswordHash { get; set; } public virtual List<string> Roles { get; set; } public virtual List<string> Permissions { get; set; } public virtual DateTime CreatedDate { get; set; } public virtual DateTime ModifiedDate { get; set; } public virtual Dictionary<string, string> Meta { get; set; } } [Test] public void Can_insert_table_with_UserAuth() { using (var db = ConnectionString.OpenDbConnection()) using (var dbCmd = db.CreateCommand()) { dbCmd.CreateTable<UserAuth>(true); var jsv = "{Id:0,UserName:UserName,Email:as@if.com,PrimaryEmail:as@if.com,FirstName:FirstName,LastName:LastName,DisplayName:DisplayName,Salt:WMQi/g==,PasswordHash:oGdE40yKOprIgbXQzEMSYZe3vRCRlKGuqX2i045vx50=,Roles:[],Permissions:[],CreatedDate:2012-03-20T07:53:48.8720739Z,ModifiedDate:2012-03-20T07:53:48.8720739Z}"; var userAuth = jsv.To<UserAuth>(); dbCmd.Insert(userAuth); var rows = dbCmd.Select<UserAuth>(q => q.UserName == "UserName"); Console.WriteLine(rows[0].Dump()); Assert.That(rows[0].UserName, Is.EqualTo(userAuth.UserName)); } } } }
// // TrackInfoDisplay.cs // // Author: // Aaron Bockover <abockover@novell.com> // Larry Ewing <lewing@novell.com> (Is my hero) // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Gtk; using Cairo; using Hyena; using Hyena.Gui; using Hyena.Gui.Theatrics; using Banshee.Base; using Banshee.Collection; using Banshee.Collection.Gui; using Banshee.ServiceStack; using Banshee.MediaEngine; namespace Banshee.Gui.Widgets { public abstract class TrackInfoDisplay : Widget { private string current_artwork_id; private bool idle; private ArtworkManager artwork_manager; protected ArtworkManager ArtworkManager { get { return artwork_manager; } } private ImageSurface current_image; protected ImageSurface CurrentImage { get { return current_image; } } private ImageSurface incoming_image; protected ImageSurface IncomingImage { get { return incoming_image; } } protected string MissingAudioIconName { get; set; } protected string MissingVideoIconName { get; set; } private ImageSurface missing_audio_image; protected ImageSurface MissingAudioImage { get { return missing_audio_image ?? (missing_audio_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingAudioIconName), true)); } } private ImageSurface missing_video_image; protected ImageSurface MissingVideoImage { get { return missing_video_image ?? (missing_video_image = PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingVideoIconName), true)); } } protected virtual Cairo.Color BackgroundColor { get; set; } private Cairo.Color text_color; protected virtual Cairo.Color TextColor { get { return text_color; } } private Cairo.Color text_light_color; protected virtual Cairo.Color TextLightColor { get { return text_light_color; } } private TrackInfo current_track; protected TrackInfo CurrentTrack { get { return current_track; } } private TrackInfo incoming_track; protected TrackInfo IncomingTrack { get { return incoming_track; } } private uint idle_timeout_id = 0; private SingleActorStage stage = new SingleActorStage (); protected TrackInfoDisplay (IntPtr native) : base (native) { } public TrackInfoDisplay () { MissingAudioIconName = "audio-x-generic"; MissingVideoIconName = "video-x-generic"; stage.Iteration += OnStageIteration; if (ServiceManager.Contains<ArtworkManager> ()) { artwork_manager = ServiceManager.Get<ArtworkManager> (); } Connected = true; HasWindow = false; } private bool connected; public bool Connected { get { return connected; } set { if (value == connected) return; if (ServiceManager.PlayerEngine != null) { connected = value; if (value) { idle = ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated | PlayerEvent.StateChange); } else { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); } } } } public static Widget GetEditable (TrackInfoDisplay display) { return CoverArtEditor.For (display, (x, y) => display.IsWithinCoverart (x, y), () => display.CurrentTrack, () => {} ); } protected override void Dispose (bool disposing) { if (disposing) { if (idle_timeout_id > 0) { GLib.Source.Remove (idle_timeout_id); } Connected = false; stage.Iteration -= OnStageIteration; stage = null; InvalidateCache (); } base.Dispose (disposing); } protected override void OnRealized () { Window = Parent.Window; base.OnRealized (); } protected override void OnUnrealized () { base.OnUnrealized (); InvalidateCache (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); ResetMissingImages (); if (current_track == null && !idle) { LoadCurrentTrack (); } else { Invalidate (); } } protected override void OnStyleUpdated () { base.OnStyleUpdated (); text_color = CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetColor (StateFlags.Normal)); BackgroundColor = CairoExtensions.GdkRGBAToCairoColor (StyleContext.GetBackgroundColor (StateFlags.Normal)); text_light_color = Hyena.Gui.Theming.GtkTheme.GetCairoTextMidColor (this); ResetMissingImages (); OnThemeChanged (); } private void ResetMissingImages () { if (missing_audio_image != null) { ((IDisposable)missing_audio_image).Dispose (); var disposed = missing_audio_image; missing_audio_image = null; if (current_image == disposed) { current_image = MissingAudioImage; } if (incoming_image == disposed) { incoming_image = MissingAudioImage; } } if (missing_video_image != null) { ((IDisposable)missing_video_image).Dispose (); var disposed = missing_video_image; missing_video_image = null; if (current_image == disposed) { current_image = MissingVideoImage; } if (incoming_image == disposed) { incoming_image = MissingVideoImage; } } } protected virtual void OnThemeChanged () { } protected override bool OnDrawn (Cairo.Context cr) { bool idle = incoming_track == null && current_track == null; if (!Visible || !IsMapped || (idle && !CanRenderIdle)) { return true; } if (idle) { RenderIdle (cr); } else { RenderAnimation (cr); } return true; } protected virtual bool CanRenderIdle { get { return false; } } protected virtual void RenderIdle (Cairo.Context cr) { } private void RenderAnimation (Cairo.Context cr) { if (stage.Actor == null) { // We are not in a transition, just render RenderStage (cr, current_track, current_image); return; } if (current_track == null) { // Fade in the whole stage, nothing to fade out CairoExtensions.PushGroup (cr); RenderStage (cr, incoming_track, incoming_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (stage.Actor.Percent); return; } // Draw the old cover art more and more translucent CairoExtensions.PushGroup (cr); RenderCoverArt (cr, current_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - stage.Actor.Percent); // Draw the new cover art more and more opaque CairoExtensions.PushGroup (cr); RenderCoverArt (cr, incoming_image); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (stage.Actor.Percent); bool same_artist_album = incoming_track != null ? incoming_track.ArtistAlbumEqual (current_track) : false; bool same_track = incoming_track != null ? incoming_track.Equals (current_track) : false; if (same_artist_album) { RenderTrackInfo (cr, incoming_track, same_track, true); } // Don't xfade the text since it'll look bad (overlapping words); instead, fade // the old out, and then the new in if (stage.Actor.Percent <= 0.5) { // Fade out old text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, current_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha (1.0 - (stage.Actor.Percent * 2.0)); } else { // Fade in new text CairoExtensions.PushGroup (cr); RenderTrackInfo (cr, incoming_track, !same_track, !same_artist_album); CairoExtensions.PopGroupToSource (cr); cr.PaintWithAlpha ((stage.Actor.Percent - 0.5) * 2.0); } } private void RenderStage (Cairo.Context cr, TrackInfo track, ImageSurface image) { RenderCoverArt (cr, image); RenderTrackInfo (cr, track, true, true); } protected virtual void RenderCoverArt (Cairo.Context cr, ImageSurface image) { ArtworkRenderer.RenderThumbnail (cr, image, false, 0, ArtworkOffset, ArtworkSizeRequest, ArtworkSizeRequest, !IsMissingImage (image), 0.0, IsMissingImage (image), BackgroundColor); } protected virtual bool IsWithinCoverart (int x, int y) { return x >= 0 && y >= ArtworkOffset && x <= ArtworkSizeRequest && y <= (ArtworkOffset + ArtworkSizeRequest); } protected bool IsMissingImage (ImageSurface pb) { return pb == missing_audio_image || pb == missing_video_image; } protected virtual void InvalidateCache () { } protected abstract void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum); private int ArtworkOffset { get { return (Allocation.Height - ArtworkSizeRequest) / 2; } } protected virtual int ArtworkSizeRequest { get { return Allocation.Height; } } protected virtual int MissingIconSizeRequest { get { return ArtworkSizeRequest; } } private void OnPlayerEvent (PlayerEventArgs args) { if (args.Event == PlayerEvent.StartOfStream) { idle = false; LoadCurrentTrack (); } else if (args.Event == PlayerEvent.TrackInfoUpdated) { LoadCurrentTrack (true); } else if (args.Event == PlayerEvent.StateChange && (incoming_track != null || incoming_image != null)) { PlayerEventStateChangeArgs state = (PlayerEventStateChangeArgs)args; if (state.Current == PlayerState.Idle) { if (idle_timeout_id == 0) { idle_timeout_id = GLib.Timeout.Add (100, IdleTimeout); } } } } private bool IdleTimeout () { if (ServiceManager.PlayerEngine == null || ServiceManager.PlayerEngine.CurrentTrack == null || ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle) { incoming_track = null; incoming_image = null; current_artwork_id = null; current_track = null; current_image = null; idle = true; if (stage != null && stage.Actor == null) { stage.Reset (); } } idle_timeout_id = 0; return false; } private void LoadCurrentTrack () { LoadCurrentTrack (false); } private void LoadCurrentTrack (bool force_reload) { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track == current_track && !IsMissingImage (current_image) && !force_reload) { return; } else if (track == null) { incoming_track = null; incoming_image = null; return; } incoming_track = track; LoadImage (track, force_reload); if (stage.Actor == null) { stage.Reset (); } } private void LoadImage (TrackInfo track, bool force) { LoadImage (track.MediaAttributes, track.ArtworkId, force); if (track == current_track) { if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) { ((IDisposable)current_image).Dispose (); } current_image = incoming_image; } } protected void LoadImage (TrackMediaAttributes attr, string artwork_id, bool force) { if (current_artwork_id != artwork_id || force) { current_artwork_id = artwork_id; if (incoming_image != null && current_image != incoming_image && !IsMissingImage (incoming_image)) { ((IDisposable)incoming_image).Dispose (); } incoming_image = artwork_manager.LookupScaleSurface (artwork_id, ArtworkSizeRequest); } if (incoming_image == null) { incoming_image = MissingImage ((attr & TrackMediaAttributes.VideoStream) != 0); } } private ImageSurface MissingImage (bool is_video) { return is_video ? MissingVideoImage : MissingAudioImage; } private double last_fps = 0.0; private void OnStageIteration (object o, EventArgs args) { Invalidate (); if (stage.Actor != null) { last_fps = stage.Actor.FramesPerSecond; return; } InvalidateCache (); if (ApplicationContext.Debugging) { Log.DebugFormat ("TrackInfoDisplay RenderAnimation: {0:0.00} FPS", last_fps); } if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) { ((IDisposable)current_image).Dispose (); } current_image = incoming_image; current_track = incoming_track; incoming_track = null; OnArtworkChanged (); } protected virtual void Invalidate () { QueueDraw (); } protected virtual void OnArtworkChanged () { } protected virtual string GetFirstLineText (TrackInfo track) { return String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (track.DisplayTrackTitle)); } protected virtual string GetSecondLineText (TrackInfo track) { string markup = null; Banshee.Streaming.RadioTrackInfo radio_track = track as Banshee.Streaming.RadioTrackInfo; if ((track.MediaAttributes & TrackMediaAttributes.Podcast) != 0) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Podcast Name and Published Date, respectively; // e.g. 'from BBtv published 7/26/2007' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2} {0}published{1} {3}"), track.DisplayAlbumTitle, track.ReleaseDate.ToShortDateString ()); } else if (radio_track != null && radio_track.ParentTrack != null) { // This is complicated because some radio streams send tags when the song changes, and we // want to display them if they do. But if they don't, we want it to look good too, so we just // display the station name for the second line. string by_from = GetByFrom ( track.ArtistName == radio_track.ParentTrack.ArtistName ? null : track.ArtistName, track.DisplayArtistName, track.AlbumTitle == radio_track.ParentTrack.AlbumTitle ? null : track.AlbumTitle, track.DisplayAlbumTitle, false ); if (String.IsNullOrEmpty (by_from)) { // simply: "Chicago Public Radio" or whatever the artist name is markup = GLib.Markup.EscapeText (radio_track.ParentTrack.ArtistName ?? Banshee.Streaming.RadioTrackInfo.UnknownStream); } else { // Translators: {0} and {1} are markup so ignore them, {2} is the name of the radio station string on = MarkupFormat (Catalog.GetString ("{0}on{1} {2}"), radio_track.ParentTrack.TrackTitle); // Translators: {0} is the "from {album} by {artist}" type string, and {1} is the "on {radio station name}" string markup = String.Format (Catalog.GetString ("{0} {1}"), by_from, on); } } else { markup = GetByFrom (track.ArtistName, track.DisplayArtistName, track.AlbumTitle, track.DisplayAlbumTitle, true); } return String.Format ("<span color=\"{0}\">{1}</span>", CairoExtensions.ColorGetHex (TextColor, false), markup); } private string MarkupFormat (string fmt, params string [] args) { string [] new_args = new string [args.Length + 2]; new_args[0] = String.Format ("<span color=\"{0}\" size=\"small\">", CairoExtensions.ColorGetHex (TextLightColor, false)); new_args[1] = "</span>"; for (int i = 0; i < args.Length; i++) { new_args[i + 2] = GLib.Markup.EscapeText (args[i]); } return String.Format (fmt, new_args); } private string GetByFrom (string artist, string display_artist, string album, string display_album, bool unknown_ok) { bool has_artist = !String.IsNullOrEmpty (artist); bool has_album = !String.IsNullOrEmpty (album); string markup = null; if (has_artist && has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} and {3} // are Artist Name and Album Title, respectively; // e.g. 'by Parkway Drive from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2} {0}from{1} {3}"), display_artist, display_album); } else if (has_album) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Album Title; // e.g. 'from Killing with a Smile' markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2}"), display_album); } else if (has_artist || unknown_ok) { // Translators: {0} and {1} are for markup so ignore them, {2} is for Artist Name; // e.g. 'by Parkway Drive' markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2}"), display_artist); } return markup; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System.Globalization; using System; using System.Text.RegularExpressions; using System.Text; using NPOI.Util; /// <summary> /// Contains methods for dealing with Excel dates. /// @author Michael Harhen /// @author Glen Stampoultzis (glens at apache.org) /// @author Dan Sherman (dsherman at Isisph.com) /// @author Hack Kampbjorn (hak at 2mba.dk) /// @author Alex Jacoby (ajacoby at gmail.com) /// @author Pavel Krupets (pkrupets at palmtreebusiness dot com) /// @author Thies Wellpott /// </summary> public class DateUtil { public const int SECONDS_PER_MINUTE = 60; public const int MINUTES_PER_HOUR = 60; public const int HOURS_PER_DAY = 24; public const int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); private const int BAD_DATE = -1; // used to specify that date Is invalid public const long DAY_MILLISECONDS = 24 * 60 * 60 * 1000; private static readonly char[] TIME_SEPARATOR_PATTERN = new char[] { ':' }; /** * The following patterns are used in {@link #isADateFormat(int, String)} */ private static Regex date_ptrn1 = new Regex("^\\[\\$\\-.*?\\]"); private static Regex date_ptrn2 = new Regex("^\\[[a-zA-Z]+\\]"); private static Regex date_ptrn3a = new Regex("[yYmMdDhHsS]"); private static Regex date_ptrn3b = new Regex("^[\\[\\]yYmMdDhHsS\\-T/,. :\"\\\\]+0*[ampAMP/]*$"); // elapsed time patterns: [h],[m] and [s] //private static Regex date_ptrn4 = new Regex("^\\[([hH]+|[mM]+|[sS]+)\\]"); private static Regex date_ptrn4 = new Regex("^\\[([hH]+|[mM]+|[sS]+)\\]$"); /// <summary> /// Given a Calendar, return the number of days since 1899/12/31. /// </summary> /// <param name="cal">the date</param> /// <param name="use1904windowing">if set to <c>true</c> [use1904windowing].</param> /// <returns>number of days since 1899/12/31</returns> public static int absoluteDay(DateTime cal, bool use1904windowing) { int daynum = (cal - new DateTime(1899, 12, 31)).Days; if (cal > new DateTime(1900, 3, 1) && use1904windowing) { daynum++; } return daynum; } public static int AbsoluteDay(DateTime cal, bool use1904windowing) { return cal.DayOfYear + DaysInPriorYears(cal.Year, use1904windowing); } /// <summary> /// Return the number of days in prior years since 1900 /// </summary> /// <param name="yr">a year (1900 &lt; yr &gt; 4000).</param> /// <param name="use1904windowing"></param> /// <returns>number of days in years prior to yr</returns> private static int DaysInPriorYears(int yr, bool use1904windowing) { if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1904)) { throw new ArgumentException("'year' must be 1900 or greater"); } int yr1 = yr - 1; int leapDays = yr1 / 4 // plus julian leap days in prior years - yr1 / 100 // minus prior century years + yr1 / 400 // plus years divisible by 400 - 460; // leap days in previous 1900 years return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays; } /// <summary> /// Given a Date, Converts it into a double representing its internal Excel representation, /// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. /// </summary> /// <param name="date">Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</param> /// <returns>the Date</returns> public static double GetExcelDate(DateTime date) { return GetExcelDate(date, false); } /// <summary> /// Gets the excel date. /// </summary> /// <param name="year">The year.</param> /// <param name="month">The month.</param> /// <param name="day">The day.</param> /// <param name="hour">The hour.</param> /// <param name="minute">The minute.</param> /// <param name="second">The second.</param> /// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param> /// <returns></returns> public static double GetExcelDate(int year, int month, int day, int hour, int minute, int second, bool use1904windowing) { if ((!use1904windowing && year < 1900) //1900 date system must bigger than 1900 || (use1904windowing && year < 1904)) //1904 date system must bigger than 1904 { return BAD_DATE; } DateTime startdate; if (use1904windowing) { startdate = new DateTime(1904, 1, 1); } else { startdate = new DateTime(1900, 1, 1); } int nextyearmonth = 0; if (month > 12) { nextyearmonth = month - 12; month = 12; } int nextmonthday = 0; if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) { //big month if (day > 31) { nextmonthday = day - 31; day = 31; } } else if ((month == 4 || month == 6 || month == 9 || month == 11)) { //small month if (day > 30) { nextmonthday = day - 30; day = 30; } } else if (DateTime.IsLeapYear(year)) { //Feb. with leap year if (day > 29) { nextmonthday = day - 29; day = 29; } } else { //Feb without leap year if (day > 28) { nextmonthday = day - 28; day = 28; } } if (day <= 0) { nextmonthday = day - 1; day = 1; } DateTime date = new DateTime(year, month, day, hour, minute, second); date = date.AddMonths(nextyearmonth); date = date.AddDays(nextmonthday); double value = (date - startdate).TotalDays + 1; if (!use1904windowing && value >= 60) { value++; } else if (use1904windowing) { value--; } return value; } /// <summary> /// Given a Date, Converts it into a double representing its internal Excel representation, /// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. /// </summary> /// <param name="date">The date.</param> /// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param> /// <returns>Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</returns> public static double GetExcelDate(DateTime date, bool use1904windowing) { if ((!use1904windowing && date.Year < 1900) //1900 date system must bigger than 1900 || (use1904windowing && date.Year < 1904)) //1904 date system must bigger than 1904 { return BAD_DATE; } DateTime startdate; if (use1904windowing) { startdate = new DateTime(1904, 1, 1); } else { startdate = new DateTime(1900, 1, 1); } double value = (date - startdate).TotalDays + 1; if (!use1904windowing && value >= 60) { value++; } else if (use1904windowing) { value--; } return value; } /// <summary> /// Given an Excel date with using 1900 date windowing, and converts it to a java.util.Date. /// Excel Dates and Times are stored without any timezone /// information. If you know (through other means) that your file /// uses a different TimeZone to the system default, you can use /// this version of the getJavaDate() method to handle it. /// </summary> /// <param name="date">The Excel date.</param> /// <returns>null if date is not a valid Excel date</returns> public static DateTime GetJavaDate(double date) { return GetJavaDate(date, false); } public static DateTime GetJavaDate(double date, TimeZoneInfo tz) { return GetJavaDate(date, false, tz, false); } [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, TimeZone tz) { return GetJavaDate(date, false, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * Converts it to a Date. * * NOTE: If the default <c>TimeZone</c> in Java uses Daylight * Saving Time then the conversion back to an Excel date may not give * the same value, that Is the comparison * <CODE>excelDate == GetExcelDate(GetJavaDate(excelDate,false))</CODE> * Is not always true. For example if default timezone Is * <c>Europe/Copenhagen</c>, on 2004-03-28 the minute after * 01:59 CET Is 03:00 CEST, if the excel date represents a time between * 02:00 and 03:00 then it Is Converted to past 03:00 summer time * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date Is not a valid Excel date * @see TimeZone */ public static DateTime GetJavaDate(double date, bool use1904windowing) { return GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZoneInfo tz) { return GetJavaCalendar(date, use1904windowing, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZone tz) { return GetJavaCalendar(date, use1904windowing, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param roundSeconds round to closest second * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZoneInfo tz, bool roundSeconds) { return GetJavaCalendar(date, use1904windowing, tz, roundSeconds); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param roundSeconds round to closest second * @return Java representation of the date, or null if date is not a valid Excel date */ [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZone tz, bool roundSeconds) { return GetJavaCalendar(date, use1904windowing, tz, roundSeconds); } public static DateTime SetCalendar(int wholeDays, int millisecondsInDay, bool use1904windowing, bool roundSeconds) { int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't if (use1904windowing) { startYear = 1904; dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day } else if (wholeDays < 61) { // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation dayAdjust = 0; } DateTime dt = (new DateTime(startYear, 1, 1)).AddDays(wholeDays + dayAdjust - 1).AddMilliseconds(millisecondsInDay); if (roundSeconds) { dt = dt.AddMilliseconds(500); dt = dt.AddMilliseconds(-dt.Millisecond); } return dt; } public static DateTime GetJavaCalendar(double date) { return GetJavaCalendar(date, false, (TimeZoneInfo)null, false); } /** * Get EXCEL date as Java Calendar with given time zone. * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param timeZone The TimeZone to evaluate the date in * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaCalendar(double date, bool use1904windowing) { return GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); } public static DateTime GetJavaCalendarUTC(double date, bool use1904windowing) { DateTime dt = GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); return TimeZoneInfo.ConvertTimeToUtc(dt); } public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZoneInfo timeZone) { return GetJavaCalendar(date, use1904windowing, timeZone, false); } /// <summary> /// Get EXCEL date as Java Calendar (with default time zone). This is like GetJavaDate(double, boolean) but returns a Calendar object. /// </summary> /// <param name="date">The Excel date.</param> /// <param name="use1904windowing">true if date uses 1904 windowing, or false if using 1900 date windowing.</param> /// <param name="timeZone"></param> /// <param name="roundSeconds"></param> /// <returns>null if date is not a valid Excel date</returns> public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZoneInfo timeZone, bool roundSeconds) { if (!IsValidExcelDate(date)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date)); } int wholeDays = (int)Math.Floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); DateTime calendar= DateTime.Now; //if (timeZone != null) //{ // calendar = LocaleUtil.GetLocaleCalendar(timeZone); //} //else //{ // calendar = LocaleUtil.GetLocaleCalendar(); // using default time-zone //} calendar = SetCalendar(wholeDays, millisecondsInDay, use1904windowing, roundSeconds); return calendar; } [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZone timeZone) { return GetJavaCalendar(date, use1904windowing, timeZone, false); } /// <summary> /// Get EXCEL date as Java Calendar (with default time zone). This is like GetJavaDate(double, boolean) but returns a Calendar object. /// </summary> /// <param name="date">The Excel date.</param> /// <param name="use1904windowing">true if date uses 1904 windowing, or false if using 1900 date windowing.</param> /// <param name="timeZone"></param> /// <param name="roundSeconds"></param> /// <returns>null if date is not a valid Excel date</returns> [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZone timeZone, bool roundSeconds) { if (!IsValidExcelDate(date)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date)); } int wholeDays = (int)Math.Floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); DateTime calendar= DateTime.Now; //if (timeZone != null) //{ // calendar = LocaleUtil.GetLocaleCalendar(timeZone); //} //else //{ // calendar = LocaleUtil.GetLocaleCalendar(); // using default time-zone //} calendar = SetCalendar(wholeDays, millisecondsInDay, use1904windowing, roundSeconds); return calendar; } /// <summary> /// Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent /// </summary> /// <param name="timeStr">The time STR.</param> /// <returns> a double between 0 and 1 representing the fraction of the day</returns> public static double ConvertTime(String timeStr) { try { return ConvertTimeInternal(timeStr); } catch (FormatException e) { String msg = "Bad time format '" + timeStr + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.Message; throw new ArgumentException(msg); } } /// <summary> /// Converts the time internal. /// </summary> /// <param name="timeStr">The time STR.</param> /// <returns></returns> private static double ConvertTimeInternal(String timeStr) { int len = timeStr.Length; if (len < 4 || len > 8) { throw new FormatException("Bad length"); } String[] parts = timeStr.Split(TIME_SEPARATOR_PATTERN); String secStr; switch (parts.Length) { case 2: secStr = "00"; break; case 3: secStr = parts[2]; break; default: throw new FormatException("Expected 2 or 3 fields but got (" + parts.Length + ")"); } String hourStr = parts[0]; String minStr = parts[1]; int hours = ParseInt(hourStr, "hour", HOURS_PER_DAY); int minutes = ParseInt(minStr, "minute", MINUTES_PER_HOUR); int seconds = ParseInt(secStr, "second", SECONDS_PER_MINUTE); double totalSeconds = seconds + (minutes + (hours) * 60) * 60; return totalSeconds / (SECONDS_PER_DAY); } // variables for performance optimization: // avoid re-checking DataUtil.isADateFormat(int, String) if a given format // string represents a date format if the same string is passed multiple times. // see https://issues.apache.org/bugzilla/show_bug.cgi?id=55611 private static int lastFormatIndex = -1; private static String lastFormatString = null; private static bool cached = false; private static string syncIsADateFormat = "IsADateFormat"; /// <summary> /// Given a format ID and its format String, will Check to see if the /// format represents a date format or not. /// Firstly, it will Check to see if the format ID corresponds to an /// internal excel date format (eg most US date formats) /// If not, it will Check to see if the format string only Contains /// date formatting Chars (ymd-/), which covers most /// non US date formats. /// </summary> /// <param name="formatIndex">The index of the format, eg from ExtendedFormatRecord.GetFormatIndex</param> /// <param name="formatString">The format string, eg from FormatRecord.GetFormatString</param> /// <returns> /// <c>true</c> if [is A date format] [the specified format index]; otherwise, <c>false</c>. /// </returns> public static bool IsADateFormat(int formatIndex, String formatString) { lock (syncIsADateFormat) { if (formatString != null && formatIndex == lastFormatIndex && formatString.Equals(lastFormatString)) { return cached; } // First up, Is this an internal date format? if (IsInternalDateFormat(formatIndex)) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = true; return true; } // If we didn't get a real string, it can't be if (formatString == null || formatString.Length == 0) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = false; return false; } String fs = formatString; // If it end in ;@, that's some crazy dd/mm vs mm/dd // switching stuff, which we can ignore fs = Regex.Replace(fs, ";@", ""); int length = fs.Length; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = fs[i]; if (i < length - 1) { char nc = fs[i + 1]; if (c == '\\') { switch (nc) { case '-': case ',': case '.': case ' ': case '\\': // skip current '\' and continue to the next char continue; } } else if (c == ';' && nc == '@') { i++; // skip ";@" duplets continue; } } sb.Append(c); } fs = sb.ToString(); // short-circuit if it indicates elapsed time: [h], [m] or [s] //if (Regex.IsMatch(fs, "^\\[([hH]+|[mM]+|[sS]+)\\]")) if (date_ptrn4.IsMatch(fs)) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = true; return true; } // If it starts with [$-...], then could be a date, but // who knows what that starting bit Is all about //fs = Regex.Replace(fs, "^\\[\\$\\-.*?\\]", ""); fs = date_ptrn1.Replace(fs, ""); // If it starts with something like [Black] or [Yellow], // then it could be a date //fs = Regex.Replace(fs, "^\\[[a-zA-Z]+\\]", ""); fs = date_ptrn2.Replace(fs, ""); // You're allowed something like dd/mm/yy;[red]dd/mm/yy // which would place dates before 1900/1904 in red // For now, only consider the first one int separatorIndex = fs.IndexOf(';'); if (separatorIndex > 0 && separatorIndex < fs.Length - 1) { fs = fs.Substring(0, separatorIndex); } // Ensure it has some date letters in it // (Avoids false positives on the rest of pattern 3) if (!date_ptrn3a.Match(fs).Success) //if (!Regex.Match(fs, "[yYmMdDhHsS]").Success) { return false; } // If we get here, check it's only made up, in any case, of: // y m d h s - \ / , . : [ ] T // optionally followed by AM/PM // Delete any string literals. fs = Regex.Replace(fs, @"""[^""\\]*(?:\\.[^""\\]*)*""", ""); //if (Regex.IsMatch(fs, @"^[\[\]yYmMdDhHsS\-/,. :\""\\]+0*[ampAMP/]*$")) //{ // return true; //} //return false; bool result = date_ptrn3b.IsMatch(fs); lastFormatIndex = formatIndex; lastFormatString = formatString; cached = result; return result; } } /// <summary> /// Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent /// </summary> /// <param name="dateStr">The date STR.</param> /// <returns>a double representing the (integer) number of days since the start of the Excel epoch</returns> public static DateTime ParseYYYYMMDDDate(String dateStr) { try { return ParseYYYYMMDDDateInternal(dateStr); } catch (FormatException e) { String msg = "Bad time format " + dateStr + " expected 'YYYY/MM/DD' - " + e.Message; throw new ArgumentException(msg); } } /// <summary> /// Parses the YYYYMMDD date internal. /// </summary> /// <param name="timeStr">The time string.</param> /// <returns></returns> private static DateTime ParseYYYYMMDDDateInternal(String timeStr) { if (timeStr.Length != 10) { throw new FormatException("Bad length"); } String yearStr = timeStr.Substring(0, 4); String monthStr = timeStr.Substring(5, 2); String dayStr = timeStr.Substring(8, 2); int year = ParseInt(yearStr, "year", short.MinValue, short.MaxValue); int month = ParseInt(monthStr, "month", 1, 12); int day = ParseInt(dayStr, "day", 1, 31); DateTime cal = new DateTime(year, month, day, 0, 0, 0); return cal; } /// <summary> /// Parses the int. /// </summary> /// <param name="strVal">The string value.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="rangeMax">The range max.</param> /// <returns></returns> private static int ParseInt(String strVal, String fieldName, int rangeMax) { return ParseInt(strVal, fieldName, 0, rangeMax - 1); } /// <summary> /// Parses the int. /// </summary> /// <param name="strVal">The STR val.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="lowerLimit">The lower limit.</param> /// <param name="upperLimit">The upper limit.</param> /// <returns></returns> private static int ParseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) { int result; try { result = int.Parse(strVal, CultureInfo.InvariantCulture); } catch (FormatException) { throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field"); } if (result < lowerLimit || result > upperLimit) { throw new FormatException(fieldName + " value (" + result + ") is outside the allowable range(0.." + upperLimit + ")"); } return result; } /// <summary> /// Given a format ID this will Check whether the format represents an internal excel date format or not. /// </summary> /// <param name="format">The format.</param> public static bool IsInternalDateFormat(int format) { bool retval = false; switch (format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev's Kit... case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x2d: case 0x2e: case 0x2f: retval = true; break; default: retval = false; break; } return retval; } /// <summary> /// Check if a cell Contains a date /// Since dates are stored internally in Excel as double values /// we infer it Is a date if it Is formatted as such. /// </summary> /// <param name="cell">The cell.</param> public static bool IsCellDateFormatted(ICell cell) { if (cell == null) return false; bool bDate = false; double d = cell.NumericCellValue; if (DateUtil.IsValidExcelDate(d)) { ICellStyle style = cell.CellStyle; if (style == null) return false; int i = style.DataFormat; String f = style.GetDataFormatString(); bDate = IsADateFormat(i, f); } return bDate; } /// <summary> /// Check if a cell contains a date, Checking only for internal excel date formats. /// As Excel stores a great many of its dates in "non-internal" date formats, you will not normally want to use this method. /// </summary> /// <param name="cell">The cell.</param> public static bool IsCellInternalDateFormatted(ICell cell) { if (cell == null) return false; bool bDate = false; double d = cell.NumericCellValue; if (DateUtil.IsValidExcelDate(d)) { ICellStyle style = cell.CellStyle; int i = style.DataFormat; bDate = IsInternalDateFormat(i); } return bDate; } /// <summary> /// Given a double, Checks if it Is a valid Excel date. /// </summary> /// <param name="value">the double value.</param> /// <returns> /// <c>true</c> if [is valid excel date] [the specified value]; otherwise, <c>false</c>. /// </returns> public static bool IsValidExcelDate(double value) { //return true; return value > -Double.Epsilon; } } }
// 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.Text; using Microsoft.Cci; using Microsoft.Cci.Extensions; using Microsoft.Cci.MutableCodeModel; namespace GenFacades { public class Generator { private const uint ReferenceAssemblyFlag = 0x70; public static bool Execute( string seeds, string contracts, string facadePath, Version assemblyFileVersion = null, bool clearBuildAndRevision = false, bool ignoreMissingTypes = false, bool ignoreBuildAndRevisionMismatch = false, bool buildDesignTimeFacades = false, string inclusionContracts = null, ErrorTreatment seedLoadErrorTreatment = ErrorTreatment.Default, ErrorTreatment contractLoadErrorTreatment = ErrorTreatment.Default, string[] seedTypePreferencesUnsplit = null, bool forceZeroVersionSeeds = false, bool producePdb = true, string partialFacadeAssemblyPath = null, bool buildPartialReferenceFacade = false) { if (!Directory.Exists(facadePath)) Directory.CreateDirectory(facadePath); var nameTable = new NameTable(); var internFactory = new InternFactory(); try { Dictionary<string, string> seedTypePreferences = ParseSeedTypePreferences(seedTypePreferencesUnsplit); using (var contractHost = new HostEnvironment(nameTable, internFactory)) using (var seedHost = new HostEnvironment(nameTable, internFactory)) { contractHost.LoadErrorTreatment = contractLoadErrorTreatment; seedHost.LoadErrorTreatment = seedLoadErrorTreatment; var contractAssemblies = LoadAssemblies(contractHost, contracts); IReadOnlyDictionary<string, IEnumerable<string>> docIdTable = GenerateDocIdTable(contractAssemblies, inclusionContracts); IAssembly[] seedAssemblies = LoadAssemblies(seedHost, seeds).ToArray(); IAssemblyReference seedCoreAssemblyRef = ((Microsoft.Cci.Immutable.PlatformType)seedHost.PlatformType).CoreAssemblyRef; if (forceZeroVersionSeeds) { // Create a deep copier, copy the seed assemblies, and zero out their versions. var copier = new MetadataDeepCopier(seedHost); for (int i = 0; i < seedAssemblies.Length; i++) { var mutableSeed = copier.Copy(seedAssemblies[i]); mutableSeed.Version = new Version(0, 0, 0, 0); // Copy the modified seed assembly back. seedAssemblies[i] = mutableSeed; if (mutableSeed.Name.UniqueKey == seedCoreAssemblyRef.Name.UniqueKey) { seedCoreAssemblyRef = mutableSeed; } } } var typeTable = GenerateTypeTable(seedAssemblies); var facadeGenerator = new FacadeGenerator(seedHost, contractHost, docIdTable, typeTable, seedTypePreferences, clearBuildAndRevision, buildDesignTimeFacades, assemblyFileVersion); if (buildPartialReferenceFacade && ignoreMissingTypes) { throw new FacadeGenerationException( "When buildPartialReferenceFacade is specified ignoreMissingTypes must not be specified."); } if (partialFacadeAssemblyPath != null) { if (contractAssemblies.Count() != 1) { throw new FacadeGenerationException( "When partialFacadeAssemblyPath is specified, only exactly one corresponding contract assembly can be specified."); } if (buildPartialReferenceFacade) { throw new FacadeGenerationException( "When partialFacadeAssemblyPath is specified, buildPartialReferenceFacade must not be specified."); } IAssembly contractAssembly = contractAssemblies.First(); IAssembly partialFacadeAssembly = seedHost.LoadAssembly(partialFacadeAssemblyPath); if (contractAssembly.Name != partialFacadeAssembly.Name || contractAssembly.Version.Major != partialFacadeAssembly.Version.Major || contractAssembly.Version.Minor != partialFacadeAssembly.Version.Minor || (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Build != partialFacadeAssembly.Version.Build) || (!ignoreBuildAndRevisionMismatch && contractAssembly.Version.Revision != partialFacadeAssembly.Version.Revision) || contractAssembly.GetPublicKeyToken() != partialFacadeAssembly.GetPublicKeyToken()) { throw new FacadeGenerationException( string.Format("The partial facade assembly's name, version, and public key token must exactly match the contract to be filled. Contract: {0}, Facade: {1}", contractAssembly.AssemblyIdentity, partialFacadeAssembly.AssemblyIdentity)); } Assembly filledPartialFacade = facadeGenerator.GenerateFacade(contractAssembly, seedCoreAssemblyRef, ignoreMissingTypes, overrideContractAssembly: partialFacadeAssembly); if (filledPartialFacade == null) { Trace.TraceError("Errors were encountered while generating the facade."); return false; } string pdbLocation = null; if (producePdb) { string pdbFolder = Path.GetDirectoryName(partialFacadeAssemblyPath); pdbLocation = Path.Combine(pdbFolder, contractAssembly.Name + ".pdb"); if (producePdb && !File.Exists(pdbLocation)) { pdbLocation = null; Trace.TraceWarning("No PDB file present for un-transformed partial facade. No PDB will be generated."); } } OutputFacadeToFile(facadePath, seedHost, filledPartialFacade, contractAssembly, pdbLocation); } else { foreach (var contract in contractAssemblies) { Assembly facade = facadeGenerator.GenerateFacade(contract, seedCoreAssemblyRef, ignoreMissingTypes, buildPartialReferenceFacade: buildPartialReferenceFacade); if (facade == null) { #if !COREFX Debug.Assert(Environment.ExitCode != 0); #endif return false; } OutputFacadeToFile(facadePath, seedHost, facade, contract); } } } return true; } catch (FacadeGenerationException ex) { Trace.TraceError(ex.Message); #if !COREFX Debug.Assert(Environment.ExitCode != 0); #endif return false; } } private static void OutputFacadeToFile(string facadePath, HostEnvironment seedHost, Assembly facade, IAssembly contract, string pdbLocation = null) { // Use the filename (including extension .dll/.winmd) so people can have some control over the output facade file name. string facadeFileName = Path.GetFileName(contract.Location); string facadeOutputPath = Path.Combine(facadePath, facadeFileName); using (Stream peOutStream = File.Create(facadeOutputPath)) { if (pdbLocation != null) { if (File.Exists(pdbLocation)) { string pdbOutputPath = Path.Combine(facadePath, contract.Name + ".pdb"); using (Stream pdbReadStream = File.OpenRead(pdbLocation)) using (PdbReader pdbReader = new PdbReader(pdbReadStream, seedHost)) using (PdbWriter pdbWriter = new PdbWriter(pdbOutputPath, pdbReader)) { PeWriter.WritePeToStream(facade, seedHost, peOutStream, pdbReader, pdbReader, pdbWriter); } } else { throw new FacadeGenerationException("Couldn't find the pdb at the given location: " + pdbLocation); } } else { PeWriter.WritePeToStream(facade, seedHost, peOutStream); } } } private static Dictionary<string, string> ParseSeedTypePreferences(string[] preferences) { var dictionary = new Dictionary<string, string>(StringComparer.Ordinal); if (preferences != null) { foreach (string preference in preferences) { int i = preference.IndexOf('='); if (i < 0) { throw new FacadeGenerationException("Invalid seed type preference. Correct usage is /preferSeedType:FullTypeName=AssemblyName"); } string key = preference.Substring(0, i); string value = preference.Substring(i + 1); if (!key.StartsWith("T:", StringComparison.Ordinal)) { key = "T:" + key; } string existingValue; if (dictionary.TryGetValue(key, out existingValue)) { Trace.TraceWarning("Overriding /preferSeedType:{0}={1} with /preferSeedType:{2}={3}.", key, existingValue, key, value); } dictionary[key] = value; } } return dictionary; } private static IEnumerable<IAssembly> LoadAssemblies(HostEnvironment host, string assemblyPaths) { host.UnifyToLibPath = true; string[] splitPaths = HostEnvironment.SplitPaths(assemblyPaths); foreach (string path in splitPaths) { if (Directory.Exists(path)) { host.AddLibPath(Path.GetFullPath(path)); } else if (File.Exists(path)) { host.AddLibPath(Path.GetDirectoryName(Path.GetFullPath(path))); } } return host.LoadAssemblies(splitPaths); } private static IReadOnlyDictionary<string, IEnumerable<string>> GenerateDocIdTable(IEnumerable<IAssembly> contractAssemblies, string inclusionContracts) { Dictionary<string, HashSet<string>> mutableDocIdTable = new Dictionary<string, HashSet<string>>(); foreach (IAssembly contractAssembly in contractAssemblies) { string simpleName = contractAssembly.AssemblyIdentity.Name.Value; if (mutableDocIdTable.ContainsKey(simpleName)) throw new FacadeGenerationException(string.Format("Multiple contracts named \"{0}\" specified on -contracts.", simpleName)); mutableDocIdTable[simpleName] = new HashSet<string>(EnumerateDocIdsToForward(contractAssembly)); } if (inclusionContracts != null) { foreach (string inclusionContractPath in HostEnvironment.SplitPaths(inclusionContracts)) { // Assembly identity conflicts are permitted and normal in the inclusion contract list so load each one in a throwaway host to avoid problems. using (HostEnvironment inclusionHost = new HostEnvironment(new NameTable(), new InternFactory())) { IAssembly inclusionAssembly = inclusionHost.LoadAssemblyFrom(inclusionContractPath); if (inclusionAssembly == null || inclusionAssembly is Dummy) throw new FacadeGenerationException(string.Format("Could not load assembly \"{0}\".", inclusionContractPath)); string simpleName = inclusionAssembly.Name.Value; HashSet<string> hashset; if (!mutableDocIdTable.TryGetValue(simpleName, out hashset)) { Trace.TraceWarning("An assembly named \"{0}\" was specified in the -include list but no contract was specified named \"{0}\". Ignoring.", simpleName); } else { foreach (string docId in EnumerateDocIdsToForward(inclusionAssembly)) { hashset.Add(docId); } } } } } Dictionary<string, IEnumerable<string>> docIdTable = new Dictionary<string, IEnumerable<string>>(); foreach (KeyValuePair<string, HashSet<string>> kv in mutableDocIdTable) { string key = kv.Key; IEnumerable<string> sortedDocIds = kv.Value.OrderBy(s => s, StringComparer.OrdinalIgnoreCase); docIdTable.Add(key, sortedDocIds); } return docIdTable; } private static IEnumerable<string> EnumerateDocIdsToForward(IAssembly contractAssembly) { // Use INamedTypeReference instead of INamespaceTypeReference in order to also include nested // class type-forwards. var typeForwardsToForward = contractAssembly.ExportedTypes.Select(alias => alias.AliasedType) .OfType<INamedTypeReference>(); var typesToForward = contractAssembly.GetAllTypes().Where(t => TypeHelper.IsVisibleOutsideAssembly(t)) .OfType<INamespaceTypeDefinition>(); List<string> result = typeForwardsToForward.Concat(typesToForward) .Select(type => TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId)).ToList(); foreach(var type in typesToForward) { AddNestedTypeDocIds(result, type); } return result; } private static void AddNestedTypeDocIds(List<string> docIds, INamedTypeDefinition type) { foreach (var nestedType in type.NestedTypes) { if (TypeHelper.IsVisibleOutsideAssembly(nestedType)) docIds.Add(TypeHelper.GetTypeName(nestedType, NameFormattingOptions.DocumentationId)); AddNestedTypeDocIds(docIds, nestedType); } } private static IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> GenerateTypeTable(IEnumerable<IAssembly> seedAssemblies) { var typeTable = new Dictionary<string, IReadOnlyList<INamedTypeDefinition>>(); foreach (var assembly in seedAssemblies) { foreach (var type in assembly.GetAllTypes().OfType<INamedTypeDefinition>()) { if (!TypeHelper.IsVisibleOutsideAssembly(type)) continue; AddTypeAndNestedTypesToTable(typeTable, type); } } return typeTable; } private static void AddTypeAndNestedTypesToTable(Dictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, INamedTypeDefinition type) { if (type != null) { IReadOnlyList<INamedTypeDefinition> seedTypes; string docId = TypeHelper.GetTypeName(type, NameFormattingOptions.DocumentationId); if (!typeTable.TryGetValue(docId, out seedTypes)) { seedTypes = new List<INamedTypeDefinition>(1); typeTable.Add(docId, seedTypes); } if (!seedTypes.Contains(type)) ((List<INamedTypeDefinition>)seedTypes).Add(type); foreach (INestedTypeDefinition nestedType in type.NestedTypes) { if (TypeHelper.IsVisibleOutsideAssembly(nestedType)) AddTypeAndNestedTypesToTable(typeTable, nestedType); } } } private class FacadeGenerator { private readonly IMetadataHost _seedHost; private readonly IMetadataHost _contractHost; private readonly IReadOnlyDictionary<string, IEnumerable<string>> _docIdTable; private readonly IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> _typeTable; private readonly IReadOnlyDictionary<string, string> _seedTypePreferences; private readonly bool _clearBuildAndRevision; private readonly bool _buildDesignTimeFacades; private readonly Version _assemblyFileVersion; public FacadeGenerator( IMetadataHost seedHost, IMetadataHost contractHost, IReadOnlyDictionary<string, IEnumerable<string>> docIdTable, IReadOnlyDictionary<string, IReadOnlyList<INamedTypeDefinition>> typeTable, IReadOnlyDictionary<string, string> seedTypePreferences, bool clearBuildAndRevision, bool buildDesignTimeFacades, Version assemblyFileVersion ) { _seedHost = seedHost; _contractHost = contractHost; _docIdTable = docIdTable; _typeTable = typeTable; _seedTypePreferences = seedTypePreferences; _clearBuildAndRevision = clearBuildAndRevision; _buildDesignTimeFacades = buildDesignTimeFacades; _assemblyFileVersion = assemblyFileVersion; } public Assembly GenerateFacade(IAssembly contractAssembly, IAssemblyReference seedCoreAssemblyReference, bool ignoreMissingTypes, IAssembly overrideContractAssembly = null, bool buildPartialReferenceFacade = false) { Assembly assembly; if (overrideContractAssembly != null) { MetadataDeepCopier copier = new MetadataDeepCopier(_seedHost); assembly = copier.Copy(overrideContractAssembly); // Use non-empty partial facade if present } else { MetadataDeepCopier copier = new MetadataDeepCopier(_contractHost); assembly = copier.Copy(contractAssembly); // if building a reference facade don't strip the contract if (!buildPartialReferenceFacade) { ReferenceAssemblyToFacadeRewriter rewriter = new ReferenceAssemblyToFacadeRewriter(_seedHost, _contractHost, seedCoreAssemblyReference, _assemblyFileVersion != null); rewriter.Rewrite(assembly); } } string contractAssemblyName = contractAssembly.AssemblyIdentity.Name.Value; IEnumerable<string> docIds = _docIdTable[contractAssemblyName]; // Add all the type forwards bool error = false; Dictionary<string, INamedTypeDefinition> existingDocIds = assembly.AllTypes.ToDictionary(typeDef => typeDef.RefDocId(), typeDef => typeDef); IEnumerable<string> docIdsToForward = buildPartialReferenceFacade ? existingDocIds.Keys : docIds.Where(id => !existingDocIds.ContainsKey(id)); Dictionary<string, INamedTypeReference> forwardedTypes = new Dictionary<string, INamedTypeReference>(); foreach (string docId in docIdsToForward) { IReadOnlyList<INamedTypeDefinition> seedTypes; if (!_typeTable.TryGetValue(docId, out seedTypes)) { if (!ignoreMissingTypes && !buildPartialReferenceFacade) { Trace.TraceError("Did not find type '{0}' in any of the seed assemblies.", docId); error = true; } continue; } INamedTypeDefinition seedType = GetSeedType(docId, seedTypes); if (seedType == null) { TraceDuplicateSeedTypeError(docId, seedTypes); error = true; continue; } if (buildPartialReferenceFacade) { // honor preferSeedType for keeping contract type string preferredSeedAssembly; bool keepType = _seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly) && contractAssemblyName.Equals(preferredSeedAssembly, StringComparison.OrdinalIgnoreCase); if (keepType) { continue; } assembly.AllTypes.Remove(existingDocIds[docId]); forwardedTypes.Add(docId, seedType); } AddTypeForward(assembly, seedType); } if (buildPartialReferenceFacade) { if (forwardedTypes.Count == 0) { Trace.TraceError("Did not find any types in any of the seed assemblies."); return null; } else { // for any thing that's now a typeforward, make sure typerefs point to that rather than // the type previously inside the assembly. TypeReferenceRewriter typeRefRewriter = new TypeReferenceRewriter(_seedHost, oldType => { INamedTypeReference newType = null; return forwardedTypes.TryGetValue(oldType.DocId(), out newType) ? newType : oldType; }); var remainingTypes = assembly.AllTypes.Where(t => t.Name.Value != "<Module>"); if (!remainingTypes.Any()) { Trace.TraceInformation($"Removed all types from {contractAssembly.Name} thus will remove ReferenceAssemblyAttribute."); assembly.AssemblyAttributes.RemoveAll(ca => ca.FullName() == "System.Runtime.CompilerServices.ReferenceAssemblyAttribute"); assembly.Flags &= ~ReferenceAssemblyFlag; } typeRefRewriter.Rewrite(assembly); } } if (error) { return null; } if (_assemblyFileVersion != null) { assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyFileVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString())); assembly.AssemblyAttributes.Add(CreateAttribute("System.Reflection.AssemblyInformationalVersionAttribute", seedCoreAssemblyReference.ResolvedAssembly, _assemblyFileVersion.ToString())); } if (_buildDesignTimeFacades) { assembly.AssemblyAttributes.Add(CreateAttribute("System.Runtime.CompilerServices.ReferenceAssemblyAttribute", seedCoreAssemblyReference.ResolvedAssembly)); assembly.Flags |= ReferenceAssemblyFlag; } if (_clearBuildAndRevision) { assembly.Version = new Version(assembly.Version.Major, assembly.Version.Minor, 0, 0); } AddWin32VersionResource(contractAssembly.Location, assembly); return assembly; } private INamedTypeDefinition GetSeedType(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes) { Debug.Assert(seedTypes.Count != 0); // we should already have checked for non-existent types. if (seedTypes.Count == 1) { return seedTypes[0]; } string preferredSeedAssembly; if (_seedTypePreferences.TryGetValue(docId, out preferredSeedAssembly)) { return seedTypes.SingleOrDefault(t => String.Equals(t.GetAssembly().Name.Value, preferredSeedAssembly, StringComparison.OrdinalIgnoreCase)); } return null; } private static void TraceDuplicateSeedTypeError(string docId, IReadOnlyList<INamedTypeDefinition> seedTypes) { Trace.TraceError("The type '{0}' is defined in multiple seed assemblies. If this is intentional, specify one of the following arguments to choose the preferred seed type:", docId); foreach (INamedTypeDefinition type in seedTypes) { Trace.TraceError(" /preferSeedType:{0}={1}", docId.Substring("T:".Length), type.GetAssembly().Name.Value); } } private void AddTypeForward(Assembly assembly, INamedTypeDefinition seedType) { var alias = new NamespaceAliasForType(); alias.AliasedType = ConvertDefinitionToReferenceIfTypeIsNested(seedType, _seedHost); alias.IsPublic = true; if (assembly.ExportedTypes == null) assembly.ExportedTypes = new List<IAliasForType>(); // Make sure that the typeforward doesn't already exist in the ExportedTypes if (!assembly.ExportedTypes.Any(t => t.AliasedType.RefDocId() == alias.AliasedType.RefDocId())) assembly.ExportedTypes.Add(alias); else throw new FacadeGenerationException($"{seedType.FullName()} typeforward already exists"); } private void AddWin32VersionResource(string contractLocation, Assembly facade) { var versionInfo = FileVersionInfo.GetVersionInfo(contractLocation); var versionSerializer = new VersionResourceSerializer( true, versionInfo.Comments, versionInfo.CompanyName, versionInfo.FileDescription, _assemblyFileVersion == null ? versionInfo.FileVersion : _assemblyFileVersion.ToString(), versionInfo.InternalName, versionInfo.LegalCopyright, versionInfo.LegalTrademarks, versionInfo.OriginalFilename, versionInfo.ProductName, _assemblyFileVersion == null ? versionInfo.ProductVersion : _assemblyFileVersion.ToString(), facade.Version); using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream, Encoding.Unicode, true)) { versionSerializer.WriteVerResource(writer); var resource = new Win32Resource(); resource.Id = 1; resource.TypeId = 0x10; resource.Data = stream.ToArray().ToList(); facade.Win32Resources.Add(resource); } } // This shouldn't be necessary, but CCI is putting a nonzero TypeDefId in the ExportedTypes table // for nested types if NamespaceAliasForType.AliasedType is set to an ITypeDefinition // so we make an ITypeReference copy as a workaround. private static INamedTypeReference ConvertDefinitionToReferenceIfTypeIsNested(INamedTypeDefinition typeDef, IMetadataHost host) { var nestedTypeDef = typeDef as INestedTypeDefinition; if (nestedTypeDef == null) return typeDef; var typeRef = new NestedTypeReference(); typeRef.Copy(nestedTypeDef, host.InternFactory); return typeRef; } private ICustomAttribute CreateAttribute(string typeName, IAssembly seedCoreAssembly, string argument = null) { var type = seedCoreAssembly.GetAllTypes().FirstOrDefault(t => t.FullName() == typeName); if (type == null) { throw new FacadeGenerationException(String.Format("Cannot find {0} type in seed core assembly.", typeName)); } IEnumerable<IMethodDefinition> constructors = type.GetMembersNamed(_seedHost.NameTable.Ctor, false).OfType<IMethodDefinition>(); IMethodDefinition constructor = null; if (argument != null) { constructor = constructors.SingleOrDefault(m => m.ParameterCount == 1 && m.Parameters.First().Type.AreEquivalent("System.String")); } else { constructor = constructors.SingleOrDefault(m => m.ParameterCount == 0); } if (constructor == null) { throw new FacadeGenerationException(String.Format("Cannot find {0} constructor taking single string argument in seed core assembly.", typeName)); } var attribute = new CustomAttribute(); attribute.Constructor = constructor; if (argument != null) { var argumentExpression = new MetadataConstant(); argumentExpression.Type = _seedHost.PlatformType.SystemString; argumentExpression.Value = argument; attribute.Arguments = new List<IMetadataExpression>(1); attribute.Arguments.Add(argumentExpression); } return attribute; } } private class ReferenceAssemblyToFacadeRewriter : MetadataRewriter { private IMetadataHost _seedHost; private IMetadataHost _contractHost; private IAssemblyReference _seedCoreAssemblyReference; private bool _stripFileVersionAttributes; public ReferenceAssemblyToFacadeRewriter( IMetadataHost seedHost, IMetadataHost contractHost, IAssemblyReference seedCoreAssemblyReference, bool stripFileVersionAttributes) : base(seedHost) { _seedHost = seedHost; _contractHost = contractHost; _stripFileVersionAttributes = stripFileVersionAttributes; _seedCoreAssemblyReference = seedCoreAssemblyReference; } public override IAssemblyReference Rewrite(IAssemblyReference assemblyReference) { if (assemblyReference == null) return assemblyReference; if (assemblyReference.UnifiedAssemblyIdentity.Equals(_contractHost.CoreAssemblySymbolicIdentity) && !assemblyReference.ModuleIdentity.Equals(host.CoreAssemblySymbolicIdentity)) { assemblyReference = _seedCoreAssemblyReference; } return base.Rewrite(assemblyReference); } public override void RewriteChildren(RootUnitNamespace rootUnitNamespace) { var assemblyReference = rootUnitNamespace.Unit as IAssemblyReference; if (assemblyReference != null) rootUnitNamespace.Unit = Rewrite(assemblyReference).ResolvedUnit; base.RewriteChildren(rootUnitNamespace); } public override List<INamespaceMember> Rewrite(List<INamespaceMember> namespaceMembers) { // Ignore traversing or rewriting any namspace members. return base.Rewrite(new List<INamespaceMember>()); } public override void RewriteChildren(Assembly assembly) { // Clear all win32 resources. The version resource will get repopulated. assembly.Win32Resources = new List<IWin32Resource>(); // Remove all the references they will get repopulated while outputing. assembly.AssemblyReferences.Clear(); // Remove all the module references (aka native references) assembly.ModuleReferences = new List<IModuleReference>(); // Remove all file references (ex: *.nlp files in mscorlib) assembly.Files = new List<IFileReference>(); // Remove all security attributes (ex: permissionset in IL) assembly.SecurityAttributes = new List<ISecurityAttribute>(); // Reset the core assembly symbolic identity to the seed core assembly (e.g. mscorlib, corefx) // and not the contract core (e.g. System.Runtime). assembly.CoreAssemblySymbolicIdentity = _seedCoreAssemblyReference.AssemblyIdentity; // Add reference to seed core assembly up-front so that we keep the same order as the C# compiler. assembly.AssemblyReferences.Add(_seedCoreAssemblyReference); // Remove all type definitions except for the "<Module>" type. Remove all fields and methods from it. NamespaceTypeDefinition moduleType = assembly.AllTypes.SingleOrDefault(t => t.Name.Value == "<Module>") as NamespaceTypeDefinition; assembly.AllTypes.Clear(); if (moduleType != null) { moduleType.Fields?.Clear(); moduleType.Methods?.Clear(); assembly.AllTypes.Add(moduleType); } // Remove any preexisting typeforwards. assembly.ExportedTypes = new List<IAliasForType>(); // Remove any preexisting resources. assembly.Resources = new List<IResourceReference>(); // Clear the reference assembly flag from the contract. // For design-time facades, it will be added back later. assembly.Flags &= ~ReferenceAssemblyFlag; // This flag should not be set until the delay-signed assembly we emit is actually signed. assembly.StrongNameSigned = false; base.RewriteChildren(assembly); } public override List<ICustomAttribute> Rewrite(List<ICustomAttribute> customAttributes) { if (customAttributes == null) return customAttributes; List<ICustomAttribute> newCustomAttributes = new List<ICustomAttribute>(); // Remove all of them except for the ones that begin with Assembly // Also remove AssemblyFileVersion and AssemblyInformationVersion if stripFileVersionAttributes is set foreach (ICustomAttribute attribute in customAttributes) { ITypeReference attributeType = attribute.Type; if (attributeType is Dummy) continue; string typeName = TypeHelper.GetTypeName(attributeType, NameFormattingOptions.OmitContainingNamespace | NameFormattingOptions.OmitContainingType); if (!typeName.StartsWith("Assembly")) continue; // We need to remove the signature key attribute otherwise we will not be able to re-sign these binaries. if (typeName == "AssemblySignatureKeyAttribute") continue; if (_stripFileVersionAttributes && ((typeName == "AssemblyFileVersionAttribute" || typeName == "AssemblyInformationalVersionAttribute"))) continue; newCustomAttributes.Add(attribute); } return base.Rewrite(newCustomAttributes); } } } }
using Avalonia.Collections; using Avalonia.Controls.Shapes; using Avalonia.Controls.Utils; using Avalonia.Layout; using Avalonia.Media; using Avalonia.VisualTree; namespace Avalonia.Controls { /// <summary> /// A control which decorates a child with a border and background. /// </summary> #pragma warning disable CS0618 // Type or member is obsolete public partial class Border : Decorator, IVisualWithRoundRectClip #pragma warning restore CS0618 // Type or member is obsolete { /// <summary> /// Defines the <see cref="Background"/> property. /// </summary> public static readonly StyledProperty<IBrush?> BackgroundProperty = AvaloniaProperty.Register<Border, IBrush?>(nameof(Background)); /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush?> BorderBrushProperty = AvaloniaProperty.Register<Border, IBrush?>(nameof(BorderBrush)); /// <summary> /// Defines the <see cref="BorderThickness"/> property. /// </summary> public static readonly StyledProperty<Thickness> BorderThicknessProperty = AvaloniaProperty.Register<Border, Thickness>(nameof(BorderThickness)); /// <summary> /// Defines the <see cref="CornerRadius"/> property. /// </summary> public static readonly StyledProperty<CornerRadius> CornerRadiusProperty = AvaloniaProperty.Register<Border, CornerRadius>(nameof(CornerRadius)); /// <summary> /// Defines the <see cref="BoxShadow"/> property. /// </summary> public static readonly StyledProperty<BoxShadows> BoxShadowProperty = AvaloniaProperty.Register<Border, BoxShadows>(nameof(BoxShadow)); /// <summary> /// Defines the <see cref="BorderDashOffset"/> property. /// </summary> public static readonly StyledProperty<double> BorderDashOffsetProperty = AvaloniaProperty.Register<Border, double>(nameof(BorderDashOffset)); /// <summary> /// Defines the <see cref="BorderDashArray"/> property. /// </summary> public static readonly StyledProperty<AvaloniaList<double>?> BorderDashArrayProperty = AvaloniaProperty.Register<Border, AvaloniaList<double>?>(nameof(BorderDashArray)); /// <summary> /// Defines the <see cref="BorderLineCap"/> property. /// </summary> public static readonly StyledProperty<PenLineCap> BorderLineCapProperty = AvaloniaProperty.Register<Border, PenLineCap>(nameof(BorderLineCap), PenLineCap.Flat); /// <summary> /// Defines the <see cref="BorderLineJoin"/> property. /// </summary> public static readonly StyledProperty<PenLineJoin> BorderLineJoinProperty = AvaloniaProperty.Register<Border, PenLineJoin>(nameof(BorderLineJoin), PenLineJoin.Miter); private readonly BorderRenderHelper _borderRenderHelper = new BorderRenderHelper(); /// <summary> /// Initializes static members of the <see cref="Border"/> class. /// </summary> static Border() { AffectsRender<Border>( BackgroundProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty, BorderDashArrayProperty, BorderLineCapProperty, BorderLineJoinProperty, BorderDashOffsetProperty, BoxShadowProperty); AffectsMeasure<Border>(BorderThicknessProperty); } /// <summary> /// Gets or sets a brush with which to paint the background. /// </summary> public IBrush? Background { get { return GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// Gets or sets a brush with which to paint the border. /// </summary> public IBrush? BorderBrush { get { return GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// Gets or sets a collection of <see cref="double"/> values that indicate the pattern of dashes and gaps that is used to outline shapes. /// </summary> public AvaloniaList<double>? BorderDashArray { get { return GetValue(BorderDashArrayProperty); } set { SetValue(BorderDashArrayProperty, value); } } /// <summary> /// Gets or sets the thickness of the border. /// </summary> public Thickness BorderThickness { get { return GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// Gets or sets a value that specifies the distance within the dash pattern where a dash begins. /// </summary> public double BorderDashOffset { get { return GetValue(BorderDashOffsetProperty); } set { SetValue(BorderDashOffsetProperty, value); } } /// <summary> /// Gets or sets a <see cref="PenLineCap"/> enumeration value that describes the shape at the ends of a line. /// </summary> public PenLineCap BorderLineCap { get { return GetValue(BorderLineCapProperty); } set { SetValue(BorderLineCapProperty, value); } } /// <summary> /// Gets or sets a <see cref="PenLineJoin"/> enumeration value that specifies the type of join that is used at the vertices of a Shape. /// </summary> public PenLineJoin BorderLineJoin { get { return GetValue(BorderLineJoinProperty); } set { SetValue(BorderLineJoinProperty, value); } } /// <summary> /// Gets or sets the radius of the border rounded corners. /// </summary> public CornerRadius CornerRadius { get { return GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } /// <summary> /// Gets or sets the box shadow effect parameters /// </summary> public BoxShadows BoxShadow { get => GetValue(BoxShadowProperty); set => SetValue(BoxShadowProperty, value); } /// <summary> /// Renders the control. /// </summary> /// <param name="context">The drawing context.</param> public override void Render(DrawingContext context) { _borderRenderHelper.Render(context, Bounds.Size, BorderThickness, CornerRadius, Background, BorderBrush, BoxShadow, BorderDashOffset, BorderLineCap, BorderLineJoin, BorderDashArray); } /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size.</param> /// <returns>The desired size of the control.</returns> protected override Size MeasureOverride(Size availableSize) { return LayoutHelper.MeasureChild(Child, availableSize, Padding, BorderThickness); } /// <summary> /// Arranges the control's child. /// </summary> /// <param name="finalSize">The size allocated to the control.</param> /// <returns>The space taken.</returns> protected override Size ArrangeOverride(Size finalSize) { return LayoutHelper.ArrangeChild(Child, finalSize, Padding, BorderThickness); } public CornerRadius ClipToBoundsRadius => CornerRadius; } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using UniRx.InternalUtil; using UnityEngine; namespace UniRx { public sealed class MainThreadDispatcher : MonoBehaviour { public enum CullingMode { /// <summary> /// Won't remove any MainThreadDispatchers. /// </summary> Disabled, /// <summary> /// Checks if there is an existing MainThreadDispatcher on Awake(). If so, the new dispatcher removes itself. /// </summary> Self, /// <summary> /// Search for excess MainThreadDispatchers and removes them all on Awake(). /// </summary> All } public static CullingMode cullingMode = CullingMode.Self; #if UNITY_EDITOR // In UnityEditor's EditorMode can't instantiate and work MonoBehaviour.Update. // EditorThreadDispatcher use EditorApplication.update instead of MonoBehaviour.Update. class EditorThreadDispatcher { static object gate = new object(); static EditorThreadDispatcher instance; public static EditorThreadDispatcher Instance { get { // Activate EditorThreadDispatcher is dangerous, completely Lazy. lock (gate) { if (instance == null) { instance = new EditorThreadDispatcher(); } return instance; } } } ThreadSafeQueueWorker editorQueueWorker = new ThreadSafeQueueWorker(); EditorThreadDispatcher() { UnityEditor.EditorApplication.update += Update; } public void Enqueue(Action action) { editorQueueWorker.Enqueue(action); } public void UnsafeInvoke(Action action) { try { action(); } catch (Exception ex) { Debug.LogException(ex); } } public void PseudoStartCoroutine(IEnumerator routine) { editorQueueWorker.Enqueue(() => ConsumeEnumerator(routine)); } void Update() { editorQueueWorker.ExecuteAll(x => Debug.LogException(x)); } void ConsumeEnumerator(IEnumerator routine) { if (routine.MoveNext()) { var current = routine.Current; if (current == null) { goto ENQUEUE; } var type = current.GetType(); if (type == typeof(WWW)) { var www = (WWW)current; editorQueueWorker.Enqueue(() => ConsumeEnumerator(UnwrapWaitWWW(www, routine))); return; } else if (type == typeof(AsyncOperation)) { var asyncOperation = (AsyncOperation)current; editorQueueWorker.Enqueue(() => ConsumeEnumerator(UnwrapWaitAsyncOperation(asyncOperation, routine))); return; } else if (type == typeof(WaitForSeconds)) { var waitForSeconds = (WaitForSeconds)current; var accessor = typeof(WaitForSeconds).GetField("m_Seconds", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic); var second = (float)accessor.GetValue(waitForSeconds); editorQueueWorker.Enqueue(() => ConsumeEnumerator(UnwrapWaitForSeconds(second, routine))); return; } else if (type == typeof(Coroutine)) { Debug.Log("Can't wait coroutine on UnityEditor"); goto ENQUEUE; } ENQUEUE: editorQueueWorker.Enqueue(() => ConsumeEnumerator(routine)); // next update } } IEnumerator UnwrapWaitWWW(WWW www, IEnumerator continuation) { while (!www.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitAsyncOperation(AsyncOperation asyncOperation, IEnumerator continuation) { while (!asyncOperation.isDone) { yield return null; } ConsumeEnumerator(continuation); } IEnumerator UnwrapWaitForSeconds(float second, IEnumerator continuation) { var startTime = DateTimeOffset.UtcNow; while (true) { yield return null; var elapsed = (DateTimeOffset.UtcNow - startTime).TotalSeconds; if (elapsed >= second) { break; } }; ConsumeEnumerator(continuation); } } #endif /// <summary>Dispatch Asyncrhonous action.</summary> public static void Post(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.queueWorker.Enqueue(action); } } /// <summary>Dispatch Synchronous action if possible.</summary> public static void Send(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.Enqueue(action); return; } #endif if (mainThreadToken != null) { try { action(); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } else { Post(action); } } /// <summary>Run Synchronous action.</summary> public static void UnsafeSend(Action action) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.UnsafeInvoke(action); return; } #endif try { action(); } catch (Exception ex) { var dispatcher = MainThreadDispatcher.Instance; if (dispatcher != null) { dispatcher.unhandledExceptionCallback(ex); } } } /// <summary>ThreadSafe StartCoroutine.</summary> public static void SendStartCoroutine(IEnumerator routine) { if (mainThreadToken != null) { StartCoroutine(routine); } else { #if UNITY_EDITOR // call from other thread if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return; } #endif var dispatcher = Instance; if (dispatcher != null) { dispatcher.queueWorker.Enqueue(() => { var distpacher2 = Instance; if (distpacher2 != null) { distpacher2.StartCoroutine_Auto(routine); } }); } } } new public static Coroutine StartCoroutine(IEnumerator routine) { #if UNITY_EDITOR if (!ScenePlaybackDetector.IsPlaying) { EditorThreadDispatcher.Instance.PseudoStartCoroutine(routine); return null; } #endif var dispatcher = Instance; if (dispatcher != null) { return dispatcher.StartCoroutine_Auto(routine); } else { return null; } } public static void RegisterUnhandledExceptionCallback(Action<Exception> exceptionCallback) { if (exceptionCallback == null) { // do nothing Instance.unhandledExceptionCallback = Stubs.Ignore<Exception>; } else { Instance.unhandledExceptionCallback = exceptionCallback; } } ThreadSafeQueueWorker queueWorker = new ThreadSafeQueueWorker(); Action<Exception> unhandledExceptionCallback = ex => Debug.LogException(ex); // default static MainThreadDispatcher instance; static bool initialized; static bool isQuitting = false; public static string InstanceName { get { if (instance == null) { throw new NullReferenceException("MainThreadDispatcher is not initialized."); } return instance.name; } } public static bool IsInitialized { get { return initialized && instance != null; } } [ThreadStatic] static object mainThreadToken; static MainThreadDispatcher Instance { get { Initialize(); return instance; } } public static void Initialize() { if (!initialized) { #if UNITY_EDITOR // Don't try to add a GameObject when the scene is not playing. Only valid in the Editor, EditorView. if (!ScenePlaybackDetector.IsPlaying) return; #endif MainThreadDispatcher dispatcher = null; try { dispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); } catch { // Throw exception when calling from a worker thread. var ex = new Exception("UniRx requires a MainThreadDispatcher component created on the main thread. Make sure it is added to the scene before calling UniRx from a worker thread."); UnityEngine.Debug.LogException(ex); throw ex; } if (isQuitting) { // don't create new instance after quitting // avoid "Some objects were not cleaned up when closing the scene find target" error. return; } if (dispatcher == null) { instance = new GameObject("MainThreadDispatcher").AddComponent<MainThreadDispatcher>(); } else { instance = dispatcher; } DontDestroyOnLoad(instance); mainThreadToken = new object(); initialized = true; } } void Awake() { if (instance == null) { instance = this; mainThreadToken = new object(); initialized = true; // Added for consistency with Initialize() DontDestroyOnLoad(gameObject); } else { if (cullingMode == CullingMode.Self) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Removing myself..."); // Destroy this dispatcher if there's already one in the scene. DestroyDispatcher(this); } else if (cullingMode == CullingMode.All) { Debug.LogWarning("There is already a MainThreadDispatcher in the scene. Cleaning up all excess dispatchers..."); CullAllExcessDispatchers(); } else { Debug.LogWarning("There is already a MainThreadDispatcher in the scene."); } } } static void DestroyDispatcher(MainThreadDispatcher aDispatcher) { if (aDispatcher != instance) { // Try to remove game object if it's empty var components = aDispatcher.gameObject.GetComponents<Component>(); if (aDispatcher.gameObject.transform.childCount == 0 && components.Length == 2) { if (components[0] is Transform && components[1] is MainThreadDispatcher) { Destroy(aDispatcher.gameObject); } } else { // Remove component MonoBehaviour.Destroy(aDispatcher); } } } public static void CullAllExcessDispatchers() { var dispatchers = GameObject.FindObjectsOfType<MainThreadDispatcher>(); for (int i = 0; i < dispatchers.Length; i++) { DestroyDispatcher(dispatchers[i]); } } void OnDestroy() { if (instance == this) { instance = GameObject.FindObjectOfType<MainThreadDispatcher>(); initialized = instance != null; /* // Although `this` still refers to a gameObject, it won't be found. var foundDispatcher = GameObject.FindObjectOfType<MainThreadDispatcher>(); if (foundDispatcher != null) { // select another game object Debug.Log("new instance: " + foundDispatcher.name); instance = foundDispatcher; initialized = true; } */ } } void Update() { queueWorker.ExecuteAll(unhandledExceptionCallback); } void OnLevelWasLoaded(int level) { // TODO clear queueWorker? //queueWorker = new ThreadSafeQueueWorker(); } // for Lifecycle Management Subject<bool> onApplicationFocus; void OnApplicationFocus(bool focus) { if (onApplicationFocus != null) onApplicationFocus.OnNext(focus); } public static IObservable<bool> OnApplicationFocusAsObservable() { return Instance.onApplicationFocus ?? (Instance.onApplicationFocus = new Subject<bool>()); } Subject<bool> onApplicationPause; void OnApplicationPause(bool pause) { if (onApplicationPause != null) onApplicationPause.OnNext(pause); } public static IObservable<bool> OnApplicationPauseAsObservable() { return Instance.onApplicationPause ?? (Instance.onApplicationPause = new Subject<bool>()); } Subject<Unit> onApplicationQuit; void OnApplicationQuit() { isQuitting = true; if (onApplicationQuit != null) onApplicationQuit.OnNext(Unit.Default); } public static IObservable<Unit> OnApplicationQuitAsObservable() { return Instance.onApplicationQuit ?? (Instance.onApplicationQuit = new Subject<Unit>()); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; using System.Text.RegularExpressions; namespace Core.Utils { public static class StringUtils { public static string[] Split(string str, string delim) { if (str == null) return null; string[] delims = { delim }; return str.Split(delims, StringSplitOptions.None); } public static List<string> SplitToList(string str, string delim) { string[] bits = Split(str, delim); return new List<string>(bits); } public static List<string> SplitToList(string str, string delim, bool trim) { if (!trim) { return SplitToList(str, delim); } string[] bits = Split(str, delim); List<string> ans = new List<string>(); foreach (string bit in bits) { ans.Add(bit.Trim()); } return ans; } public static bool IsNumeric(object Expression) { bool isNum; double retNum; isNum = Double.TryParse(Convert.ToString(Expression), NumberStyles.Any, NumberFormatInfo.InvariantInfo, out retNum); return isNum; } public static bool IsAlphaNumeric(char x) { Regex an = new Regex(@"\w"); return an.Match(x.ToString()).Success; } public static bool IsAlphaNumeric(string x) { foreach (char c in x) { if (!IsAlphaNumeric(c)) { return false; } } return true; } public static string SubstringAlphaNumericAtPosition(string str, int pos) { if (pos < 0 || pos > str.Length - 1) { return ""; } char[] chars = str.ToCharArray(); int last = pos - 1; for (int i = pos; i < chars.Length; i++) { if (IsAlphaNumeric(chars[i])) { last++; } else { break; } } if (last >= pos) { return str.Substring(pos, last - pos + 1); } return ""; } public static string SubstringBetween(string str, string start, string end) { int startPos = str.IndexOf(start); if (startPos < 0) { return ""; } startPos++; int endPos = str.IndexOf(end); if (endPos < startPos) { return str.Substring(startPos); } endPos--; return str.Substring(startPos, endPos - startPos + 1); } /// <summary> /// Get phrase in present tense: e.g. there "are no boxes" selected; there "is one box" selected; there "are 5 boxes" selected /// </summary> public static string GetSmartPlural(int num, string noun) { return GetSmartPlural(num, noun, "s"); } public static string GetSmartPlural(int num, string noun, string addToMakePlural) { //--e.g. there are no polylines selected... switch (num) { case 0: return "are no " + noun + addToMakePlural; case 1: return "is one " + noun; default: return "are " + num + " " + noun + addToMakePlural; } } /// <summary> /// Get phrase in past tense: e.g. "no boxes were" selected; "one box was" selected; "5 boxes were" selected /// </summary> public static string GetSmartPluralPastTense(int num, string noun) { return GetSmartPluralPastTense(num, noun, "s"); } public static string GetSmartPluralPastTense(int num, string noun, string addToMakePlural) { switch (num) { case 0: return "no " + noun + addToMakePlural + " were"; case 1: return "one " + noun + " was"; default: return num + " " + noun + addToMakePlural + " were"; } } public static string RenameFolder(string oldDirPath, string proposedName) { return oldDirPath.Substring(0, oldDirPath.LastIndexOf(Path.DirectorySeparatorChar)) + Path.DirectorySeparatorChar + proposedName; } public static string RemoveFromFront(string str, string frontStr) { if (!str.StartsWith(frontStr)) { throw new ArgumentException("Error in RemoveFromFront: " + str + " does not start with " + frontStr); } return str.Substring(frontStr.Length); } public static string RemoveExcessWhiteSpace(string str) { string ans = str.Trim(); while (ans.Contains(" ")) { ans = ans.Replace(" ", " "); } return ans; } /// <summary> /// Comparison delegate for strings that contain letters and numbers. Improves upon standard string comparisons where "A11" comes before "A2". Usage: Array.Sort(list, StringUtils.CompareAlphaNumeric); /// </summary> public static int CompareAlphaNumeric(string a, string b) { if (String.IsNullOrEmpty(a) && String.IsNullOrEmpty(b)) { return 0; } int ans = CompareAlphaNumericNums(a, b); if (ans == 0) { return a.CompareTo(b); } return ans; } private static int CompareAlphaNumericNums(string a, string b) { if (String.IsNullOrEmpty(a)) { return -1; } if (String.IsNullOrEmpty(b)) { return 1; } if (a.Length != b.Length) { //--e.g. 11 vs 2 int testA, testB; if (int.TryParse(a, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out testA)) { if (int.TryParse(b, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out testB)) { return testA.CompareTo(testB); } } int numStrtA = FindNumericStart(a); int numStrtB = FindNumericStart(b); //--e.g. 2nd floor vs 10th floor if (numStrtA == 0 && numStrtB == 0) { int numA = ExtractNumber(a); int numB = ExtractNumber(b); if (numA > 0 && numB > 0) { return numA.CompareTo(numB); } } //--e.g. New.11 vs New.2 if (numStrtA > 0 && numStrtB == numStrtA) { if (a.Substring(0, numStrtA) == b.Substring(0, numStrtA)) { string postA = a.Substring(numStrtA); string postB = b.Substring(numStrtA); int numA = ExtractNumber(postA); int numB = ExtractNumber(postB); if (numA != -1 && numB != -1) { int ans = numA.CompareTo(numB); if (ans != 0) { return ans; } //--e.g. New.11A vs New.11A.B return postA.CompareTo(postB); } } } } int tstA, tstB;//--- only necessary if number formats are mixed -- e.g. 30,000 vs 100000 if (int.TryParse(a, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out tstA)) { if (int.TryParse(b, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out tstB)) { return tstA.CompareTo(tstB); } } return a.CompareTo(b); } public static int FindNumericStart(string numStr) { int test; int numStrt = -1; for (int i = 0; i < numStr.Length; i++) { if (int.TryParse(numStr.Substring(i, 1), out test)) { numStrt = i; break; } } return numStrt; } public static int FindNumericEnd(string numStr) { return FindNumericEnd(FindNumericStart(numStr), numStr); } public static int FindNumericEnd(int start, string numStr) { int test; int numEnd = -1; for (int i = start; i < numStr.Length; i++) { if (!int.TryParse(numStr.Substring(i, 1), out test)) { numEnd = i; break; } } return numEnd; } public static int ExtractNumber(string numStr) { int ans = -1; if (int.TryParse(numStr, out ans)) { return ans; } int test; int numStrt = FindNumericStart(numStr); if (numStrt == -1) { return -1; } string concat = ""; for (int i = numStrt; i < numStr.Length; i++) { concat += numStr[i]; if (!int.TryParse(concat, out test)) { return ans; } ans = test; } return ans; } public static string Join(System.Collections.IEnumerable list, string delim) { string ans = ""; foreach (object o in list) { ans += Convert.ToString(o) + delim; } ans = ans.Substring(0, ans.Length - delim.Length); return ans; } public static string AppendIfExists(string div, string val) { if (String.IsNullOrEmpty(val)) { return ""; } return div + val; } internal const char WILDCARD_STRING = '*'; internal const char WILDCARD_CHAR = '?'; static public bool WildcardEquals(string pattern, string str) { return WildcardEquals(pattern, str, false); } static public bool WildcardEquals(string pattern, string str, bool ignoreCase) { if (ignoreCase) { pattern = pattern.ToLower(); str = str.ToLower(); } if (pattern == null || str == null) return false; else if (pattern.Length == 1 && pattern[0] == WILDCARD_STRING) return true; else if (str == String.Empty && pattern != String.Empty) return false; else if (pattern.IndexOf(WILDCARD_STRING) == -1 && pattern.IndexOf(WILDCARD_CHAR) == -1) return pattern == str; else return WildcardEquals(pattern, 0, str, 0); } // Copied from beagled/Lucene.Net/Search/WildcardTermEnum.cs internal static bool WildcardEquals(string pattern, int patternIdx, string string_Renamed, int stringIdx) { int p = patternIdx; for (int s = stringIdx; ; ++p, ++s) { // End of string yet? bool sEnd = (s >= string_Renamed.Length); // End of pattern yet? bool pEnd = (p >= pattern.Length); // If we're looking at the end of the string... if (sEnd) { // Assume the only thing left on the pattern is/are wildcards bool justWildcardsLeft = true; // Current wildcard position int wildcardSearchPos = p; // While we haven't found the end of the pattern, // and haven't encountered any non-wildcard characters while (wildcardSearchPos < pattern.Length && justWildcardsLeft) { // Check the character at the current position char wildchar = pattern[wildcardSearchPos]; // If it's not a wildcard character, then there is more // pattern information after this/these wildcards. if (wildchar != WILDCARD_CHAR && wildchar != WILDCARD_STRING) { justWildcardsLeft = false; } else { // to prevent "cat" matches "ca??" if (wildchar == WILDCARD_CHAR) { return false; } // Look at the next character wildcardSearchPos++; } } // This was a prefix wildcard search, and we've matched, so // return true. if (justWildcardsLeft) { return true; } } // If we've gone past the end of the string, or the pattern, // return false. if (sEnd || pEnd) { break; } // Match a single character, so continue. if (pattern[p] == WILDCARD_CHAR) { continue; } // if (pattern[p] == WILDCARD_STRING) { // Look at the character beyond the '*'. ++p; // Examine the string, starting at the last character. for (int i = string_Renamed.Length; i >= s; --i) { if (WildcardEquals(pattern, p, string_Renamed, i)) { return true; } } break; } if (pattern[p] != string_Renamed[s]) { break; } } return false; } } }
// *********************************************************************** // Copyright (c) 2012-2017 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.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { using Commands; /// <summary> /// A WorkItem may be an individual test case, a fixture or /// a higher level grouping of tests. All WorkItems inherit /// from the abstract WorkItem class, which uses the template /// pattern to allow derived classes to perform work in /// whatever way is needed. /// /// A WorkItem is created with a particular TestExecutionContext /// and is responsible for re-establishing that context in the /// current thread before it begins or resumes execution. /// </summary> public abstract class WorkItem : IDisposable { static Logger log = InternalTrace.GetLogger("WorkItem"); #region Construction and Initialization /// <summary> /// Construct a WorkItem for a particular test. /// </summary> /// <param name="test">The test that the WorkItem will run</param> /// <param name="filter">Filter used to include or exclude child items</param> public WorkItem(Test test, ITestFilter filter) { Test = test; Filter = filter; Result = test.MakeTestResult(); State = WorkItemState.Ready; ParallelScope = Test.Properties.ContainsKey(PropertyNames.ParallelScope) ? (ParallelScope)Test.Properties.Get(PropertyNames.ParallelScope) : ParallelScope.Default; #if APARTMENT_STATE TargetApartment = GetTargetApartment(Test); #endif State = WorkItemState.Ready; } /// <summary> /// Construct a work Item that wraps another work Item. /// Wrapper items are used to represent independently /// dispatched tasks, which form part of the execution /// of a single test, such as OneTimeTearDown. /// </summary> /// <param name="wrappedItem">The WorkItem being wrapped</param> public WorkItem(WorkItem wrappedItem) { // Use the same Test, Result, Actions, Context, ParallelScope // and TargetApartment as the item being wrapped. Test = wrappedItem.Test; Result = wrappedItem.Result; Context = wrappedItem.Context; ParallelScope = wrappedItem.ParallelScope; #if PARALLEL TestWorker = wrappedItem.TestWorker; #endif #if APARTMENT_STATE TargetApartment = wrappedItem.TargetApartment; #endif // State is independent of the wrapped item State = WorkItemState.Ready; } /// <summary> /// Initialize the TestExecutionContext. This must be done /// before executing the WorkItem. /// </summary> /// <remarks> /// Originally, the context was provided in the constructor /// but delaying initialization of the context until the item /// is about to be dispatched allows changes in the parent /// context during OneTimeSetUp to be reflected in the child. /// </remarks> /// <param name="context">The TestExecutionContext to use</param> public void InitializeContext(TestExecutionContext context) { Guard.OperationValid(Context == null, "The context has already been initialized"); Context = context; } #endregion #region Properties and Events /// <summary> /// Event triggered when the item is complete /// </summary> public event EventHandler Completed; /// <summary> /// Gets the current state of the WorkItem /// </summary> public WorkItemState State { get; private set; } /// <summary> /// The test being executed by the work item /// </summary> public Test Test { get; private set; } /// <summary> /// The name of the work item - defaults to the Test name. /// </summary> public virtual string Name { get { return Test.Name; } } /// <summary> /// Filter used to include or exclude child tests /// </summary> public ITestFilter Filter { get; private set; } /// <summary> /// The execution context /// </summary> public TestExecutionContext Context { get; private set; } #if PARALLEL /// <summary> /// The worker executing this item. /// </summary> public TestWorker TestWorker { get; internal set; } private ParallelExecutionStrategy? _executionStrategy; /// <summary> /// The ParallelExecutionStrategy to use for this work item /// </summary> public virtual ParallelExecutionStrategy ExecutionStrategy { get { if (!_executionStrategy.HasValue) _executionStrategy = GetExecutionStrategy(); return _executionStrategy.Value; } } /// <summary> /// Indicates whether this work item should use a separate dispatcher. /// </summary> public virtual bool IsolateChildTests { get; } = false; #endif /// <summary> /// The test result /// </summary> public TestResult Result { get; protected set; } /// <summary> /// Gets the ParallelScope associated with the test, if any, /// otherwise returning ParallelScope.Default; /// </summary> public ParallelScope ParallelScope { get; private set; } #if APARTMENT_STATE internal ApartmentState TargetApartment { get; set; } private ApartmentState CurrentApartment { get; set; } #endif #endregion #region Public Methods /// <summary> /// Execute the current work item, including any /// child work items. /// </summary> public virtual void Execute() { #if !NETSTANDARD1_6 // A supplementary thread is required in two conditions... // // 1. If the test used the RequiresThreadAttribute. This // is at the discretion of the user. // // 2. If the test needs to run in a different apartment. // This should not normally occur when using the parallel // dispatcher because tests are dispatches to a queue that // matches the requested apartment. Under the SimpleDispatcher // (--workers=0 option) it occurs routinely whenever a // different apartment is requested. #if APARTMENT_STATE CurrentApartment = Thread.CurrentThread.GetApartmentState(); var targetApartment = TargetApartment == ApartmentState.Unknown ? CurrentApartment : TargetApartment; if (Test.RequiresThread || targetApartment != CurrentApartment) #else if (Test.RequiresThread) #endif { // Handle error conditions in a single threaded fixture if (Context.IsSingleThreaded) { string msg = Test.RequiresThread ? "RequiresThreadAttribute may not be specified on a test within a single-SingleThreadedAttribute fixture." : "Tests in a single-threaded fixture may not specify a different apartment"; log.Error(msg); Result.SetResult(ResultState.NotRunnable, msg); WorkItemComplete(); return; } log.Debug("Running on separate thread because {0} is specified.", Test.RequiresThread ? "RequiresThread" : "different Apartment"); #if APARTMENT_STATE RunOnSeparateThread(targetApartment); #else RunOnSeparateThread(); #endif } else RunOnCurrentThread(); #else RunOnCurrentThread(); #endif } private readonly ManualResetEvent _completionEvent = new ManualResetEvent(false); /// <summary> /// Wait until the execution of this item is complete /// </summary> public void WaitForCompletion() { _completionEvent.WaitOne(); } /// <summary> /// Marks the WorkItem as NotRunnable. /// </summary> /// <param name="reason">Reason for test being NotRunnable.</param> public void MarkNotRunnable(string reason) { Result.SetResult(ResultState.NotRunnable, reason); WorkItemComplete(); } #if THREAD_ABORT private readonly object threadLock = new object(); private int nativeThreadId; #endif /// <summary> /// Cancel (abort or stop) a WorkItem /// </summary> /// <param name="force">true if the WorkItem should be aborted, false if it should run to completion</param> public virtual void Cancel(bool force) { if (Context != null) Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; #if THREAD_ABORT if (force) { Thread tThread; int tNativeThreadId; lock (threadLock) { if (thread == null) return; tThread = thread; tNativeThreadId = nativeThreadId; thread = null; } if (!tThread.Join(0)) { log.Debug("Killing thread {0} for cancel", tThread.ManagedThreadId); ThreadUtility.Kill(tThread, tNativeThreadId); tThread.Join(); ChangeResult(ResultState.Cancelled, "Cancelled by user"); WorkItemComplete(); } } #endif } #endregion #region IDisposable Implementation /// <summary> /// Standard Dispose /// </summary> public void Dispose() { if (_completionEvent != null) #if NET20 || NET35 _completionEvent.Close(); #else _completionEvent.Dispose(); #endif } #endregion #region Protected Methods /// <summary> /// Method that performs actually performs the work. It should /// set the State to WorkItemState.Complete when done. /// </summary> protected abstract void PerformWork(); /// <summary> /// Method called by the derived class when all work is complete /// </summary> protected void WorkItemComplete() { State = WorkItemState.Complete; Result.StartTime = Context.StartTime; Result.EndTime = DateTime.UtcNow; long tickCount = Stopwatch.GetTimestamp() - Context.StartTicks; double seconds = (double)tickCount / Stopwatch.Frequency; Result.Duration = seconds; // We add in the assert count from the context. If // this item is for a test case, we are adding the // test assert count to zero. If it's a fixture, we // are adding in any asserts that were run in the // fixture setup or teardown. Each context only // counts the asserts taking place in that context. // Each result accumulates the count from child // results along with it's own asserts. Result.AssertCount += Context.AssertCount; Context.Listener.TestFinished(Result); Completed?.Invoke(this, EventArgs.Empty); _completionEvent.Set(); //Clear references to test objects to reduce memory usage Context.TestObject = null; Test.Fixture = null; } /// <summary> /// Builds the set up tear down list. /// </summary> /// <param name="setUpMethods">Unsorted array of setup MethodInfos.</param> /// <param name="tearDownMethods">Unsorted array of teardown MethodInfos.</param> /// <returns>A list of SetUpTearDownItems</returns> protected List<SetUpTearDownItem> BuildSetUpTearDownList(MethodInfo[] setUpMethods, MethodInfo[] tearDownMethods) { Guard.ArgumentNotNull(setUpMethods, nameof(setUpMethods)); Guard.ArgumentNotNull(tearDownMethods, nameof(tearDownMethods)); var list = new List<SetUpTearDownItem>(); Type fixtureType = Test.TypeInfo?.Type; if (fixtureType == null) return list; while (fixtureType != null && !fixtureType.Equals(typeof(object))) { var node = BuildNode(fixtureType, setUpMethods, tearDownMethods); if (node.HasMethods) list.Add(node); fixtureType = fixtureType.GetTypeInfo().BaseType; } return list; } // This method builds a list of nodes that can be used to // run setup and teardown according to the NUnit specs. // We need to execute setup and teardown methods one level // at a time. However, we can't discover them by reflection // one level at a time, because that would cause overridden // methods to be called twice, once on the base class and // once on the derived class. // // For that reason, we start with a list of all setup and // teardown methods, found using a single reflection call, // and then descend through the inheritance hierarchy, // adding each method to the appropriate level as we go. private static SetUpTearDownItem BuildNode(Type fixtureType, IList<MethodInfo> setUpMethods, IList<MethodInfo> tearDownMethods) { // Create lists of methods for this level only. // Note that FindAll can't be used because it's not // available on all the platforms we support. var mySetUpMethods = SelectMethodsByDeclaringType(fixtureType, setUpMethods); var myTearDownMethods = SelectMethodsByDeclaringType(fixtureType, tearDownMethods); return new SetUpTearDownItem(mySetUpMethods, myTearDownMethods); } private static List<MethodInfo> SelectMethodsByDeclaringType(Type type, IList<MethodInfo> methods) { var list = new List<MethodInfo>(); foreach (var method in methods) if (method.DeclaringType == type) list.Add(method); return list; } /// <summary> /// Changes the result of the test, logging the old and new states /// </summary> /// <param name="resultState">The new ResultState</param> /// <param name="message">The new message</param> protected void ChangeResult(ResultState resultState, string message) { log.Debug("Changing result from {0} to {1}", Result.ResultState, resultState); Result.SetResult(resultState, message); } #endregion #region Private Methods #if !NETSTANDARD1_6 private Thread thread; #if APARTMENT_STATE private void RunOnSeparateThread(ApartmentState apartment) #else private void RunOnSeparateThread() #endif { thread = new Thread(() => { thread.CurrentCulture = Context.CurrentCulture; thread.CurrentUICulture = Context.CurrentUICulture; #if THREAD_ABORT lock (threadLock) nativeThreadId = ThreadUtility.GetCurrentThreadNativeId(); #endif RunOnCurrentThread(); }); #if APARTMENT_STATE thread.SetApartmentState(apartment); #endif thread.Start(); thread.Join(); } #endif private void RunOnCurrentThread() { Context.CurrentTest = this.Test; Context.CurrentResult = this.Result; Context.Listener.TestStarted(this.Test); Context.StartTime = DateTime.UtcNow; Context.StartTicks = Stopwatch.GetTimestamp(); #if PARALLEL Context.TestWorker = this.TestWorker; #endif Context.EstablishExecutionEnvironment(); State = WorkItemState.Running; PerformWork(); } #if PARALLEL private ParallelExecutionStrategy GetExecutionStrategy() { // If there is no fixture and so nothing to do but dispatch // grandchildren we run directly. This saves time that would // otherwise be spent enqueuing and dequeing items. if (Test.TypeInfo == null) return ParallelExecutionStrategy.Direct; // If the context is single-threaded we are required to run // the tests one by one on the same thread as the fixture. if (Context.IsSingleThreaded) return ParallelExecutionStrategy.Direct; // Check if item is explicitly marked as non-parallel if (ParallelScope.HasFlag(ParallelScope.None)) return ParallelExecutionStrategy.NonParallel; // Check if item is explicitly marked as parallel if (ParallelScope.HasFlag(ParallelScope.Self)) return ParallelExecutionStrategy.Parallel; // Item is not explicitly marked, so check the inherited context if (Context.ParallelScope.HasFlag(ParallelScope.Children) || Test is TestFixture && Context.ParallelScope.HasFlag(ParallelScope.Fixtures)) return ParallelExecutionStrategy.Parallel; // There is no scope specified either on the item itself or in the context. // In that case, simple work items are test cases and just run on the same // thread, while composite work items and teardowns are non-parallel. return this is SimpleWorkItem ? ParallelExecutionStrategy.Direct : ParallelExecutionStrategy.NonParallel; } #endif #if APARTMENT_STATE /// <summary> /// Recursively walks up the test hierarchy to see if the /// <see cref="ApartmentState"/> has been set on any of the parent tests. /// </summary> static ApartmentState GetTargetApartment(ITest test) { var apartment = test.Properties.ContainsKey(PropertyNames.ApartmentState) ? (ApartmentState)test.Properties.Get(PropertyNames.ApartmentState) : ApartmentState.Unknown; if (apartment == ApartmentState.Unknown && test.Parent != null) return GetTargetApartment(test.Parent); return apartment; } #endif #endregion } #if NET20 || NET35 static class ActionTargetsExtensions { public static bool HasFlag(this ActionTargets targets, ActionTargets value) { return (targets & value) != 0; } } #endif }
/* 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 RDFSharp.Model; using System; using System.Linq; namespace RDFSharp.Test.Model { [TestClass] public class RDFInConstraintTest { #region Tests [TestMethod] public void ShouldCreateInResourceConstraint() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource); Assert.IsNotNull(inConstraint); Assert.IsNotNull(inConstraint.InValues); Assert.IsTrue(inConstraint.InValues.Count == 0); Assert.IsTrue(inConstraint.ItemType == RDFModelEnums.RDFItemTypes.Resource); } [TestMethod] public void ShouldAddResourceValue() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource); inConstraint.AddValue(new RDFResource("ex:value")); inConstraint.AddValue(new RDFResource("ex:value")); //Will be discarded because duplicates not allowed inConstraint.AddValue(null as RDFResource); //Will be discarded because null not allowed inConstraint.AddValue(new RDFPlainLiteral("value")); //Will be discarded because wrong item type Assert.IsTrue(inConstraint.InValues.Count == 1); } [TestMethod] public void ShouldCreateInLiteralConstraint() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Literal); Assert.IsNotNull(inConstraint); Assert.IsNotNull(inConstraint.InValues); Assert.IsTrue(inConstraint.InValues.Count == 0); Assert.IsTrue(inConstraint.ItemType == RDFModelEnums.RDFItemTypes.Literal); } [TestMethod] public void ShouldAddLiteralValue() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Literal); inConstraint.AddValue(new RDFPlainLiteral("value")); inConstraint.AddValue(new RDFPlainLiteral("value")); //Will be discarded because duplicates not allowed inConstraint.AddValue(null as RDFLiteral); //Will be discarded because null not allowed inConstraint.AddValue(new RDFResource("ex:value")); //Will be discarded because wrong item type Assert.IsTrue(inConstraint.InValues.Count == 1); } [TestMethod] public void ShouldExportInResourceConstraint() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource); inConstraint.AddValue(new RDFResource("ex:value1")); inConstraint.AddValue(new RDFResource("ex:value2")); RDFGraph graph = inConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 7); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.IN) && t.Value.Object is RDFResource objRes && objRes.IsBlank)); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.TYPE) && t.Value.Object.Equals(RDFVocabulary.RDF.LIST))); //2 occurrences of this Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.FIRST) && t.Value.Object.Equals(new RDFResource("ex:value1")))); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.REST) && t.Value.Object is RDFResource objRes && objRes.IsBlank)); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.FIRST) && t.Value.Object.Equals(new RDFResource("ex:value2")))); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.REST) && t.Value.Object.Equals(RDFVocabulary.RDF.NIL))); } [TestMethod] public void ShouldExportInLiteralConstraint() { RDFInConstraint inConstraint = new RDFInConstraint(RDFModelEnums.RDFItemTypes.Literal); inConstraint.AddValue(new RDFPlainLiteral("value1")); inConstraint.AddValue(new RDFPlainLiteral("value2")); RDFGraph graph = inConstraint.ToRDFGraph(new RDFNodeShape(new RDFResource("ex:NodeShape"))); Assert.IsNotNull(graph); Assert.IsTrue(graph.TriplesCount == 7); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject.Equals(new RDFResource("ex:NodeShape")) && t.Value.Predicate.Equals(RDFVocabulary.SHACL.IN) && t.Value.Object is RDFResource objRes && objRes.IsBlank)); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.TYPE) && t.Value.Object.Equals(RDFVocabulary.RDF.LIST))); //2 occurrences of this Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.FIRST) && t.Value.Object.Equals(new RDFPlainLiteral("value1")))); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.REST) && t.Value.Object is RDFResource objRes && objRes.IsBlank)); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.FIRST) && t.Value.Object.Equals(new RDFPlainLiteral("value2")))); Assert.IsTrue(graph.Triples.Any(t => t.Value.Subject is RDFResource subjRes && subjRes.IsBlank && t.Value.Predicate.Equals(RDFVocabulary.RDF.REST) && t.Value.Object.Equals(RDFVocabulary.RDF.NIL))); } //NS-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice")) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice")) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.RDF.TYPE)); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice")) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice")) .AddValue(new RDFResource("ex:Bob"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //PS-CONFORMS:TRUE [TestMethod] public void ShouldConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } [TestMethod] public void ShouldConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //NS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Alice")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } [TestMethod] public void ShouldNotConformNodeShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:NodeShape")); nodeShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); nodeShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Bob")) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(nodeShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsNull(validationReport.Results[0].ResultPath); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:NodeShape"))); } //PS-CONFORMS:FALSE [TestMethod] public void ShouldNotConformPropertyShapeWithClassTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetClass(new RDFResource("ex:Person"))); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithNodeTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.KNOWS); propertyShape.AddTarget(new RDFTargetNode(new RDFResource("ex:Alice"))); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.KNOWS)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithSubjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Bob"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetSubjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } [TestMethod] public void ShouldNotConformPropertyShapeWithObjectsOfTarget() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Man"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Woman"), RDFVocabulary.RDFS.SUB_CLASS_OF, new RDFResource("ex:Person"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Woman"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Steve"), RDFVocabulary.RDF.TYPE, new RDFResource("ex:Man"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Alice"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Bob"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.KNOWS, new RDFResource("ex:Steve"))); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:Bob"), RDFVocabulary.FOAF.AGENT, new RDFResource("ex:Alice"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFPropertyShape propertyShape = new RDFPropertyShape(new RDFResource("ex:PropertyShape"), RDFVocabulary.FOAF.AGENT); propertyShape.AddTarget(new RDFTargetObjectsOf(RDFVocabulary.FOAF.KNOWS)); propertyShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Steve"))); shapesGraph.AddShape(propertyShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:Bob"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Alice"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(RDFVocabulary.FOAF.AGENT)); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropertyShape"))); } //MIXED-CONFORMS:TRUE [TestMethod] public void ShouldConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:RainbowPony"), new RDFResource("ex:color"), new RDFResource("ex:Pink"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:InExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:RainbowPony"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:color")); propShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Pink")) .AddValue(new RDFResource("ex:Purple"))); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsTrue(validationReport.Conforms); } //MIXED-CONFORMS:FALSE [TestMethod] public void ShouldNotConformNodeShapeWithPropertyShape() { //DataGraph RDFGraph dataGraph = new RDFGraph().SetContext(new Uri("ex:DataGraph")); dataGraph.AddTriple(new RDFTriple(new RDFResource("ex:RainbowPony"), new RDFResource("ex:color"), new RDFResource("ex:Green"))); //ShapesGraph RDFShapesGraph shapesGraph = new RDFShapesGraph(new RDFResource("ex:ShapesGraph")); RDFNodeShape nodeShape = new RDFNodeShape(new RDFResource("ex:InExampleShape")); nodeShape.AddTarget(new RDFTargetNode(new RDFResource("ex:RainbowPony"))); RDFPropertyShape propShape = new RDFPropertyShape(new RDFResource("ex:PropShape"), new RDFResource("ex:color")); propShape.AddConstraint(new RDFInConstraint(RDFModelEnums.RDFItemTypes.Resource) .AddValue(new RDFResource("ex:Pink")) .AddValue(new RDFResource("ex:Purple"))); nodeShape.AddConstraint(new RDFPropertyConstraint(propShape)); shapesGraph.AddShape(nodeShape); shapesGraph.AddShape(propShape); //Validate RDFValidationReport validationReport = shapesGraph.Validate(dataGraph); Assert.IsNotNull(validationReport); Assert.IsFalse(validationReport.Conforms); Assert.IsTrue(validationReport.ResultsCount == 1); Assert.IsTrue(validationReport.Results[0].Severity == RDFValidationEnums.RDFShapeSeverity.Violation); Assert.IsTrue(validationReport.Results[0].ResultMessages.Count == 1); Assert.IsTrue(validationReport.Results[0].ResultMessages[0].Equals(new RDFPlainLiteral("Not a value from the sh:in enumeration"))); Assert.IsTrue(validationReport.Results[0].FocusNode.Equals(new RDFResource("ex:RainbowPony"))); Assert.IsTrue(validationReport.Results[0].ResultValue.Equals(new RDFResource("ex:Green"))); Assert.IsTrue(validationReport.Results[0].ResultPath.Equals(new RDFResource("ex:color"))); Assert.IsTrue(validationReport.Results[0].SourceConstraintComponent.Equals(RDFVocabulary.SHACL.IN_CONSTRAINT_COMPONENT)); Assert.IsTrue(validationReport.Results[0].SourceShape.Equals(new RDFResource("ex:PropShape"))); } #endregion } }
#region License // // Author: Nate Kohari <nkohari@gmail.com> // Copyright (c) 2007-2008, Enkari, Ltd. // // 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 #region Using Directives using System; using System.Collections.Generic; using Ninject.Core.Activation; using Ninject.Core.Infrastructure; using Ninject.Core.Parameters; #endregion namespace Ninject.Core.Tracking { /// <summary> /// A stock implementation of a scope. /// </summary> public class StandardScope : LocatorBase, IScope { /*----------------------------------------------------------------------------------------*/ #region Fields private readonly Dictionary<object, IContext> _items = new Dictionary<object, IContext>(); #endregion /*----------------------------------------------------------------------------------------*/ #region Properties /// <summary> /// Gets the kernel associated with the scope. /// </summary> public IKernel Kernel { get; private set; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Gets or sets the parent scope. /// </summary> public IScope Parent { get; set; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Gets all child scopes. /// </summary> public ICollection<IScope> Children { get; private set; } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Gets the number of items being tracked in the scope. /// </summary> public int Count { get { return _items.Count; } } #endregion /*----------------------------------------------------------------------------------------*/ #region Disposal /// <summary> /// Releases all resources currently held by the object. /// </summary> /// <param name="disposing"><see langword="True"/> if managed objects should be disposed, otherwise <see langword="false"/>.</param> protected override void Dispose(bool disposing) { if (disposing && !IsDisposed) { if (Parent != null) { Parent.Children.Remove(this); Parent = null; } Children.Each(s => s.Dispose()); Children.Clear(); _items.Values.Each(DoRelease); _items.Clear(); Kernel = null; Children = null; } base.Dispose(disposing); } #endregion /*----------------------------------------------------------------------------------------*/ #region Constructors /// <summary> /// Initializes a new instance of the <see cref="StandardScope"/> class. /// </summary> /// <param name="kernel">The kernel to associate with the scope.</param> public StandardScope(IKernel kernel) { Ensure.ArgumentNotNull(kernel, "kernel"); Kernel = kernel; Children = new List<IScope>(); } #endregion /*----------------------------------------------------------------------------------------*/ #region Public Methods: Tracking /// <summary> /// Registers the specified context with the scope. /// </summary> /// <param name="context">The context to register.</param> public void Register(IContext context) { lock (_items) { Ensure.NotDisposed(this); if (!_items.ContainsKey(context.Instance)) _items.Add(context.Instance, context); } } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Releases the provided instance. This method should be called after the instance is no /// longer needed. /// </summary> /// <param name="instance">The instance to release.</param> /// <returns><see langword="True"/> if the instance was being tracked, otherwise <see langword="false"/>.</returns> public bool Release(object instance) { lock (_items) { if (!_items.ContainsKey(instance)) return false; IContext context = _items[instance]; DoRelease(context); _items.Remove(instance); return true; } } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Releases the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns><see langword="True"/> if the context was being tracked, otherwise <see langword="false"/>.</returns> public bool Release(IContext context) { lock (_items) { DoRelease(context); if (!_items.ContainsKey(context.Instance)) return false; _items.Remove(context.Instance); return true; } } #endregion /*----------------------------------------------------------------------------------------*/ #region Protected Methods /// <summary> /// Resolves an instance of a bound type. /// </summary> /// <param name="service">The type of instance to resolve.</param> /// <param name="context">The context in which the instance should be resolved.</param> /// <returns>The resolved instance.</returns> protected override object DoResolve(Type service, IContext context) { return Kernel.Get(service, context); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Injects an existing instance of a service. /// </summary> /// <param name="instance">The existing instance to inject.</param> /// <param name="context">The context in which the instance should be injected.</param> protected override void DoInject(object instance, IContext context) { Kernel.Inject(instance, context); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Releases the specified context. /// </summary> /// <param name="context">The context to release.</param> protected virtual void DoRelease(IContext context) { context.Plan.Behavior.Release(context); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Creates a new root context. /// </summary> /// <param name="service">The type that was requested.</param> /// <returns>A new <see cref="IContext"/> representing the root context.</returns> protected override IContext CreateRootContext(Type service) { return Kernel.Components.ContextFactory.Create(service, this); } /*----------------------------------------------------------------------------------------*/ /// <summary> /// Creates a new root context. /// </summary> /// <param name="service">The type that was requested.</param> /// <param name="parameters">A collection of transient parameters, or <see langword="null"/> for none.</param> /// <returns>A new <see cref="IContext"/> representing the root context.</returns> protected override IContext CreateRootContext(Type service, IParameterCollection parameters) { return Kernel.Components.ContextFactory.Create(service, this, parameters); } #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; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.WebUtilities; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters.Xml { public class XmlSerializerInputFormatterTest { public class DummyClass { public int SampleInt { get; set; } } public class TestLevelOne { public int SampleInt { get; set; } public string sampleString; public DateTime SampleDate { get; set; } } public class TestLevelTwo { public string SampleString { get; set; } public TestLevelOne TestOne { get; set; } } [Fact] public async Task BuffersRequestBody_ByDefault() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: true); httpContext.Request.ContentType = "application/json"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody_ObsoleteParameter() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions { SuppressInputFormatterBuffering = true}); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); } [Fact] public async Task BuffersRequestBody_ByDefaultUsingMvcOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: false); httpContext.Request.ContentType = "application/json"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions() { SuppressInputFormatterBuffering = true }); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context)); } [Fact] public async Task SuppressInputFormatterBufferingSetToTrue_UsingMutatedOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var mvcOptions = new MvcOptions(); mvcOptions.SuppressInputFormatterBuffering = false; var formatter = new XmlSerializerInputFormatter(mvcOptions); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act // Mutate options after passing into the constructor to make sure that the value type is not store in the constructor mvcOptions.SuppressInputFormatterBuffering = true; var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync<XmlException>(() => formatter.ReadAsync(context)); } [Theory] [InlineData("application/xml", true)] [InlineData("application/*", false)] [InlineData("*/*", false)] [InlineData("text/xml", true)] [InlineData("text/*", false)] [InlineData("text/json", false)] [InlineData("application/json", false)] [InlineData("application/some.entity+xml", true)] [InlineData("application/some.entity+xml;v=2", true)] [InlineData("application/some.entity+json", false)] [InlineData("application/some.entity+*", false)] [InlineData("text/some.entity+json", false)] [InlineData("", false)] [InlineData("invalid", false)] [InlineData(null, false)] public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes("content"); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: requestContentType); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(string)); var formatterContext = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); } [Theory] [InlineData(typeof(Dictionary<string, object>), false)] [InlineData(typeof(string), true)] public void CanRead_ReturnsFalse_ForAnyUnsupportedModelType(Type modelType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes("content"); var context = GetInputFormatterContext(contentBytes, modelType); // Act var result = formatter.CanRead(context); // Assert Assert.Equal(expectedCanRead, result); } [Fact] public void XmlSerializer_CachesSerializerForType() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new TestXmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act formatter.CanRead(context); formatter.CanRead(context); // Assert Assert.Equal(1, formatter.createSerializerCalledCount); } [Fact] public void HasProperSupportedMediaTypes() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains("application/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); Assert.Contains("text/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); } [Fact] public void HasProperSupportedEncodings() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-8"); Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-16"); } [Fact] public async Task ReadAsync_ReadsSimpleTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); } [Fact] public async Task ReadAsync_ReadsComplexTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var expectedLevelTwoString = "102"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>" + expectedLevelTwoString + "</SampleString>" + "<TestOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelTwo>(result.Model); Assert.Equal(expectedLevelTwoString, model.SampleString); Assert.Equal(expectedInt, model.TestOne.SampleInt); Assert.Equal(expectedString, model.TestOne.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.TestOne.SampleDate); } [Fact] public async Task ReadAsync_ReadsWhenMaxDepthIsModified() { // Arrange var expectedInt = 10; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); formatter.MaxDepth = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<DummyClass>(result.Model); Assert.Equal(expectedInt, model.SampleInt); } [ConditionalFact] // ReaderQuotas are not honored on Mono [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ThrowsOnExceededMaxDepth() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString>" + "<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); formatter.MaxDepth = 1; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(() => formatter.ReadAsync(context)); } [ConditionalFact] // ReaderQuotas are not honored on Mono [FrameworkSkipCondition(RuntimeFrameworks.Mono)] public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString>" + "<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync<InputFormatterException>(() => formatter.ReadAsync(context)); } [Fact] public void SetMaxDepth_ThrowsWhenMaxDepthIsBelowOne() { // Arrange var formatter = new XmlSerializerInputFormatter(new MvcOptions()); // Act & Assert Assert.Throws<ArgumentException>(() => formatter.MaxDepth = 0); } [Fact] public async Task ReadAsync_VerifyStreamIsOpenAfterRead() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); Assert.NotNull(result.Model); Assert.True(context.HttpContext.Request.Body.CanRead); } [ReplaceCulture] [Fact] public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() { // Arrange var expectedException = typeof(XmlException); var expectedMessage = "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'."; var inpStart = Encoding.Unicode.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<DummyClass><SampleInt>"); byte[] inp = { 192, 193 }; var inpEnd = Encoding.Unicode.GetBytes("</SampleInt></DummyClass>"); var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length]; Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length); Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length); Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length); var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act and Assert var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Equal(expectedMessage, ex.Message); } [Fact] [ReplaceCulture] public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() { // Arrange var expectedException = typeof(XmlException); var expectedMessage = "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'."; var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>1000</SampleInt></DummyClass>"); var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act and Assert var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Equal(expectedMessage, ex.Message); } [Fact] public async Task ReadAsync_IgnoresBOMCharacters() { // Arrange var sampleString = "Test"; var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString); var inputStart = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine + "<TestLevelTwo><SampleString>" + sampleString); byte[] bom = { 0xef, 0xbb, 0xbf }; var inputEnd = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>"); var expectedBytes = new byte[sampleString.Length + bom.Length]; var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length]; Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length); Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length); Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length); var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelTwo>(result.Model); Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length); Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length); Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(model.SampleString)); } [Fact] public async Task ReadAsync_AcceptsUTF16Characters() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.Unicode.GetBytes(input); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); } [Fact] public async Task ReadAsync_DoesNotDisposeBufferedStreamIfItDidNotCreateIt() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); var testBufferedReadStream = new VerifyDisposeFileBufferingReadStream(new MemoryStream(contentBytes), 1024); httpContext.Request.Body = testBufferedReadStream; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.False(testBufferedReadStream.Disposed); } private InputFormatterContext GetInputFormatterContext(byte[] contentBytes, Type modelType) { var httpContext = GetHttpContext(contentBytes); return GetInputFormatterContext(httpContext, modelType); } private InputFormatterContext GetInputFormatterContext(HttpContext httpContext, Type modelType) { var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(modelType); return new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); } private static HttpContext GetHttpContext( byte[] contentBytes, string contentType = "application/xml") { var request = new Mock<HttpRequest>(); var headers = new Mock<IHeaderDictionary>(); request.SetupGet(r => r.Headers).Returns(headers.Object); request.SetupGet(f => f.Body).Returns(new MemoryStream(contentBytes)); request.SetupGet(f => f.ContentType).Returns(contentType); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Request).Returns(request.Object); return httpContext.Object; } private class TestXmlSerializerInputFormatter : XmlSerializerInputFormatter { public int createSerializerCalledCount = 0; public TestXmlSerializerInputFormatter() : base(new MvcOptions()) { } protected override XmlSerializer CreateSerializer(Type type) { createSerializerCalledCount++; return base.CreateSerializer(type); } } private class TestResponseFeature : HttpResponseFeature { public override void OnCompleted(Func<object, Task> callback, object state) { // do not do anything } } private class VerifyDisposeFileBufferingReadStream : FileBufferingReadStream { public bool Disposed { get; private set; } public VerifyDisposeFileBufferingReadStream(Stream inner, int memoryThreshold) : base(inner, memoryThreshold) { } protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } public override ValueTask DisposeAsync() { Disposed = true; return base.DisposeAsync(); } } } }
using System; using System.Collections.Generic; using System.Linq; using ModestTree; #if !NOT_UNITY3D using UnityEngine; #endif namespace Zenject { public class FactoryFromBinderBase<TContract> : ConditionBinder { public FactoryFromBinderBase( BindInfo bindInfo, Type factoryType, BindFinalizerWrapper finalizerWrapper) : base(bindInfo) { // Note that it doesn't derive from Factory<TContract> // when used with To<>, so we can only check IDynamicFactory Assert.That(factoryType.DerivesFrom<IDynamicFactory>()); FactoryType = factoryType; FinalizerWrapper = finalizerWrapper; // Default to just creating it using new finalizerWrapper.SubFinalizer = CreateFinalizer( (container) => new TransientProvider(ContractType, container)); } protected Type FactoryType { get; private set; } protected Type ContractType { get { return typeof(TContract); } } protected BindFinalizerWrapper FinalizerWrapper { get; private set; } protected IBindingFinalizer SubFinalizer { set { FinalizerWrapper.SubFinalizer = value; } } public IEnumerable<Type> AllParentTypes { get { yield return ContractType; foreach (var type in BindInfo.ToTypes) { yield return type; } } } protected IBindingFinalizer CreateFinalizer(Func<DiContainer, IProvider> providerFunc) { return new DynamicFactoryBindingFinalizer<TContract>( BindInfo, FactoryType, providerFunc); } // Note that this isn't necessary to call since it's the default public ConditionBinder FromNew() { BindingUtil.AssertIsNotComponent(ContractType); BindingUtil.AssertIsNotAbstract(ContractType); return this; } public ConditionBinder FromResolve() { return FromResolve(null); } public ConditionBinder FromResolve(object subIdentifier) { SubFinalizer = CreateFinalizer( (container) => new ResolveProvider( ContractType, container, subIdentifier, false)); return this; } #if !NOT_UNITY3D public GameObjectNameGroupNameBinder FromGameObject() { var gameObjectInfo = new GameObjectBindInfo(); if (ContractType == typeof(GameObject)) { SubFinalizer = CreateFinalizer( (container) => new EmptyGameObjectProvider( container, gameObjectInfo.Name, gameObjectInfo.GroupName)); } else { BindingUtil.AssertIsComponent(ContractType); BindingUtil.AssertIsNotAbstract(ContractType); SubFinalizer = CreateFinalizer( (container) => new AddToNewGameObjectComponentProvider( container, ContractType, null, new List<TypeValuePair>(), gameObjectInfo.Name, gameObjectInfo.GroupName)); } return new GameObjectNameGroupNameBinder(BindInfo, gameObjectInfo); } public ConditionBinder FromComponent(GameObject gameObject) { BindingUtil.AssertIsValidGameObject(gameObject); BindingUtil.AssertIsComponent(ContractType); BindingUtil.AssertIsNotAbstract(ContractType); SubFinalizer = CreateFinalizer( (container) => new AddToExistingGameObjectComponentProvider( gameObject, container, ContractType, null, new List<TypeValuePair>())); return this; } public GameObjectNameGroupNameBinder FromPrefab(UnityEngine.Object prefab) { BindingUtil.AssertIsValidPrefab(prefab); var gameObjectInfo = new GameObjectBindInfo(); if (ContractType == typeof(GameObject)) { SubFinalizer = CreateFinalizer( (container) => new PrefabGameObjectProvider( new PrefabInstantiator( container, gameObjectInfo.Name, gameObjectInfo.GroupName, new List<TypeValuePair>(), new PrefabProvider(prefab)))); } else { BindingUtil.AssertIsAbstractOrComponent(ContractType); SubFinalizer = CreateFinalizer( (container) => new GetFromPrefabComponentProvider( ContractType, new PrefabInstantiator( container, gameObjectInfo.Name, gameObjectInfo.GroupName, new List<TypeValuePair>(), new PrefabProvider(prefab)))); } return new GameObjectNameGroupNameBinder(BindInfo, gameObjectInfo); } public GameObjectNameGroupNameBinder FromPrefabResource(string resourcePath) { BindingUtil.AssertIsValidResourcePath(resourcePath); var gameObjectInfo = new GameObjectBindInfo(); if (ContractType == typeof(GameObject)) { SubFinalizer = CreateFinalizer( (container) => new PrefabGameObjectProvider( new PrefabInstantiator( container, gameObjectInfo.Name, gameObjectInfo.GroupName, new List<TypeValuePair>(), new PrefabProviderResource(resourcePath)))); } else { BindingUtil.AssertIsAbstractOrComponent(ContractType); SubFinalizer = CreateFinalizer( (container) => new GetFromPrefabComponentProvider( ContractType, new PrefabInstantiator( container, gameObjectInfo.Name, gameObjectInfo.GroupName, new List<TypeValuePair>(), new PrefabProviderResource(resourcePath)))); } return new GameObjectNameGroupNameBinder(BindInfo, gameObjectInfo); } #endif } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Abp.Application.Features; using Abp.Authorization.Roles; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Domain.Repositories; using Abp.Domain.Services; using Abp.Domain.Uow; using Abp.Json; using Abp.Localization; using Abp.MultiTenancy; using Abp.Organizations; using Abp.Runtime.Caching; using Abp.Runtime.Session; using Abp.UI; using Abp.Zero; using Abp.Zero.Configuration; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Abp.Authorization.Users { public class AbpUserManager<TRole, TUser> : UserManager<TUser>, IDomainService where TRole : AbpRole<TUser>, new() where TUser : AbpUser<TUser> { protected IUserPermissionStore<TUser> UserPermissionStore { get { if (!(Store is IUserPermissionStore<TUser>)) { throw new AbpException("Store is not IUserPermissionStore"); } return Store as IUserPermissionStore<TUser>; } } public ILocalizationManager LocalizationManager { get; set; } protected string LocalizationSourceName { get; set; } public IAbpSession AbpSession { get; set; } public FeatureDependencyContext FeatureDependencyContext { get; set; } protected AbpRoleManager<TRole, TUser> RoleManager { get; } protected AbpUserStore<TRole, TUser> AbpUserStore { get; } public IMultiTenancyConfig MultiTenancy { get; set; } private readonly IPermissionManager _permissionManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ICacheManager _cacheManager; private readonly IRepository<OrganizationUnit, long> _organizationUnitRepository; private readonly IRepository<UserOrganizationUnit, long> _userOrganizationUnitRepository; private readonly IOrganizationUnitSettings _organizationUnitSettings; private readonly ISettingManager _settingManager; private readonly IOptions<IdentityOptions> _optionsAccessor; public AbpUserManager( AbpRoleManager<TRole, TUser> roleManager, AbpUserStore<TRole, TUser> userStore, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository<OrganizationUnit, long> organizationUnitRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager) : base( userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { _permissionManager = permissionManager; _unitOfWorkManager = unitOfWorkManager; _cacheManager = cacheManager; _organizationUnitRepository = organizationUnitRepository; _userOrganizationUnitRepository = userOrganizationUnitRepository; _organizationUnitSettings = organizationUnitSettings; _settingManager = settingManager; _optionsAccessor = optionsAccessor; AbpUserStore = userStore; RoleManager = roleManager; LocalizationManager = NullLocalizationManager.Instance; LocalizationSourceName = AbpZeroConsts.LocalizationSourceName; } public override async Task<IdentityResult> CreateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } var tenantId = GetCurrentTenantId(); if (tenantId.HasValue && !user.TenantId.HasValue) { user.TenantId = tenantId.Value; } var isLockoutEnabled = user.IsLockoutEnabled; var identityResult = await base.CreateAsync(user); if (identityResult.Succeeded) { await SetLockoutEnabledAsync(user, isLockoutEnabled); } return identityResult; } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permissionName">Permission name</param> public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName) { return await IsGrantedAsync( userId, _permissionManager.GetPermission(permissionName) ); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission) { return IsGrantedAsync(user.Id, permission); } /// <summary> /// Check whether a user is granted for a permission. /// </summary> /// <param name="userId">User id</param> /// <param name="permission">Permission</param> public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission) { //Check for multi-tenancy side if (!permission.MultiTenancySides.HasFlag(GetCurrentMultiTenancySide())) { return false; } //Check for depended features if (permission.FeatureDependency != null && GetCurrentMultiTenancySide() == MultiTenancySides.Tenant) { FeatureDependencyContext.TenantId = GetCurrentTenantId(); if (!await permission.FeatureDependency.IsSatisfiedAsync(FeatureDependencyContext)) { return false; } } //Get cached user permissions var cacheItem = await GetUserPermissionCacheItemAsync(userId); if (cacheItem == null) { return false; } //Check for user-specific value if (cacheItem.GrantedPermissions.Contains(permission.Name)) { return true; } if (cacheItem.ProhibitedPermissions.Contains(permission.Name)) { return false; } //Check for roles foreach (var roleId in cacheItem.RoleIds) { if (await RoleManager.IsGrantedAsync(roleId, permission)) { return true; } } return false; } /// <summary> /// Gets granted permissions for a user. /// </summary> /// <param name="user">Role</param> /// <returns>List of granted permissions</returns> public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user) { var permissionList = new List<Permission>(); foreach (var permission in _permissionManager.GetAllPermissions()) { if (await IsGrantedAsync(user.Id, permission)) { permissionList.Add(permission); } } return permissionList; } /// <summary> /// Sets all granted permissions of a user at once. /// Prohibits all other permissions. /// </summary> /// <param name="user">The user</param> /// <param name="permissions">Permissions</param> public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions) { var oldPermissions = await GetGrantedPermissionsAsync(user); var newPermissions = permissions.ToArray(); foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p))) { await ProhibitPermissionAsync(user, permission); } foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p))) { await GrantPermissionAsync(user, permission); } } /// <summary> /// Prohibits all permissions for a user. /// </summary> /// <param name="user">User</param> public async Task ProhibitAllPermissionsAsync(TUser user) { foreach (var permission in _permissionManager.GetAllPermissions()) { await ProhibitPermissionAsync(user, permission); } } /// <summary> /// Resets all permission settings for a user. /// It removes all permission settings for the user. /// User will have permissions according to his roles. /// This method does not prohibit all permissions. /// For that, use <see cref="ProhibitAllPermissionsAsync"/>. /// </summary> /// <param name="user">User</param> public async Task ResetAllPermissionsAsync(TUser user) { await UserPermissionStore.RemoveAllPermissionSettingsAsync(user); } /// <summary> /// Grants a permission for a user if not already granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task GrantPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); if (await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); } /// <summary> /// Prohibits a permission for a user if it's granted. /// </summary> /// <param name="user">User</param> /// <param name="permission">Permission</param> public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission) { await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true)); if (!await IsGrantedAsync(user.Id, permission)) { return; } await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false)); } public virtual Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(userNameOrEmailAddress); } public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login) { return AbpUserStore.FindAllAsync(login); } public virtual Task<TUser> FindAsync(int? tenantId, UserLoginInfo login) { return AbpUserStore.FindAsync(tenantId, login); } public virtual Task<TUser> FindByNameOrEmailAsync(int? tenantId, string userNameOrEmailAddress) { return AbpUserStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress); } /// <summary> /// Gets a user by given id. /// Throws exception if no user found with given id. /// </summary> /// <param name="userId">User id</param> /// <returns>User</returns> /// <exception cref="AbpException">Throws exception if no user found with given id</exception> public virtual async Task<TUser> GetUserByIdAsync(long userId) { var user = await FindByIdAsync(userId.ToString()); if (user == null) { throw new AbpException("There is no user with id: " + userId); } return user; } public override async Task<IdentityResult> UpdateAsync(TUser user) { var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress); if (!result.Succeeded) { return result; } //Admin user's username can not be changed! if (user.UserName != AbpUserBase.AdminUserName) { if ((await GetOldUserNameAsync(user.Id)) == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotRenameAdminUser"), AbpUserBase.AdminUserName)); } } return await base.UpdateAsync(user); } public override async Task<IdentityResult> DeleteAsync(TUser user) { if (user.UserName == AbpUserBase.AdminUserName) { throw new UserFriendlyException(string.Format(L("CanNotDeleteAdminUser"), AbpUserBase.AdminUserName)); } return await base.DeleteAsync(user); } public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword) { var errors = new List<IdentityError>(); foreach (var validator in PasswordValidators) { var validationResult = await validator.ValidateAsync(this, user, newPassword); if (!validationResult.Succeeded) { errors.AddRange(validationResult.Errors); } } if (errors.Any()) { return IdentityResult.Failed(errors.ToArray()); } await AbpUserStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(user, newPassword)); return IdentityResult.Success; } public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress) { var user = (await FindByNameAsync(userName)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateUserName"), userName)); } user = (await FindByEmailAsync(emailAddress)); if (user != null && user.Id != expectedUserId) { throw new UserFriendlyException(string.Format(L("Identity.DuplicateEmail"), emailAddress)); } return IdentityResult.Success; } public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames) { await AbpUserStore.UserRepository.EnsureCollectionLoadedAsync(user, u => u.Roles); //Remove from removed roles foreach (var userRole in user.Roles.ToList()) { var role = await RoleManager.FindByIdAsync(userRole.RoleId.ToString()); if (roleNames.All(roleName => role.Name != roleName)) { var result = await RemoveFromRoleAsync(user, role.Name); if (!result.Succeeded) { return result; } } } //Add to added roles foreach (var roleName in roleNames) { var role = await RoleManager.GetRoleByNameAsync(roleName); if (user.Roles.All(ur => ur.RoleId != role.Id)) { var result = await AddToRoleAsync(user, roleName); if (!result.Succeeded) { return result; } } } return IdentityResult.Success; } public virtual async Task<bool> IsInOrganizationUnitAsync(long userId, long ouId) { return await IsInOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task<bool> IsInOrganizationUnitAsync(TUser user, OrganizationUnit ou) { return await _userOrganizationUnitRepository.CountAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id ) > 0; } public virtual async Task AddToOrganizationUnitAsync(long userId, long ouId) { await AddToOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task AddToOrganizationUnitAsync(TUser user, OrganizationUnit ou) { var currentOus = await GetOrganizationUnitsAsync(user); if (currentOus.Any(cou => cou.Id == ou.Id)) { return; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, currentOus.Count + 1); await _userOrganizationUnitRepository.InsertAsync(new UserOrganizationUnit(user.TenantId, user.Id, ou.Id)); } public virtual async Task RemoveFromOrganizationUnitAsync(long userId, long ouId) { await RemoveFromOrganizationUnitAsync( await GetUserByIdAsync(userId), await _organizationUnitRepository.GetAsync(ouId) ); } public virtual async Task RemoveFromOrganizationUnitAsync(TUser user, OrganizationUnit ou) { await _userOrganizationUnitRepository.DeleteAsync(uou => uou.UserId == user.Id && uou.OrganizationUnitId == ou.Id); } public virtual async Task SetOrganizationUnitsAsync(long userId, params long[] organizationUnitIds) { await SetOrganizationUnitsAsync( await GetUserByIdAsync(userId), organizationUnitIds ); } private async Task CheckMaxUserOrganizationUnitMembershipCountAsync(int? tenantId, int requestedCount) { var maxCount = await _organizationUnitSettings.GetMaxUserMembershipCountAsync(tenantId); if (requestedCount > maxCount) { throw new AbpException($"Can not set more than {maxCount} organization unit for a user!"); } } public virtual async Task SetOrganizationUnitsAsync(TUser user, params long[] organizationUnitIds) { if (organizationUnitIds == null) { organizationUnitIds = new long[0]; } await CheckMaxUserOrganizationUnitMembershipCountAsync(user.TenantId, organizationUnitIds.Length); var currentOus = await GetOrganizationUnitsAsync(user); //Remove from removed OUs foreach (var currentOu in currentOus) { if (!organizationUnitIds.Contains(currentOu.Id)) { await RemoveFromOrganizationUnitAsync(user, currentOu); } } //Add to added OUs foreach (var organizationUnitId in organizationUnitIds) { if (currentOus.All(ou => ou.Id != organizationUnitId)) { await AddToOrganizationUnitAsync( user, await _organizationUnitRepository.GetAsync(organizationUnitId) ); } } } [UnitOfWork] public virtual Task<List<OrganizationUnit>> GetOrganizationUnitsAsync(TUser user) { var query = from uou in _userOrganizationUnitRepository.GetAll() join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where uou.UserId == user.Id select ou; return Task.FromResult(query.ToList()); } [UnitOfWork] public virtual Task<List<TUser>> GetUsersInOrganizationUnit(OrganizationUnit organizationUnit, bool includeChildren = false) { if (!includeChildren) { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id where uou.OrganizationUnitId == organizationUnit.Id select user; return Task.FromResult(query.ToList()); } else { var query = from uou in _userOrganizationUnitRepository.GetAll() join user in Users on uou.UserId equals user.Id join ou in _organizationUnitRepository.GetAll() on uou.OrganizationUnitId equals ou.Id where ou.Code.StartsWith(organizationUnit.Code) select user; return Task.FromResult(query.ToList()); } } public virtual async Task InitializeOptionsAsync(int? tenantId) { Options = JsonConvert.DeserializeObject<IdentityOptions>(_optionsAccessor.Value.ToJsonString()); //Lockout Options.Lockout.AllowedForNewUsers = await IsTrueAsync(AbpZeroSettingNames.UserManagement.UserLockOut.IsEnabled, tenantId); Options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.DefaultAccountLockoutSeconds, tenantId)); Options.Lockout.MaxFailedAccessAttempts = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.UserLockOut.MaxFailedAccessAttemptsBeforeLockout, tenantId); //Password complexity Options.Password.RequireDigit = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireDigit, tenantId); Options.Password.RequireLowercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireLowercase, tenantId); Options.Password.RequireNonAlphanumeric = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, tenantId); Options.Password.RequireUppercase = await GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, tenantId); Options.Password.RequiredLength = await GetSettingValueAsync<int>(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, tenantId); } protected virtual Task<string> GetOldUserNameAsync(long userId) { return AbpUserStore.GetUserNameFromDatabaseAsync(userId); } private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId) { var cacheKey = userId + "@" + (GetCurrentTenantId() ?? 0); return await _cacheManager.GetUserPermissionCache().GetAsync(cacheKey, async () => { var user = await FindByIdAsync(userId.ToString()); if (user == null) { return null; } var newCacheItem = new UserPermissionCacheItem(userId); foreach (var roleName in await GetRolesAsync(user)) { newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id); } foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId)) { if (permissionInfo.IsGranted) { newCacheItem.GrantedPermissions.Add(permissionInfo.Name); } else { newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name); } } return newCacheItem; }); } public override async Task<IList<string>> GetValidTwoFactorProvidersAsync(TUser user) { var providers = new List<string>(); foreach (var provider in await base.GetValidTwoFactorProvidersAsync(user)) { if (provider == "Email" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEmailProviderEnabled, user.TenantId)) { continue; } if (provider == "Phone" && !await IsTrueAsync(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsSmsProviderEnabled, user.TenantId)) { continue; } providers.Add(provider); } return providers; } private bool IsTrue(string settingName, int? tenantId) { return GetSettingValue<bool>(settingName, tenantId); } private Task<bool> IsTrueAsync(string settingName, int? tenantId) { return GetSettingValueAsync<bool>(settingName, tenantId); } private T GetSettingValue<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplication<T>(settingName) : _settingManager.GetSettingValueForTenant<T>(settingName, tenantId.Value); } private Task<T> GetSettingValueAsync<T>(string settingName, int? tenantId) where T : struct { return tenantId == null ? _settingManager.GetSettingValueForApplicationAsync<T>(settingName) : _settingManager.GetSettingValueForTenantAsync<T>(settingName, tenantId.Value); } protected virtual string L(string name) { return LocalizationManager.GetString(LocalizationSourceName, name); } protected virtual string L(string name, CultureInfo cultureInfo) { return LocalizationManager.GetString(LocalizationSourceName, name, cultureInfo); } private int? GetCurrentTenantId() { if (_unitOfWorkManager.Current != null) { return _unitOfWorkManager.Current.GetTenantId(); } return AbpSession.TenantId; } private MultiTenancySides GetCurrentMultiTenancySide() { if (_unitOfWorkManager.Current != null) { return MultiTenancy.IsEnabled && !_unitOfWorkManager.Current.GetTenantId().HasValue ? MultiTenancySides.Host : MultiTenancySides.Tenant; } return AbpSession.MultiTenancySide; } public virtual async Task AddTokenValidityKeyAsync( TUser user, string tokenValidityKey, DateTime expireDate, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.AddTokenValidityKeyAsync(user, tokenValidityKey, expireDate, cancellationToken); } public virtual async Task<bool> IsTokenValidityKeyValidAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { return await AbpUserStore.IsTokenValidityKeyValidAsync(user, tokenValidityKey, cancellationToken); } public virtual async Task RemoveTokenValidityKeyAsync( TUser user, string tokenValidityKey, CancellationToken cancellationToken = default(CancellationToken)) { await AbpUserStore.RemoveTokenValidityKeyAsync(user, tokenValidityKey, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using System.Xml.Schema; using System.Xml.XPath; using System.Security; using System.Globalization; using System.Runtime.Versioning; namespace System.Xml { // Represents an entire document. An XmlDocument contains XML data. public class XmlDocument : XmlNode { private XmlImplementation _implementation; private DomNameTable _domNameTable; // hash table of XmlName private XmlLinkedNode _lastChild; private XmlNamedNodeMap _entities; // TODO: _htElementIdMap can be Dictionary<string, List<WeakReference<XmlElement>>> private Hashtable _htElementIdMap; private Hashtable _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected) private SchemaInfo _schemaInfo; private XmlSchemaSet _schemas; // schemas associated with the cache private bool _reportValidity; //This variable represents the actual loading status. Since, IsLoading will //be manipulated sometimes for adding content to EntityReference this variable //has been added which would always represent the loading status of document. private bool _actualLoadingStatus; private XmlNodeChangedEventHandler _onNodeInsertingDelegate; private XmlNodeChangedEventHandler _onNodeInsertedDelegate; private XmlNodeChangedEventHandler _onNodeRemovingDelegate; private XmlNodeChangedEventHandler _onNodeRemovedDelegate; private XmlNodeChangedEventHandler _onNodeChangingDelegate; private XmlNodeChangedEventHandler _onNodeChangedDelegate; // false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag) internal bool fEntRefNodesPresent; internal bool fCDataNodesPresent; private bool _preserveWhitespace; private bool _isLoading; // special name strings for internal string strDocumentName; internal string strDocumentFragmentName; internal string strCommentName; internal string strTextName; internal string strCDataSectionName; internal string strEntityName; internal string strID; internal string strXmlns; internal string strXml; internal string strSpace; internal string strLang; internal string strEmpty; internal string strNonSignificantWhitespaceName; internal string strSignificantWhitespaceName; internal string strReservedXmlns; internal string strReservedXml; internal String baseURI; private XmlResolver _resolver; internal bool bSetResolver; internal object objLock; private XmlAttribute _namespaceXml; internal static EmptyEnumerator EmptyEnumerator = new EmptyEnumerator(); internal static IXmlSchemaInfo NotKnownSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.NotKnown); internal static IXmlSchemaInfo ValidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Valid); internal static IXmlSchemaInfo InvalidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Invalid); // Initializes a new instance of the XmlDocument class. public XmlDocument() : this(new XmlImplementation()) { } // Initializes a new instance // of the XmlDocument class with the specified XmlNameTable. public XmlDocument(XmlNameTable nt) : this(new XmlImplementation(nt)) { } protected internal XmlDocument(XmlImplementation imp) : base() { _implementation = imp; _domNameTable = new DomNameTable(this); // force the following string instances to be default in the nametable XmlNameTable nt = this.NameTable; nt.Add(string.Empty); strDocumentName = nt.Add("#document"); strDocumentFragmentName = nt.Add("#document-fragment"); strCommentName = nt.Add("#comment"); strTextName = nt.Add("#text"); strCDataSectionName = nt.Add("#cdata-section"); strEntityName = nt.Add("#entity"); strID = nt.Add("id"); strNonSignificantWhitespaceName = nt.Add("#whitespace"); strSignificantWhitespaceName = nt.Add("#significant-whitespace"); strXmlns = nt.Add("xmlns"); strXml = nt.Add("xml"); strSpace = nt.Add("space"); strLang = nt.Add("lang"); strReservedXmlns = nt.Add(XmlReservedNs.NsXmlNs); strReservedXml = nt.Add(XmlReservedNs.NsXml); strEmpty = nt.Add(String.Empty); baseURI = String.Empty; objLock = new object(); } internal SchemaInfo DtdSchemaInfo { get { return _schemaInfo; } set { _schemaInfo = value; } } // NOTE: This does not correctly check start name char, but we cannot change it since it would be a breaking change. internal static void CheckName(String name) { int endPos = ValidateNames.ParseNmtoken(name, 0); if (endPos < name.Length) { throw new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } } internal XmlName AddXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)); Debug.Assert(n.LocalName == localName); Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)); return n; } internal XmlName GetXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix))); Debug.Assert(n == null || n.LocalName == localName); Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI))); return n; } internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo) { XmlName xmlName = AddXmlName(prefix, localName, namespaceURI, schemaInfo); Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix)); Debug.Assert(xmlName.LocalName == localName); Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI)); if (!this.IsLoading) { // Use atomized versions instead of prefix, localName and nsURI object oPrefix = xmlName.Prefix; object oNamespaceURI = xmlName.NamespaceURI; object oLocalName = xmlName.LocalName; if ((oPrefix == (object)strXmlns || (oPrefix == (object)strEmpty && oLocalName == (object)strXmlns)) ^ (oNamespaceURI == (object)strReservedXmlns)) throw new ArgumentException(SR.Format(SR.Xdom_Attr_Reserved_XmlNS, namespaceURI)); } return xmlName; } internal bool AddIdInfo(XmlName eleName, XmlName attrName) { //when XmlLoader call XmlDocument.AddInfo, the element.XmlName and attr.XmlName //have already been replaced with the ones that don't have namespace values (or just //string.Empty) because in DTD, the namespace is not supported if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null) { if (_htElementIDAttrDecl == null) _htElementIDAttrDecl = new Hashtable(); _htElementIDAttrDecl.Add(eleName, attrName); return true; } return false; } private XmlName GetIDInfoByElement_(XmlName eleName) { //When XmlDocument is getting the IDAttribute for a given element, //we need only compare the prefix and localname of element.XmlName with //the registered htElementIDAttrDecl. XmlName newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null); if (newName != null) { return (XmlName)(_htElementIDAttrDecl[newName]); } return null; } internal XmlName GetIDInfoByElement(XmlName eleName) { if (_htElementIDAttrDecl == null) return null; else return GetIDInfoByElement_(eleName); } private WeakReference GetElement(ArrayList elementList, XmlElement elem) { ArrayList gcElemRefs = new ArrayList(); foreach (WeakReference elemRef in elementList) { if (!elemRef.IsAlive) //take notes on the garbage collected nodes gcElemRefs.Add(elemRef); else { if ((XmlElement)(elemRef.Target) == elem) return elemRef; } } //Clear out the gced elements foreach (WeakReference elemRef in gcElemRefs) elementList.Remove(elemRef); return null; } internal void AddElementWithId(string id, XmlElement elem) { if (_htElementIdMap == null || !_htElementIdMap.Contains(id)) { if (_htElementIdMap == null) _htElementIdMap = new Hashtable(); ArrayList elementList = new ArrayList(); elementList.Add(new WeakReference(elem)); _htElementIdMap.Add(id, elementList); } else { // there are other element(s) that has the same id ArrayList elementList = (ArrayList)(_htElementIdMap[id]); if (GetElement(elementList, elem) == null) elementList.Add(new WeakReference(elem)); } } internal void RemoveElementWithId(string id, XmlElement elem) { if (_htElementIdMap != null && _htElementIdMap.Contains(id)) { ArrayList elementList = (ArrayList)(_htElementIdMap[id]); WeakReference elemRef = GetElement(elementList, elem); if (elemRef != null) { elementList.Remove(elemRef); if (elementList.Count == 0) _htElementIdMap.Remove(id); } } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { XmlDocument clone = Implementation.CreateDocument(); clone.SetBaseURI(this.baseURI); if (deep) clone.ImportChildren(this, clone, deep); return clone; } // Gets the type of the current node. public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } public override XmlNode ParentNode { get { return null; } } // Gets the node for the DOCTYPE declaration. public virtual XmlDocumentType DocumentType { get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); } } internal virtual XmlDeclaration Declaration { get { if (HasChildNodes) { XmlDeclaration dec = FirstChild as XmlDeclaration; return dec; } return null; } } // Gets the XmlImplementation object for this document. public XmlImplementation Implementation { get { return _implementation; } } // Gets the name of the node. public override String Name { get { return strDocumentName; } } // Gets the name of the current node without the namespace prefix. public override String LocalName { get { return strDocumentName; } } // Gets the root XmlElement for the document. public XmlElement DocumentElement { get { return (XmlElement)FindChild(XmlNodeType.Element); } } internal override bool IsContainer { get { return true; } } internal override XmlLinkedNode LastNode { get { return _lastChild; } set { _lastChild = value; } } // Gets the XmlDocument that contains this node. public override XmlDocument OwnerDocument { get { return null; } } public XmlSchemaSet Schemas { get { if (_schemas == null) { _schemas = new XmlSchemaSet(NameTable); } return _schemas; } set { _schemas = value; } } internal bool CanReportValidity { get { return _reportValidity; } } internal bool HasSetResolver { get { return bSetResolver; } } internal XmlResolver GetResolver() { return _resolver; } public virtual XmlResolver XmlResolver { set { _resolver = value; if (!bSetResolver) bSetResolver = true; XmlDocumentType dtd = this.DocumentType; if (dtd != null) { dtd.DtdSchemaInfo = null; } } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: if (DocumentType != null) throw new InvalidOperationException(SR.Xdom_DualDocumentTypeNode); return true; case XmlNodeType.Element: if (DocumentElement != null) throw new InvalidOperationException(SR.Xdom_DualDocumentElementNode); return true; case XmlNodeType.XmlDeclaration: if (Declaration != null) throw new InvalidOperationException(SR.Xdom_DualDeclarationNode); return true; default: return false; } } // the function examines all the siblings before the refNode // if any of the nodes has type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode) { if (refNode == null) return false; XmlNode node = null; if (refNode.ParentNode != null) node = refNode.ParentNode.FirstChild; while (node != null) { if (node.NodeType == nt) return true; if (node == refNode) break; node = node.NextSibling; } return false; } // the function examines all the siblings after the refNode // if any of the nodes has the type equals to "nt", return true; otherwise, return false; private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode) { XmlNode node = refNode; while (node != null) { if (node.NodeType == nt) return true; node = node.NextSibling; } return false; } internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = FirstChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.XmlDeclaration: return (refChild == FirstChild); case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: return refChild.NodeType != XmlNodeType.XmlDeclaration; case XmlNodeType.DocumentType: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the sibling before and including refChild to // make sure no Element ( rootElem node ) before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild.PreviousSibling); } } break; case XmlNodeType.Element: { if (refChild.NodeType != XmlNodeType.XmlDeclaration) { //if refChild is not the XmlDeclaration node, only need to go through the siblings after and including the refChild to // make sure no DocType node and XmlDeclaration node after the current position. return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild); } } break; } return false; } internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild) { if (refChild == null) refChild = LastChild; if (refChild == null) return true; switch (newChild.NodeType) { case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.DocumentType: { //we will have to go through all the siblings before the refChild just to make sure no Element node ( rootElem ) // before the current position return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild); } case XmlNodeType.Element: { return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild.NextSibling); } } return false; } // Creates an XmlAttribute with the specified name. public XmlAttribute CreateAttribute(String name) { String prefix = String.Empty; String localName = String.Empty; String namespaceURI = String.Empty; SplitName(name, out prefix, out localName); SetDefaultNamespace(prefix, localName, ref namespaceURI); return CreateAttribute(prefix, localName, namespaceURI); } internal void SetDefaultNamespace(String prefix, String localName, ref String namespaceURI) { if (prefix == strXmlns || (prefix.Length == 0 && localName == strXmlns)) { namespaceURI = strReservedXmlns; } else if (prefix == strXml) { namespaceURI = strReservedXml; } } // Creates a XmlCDataSection containing the specified data. public virtual XmlCDataSection CreateCDataSection(String data) { fCDataNodesPresent = true; return new XmlCDataSection(data, this); } // Creates an XmlComment containing the specified data. public virtual XmlComment CreateComment(String data) { return new XmlComment(data, this); } // Returns a new XmlDocumentType object. public virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset) { return new XmlDocumentType(name, publicId, systemId, internalSubset, this); } // Creates an XmlDocumentFragment. public virtual XmlDocumentFragment CreateDocumentFragment() { return new XmlDocumentFragment(this); } // Creates an element with the specified name. public XmlElement CreateElement(String name) { string prefix = String.Empty; string localName = String.Empty; SplitName(name, out prefix, out localName); return CreateElement(prefix, localName, string.Empty); } internal void AddDefaultAttributes(XmlElement elem) { SchemaInfo schInfo = DtdSchemaInfo; SchemaElementDecl ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator(); while (attrDefs.MoveNext()) { SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value; if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed) { //build a default attribute and return string attrPrefix = string.Empty; string attrLocalname = attdef.Name.Name; string attrNamespaceURI = string.Empty; if (schInfo.SchemaType == SchemaType.DTD) attrPrefix = attdef.Name.Namespace; else { attrPrefix = attdef.Prefix; attrNamespaceURI = attdef.Name.Namespace; } XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI); elem.SetAttributeNode(defattr); } } } } private SchemaElementDecl GetSchemaElementDecl(XmlElement elem) { SchemaInfo schInfo = DtdSchemaInfo; if (schInfo != null) { //build XmlQualifiedName used to identify the element schema declaration XmlQualifiedName qname = new XmlQualifiedName(elem.LocalName, schInfo.SchemaType == SchemaType.DTD ? elem.Prefix : elem.NamespaceURI); //get the schema info for the element SchemaElementDecl elemDecl; if (schInfo.ElementDecls.TryGetValue(qname, out elemDecl)) { return elemDecl; } } return null; } //Will be used by AddDeafulatAttributes() and GetDefaultAttribute() methods private XmlAttribute PrepareDefaultAttribute(SchemaAttDef attdef, string attrPrefix, string attrLocalname, string attrNamespaceURI) { SetDefaultNamespace(attrPrefix, attrLocalname, ref attrNamespaceURI); XmlAttribute defattr = CreateDefaultAttribute(attrPrefix, attrLocalname, attrNamespaceURI); //parsing the default value for the default attribute defattr.InnerXml = attdef.DefaultValueRaw; //during the expansion of the tree, the flag could be set to true, we need to set it back. XmlUnspecifiedAttribute unspAttr = defattr as XmlUnspecifiedAttribute; if (unspAttr != null) { unspAttr.SetSpecified(false); } return defattr; } // Creates an XmlEntityReference with the specified name. public virtual XmlEntityReference CreateEntityReference(String name) { return new XmlEntityReference(name, this); } // Creates a XmlProcessingInstruction with the specified name // and data strings. public virtual XmlProcessingInstruction CreateProcessingInstruction(String target, String data) { return new XmlProcessingInstruction(target, data, this); } // Creates a XmlDeclaration node with the specified values. public virtual XmlDeclaration CreateXmlDeclaration(String version, string encoding, string standalone) { return new XmlDeclaration(version, encoding, standalone, this); } // Creates an XmlText with the specified text. public virtual XmlText CreateTextNode(String text) { return new XmlText(text, this); } // Creates a XmlSignificantWhitespace node. public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text) { return new XmlSignificantWhitespace(text, this); } public override XPathNavigator CreateNavigator() { return CreateNavigator(this); } protected internal virtual XPathNavigator CreateNavigator(XmlNode node) { XmlNodeType nodeType = node.NodeType; XmlNode parent; XmlNodeType parentType; switch (nodeType) { case XmlNodeType.EntityReference: case XmlNodeType.Entity: case XmlNodeType.DocumentType: case XmlNodeType.Notation: case XmlNodeType.XmlDeclaration: return null; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.SignificantWhitespace: parent = node.ParentNode; if (parent != null) { do { parentType = parent.NodeType; if (parentType == XmlNodeType.Attribute) { return null; } else if (parentType == XmlNodeType.EntityReference) { parent = parent.ParentNode; } else { break; } } while (parent != null); } node = NormalizeText(node); break; case XmlNodeType.Whitespace: parent = node.ParentNode; if (parent != null) { do { parentType = parent.NodeType; if (parentType == XmlNodeType.Document || parentType == XmlNodeType.Attribute) { return null; } else if (parentType == XmlNodeType.EntityReference) { parent = parent.ParentNode; } else { break; } } while (parent != null); } node = NormalizeText(node); break; default: break; } return new DocumentXPathNavigator(this, node); } internal static bool IsTextNode(XmlNodeType nt) { switch (nt) { case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: return true; default: return false; } } private XmlNode NormalizeText(XmlNode n) { XmlNode retnode = null; while (IsTextNode(n.NodeType)) { retnode = n; n = n.PreviousSibling; if (n == null) { XmlNode intnode = retnode; while (true) { if (intnode.ParentNode != null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference) { if (intnode.ParentNode.PreviousSibling != null) { n = intnode.ParentNode.PreviousSibling; break; } else { intnode = intnode.ParentNode; if (intnode == null) break; } } else break; } } if (n == null) break; while (n.NodeType == XmlNodeType.EntityReference) { n = n.LastChild; } } return retnode; } // Creates a XmlWhitespace node. public virtual XmlWhitespace CreateWhitespace(string text) { return new XmlWhitespace(text, this); } // Returns an XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String name) { return new XmlElementList(this, name); } // DOM Level 2 // Creates an XmlAttribute with the specified LocalName // and NamespaceURI. public XmlAttribute CreateAttribute(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateAttribute(prefix, localName, namespaceURI); } // Creates an XmlElement with the specified LocalName and // NamespaceURI. public XmlElement CreateElement(String qualifiedName, String namespaceURI) { string prefix = String.Empty; string localName = String.Empty; SplitName(qualifiedName, out prefix, out localName); return CreateElement(prefix, localName, namespaceURI); } // Returns a XmlNodeList containing // a list of all descendant elements that match the specified name. public virtual XmlNodeList GetElementsByTagName(String localName, String namespaceURI) { return new XmlElementList(this, localName, namespaceURI); } // Returns the XmlElement with the specified ID. public virtual XmlElement GetElementById(string elementId) { if (_htElementIdMap != null) { ArrayList elementList = (ArrayList)(_htElementIdMap[elementId]); if (elementList != null) { foreach (WeakReference elemRef in elementList) { XmlElement elem = (XmlElement)elemRef.Target; if (elem != null && elem.IsConnected()) return elem; } } } return null; } // Imports a node from another document to this document. public virtual XmlNode ImportNode(XmlNode node, bool deep) { return ImportNodeInternal(node, deep); } private XmlNode ImportNodeInternal(XmlNode node, bool deep) { XmlNode newNode = null; if (node == null) { throw new InvalidOperationException(SR.Xdom_Import_NullNode); } else { switch (node.NodeType) { case XmlNodeType.Element: newNode = CreateElement(node.Prefix, node.LocalName, node.NamespaceURI); ImportAttributes(node, newNode); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.Attribute: Debug.Assert(((XmlAttribute)node).Specified); newNode = CreateAttribute(node.Prefix, node.LocalName, node.NamespaceURI); ImportChildren(node, newNode, true); break; case XmlNodeType.Text: newNode = CreateTextNode(node.Value); break; case XmlNodeType.Comment: newNode = CreateComment(node.Value); break; case XmlNodeType.ProcessingInstruction: newNode = CreateProcessingInstruction(node.Name, node.Value); break; case XmlNodeType.XmlDeclaration: XmlDeclaration decl = (XmlDeclaration)node; newNode = CreateXmlDeclaration(decl.Version, decl.Encoding, decl.Standalone); break; case XmlNodeType.CDATA: newNode = CreateCDataSection(node.Value); break; case XmlNodeType.DocumentType: XmlDocumentType docType = (XmlDocumentType)node; newNode = CreateDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset); break; case XmlNodeType.DocumentFragment: newNode = CreateDocumentFragment(); if (deep) ImportChildren(node, newNode, deep); break; case XmlNodeType.EntityReference: newNode = CreateEntityReference(node.Name); // we don't import the children of entity reference because they might result in different // children nodes given different namespace context in the new document. break; case XmlNodeType.Whitespace: newNode = CreateWhitespace(node.Value); break; case XmlNodeType.SignificantWhitespace: newNode = CreateSignificantWhitespace(node.Value); break; default: throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType.ToString())); } } return newNode; } private void ImportAttributes(XmlNode fromElem, XmlNode toElem) { int cAttr = fromElem.Attributes.Count; for (int iAttr = 0; iAttr < cAttr; iAttr++) { if (fromElem.Attributes[iAttr].Specified) toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true)); } } private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep) { Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference); for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling) { toNode.AppendChild(ImportNodeInternal(n, deep)); } } // Microsoft extensions // Gets the XmlNameTable associated with this // implementation. public XmlNameTable NameTable { get { return _implementation.NameTable; } } // Creates a XmlAttribute with the specified Prefix, LocalName, // and NamespaceURI. public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI) { return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI, null), this); } protected internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI) { return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this); } public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI) { XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI, null), true, this); if (!IsLoading) AddDefaultAttributes(elem); return elem; } // Gets or sets a value indicating whether to preserve whitespace. public bool PreserveWhitespace { get { return _preserveWhitespace; } set { _preserveWhitespace = value; } } // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return false; } } internal XmlNamedNodeMap Entities { get { if (_entities == null) _entities = new XmlNamedNodeMap(this); return _entities; } set { _entities = value; } } internal bool IsLoading { get { return _isLoading; } set { _isLoading = value; } } internal bool ActualLoadingStatus { get { return _actualLoadingStatus; } set { _actualLoadingStatus = value; } } // Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI) { switch (type) { case XmlNodeType.Element: if (prefix != null) return CreateElement(prefix, name, namespaceURI); else return CreateElement(name, namespaceURI); case XmlNodeType.Attribute: if (prefix != null) return CreateAttribute(prefix, name, namespaceURI); else return CreateAttribute(name, namespaceURI); case XmlNodeType.Text: return CreateTextNode(string.Empty); case XmlNodeType.CDATA: return CreateCDataSection(string.Empty); case XmlNodeType.EntityReference: return CreateEntityReference(name); case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction(name, string.Empty); case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration("1.0", null, null); case XmlNodeType.Comment: return CreateComment(string.Empty); case XmlNodeType.DocumentFragment: return CreateDocumentFragment(); case XmlNodeType.DocumentType: return CreateDocumentType(name, string.Empty, string.Empty, string.Empty); case XmlNodeType.Document: return new XmlDocument(); case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace(string.Empty); case XmlNodeType.Whitespace: return CreateWhitespace(string.Empty); default: throw new ArgumentException(SR.Format(SR.Arg_CannotCreateNode, type)); } } // Creates an XmlNode with the specified node type, Name, and // NamespaceURI. public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI) { return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI); } // Creates an XmlNode with the specified XmlNodeType, Name, and // NamespaceURI. public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI) { return CreateNode(type, null, name, namespaceURI); } // Creates an XmlNode object based on the information in the XmlReader. // The reader must be positioned on a node or attribute. public virtual XmlNode ReadNode(XmlReader reader) { XmlNode node = null; try { IsLoading = true; XmlLoader loader = new XmlLoader(); node = loader.ReadCurrentNode(this, reader); } finally { IsLoading = false; } return node; } internal XmlNodeType ConvertToNodeType(string nodeTypeString) { if (nodeTypeString == "element") { return XmlNodeType.Element; } else if (nodeTypeString == "attribute") { return XmlNodeType.Attribute; } else if (nodeTypeString == "text") { return XmlNodeType.Text; } else if (nodeTypeString == "cdatasection") { return XmlNodeType.CDATA; } else if (nodeTypeString == "entityreference") { return XmlNodeType.EntityReference; } else if (nodeTypeString == "entity") { return XmlNodeType.Entity; } else if (nodeTypeString == "processinginstruction") { return XmlNodeType.ProcessingInstruction; } else if (nodeTypeString == "comment") { return XmlNodeType.Comment; } else if (nodeTypeString == "document") { return XmlNodeType.Document; } else if (nodeTypeString == "documenttype") { return XmlNodeType.DocumentType; } else if (nodeTypeString == "documentfragment") { return XmlNodeType.DocumentFragment; } else if (nodeTypeString == "notation") { return XmlNodeType.Notation; } else if (nodeTypeString == "significantwhitespace") { return XmlNodeType.SignificantWhitespace; } else if (nodeTypeString == "whitespace") { return XmlNodeType.Whitespace; } throw new ArgumentException(SR.Format(SR.Xdom_Invalid_NT_String, nodeTypeString)); } private XmlTextReader SetupReader(XmlTextReader tr) { tr.XmlValidatingReaderCompatibilityMode = true; tr.EntityHandling = EntityHandling.ExpandCharEntities; if (this.HasSetResolver) tr.XmlResolver = GetResolver(); return tr; } // Loads the XML document from the specified URL. public virtual void Load(string filename) { XmlTextReader reader = SetupReader(new XmlTextReader(filename, NameTable)); try { Load(reader); } finally { reader.Close(); } } public virtual void Load(Stream inStream) { XmlTextReader reader = SetupReader(new XmlTextReader(inStream, NameTable)); try { Load(reader); } finally { reader.Impl.Close(false); } } // Loads the XML document from the specified TextReader. public virtual void Load(TextReader txtReader) { XmlTextReader reader = SetupReader(new XmlTextReader(txtReader, NameTable)); try { Load(reader); } finally { reader.Impl.Close(false); } } // Loads the XML document from the specified XmlReader. public virtual void Load(XmlReader reader) { try { IsLoading = true; _actualLoadingStatus = true; RemoveAll(); fEntRefNodesPresent = false; fCDataNodesPresent = false; _reportValidity = true; XmlLoader loader = new XmlLoader(); loader.Load(this, reader, _preserveWhitespace); } finally { IsLoading = false; _actualLoadingStatus = false; // Ensure the bit is still on after loading a dtd _reportValidity = true; } } // Loads the XML document from the specified string. public virtual void LoadXml(string xml) { XmlTextReader reader = SetupReader(new XmlTextReader(new StringReader(xml), NameTable)); try { Load(reader); } finally { reader.Close(); } } //TextEncoding is the one from XmlDeclaration if there is any internal Encoding TextEncoding { get { if (Declaration != null) { string value = Declaration.Encoding; if (value.Length > 0) { return System.Text.Encoding.GetEncoding(value); } } return null; } } public override string InnerText { set { throw new InvalidOperationException(SR.Xdom_Document_Innertext); } } public override string InnerXml { get { return base.InnerXml; } set { LoadXml(value); } } // Saves the XML document to the specified file. //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(string filename) { if (DocumentElement == null) throw new XmlException(SR.Xml_InvalidXmlDocument, SR.Xdom_NoRootEle); XmlDOMTextWriter xw = new XmlDOMTextWriter(filename, TextEncoding); try { if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; WriteTo(xw); xw.Flush(); } finally { xw.Close(); } } //Saves out the to the file with exact content in the XmlDocument. public virtual void Save(Stream outStream) { XmlDOMTextWriter xw = new XmlDOMTextWriter(outStream, TextEncoding); if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; WriteTo(xw); xw.Flush(); } // Saves the XML document to the specified TextWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(TextWriter writer) { XmlDOMTextWriter xw = new XmlDOMTextWriter(writer); if (_preserveWhitespace == false) xw.Formatting = Formatting.Indented; Save(xw); } // Saves the XML document to the specified XmlWriter. // //Saves out the file with xmldeclaration which has encoding value equal to //that of textwriter's encoding public virtual void Save(XmlWriter w) { XmlNode n = this.FirstChild; if (n == null) return; if (w.WriteState == WriteState.Start) { if (n is XmlDeclaration) { if (Standalone.Length == 0) w.WriteStartDocument(); else if (Standalone == "yes") w.WriteStartDocument(true); else if (Standalone == "no") w.WriteStartDocument(false); n = n.NextSibling; } else { w.WriteStartDocument(); } } while (n != null) { n.WriteTo(w); n = n.NextSibling; } w.Flush(); } // Saves the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteTo(XmlWriter w) { WriteContentTo(w); } // Saves all the children of the node to the specified XmlWriter. // //Writes out the to the file with exact content in the XmlDocument. public override void WriteContentTo(XmlWriter xw) { foreach (XmlNode n in this) { n.WriteTo(xw); } } public void Validate(ValidationEventHandler validationEventHandler) { Validate(validationEventHandler, this); } public void Validate(ValidationEventHandler validationEventHandler, XmlNode nodeToValidate) { if (_schemas == null || _schemas.Count == 0) { //Should we error throw new InvalidOperationException(SR.XmlDocument_NoSchemaInfo); } XmlDocument parentDocument = nodeToValidate.Document; if (parentDocument != this) { throw new ArgumentException(SR.Format(SR.XmlDocument_NodeNotFromDocument, nameof(nodeToValidate))); } if (nodeToValidate == this) { _reportValidity = false; } DocumentSchemaValidator validator = new DocumentSchemaValidator(this, _schemas, validationEventHandler); validator.Validate(nodeToValidate); if (nodeToValidate == this) { _reportValidity = true; } } public event XmlNodeChangedEventHandler NodeInserting { add { _onNodeInsertingDelegate += value; } remove { _onNodeInsertingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeInserted { add { _onNodeInsertedDelegate += value; } remove { _onNodeInsertedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoving { add { _onNodeRemovingDelegate += value; } remove { _onNodeRemovingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeRemoved { add { _onNodeRemovedDelegate += value; } remove { _onNodeRemovedDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanging { add { _onNodeChangingDelegate += value; } remove { _onNodeChangingDelegate -= value; } } public event XmlNodeChangedEventHandler NodeChanged { add { _onNodeChangedDelegate += value; } remove { _onNodeChangedDelegate -= value; } } internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action) { _reportValidity = false; switch (action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) { return null; } break; case XmlNodeChangedAction.Remove: if (_onNodeRemovingDelegate == null && _onNodeRemovedDelegate == null) { return null; } break; case XmlNodeChangedAction.Change: if (_onNodeChangingDelegate == null && _onNodeChangedDelegate == null) { return null; } break; } return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action); } internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent) { if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null) { return null; } string nodeValue = node.Value; return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert); } internal override void BeforeEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertingDelegate != null) _onNodeInsertingDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (_onNodeRemovingDelegate != null) _onNodeRemovingDelegate(this, args); break; case XmlNodeChangedAction.Change: if (_onNodeChangingDelegate != null) _onNodeChangingDelegate(this, args); break; } } } internal override void AfterEvent(XmlNodeChangedEventArgs args) { if (args != null) { switch (args.Action) { case XmlNodeChangedAction.Insert: if (_onNodeInsertedDelegate != null) _onNodeInsertedDelegate(this, args); break; case XmlNodeChangedAction.Remove: if (_onNodeRemovedDelegate != null) _onNodeRemovedDelegate(this, args); break; case XmlNodeChangedAction.Change: if (_onNodeChangedDelegate != null) _onNodeChangedDelegate(this, args); break; } } } // The function such through schema info to find out if there exists a default attribute with passed in names in the passed in element // If so, return the newly created default attribute (with children tree); // Otherwise, return null. internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI) { SchemaInfo schInfo = DtdSchemaInfo; SchemaElementDecl ed = GetSchemaElementDecl(elem); if (ed != null && ed.AttDefs != null) { IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator(); while (attrDefs.MoveNext()) { SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value; if (attdef.Presence == SchemaDeclBase.Use.Default || attdef.Presence == SchemaDeclBase.Use.Fixed) { if (attdef.Name.Name == attrLocalname) { if ((schInfo.SchemaType == SchemaType.DTD && attdef.Name.Namespace == attrPrefix) || (schInfo.SchemaType != SchemaType.DTD && attdef.Name.Namespace == attrNamespaceURI)) { //find a def attribute with the same name, build a default attribute and return XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI); return defattr; } } } } } return null; } internal String Version { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Version; return null; } } internal String Encoding { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Encoding; return null; } } internal String Standalone { get { XmlDeclaration decl = Declaration; if (decl != null) return decl.Standalone; return null; } } internal XmlEntity GetEntityNode(String name) { if (DocumentType != null) { XmlNamedNodeMap entites = DocumentType.Entities; if (entites != null) return (XmlEntity)(entites.GetNamedItem(name)); } return null; } public override IXmlSchemaInfo SchemaInfo { get { if (_reportValidity) { XmlElement documentElement = DocumentElement; if (documentElement != null) { switch (documentElement.SchemaInfo.Validity) { case XmlSchemaValidity.Valid: return ValidSchemaInfo; case XmlSchemaValidity.Invalid: return InvalidSchemaInfo; } } } return NotKnownSchemaInfo; } } public override String BaseURI { get { return baseURI; } } internal void SetBaseURI(String inBaseURI) { baseURI = inBaseURI; } internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc) { Debug.Assert(doc == this); if (!IsValidChildType(newChild.NodeType)) throw new InvalidOperationException(SR.Xdom_Node_Insert_TypeConflict); if (!CanInsertAfter(newChild, LastChild)) throw new InvalidOperationException(SR.Xdom_Node_Insert_Location); XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this); if (args != null) BeforeEvent(args); XmlLinkedNode newNode = (XmlLinkedNode)newChild; if (_lastChild == null) { newNode.next = newNode; } else { newNode.next = _lastChild.next; _lastChild.next = newNode; } _lastChild = newNode; newNode.SetParentForLoad(this); if (args != null) AfterEvent(args); return newNode; } internal override XPathNodeType XPNodeType { get { return XPathNodeType.Root; } } internal bool HasEntityReferences { get { return fEntRefNodesPresent; } } internal XmlAttribute NamespaceXml { get { if (_namespaceXml == null) { _namespaceXml = new XmlAttribute(AddAttrXmlName(strXmlns, strXml, strReservedXmlns, null), this); _namespaceXml.Value = strReservedXml; } return _namespaceXml; } } } }
// 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.Design; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Versions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Setup { [Guid(Guids.RoslynPackageIdString)] [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", version: 16)] internal class RoslynPackage : AbstractPackage { private LibraryManager _libraryManager; private uint _libraryManagerCookie; private VisualStudioWorkspace _workspace; private WorkspaceFailureOutputPane _outputPane; private IComponentModel _componentModel; private RuleSetEventHandler _ruleSetEventHandler; private IDisposable _solutionEventMonitor; protected override void Initialize() { base.Initialize(); FatalError.Handler = FailFast.OnFatalException; FatalError.NonFatalHandler = WatsonReporter.Report; // We also must set the FailFast handler for the compiler layer as well var compilerAssembly = typeof(Compilation).Assembly; var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true); var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public); var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true); var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic); property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method)); RegisterFindResultsLibraryManager(); var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel)); _workspace = componentModel.GetService<VisualStudioWorkspace>(); var telemetrySetupExtensions = componentModel.GetExtensions<IRoslynTelemetrySetup>(); foreach (var telemetrySetup in telemetrySetupExtensions) { telemetrySetup.Initialize(this); } // set workspace output pane _outputPane = new WorkspaceFailureOutputPane(this, _workspace); InitializeColors(); // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoaded(); _solutionEventMonitor = new SolutionEventMonitor(_workspace); } private void InitializeColors() { // Use VS color keys in order to support theming. CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey; CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey; CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey; CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey; CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey; CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey; } protected override void LoadComponentsInUIContext() { // we need to load it as early as possible since we can have errors from // package from each language very early this.ComponentModel.GetService<VisualStudioDiagnosticListTable>(); this.ComponentModel.GetService<VisualStudioTodoListTable>(); this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this); this.ComponentModel.GetService<HACK_ThemeColorFixer>(); this.ComponentModel.GetExtensions<IDefinitionsAndReferencesPresenter>(); this.ComponentModel.GetExtensions<INavigableItemsPresenter>(); this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>(); this.ComponentModel.GetService<VirtualMemoryNotificationListener>(); // The misc files workspace needs to be loaded on the UI thread. This way it will have // the appropriate task scheduler to report events on. this.ComponentModel.GetService<MiscellaneousFilesWorkspace>(); LoadAnalyzerNodeComponents(); Task.Run(() => LoadComponentsBackground()); } private void LoadComponentsBackground() { // Perf: Initialize the command handlers. var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>(); commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType); LoadInteractiveMenus(); this.ComponentModel.GetService<MiscellaneousTodoListTable>(); this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>(); } private void LoadInteractiveMenus() { var menuCommandService = (OleMenuCommandService)GetService(typeof(IMenuCommandService)); var monitorSelectionService = (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection)); new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommand(); new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommand(); } internal IComponentModel ComponentModel { get { if (_componentModel == null) { _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } return _componentModel; } } protected override void Dispose(bool disposing) { UnregisterFindResultsLibraryManager(); DisposeVisualStudioDocumentTrackingService(); UnregisterAnalyzerTracker(); UnregisterRuleSetEventHandler(); ReportSessionWideTelemetry(); if (_solutionEventMonitor != null) { _solutionEventMonitor.Dispose(); _solutionEventMonitor = null; } base.Dispose(disposing); } private void ReportSessionWideTelemetry() { PersistedVersionStampLogger.LogSummary(); LinkedFileDiffMergingLogger.ReportTelemetry(); } private void RegisterFindResultsLibraryManager() { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { _libraryManager = new LibraryManager(this); if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie))) { _libraryManagerCookie = 0; } ((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true); } } private void UnregisterFindResultsLibraryManager() { if (_libraryManagerCookie != 0) { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { objectManager.UnregisterLibrary(_libraryManagerCookie); _libraryManagerCookie = 0; } ((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true); _libraryManager = null; } } private void DisposeVisualStudioDocumentTrackingService() { if (_workspace != null) { var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService; documentTrackingService.Dispose(); } } private void LoadAnalyzerNodeComponents() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this); _ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>(); if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Register(); } } private void UnregisterAnalyzerTracker() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister(); } private void UnregisterRuleSetEventHandler() { if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Unregister(); _ruleSetEventHandler = null; } } } }
using System; using System.Collections.Generic; namespace GodLesZ.Library { /// <summary> /// Priority Queue /// </summary> /// <typeparam name="T"></typeparam> public class AutoPriorityQueue<T> where T : IComparable<T> { protected List<T> mStoredValues; /// <summary> /// Gets the number of values stored within the Priority Queue /// </summary> public int Count { get { return mStoredValues.Count - 1; } } public AutoPriorityQueue() { //Initialize the array that will hold the values mStoredValues = new List<T>(); //Fill the first cell in the array with an empty value mStoredValues.Add(default(T)); } public bool Contains(T value) { return mStoredValues.Contains(value); } public T Find(T value) { int index = mStoredValues.IndexOf(value); if (index < 0) return default(T); return mStoredValues[index]; } /// <summary> /// Returns the value at the head of the Priority Queue without removing it. /// </summary> public T Peek() { if (this.Count == 0) return default(T); //Priority Queue empty else return mStoredValues[1]; //head of the queue } /// <summary> /// Adds a value to the Priority Queue /// </summary> public void Enqueue(T value) { //Add the value to the internal array mStoredValues.Add(value); //Bubble up to preserve the heap property, //starting at the inserted value this.BubbleUp(mStoredValues.Count - 1); } /// <summary> /// Returns the minimum value inside the Priority Queue /// </summary> public T Dequeue() { if (this.Count == 0) return default(T); //queue is empty else { //The smallest value in the Priority Queue is the first item in the array T minValue = this.mStoredValues[1]; //If there's more than one item, replace the first item in the array with the last one if (this.mStoredValues.Count > 2) { T lastValue = this.mStoredValues[mStoredValues.Count - 1]; //Move last node to the head this.mStoredValues.RemoveAt(mStoredValues.Count - 1); this.mStoredValues[1] = lastValue; //Bubble down this.BubbleDown(1); } else { //Remove the only value stored in the queue mStoredValues.RemoveAt(1); } return minValue; } } /// <summary> /// When item was changed this restores the heap condition. /// This works only for reference types or types that implement /// IEquatable correctly, since it searches for the given item /// in the queue. To change an item you would typically obtain /// it by calling Find(item), change any property and finally call /// Update(item). /// </summary> /// <param name="item"></param> public void Update(T item) { int index = mStoredValues.IndexOf(item); if (IsParentBigger(index)) BubbleUp(index); else if (IsLeftChildSmaller(index) || IsRightChildSmaller(index)) BubbleDown(index); } /// <summary> /// Restores the heap-order property between child and parent values going up towards the head /// </summary> protected void BubbleUp(int startCell) { int cell = startCell; //Bubble up as long as the parent is greater while (this.IsParentBigger(cell)) { //Get values of parent and child T parentValue = this.mStoredValues[cell / 2]; T childValue = this.mStoredValues[cell]; //Swap the values this.mStoredValues[cell / 2] = childValue; this.mStoredValues[cell] = parentValue; cell /= 2; //go up parents } } /// <summary> /// Restores the heap-order property between child and parent values going down towards the bottom /// </summary> protected void BubbleDown(int startCell) { int cell = startCell; //Bubble down as long as either child is smaller while (this.IsLeftChildSmaller(cell) || this.IsRightChildSmaller(cell)) { int child = this.CompareChild(cell); if (child == -1) //Left Child { //Swap values T parentValue = mStoredValues[cell]; T leftChildValue = mStoredValues[2 * cell]; mStoredValues[cell] = leftChildValue; mStoredValues[2 * cell] = parentValue; cell = 2 * cell; //move down to left child } else if (child == 1) { //Right Child //Swap values T parentValue = mStoredValues[cell]; T rightChildValue = mStoredValues[2 * cell + 1]; mStoredValues[cell] = rightChildValue; mStoredValues[2 * cell + 1] = parentValue; cell = 2 * cell + 1; //move down to right child } } } /// <summary> /// Returns if the value of a parent is greater than its child /// </summary> protected bool IsParentBigger(int childCell) { if (childCell == 1) return false; //top of heap, no parent else return mStoredValues[childCell / 2].CompareTo(mStoredValues[childCell]) > 0; //return storedNodes[childCell / 2].Key > storedNodes[childCell].Key; } /// <summary> /// Returns whether the left child cell is smaller than the parent cell. /// Returns false if a left child does not exist. /// </summary> protected bool IsLeftChildSmaller(int parentCell) { if (2 * parentCell >= mStoredValues.Count) return false; //out of bounds else return mStoredValues[2 * parentCell].CompareTo(mStoredValues[parentCell]) < 0; //return storedNodes[2 * parentCell].Key < storedNodes[parentCell].Key; } /// <summary> /// Returns whether the right child cell is smaller than the parent cell. /// Returns false if a right child does not exist. /// </summary> protected bool IsRightChildSmaller(int parentCell) { if (2 * parentCell + 1 >= mStoredValues.Count) return false; //out of bounds else return mStoredValues[2 * parentCell + 1].CompareTo(mStoredValues[parentCell]) < 0; //return storedNodes[2 * parentCell + 1].Key < storedNodes[parentCell].Key; } /// <summary> /// Compares the children cells of a parent cell. -1 indicates the left child is the smaller of the two, /// 1 indicates the right child is the smaller of the two, 0 inidicates that neither child is smaller than the parent. /// </summary> protected int CompareChild(int parentCell) { bool leftChildSmaller = this.IsLeftChildSmaller(parentCell); bool rightChildSmaller = this.IsRightChildSmaller(parentCell); if (leftChildSmaller || rightChildSmaller) { if (leftChildSmaller && rightChildSmaller) { //Figure out which of the two is smaller int leftChild = 2 * parentCell; int rightChild = 2 * parentCell + 1; T leftValue = this.mStoredValues[leftChild]; T rightValue = this.mStoredValues[rightChild]; //Compare the values of the children if (leftValue.CompareTo(rightValue) <= 0) return -1; //left child is smaller else return 1; //right child is smaller } else if (leftChildSmaller) return -1; //left child is smaller else return 1; //right child smaller } else return 0; //both children are bigger or don't exist } } }
namespace GraphQLTemplate { using System; #if ResponseCompression using System.IO.Compression; #endif using System.Linq; #if CorrelationId using CorrelationId; #endif using Boxed.AspNetCore; using GraphQL; #if Authorization using GraphQL.Authorization; #endif using GraphQL.Server; using GraphQL.Server.Internal; using GraphQL.Validation; using GraphQLTemplate.Constants; using GraphQLTemplate.Options; using Microsoft.AspNetCore.Builder; #if !ForwardedHeaders && HostFiltering using Microsoft.AspNetCore.HostFiltering; #endif using Microsoft.AspNetCore.Hosting; #if ResponseCompression using Microsoft.AspNetCore.ResponseCompression; #endif using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; /// <summary> /// <see cref="IServiceCollection"/> extension methods which extend ASP.NET Core services. /// </summary> public static class CustomServiceCollectionExtensions { public static IServiceCollection AddCorrelationIdFluent(this IServiceCollection services) { services.AddCorrelationId(); return services; } /// <summary> /// Configures caching for the application. Registers the <see cref="IDistributedCache"/> and /// <see cref="IMemoryCache"/> types with the services collection or IoC container. The /// <see cref="IDistributedCache"/> is intended to be used in cloud hosted scenarios where there is a shared /// cache, which is shared between multiple instances of the application. Use the <see cref="IMemoryCache"/> /// otherwise. /// </summary> public static IServiceCollection AddCustomCaching(this IServiceCollection services) => services // Adds IMemoryCache which is a simple in-memory cache. .AddMemoryCache() // Adds IDistributedCache which is a distributed cache shared between multiple servers. This adds a // default implementation of IDistributedCache which is not distributed. See below: .AddDistributedMemoryCache(); // Uncomment the following line to use the Redis implementation of IDistributedCache. This will // override any previously registered IDistributedCache service. // Redis is a very fast cache provider and the recommended distributed cache provider. // .AddDistributedRedisCache(options => { ... }); // Uncomment the following line to use the Microsoft SQL Server implementation of IDistributedCache. // Note that this would require setting up the session state database. // Redis is the preferred cache implementation but you can use SQL Server if you don't have an alternative. // .AddSqlServerCache( // x => // { // x.ConnectionString = "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;"; // x.SchemaName = "dbo"; // x.TableName = "Sessions"; // }); /// <summary> /// Configures the settings by binding the contents of the appsettings.json file to the specified Plain Old CLR /// Objects (POCO) and adding <see cref="IOptions{T}"/> objects to the services collection. /// </summary> public static IServiceCollection AddCustomOptions( this IServiceCollection services, IConfiguration configuration) => services // ConfigureSingleton registers IOptions<T> and also T as a singleton to the services collection. .ConfigureAndValidateSingleton<ApplicationOptions>(configuration) .ConfigureAndValidateSingleton<CacheProfileOptions>(configuration.GetSection(nameof(ApplicationOptions.CacheProfiles))) #if ResponseCompression .ConfigureAndValidateSingleton<CompressionOptions>(configuration.GetSection(nameof(ApplicationOptions.Compression))) #endif #if ForwardedHeaders .ConfigureAndValidateSingleton<ForwardedHeadersOptions>(configuration.GetSection(nameof(ApplicationOptions.ForwardedHeaders))) #elif HostFiltering .ConfigureAndValidateSingleton<HostFilteringOptions>(configuration.GetSection(nameof(ApplicationOptions.HostFiltering))) #endif .ConfigureAndValidateSingleton<GraphQLOptions>(configuration.GetSection(nameof(ApplicationOptions.GraphQL))); #if ResponseCompression /// <summary> /// Adds dynamic response compression to enable GZIP compression of responses. This is turned off for HTTPS /// requests by default to avoid the BREACH security vulnerability. /// </summary> public static IServiceCollection AddCustomResponseCompression(this IServiceCollection services) => services .Configure<BrotliCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal) .Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal) .AddResponseCompression( options => { // Add additional MIME types (other than the built in defaults) to enable GZIP compression for. var customMimeTypes = services .BuildServiceProvider() .GetRequiredService<CompressionOptions>() .MimeTypes ?? Enumerable.Empty<string>(); options.MimeTypes = customMimeTypes.Concat(ResponseCompressionDefaults.MimeTypes); options.Providers.Add<BrotliCompressionProvider>(); options.Providers.Add<GzipCompressionProvider>(); }); #endif /// <summary> /// Add custom routing settings which determines how URL's are generated. /// </summary> public static IServiceCollection AddCustomRouting(this IServiceCollection services) => services.AddRouting(options => options.LowercaseUrls = true); #if HttpsEverywhere /// <summary> /// Adds the Strict-Transport-Security HTTP header to responses. This HTTP header is only relevant if you are /// using TLS. It ensures that content is loaded over HTTPS and refuses to connect in case of certificate /// errors and warnings. /// See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security and /// http://www.troyhunt.com/2015/06/understanding-http-strict-transport.html /// Note: Including subdomains and a minimum maxage of 18 weeks is required for preloading. /// Note: You can refer to the following article to clear the HSTS cache in your browser: /// http://classically.me/blogs/how-clear-hsts-settings-major-browsers /// </summary> public static IServiceCollection AddCustomStrictTransportSecurity(this IServiceCollection services) => services .AddHsts( options => { // Preload the HSTS HTTP header for better security. See https://hstspreload.org/ #if HstsPreload options.IncludeSubDomains = true; options.MaxAge = TimeSpan.FromSeconds(31536000); // 1 Year options.Preload = true; #else // options.IncludeSubDomains = true; // options.MaxAge = TimeSpan.FromSeconds(31536000); // 1 Year // options.Preload = true; #endif }); #endif #if HealthCheck public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services) => services .AddHealthChecks() // Add health checks for external dependencies here. See https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks .Services; #endif public static IServiceCollection AddCustomGraphQL(this IServiceCollection services, IHostingEnvironment hostingEnvironment) => services // Add a way for GraphQL.NET to resolve types. .AddSingleton<IDependencyResolver, GraphQLDependencyResolver>() .AddGraphQL( options => { var configuration = services .BuildServiceProvider() .GetRequiredService<IOptions<GraphQLOptions>>() .Value; // Set some limits for security, read from configuration. options.ComplexityConfiguration = configuration.ComplexityConfiguration; // Enable GraphQL metrics to be output in the response, read from configuration. options.EnableMetrics = configuration.EnableMetrics; // Show stack traces in exceptions. Don't turn this on in production. options.ExposeExceptions = hostingEnvironment.IsDevelopment(); }) // Adds all graph types in the current assembly with a singleton lifetime. .AddGraphTypes() // Adds ConnectionType<T>, EdgeType<T> and PageInfoType. .AddRelayGraphTypes() // Add a user context from the HttpContext and make it available in field resolvers. .AddUserContextBuilder<GraphQLUserContextBuilder>() // Add GraphQL data loader to reduce the number of calls to our repository. .AddDataLoader() #if Subscriptions // Add WebSockets support for subscriptions. .AddWebSockets() #endif .Services .AddTransient(typeof(IGraphQLExecuter<>), typeof(InstrumentingGraphQLExecutor<>)); #if Authorization /// <summary> /// Add GraphQL authorization (See https://github.com/graphql-dotnet/authorization). /// </summary> public static IServiceCollection AddCustomGraphQLAuthorization(this IServiceCollection services) => services .AddSingleton<IAuthorizationEvaluator, AuthorizationEvaluator>() .AddTransient<IValidationRule, AuthorizationValidationRule>() .AddSingleton( x => { var authorizationSettings = new AuthorizationSettings(); authorizationSettings.AddPolicy( AuthorizationPolicyName.Admin, y => y.RequireClaim("role", "admin")); return authorizationSettings; }); #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServerManagement { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for PowerShellOperations. /// </summary> public static partial class PowerShellOperationsExtensions { /// <summary> /// Gets a list of the active sessions. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> public static PowerShellSessionResources ListSession(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).ListSessionAsync(resourceGroupName, nodeName, session), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of the active sessions. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellSessionResources> ListSessionAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListSessionWithHttpMessagesAsync(resourceGroupName, nodeName, session, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellSessionResource CreateSession(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).CreateSessionAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellSessionResource> CreateSessionAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateSessionWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellSessionResource BeginCreateSession(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).BeginCreateSessionAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a PowerShell session /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellSessionResource> BeginCreateSessionAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginCreateSessionWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the status of a command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='expand'> /// Gets current output from an ongoing call. Possible values include: 'output' /// </param> public static PowerShellCommandStatus GetCommandStatus(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, PowerShellExpandOption? expand = default(PowerShellExpandOption?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).GetCommandStatusAsync(resourceGroupName, nodeName, session, pssession, expand), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of a command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='expand'> /// Gets current output from an ongoing call. Possible values include: 'output' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandStatus> GetCommandStatusAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, PowerShellExpandOption? expand = default(PowerShellExpandOption?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetCommandStatusWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellCommandResults UpdateCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).UpdateCommandAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> UpdateCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.UpdateCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellCommandResults BeginUpdateCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).BeginUpdateCommandAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// updates a running PowerShell command with more data. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> BeginUpdateCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginUpdateCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> public static PowerShellCommandResults InvokeCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).InvokeCommandAsync(resourceGroupName, nodeName, session, pssession, command), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> InvokeCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.InvokeCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, command, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> public static PowerShellCommandResults BeginInvokeCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).BeginInvokeCommandAsync(resourceGroupName, nodeName, session, pssession, command), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates a PowerShell script and invokes it. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Script to execute /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> BeginInvokeCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginInvokeCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, command, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellCommandResults CancelCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).CancelCommandAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> CancelCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CancelCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> public static PowerShellCommandResults BeginCancelCommand(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).BeginCancelCommandAsync(resourceGroupName, nodeName, session, pssession), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancels a PowerShell command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellCommandResults> BeginCancelCommandAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.BeginCancelCommandWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// gets tab completion values for a command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Command to get tab completion for. /// </param> public static PowerShellTabCompletionResults TabCompletion(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IPowerShellOperations)s).TabCompletionAsync(resourceGroupName, nodeName, session, pssession, command), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// gets tab completion values for a command. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='pssession'> /// The PowerShell sessionId from the user /// </param> /// <param name='command'> /// Command to get tab completion for. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PowerShellTabCompletionResults> TabCompletionAsync(this IPowerShellOperations operations, string resourceGroupName, string nodeName, string session, string pssession, string command = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.TabCompletionWithHttpMessagesAsync(resourceGroupName, nodeName, session, pssession, command, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
namespace Tools.WPF.Controls { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// A Canvas which manages dragging of the UIElements it contains. /// </summary> public class DragCanvas : Canvas { #region Data // Stores a reference to the UIElement currently being dragged by the user. UIElement _elementBeingDragged; // Keeps track of where the mouse cursor was when a drag operation began. Point _origCursorLocation; // The offsets from the DragCanvas' edges when the drag operation began. double _origHorizOffset; double _origVertOffset; // Keeps track of which horizontal and vertical offset should be modified for the drag element. bool _modifyLeftOffset; bool _modifyTopOffset; // True if a drag operation is underway, else false. bool _isDragInProgress; #endregion // Data #region Attached Properties #region CanBeDragged public static readonly DependencyProperty CanBeDraggedProperty; public static bool GetCanBeDragged(UIElement uiElement) { if (uiElement == null) { return false; } return (bool)uiElement.GetValue(CanBeDraggedProperty); } public static void SetCanBeDragged(UIElement uiElement, bool value) { if (uiElement != null) { uiElement.SetValue(CanBeDraggedProperty, value); } } #endregion // CanBeDragged #endregion // Attached Properties #region Dependency Properties public static readonly DependencyProperty AllowDraggingProperty; public static readonly DependencyProperty AllowDragOutOfViewProperty; #endregion // Dependency Properties #region Static Constructor static DragCanvas() { AllowDraggingProperty = DependencyProperty.Register( "AllowDragging", typeof(bool), typeof(DragCanvas), new PropertyMetadata(true)); AllowDragOutOfViewProperty = DependencyProperty.Register( "AllowDragOutOfView", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(false)); CanBeDraggedProperty = DependencyProperty.RegisterAttached( "CanBeDragged", typeof(bool), typeof(DragCanvas), new UIPropertyMetadata(true)); } #endregion // Static Constructor #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DragCanvas"/> class. /// Initializes a new instance of DragCanvas. UIElements in /// the DragCanvas will immediately be draggable by the user. /// </summary> public DragCanvas() { } #endregion // Constructor #region Interface #region AllowDragging /// <summary> /// Gets/sets whether elements in the DragCanvas should be draggable by the user. /// The default value is true. This is a dependency property. /// </summary> public bool AllowDragging { get { return (bool)this.GetValue(AllowDraggingProperty); } set { this.SetValue(AllowDraggingProperty, value); } } #endregion // AllowDragging #region AllowDragOutOfView /// <summary> /// Gets/sets whether the user should be able to drag elements in the DragCanvas out of /// the viewable area. The default value is false. This is a dependency property. /// </summary> public bool AllowDragOutOfView { get { return (bool)GetValue(AllowDragOutOfViewProperty); } set { SetValue(AllowDragOutOfViewProperty, value); } } #endregion // AllowDragOutOfView #region BringToFront / SendToBack /// <summary> /// Assigns the element a z-index which will ensure that /// it is in front of every other element in the Canvas. /// The z-index of every element whose z-index is between /// the element's old and new z-index will have its z-index /// decremented by one. /// </summary> /// <param name="element"> /// The element to be sent to the front of the z-order. /// </param> public void BringToFront(UIElement element) { UpdateZOrder(element, true); } /// <summary> /// Assigns the element a z-index which will ensure that /// it is behind every other element in the Canvas. /// The z-index of every element whose z-index is between /// the element's old and new z-index will have its z-index /// incremented by one. /// </summary> /// <param name="element"> /// The element to be sent to the back of the z-order. /// </param> public void SendToBack(UIElement element) { UpdateZOrder(element, false); } #endregion // BringToFront / SendToBack #region ElementBeingDragged /// <summary> /// Returns the UIElement currently being dragged, or null. /// </summary> /// <remarks> /// Note to inheritors: This property exposes a protected /// setter which should be used to modify the drag element. /// </remarks> public UIElement ElementBeingDragged { get { if (!AllowDragging) { return null; } else { return _elementBeingDragged; } } protected set { if (_elementBeingDragged != null) { _elementBeingDragged.ReleaseMouseCapture(); } if (!AllowDragging) { _elementBeingDragged = null; } else { if (GetCanBeDragged(value)) { _elementBeingDragged = value; _elementBeingDragged.CaptureMouse(); } else { _elementBeingDragged = null; } } } } #endregion // ElementBeingDragged #region FindCanvasChild /// <summary> /// Walks up the visual tree starting with the specified DependencyObject, /// looking for a UIElement which is a child of the Canvas. If a suitable /// element is not found, null is returned. If the 'depObj' object is a /// UIElement in the Canvas's Children collection, it will be returned. /// </summary> /// <param name="depObj"> /// A DependencyObject from which the search begins. /// </param> public UIElement FindCanvasChild(DependencyObject depObj) { while (depObj != null) { // If the current object is a UIElement which is a child of the // Canvas, exit the loop and return it. UIElement elem = depObj as UIElement; if (elem != null && base.Children.Contains(elem)) { break; } // VisualTreeHelper works with objects of type Visual or Visual3D. // If the current object is not derived from Visual or Visual3D, // then use the LogicalTreeHelper to find the parent element. if (depObj is Visual || depObj is Visual3D) { depObj = VisualTreeHelper.GetParent(depObj); } else { depObj = LogicalTreeHelper.GetParent(depObj); } } return depObj as UIElement; } #endregion // FindCanvasChild #endregion // Interface #region Overrides #region OnPreviewMouseLeftButtonDown protected override void OnPreviewMouseRightButtonDown(MouseButtonEventArgs e) { base.OnPreviewMouseRightButtonDown(e); _isDragInProgress = false; // Cache the mouse cursor location. _origCursorLocation = e.GetPosition(this); // Walk up the visual tree from the element that was clicked, // looking for an element that is a direct child of the Canvas. ElementBeingDragged = FindCanvasChild(e.Source as DependencyObject); if (ElementBeingDragged == null) { return; } // Get the element's offsets from the four sides of the Canvas. double left = GetLeft(ElementBeingDragged); double right = GetRight(ElementBeingDragged); double top = GetTop(ElementBeingDragged); double bottom = GetBottom(ElementBeingDragged); // Calculate the offset deltas and determine for which sides // of the Canvas to adjust the offsets. _origHorizOffset = ResolveOffset(left, right, out _modifyLeftOffset); _origVertOffset = ResolveOffset(top, bottom, out _modifyTopOffset); // Set the Handled flag so that a control being dragged // does not react to the mouse input. e.Handled = true; _isDragInProgress = true; } #endregion // OnPreviewMouseLeftButtonDown #region OnPreviewMouseMove protected override void OnPreviewMouseMove(MouseEventArgs e) { base.OnPreviewMouseMove(e); // If no element is being dragged, there is nothing to do. if (ElementBeingDragged == null || !_isDragInProgress) { return; } // Get the position of the mouse cursor, relative to the Canvas. Point cursorLocation = e.GetPosition(this); // These values will store the new offsets of the drag element. double newHorizontalOffset, newVerticalOffset; // Determine the horizontal offset. if (_modifyLeftOffset) { newHorizontalOffset = _origHorizOffset + (cursorLocation.X - _origCursorLocation.X); } else { newHorizontalOffset = _origHorizOffset - (cursorLocation.X - _origCursorLocation.X); } // Determine the vertical offset. if (_modifyTopOffset) { newVerticalOffset = _origVertOffset + (cursorLocation.Y - _origCursorLocation.Y); } else { newVerticalOffset = _origVertOffset - (cursorLocation.Y - _origCursorLocation.Y); } if (! AllowDragOutOfView) { CorrectOffsetsToKeepElementInsideCanvas(ref newHorizontalOffset, ref newVerticalOffset); } if (_modifyLeftOffset) { SetLeft(ElementBeingDragged, newHorizontalOffset); } else { SetRight(ElementBeingDragged, newHorizontalOffset); } if (_modifyTopOffset) { SetTop(ElementBeingDragged, newVerticalOffset); } else { SetBottom(ElementBeingDragged, newVerticalOffset); } } void CorrectOffsetsToKeepElementInsideCanvas(ref double newHorizontalOffset, ref double newVerticalOffset) { // Get the bounding rect of the drag element. Rect elemRect = CalculateDragElementRect(newHorizontalOffset, newVerticalOffset); // If the element is being dragged out of the viewable area, // determine the ideal rect location, so that the element is // within the edge(s) of the canvas. bool leftAlign = elemRect.Left < 0 - (elemRect.Width / 2); bool rightAlign = elemRect.Right > ActualWidth + (elemRect.Width / 2); if (leftAlign) { newHorizontalOffset = _modifyLeftOffset ? 0 - (elemRect.Width / 2) : ActualWidth - elemRect.Width; } else if (rightAlign) { newHorizontalOffset = _modifyLeftOffset ? ActualWidth - (elemRect.Width / 2) : 0; } bool topAlign = elemRect.Top < 0 - (elemRect.Height / 2); bool bottomAlign = elemRect.Bottom > ActualHeight + (elemRect.Height / 2); if (topAlign) { newVerticalOffset = _modifyTopOffset ? 0 - (elemRect.Height / 2) : ActualHeight - elemRect.Height; } else if (bottomAlign) { newVerticalOffset = _modifyTopOffset ? ActualHeight - (elemRect.Height / 2) : 0; } } #endregion // OnPreviewMouseMove #region OnHostPreviewMouseUp protected override void OnPreviewMouseRightButtonUp(MouseButtonEventArgs e) { base.OnPreviewMouseRightButtonUp(e); // Reset the field whether the left or right mouse button was // released, in case a context menu was opened on the drag element. ElementBeingDragged = null; } #endregion // OnHostPreviewMouseUp #endregion // Host Event Handlers #region CalculateDragElementRect /// <summary> /// Returns a Rect which describes the bounds of the element being dragged. /// </summary> Rect CalculateDragElementRect(double newHorizOffset, double newVertOffset) { if (ElementBeingDragged == null) { throw new InvalidOperationException("ElementBeingDragged is null."); } Size elemSize = ElementBeingDragged.RenderSize; double x, y; if (_modifyLeftOffset) { x = newHorizOffset; } else { x = ActualWidth - newHorizOffset - elemSize.Width; } if (_modifyTopOffset) { y = newVertOffset; } else { y = ActualHeight - newVertOffset - elemSize.Height; } var elemLoc = new Point(x, y); return new Rect(elemLoc, elemSize); } #endregion // CalculateDragElementRect #region ResolveOffset /// <summary> /// Determines one component of a UIElement's location /// within a Canvas (either the horizontal or vertical offset). /// </summary> /// <param name="side1"> /// The value of an offset relative to a default side of the /// Canvas (i.e. top or left). /// </param> /// <param name="side2"> /// The value of the offset relative to the other side of the /// Canvas (i.e. bottom or right). /// </param> /// <param name="useSide1"> /// Will be set to true if the returned value should be used /// for the offset from the side represented by the 'side1' /// parameter. Otherwise, it will be set to false. /// </param> static double ResolveOffset(double side1, double side2, out bool useSide1) { // If the Canvas.Left and Canvas.Right attached properties // are specified for an element, the 'Left' value is honored. // The 'Top' value is honored if both Canvas.Top and // Canvas.Bottom are set on the same element. If one // of those attached properties is not set on an element, // the default value is Double.NaN. useSide1 = true; double result; if (Double.IsNaN(side1)) { if (Double.IsNaN(side2)) { // Both sides have no value, so set the // first side to a value of zero. result = 0; } else { result = side2; useSide1 = false; } } else { result = side1; } return result; } #endregion // ResolveOffset /// <summary> /// Helper method used by the BringToFront and SendToBack methods. /// </summary> /// <param name="element"> /// The element to bring to the front or send to the back. /// </param> /// <param name="bringToFront"> /// Pass true if calling from BringToFront, else false. /// </param> void UpdateZOrder(UIElement element, bool bringToFront) { if (element == null) { throw new ArgumentNullException("element"); } if (!base.Children.Contains(element)) { throw new ArgumentException("Must be a child element of the Canvas.", "element"); } // Determine the Z-Index for the target UIElement. int elementNewZIndex = -1; if (bringToFront) { foreach (UIElement elem in base.Children) { if (elem.Visibility != Visibility.Collapsed) { ++elementNewZIndex; } } } else { elementNewZIndex = 0; } // Determine if the other UIElements' Z-Index // should be raised or lowered by one. int offset = (elementNewZIndex == 0) ? +1 : -1; int elementCurrentZIndex = GetZIndex(element); // Update the Z-Index of every UIElement in the Canvas. foreach (UIElement childElement in base.Children) { if (childElement == element) { SetZIndex(element, elementNewZIndex); } else { int zIndex = GetZIndex(childElement); // Only modify the z-index of an element if it is // in between the target element's old and new z-index. if (bringToFront && elementCurrentZIndex < zIndex || !bringToFront && zIndex < elementCurrentZIndex) { SetZIndex(childElement, zIndex + offset); } } } } } }
#region Copyright /* Copyright 2014 Cluster Reply s.r.l. 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 /// ----------------------------------------------------------------------------------------------------------- /// Module : FileAdapterBindingElementExtensionElement.cs /// Description : This class is provided to surface Adapter as a binding element, so that it /// can be used within a user-defined WCF "Custom Binding". /// In configuration file, it is defined under /// <system.serviceModel> /// <extensions> /// <bindingElementExtensions> /// <add name="{name}" type="{this}, {assembly}"/> /// </bindingElementExtensions> /// </extensions> /// </system.serviceModel> /// ----------------------------------------------------------------------------------------------------------- #region Using Directives using System; using System.Collections.Generic; using System.Text; using System.ServiceModel; using System.ServiceModel.Configuration; using System.ServiceModel.Channels; using System.Configuration; using System.Globalization; using Microsoft.ServiceModel.Channels.Common; #endregion namespace Reply.Cluster.Mercury.Adapters.File { using System; using System.Configuration; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; public class FileAdapterBindingElementExtensionElement : BindingElementExtensionElement { #region Constructor /// <summary> /// Default constructor /// </summary> public FileAdapterBindingElementExtensionElement() { } #endregion Constructor #region Custom Generated Properties [System.ComponentModel.Category("Path")] [System.Configuration.ConfigurationProperty("pollingType", DefaultValue = PollingType.Event)] public PollingType PollingType { get { return ((PollingType)(base["PollingType"])); } set { base["PollingType"] = value; } } [System.ComponentModel.Category("Path")] [System.Configuration.ConfigurationProperty("pollingInterval", DefaultValue = 60)] public int PollingInterval { get { return ((int)(base["PollingInterval"])); } set { base["PollingInterval"] = value; } } [System.ComponentModel.Category("Path")] [System.Configuration.ConfigurationProperty("ScheduleName")] public string ScheduleName { get { return ((string)(base["ScheduleName"])); } set { base["ScheduleName"] = value; } } [System.ComponentModel.Category("Folders")] [System.Configuration.ConfigurationProperty("TempFolder")] public string TempFolder { get { return ((string)(base["TempFolder"])); } set { base["TempFolder"] = value; } } [System.ComponentModel.Category("Folders")] [System.Configuration.ConfigurationProperty("RemoteBackup")] public string RemoteBackup { get { return ((string)(base["RemoteBackup"])); } set { base["RemoteBackup"] = value; } } [System.ComponentModel.Category("Folders")] [System.Configuration.ConfigurationProperty("LocalBackup")] public string LocalBackup { get { return ((string)(base["LocalBackup"])); } set { base["LocalBackup"] = value; } } [System.ComponentModel.Category("Overwrite")] [System.Configuration.ConfigurationProperty("overwriteAction", DefaultValue = OverwriteAction.None)] public OverwriteAction OverwriteAction { get { return ((OverwriteAction)(base["OverwriteAction"])); } set { base["OverwriteAction"] = value; } } #endregion Custom Generated Properties #region BindingElementExtensionElement Methods /// <summary> /// Return the type of the adapter (binding element) /// </summary> public override Type BindingElementType { get { return typeof(FileAdapter); } } /// <summary> /// Returns a collection of the configuration properties /// </summary> protected override ConfigurationPropertyCollection Properties { get { ConfigurationPropertyCollection configProperties = base.Properties; configProperties.Add(new ConfigurationProperty("PollingType", typeof(PollingType), PollingType.Event, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("PollingInterval", typeof(System.Int32), (System.Int32)60, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("ScheduleName", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("TempFolder", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("RemoteBackup", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("LocalBackup", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None)); configProperties.Add(new ConfigurationProperty("OverwriteAction", typeof(OverwriteAction), OverwriteAction.None, null, null, ConfigurationPropertyOptions.None)); return configProperties; } } /// <summary> /// Instantiate the adapter. /// </summary> /// <returns></returns> protected override BindingElement CreateBindingElement() { FileAdapter adapter = new FileAdapter(); this.ApplyConfiguration(adapter); return adapter; } /// <summary> /// Apply the configuration properties to the adapter. /// </summary> /// <param name="bindingElement"></param> public override void ApplyConfiguration(BindingElement bindingElement) { base.ApplyConfiguration(bindingElement); FileAdapter adapterBinding = ((FileAdapter)(bindingElement)); adapterBinding.PollingType = (PollingType)this["PollingType"]; adapterBinding.PollingInterval = (System.Int32)this["PollingInterval"]; adapterBinding.ScheduleName = (System.String)this["ScheduleName"]; adapterBinding.TempFolder = (System.String)this["TempFolder"]; adapterBinding.RemoteBackup = (System.String)this["RemoteBackup"]; adapterBinding.LocalBackup = (System.String)this["LocalBackup"]; adapterBinding.OverwriteAction = (OverwriteAction)this["OverwriteAction"]; } /// <summary> /// Initialize the binding properties from the adapter. /// </summary> /// <param name="bindingElement"></param> protected override void InitializeFrom(BindingElement bindingElement) { base.InitializeFrom(bindingElement); FileAdapter adapterBinding = ((FileAdapter)(bindingElement)); this["PollingType"] = adapterBinding.PollingType; this["PollingInterval"] = adapterBinding.PollingInterval; this["ScheduleName"] = adapterBinding.ScheduleName; this["TempFolder"] = adapterBinding.TempFolder; this["RemoteBackup"] = adapterBinding.RemoteBackup; this["LocalBackup"] = adapterBinding.LocalBackup; this["OverwriteAction"] = adapterBinding.OverwriteAction; } /// <summary> /// Copy the properties to the custom binding /// </summary> /// <param name="from"></param> public override void CopyFrom(ServiceModelExtensionElement from) { base.CopyFrom(from); FileAdapterBindingElementExtensionElement adapterBinding = ((FileAdapterBindingElementExtensionElement)(from)); this["PollingType"] = adapterBinding.PollingType; this["PollingInterval"] = adapterBinding.PollingInterval; this["ScheduleName"] = adapterBinding.ScheduleName; this["TempFolder"] = adapterBinding.TempFolder; this["RemoteBackup"] = adapterBinding.RemoteBackup; this["LocalBackup"] = adapterBinding.LocalBackup; this["OverwriteAction"] = adapterBinding.OverwriteAction; } #endregion BindingElementExtensionElement Methods } }
/* * This module was originally posted on CodeProject in an article titled * ST Micro-electronics Device Firmware Upgrade (DFU/DfuSe) from C# * By Mark McLean (ExpElec), 4 Mar 2013 * http://www.codeproject.com/Tips/540963/ST-Micro-electronics-Device-Firmware-Upgrade-DFU-D * * and is licensed under the The Code Project Open License (CPOL) 1.02, * which can be found here * http://www.codeproject.com/info/cpol10.aspx */ // From the "Working with USB devices in .NET and C#" tutorial by Ashley Deakin on // http://www.developerfusion.com/article/84338/making-usb-c-friendly/ // // Had to make a couple of changes for 64 bit compatibility using System; using System.Text; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace NetDFULib { /// <summary> /// Class that wraps USB API calls and structures /// </summary> [Serializable] public class Win32Usb { #region Structures /// <summary> /// An overlapped structure used for overlapped IO operations. The structure is /// only used by the OS to keep state on pending operations. You don't need to fill anything in if you /// unless you want a Windows event to fire when the operation is complete. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] protected struct Overlapped { public uint Internal; public uint InternalHigh; public uint Offset; public uint OffsetHigh; public IntPtr Event; } /// <summary> /// Provides details about a single USB device /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] protected struct DeviceInterfaceData { public int Size; public Guid InterfaceClassGuid; public int Flags; public IntPtr Reserved; // public int Reserved; - int and IntPtr are the same thing in 32 bit, but NOT in 64bit ! } /// <summary> /// Provides the capabilities of a HID device /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] protected struct HidCaps { public short Usage; public short UsagePage; public short InputReportByteLength; public short OutputReportByteLength; public short FeatureReportByteLength; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)] public short[] Reserved; public short NumberLinkCollectionNodes; public short NumberInputButtonCaps; public short NumberInputValueCaps; public short NumberInputDataIndices; public short NumberOutputButtonCaps; public short NumberOutputValueCaps; public short NumberOutputDataIndices; public short NumberFeatureButtonCaps; public short NumberFeatureValueCaps; public short NumberFeatureDataIndices; } /// <summary> /// Access to the path for a device /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct DeviceInterfaceDetailData { public int Size; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string DevicePath; } /// <summary> /// Used when registering a window to receive messages about devices added or removed from the system. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)] public class DeviceBroadcastInterface { public int Size; public int DeviceType; public int Reserved; public Guid ClassGuid; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string Name; } #endregion #region Constants /// <summary>Windows message sent when a device is inserted or removed</summary> public const int WM_DEVICECHANGE = 0x0219; /// <summary>WParam for above : A device was inserted</summary> public const int DEVICE_ARRIVAL = 0x8000; /// <summary>WParam for above : A device was removed</summary> public const int DEVICE_REMOVECOMPLETE = 0x8004; /// <summary>Used in SetupDiClassDevs to get devices present in the system</summary> protected const int DIGCF_PRESENT = 0x02; /// <summary>Used in SetupDiClassDevs to get device interface details</summary> protected const int DIGCF_DEVICEINTERFACE = 0x10; /// <summary>Used when registering for device insert/remove messages : specifies the type of device</summary> protected const int DEVTYP_DEVICEINTERFACE = 0x05; /// <summary>Used when registering for device insert/remove messages : we're giving the API call a window handle</summary> protected const int DEVICE_NOTIFY_WINDOW_HANDLE = 0; /// <summary>Purges Win32 transmit buffer by aborting the current transmission.</summary> protected const uint PURGE_TXABORT = 0x01; /// <summary>Purges Win32 receive buffer by aborting the current receive.</summary> protected const uint PURGE_RXABORT = 0x02; /// <summary>Purges Win32 transmit buffer by clearing it.</summary> protected const uint PURGE_TXCLEAR = 0x04; /// <summary>Purges Win32 receive buffer by clearing it.</summary> protected const uint PURGE_RXCLEAR = 0x08; /// <summary>CreateFile : Open file for read</summary> protected const uint GENERIC_READ = 0x80000000; /// <summary>CreateFile : Open file for write</summary> protected const uint GENERIC_WRITE = 0x40000000; /// <summary>CreateFile : Open handle for overlapped operations</summary> protected const uint FILE_FLAG_OVERLAPPED = 0x40000000; /// <summary>CreateFile : Resource to be "created" must exist</summary> protected const uint OPEN_EXISTING = 3; /// <summary>ReadFile/WriteFile : Overlapped operation is incomplete.</summary> protected const uint ERROR_NO_MORE_ITEMS = 259; /// <summary>Infinite timeout</summary> protected const uint ERROR_IO_PENDING = 997; /// <summary>Infinite timeout</summary> protected const uint ERROR_INVALID_USER_BUFFER = 1784; /// <summary>Infinite timeout</summary> protected const uint INFINITE = 0xFFFFFFFF; /// <summary>Simple representation of a null handle : a closed stream will get this handle. Note it is public for comparison by higher level classes.</summary> public static IntPtr NullHandle = IntPtr.Zero; /// <summary>Simple representation of the handle returned when CreateFile fails.</summary> protected static IntPtr InvalidHandleValue = new IntPtr(-1); #endregion #region P/Invoke /// <summary> /// Gets the GUID that Windows uses to represent HID class devices /// </summary> /// <param name="gHid">An out parameter to take the Guid</param> [DllImport("hid.dll", SetLastError = true)] protected static extern void HidD_GetHidGuid(out Guid gHid); /// <summary> /// Allocates an InfoSet memory block within Windows that contains details of devices. /// </summary> /// <param name="gClass">Class guid (e.g. HID guid)</param> /// <param name="strEnumerator">Not used</param> /// <param name="hParent">Not used</param> /// <param name="nFlags">Type of device details required (DIGCF_ constants)</param> /// <returns>A reference to the InfoSet</returns> [DllImport("setupapi.dll", SetLastError = true)] protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags); /// <summary> /// Frees InfoSet allocated in call to above. /// </summary> /// <param name="lpInfoSet">Reference to InfoSet</param> /// <returns>true if successful</returns> [DllImport("setupapi.dll", SetLastError = true)] protected static extern int SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet); /// <summary> /// Gets the DeviceInterfaceData for a device from an InfoSet. /// </summary> /// <param name="lpDeviceInfoSet">InfoSet to access</param> /// <param name="nDeviceInfoData">Not used</param> /// <param name="gClass">Device class guid</param> /// <param name="nIndex">Index into InfoSet for device</param> /// <param name="oInterfaceData">DeviceInterfaceData to fill with data</param> /// <returns>True if successful, false if not (e.g. when index is passed end of InfoSet)</returns> [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref DeviceInterfaceData oInterfaceData); /// <summary> /// SetupDiGetDeviceInterfaceDetail - two of these, overloaded because they are used together in slightly different /// ways and the parameters have different meanings. /// Gets the interface detail from a DeviceInterfaceData. This is pretty much the device path. /// You call this twice, once to get the size of the struct you need to send (nDeviceInterfaceDetailDataSize=0) /// and once again when you've allocated the required space. /// </summary> /// <param name="lpDeviceInfoSet">InfoSet to access</param> /// <param name="oInterfaceData">DeviceInterfaceData to use</param> /// <param name="lpDeviceInterfaceDetailData">DeviceInterfaceDetailData to fill with data</param> /// <param name="nDeviceInterfaceDetailDataSize">The size of the above</param> /// <param name="nRequiredSize">The required size of the above when above is set as zero</param> /// <param name="lpDeviceInfoData">Not used</param> /// <returns></returns> [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, IntPtr lpDeviceInterfaceDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData); [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref DeviceInterfaceData oInterfaceData, ref DeviceInterfaceDetailData oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData); /// <summary> /// Registers a window for device insert/remove messages /// </summary> /// <param name="hwnd">Handle to the window that will receive the messages</param> /// <param name="lpInterface">DeviceBroadcastInterrface structure</param> /// <param name="nFlags">set to DEVICE_NOTIFY_WINDOW_HANDLE</param> /// <returns>A handle used when unregistering</returns> [DllImport("user32.dll", SetLastError = true)] protected static extern IntPtr RegisterDeviceNotification(IntPtr hwnd, DeviceBroadcastInterface oInterface, uint nFlags); /// <summary> /// Unregister from above. /// </summary> /// <param name="hHandle">Handle returned in call to RegisterDeviceNotification</param> /// <returns>True if success</returns> [DllImport("user32.dll", SetLastError = true)] protected static extern bool UnregisterDeviceNotification(IntPtr hHandle); /// <summary> /// Gets details from an open device. Reserves a block of memory which must be freed. /// </summary> /// <param name="hFile">Device file handle</param> /// <param name="lpData">Reference to the preparsed data block</param> /// <returns></returns> [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_GetPreparsedData(IntPtr hFile, out IntPtr lpData); /// <summary> /// Frees the memory block reserved above. /// </summary> /// <param name="pData">Reference to preparsed data returned in call to GetPreparsedData</param> /// <returns></returns> [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_FreePreparsedData(ref IntPtr pData); /// <summary> /// Gets a device's capabilities from the preparsed data. /// </summary> /// <param name="lpData">Preparsed data reference</param> /// <param name="oCaps">HidCaps structure to receive the capabilities</param> /// <returns>True if successful</returns> [DllImport("hid.dll", SetLastError = true)] protected static extern int HidP_GetCaps(IntPtr lpData, out HidCaps oCaps); // Additional P/Invokes for device firmware update [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_GetFeature(IntPtr lpData, out byte lpReportBuffer, uint uBufferLength); [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_SetFeature(SafeFileHandle hFile, IntPtr Buffer, uint uBufferLength); /// <summary> /// Set the size of the USB Report IN input buffer /// </summary> /// <param name="hFile">Handle to device</param> /// <param name="nBuffers">Required size of buffer in USB IN Reports</param> /// <returns>True if successful</returns> [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_SetNumInputBuffers(IntPtr hFile, uint nBuffers); /// <summary> /// Get the indexed string. (MMc added) /// Remember to initialise the string first so that it has some size, e.g. StringBuilder myValue = new StringBuilder("", 256); /// </summary> /// <param name="hFile">Handle to HID device</param> /// <param name="ulStringIndex">Index for string</param> /// <param name="pvBuffer">Buffer for string</param> /// <param name="ulBufferLength">Size of buffer</param> /// <returns></returns> [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_GetIndexedString(SafeFileHandle hFile, uint uStringIndex, IntPtr Buffer, uint uBufferLength ); [DllImport("hid.dll", SetLastError = true)] protected static extern bool HidD_GetInputReport(IntPtr hFile, IntPtr Buffer, uint uBufferLength); [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)] internal static extern bool HidD_GetProductString(IntPtr hDevice, IntPtr Buffer, uint BufferLength); /// <summary> /// Creates/opens a file, serial port, USB device... etc /// </summary> /// <param name="strName">Path to object to open</param> /// <param name="nAccess">Access mode. e.g. Read, write</param> /// <param name="nShareMode">Sharing mode</param> /// <param name="lpSecurity">Security details (can be null)</param> /// <param name="nCreationFlags">Specifies if the file is created or opened</param> /// <param name="nAttributes">Any extra attributes? e.g. open overlapped</param> /// <param name="lpTemplate">Not used</param> /// <returns></returns> [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] protected static extern SafeFileHandle CreateFile(string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate); /// <summary> /// Closes a window handle. File handles, event handles, mutex handles... etc /// </summary> /// <param name="hFile">Handle to close</param> /// <returns>True if successful.</returns> [DllImport("kernel32.dll", SetLastError = true)] protected static extern int CloseHandle(IntPtr hFile); #endregion #region Public methods /// <summary> /// Registers a window to receive windows messages when a device is inserted/removed. Need to call this /// from a form when its handle has been created, not in the form constructor. Use form's OnHandleCreated override. /// </summary> /// <param name="hWnd">Handle to window that will receive messages</param> /// <param name="gClass">Class of devices to get messages for</param> /// <returns>A handle used when unregistering</returns> public static IntPtr RegisterForUsbEvents(IntPtr hWnd, Guid gClass) { DeviceBroadcastInterface oInterfaceIn = new DeviceBroadcastInterface(); oInterfaceIn.Size = Marshal.SizeOf(oInterfaceIn); oInterfaceIn.ClassGuid = gClass; oInterfaceIn.DeviceType = DEVTYP_DEVICEINTERFACE; oInterfaceIn.Reserved = 0; return RegisterDeviceNotification(hWnd, oInterfaceIn, DEVICE_NOTIFY_WINDOW_HANDLE); } /// <summary> /// Unregisters notifications. Can be used in form dispose /// </summary> /// <param name="hHandle">Handle returned from RegisterForUSBEvents</param> /// <returns>True if successful</returns> public static bool UnregisterForUsbEvents(IntPtr hHandle) { return UnregisterDeviceNotification(hHandle); } /// <summary> /// Helper to get the HID guid. /// </summary> public static Guid HIDGuid { get { Guid gHid; HidD_GetHidGuid(out gHid); return gHid; } } #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.Globalization; 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 Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation runbook draft. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> internal partial class RunbookDraftOperations : IServiceOperations<AutomationManagementClient>, IRunbookDraftOperations { /// <summary> /// Initializes a new instance of the RunbookDraftOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RunbookDraftOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> BeginPublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.PublishedBy == null) { throw new ArgumentNullException("parameters.PublishedBy"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginPublishAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/draft/publish"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResultResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LongRunningOperationResultResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ocp-location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> BeginUpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Stream == null) { throw new ArgumentNullException("parameters.Stream"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/draft/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Stream; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResultResponse result = null; // Deserialize Response result = new LongRunningOperationResultResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ocp-location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> BeginUpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Name == null) { throw new ArgumentNullException("parameters.Name"); } if (parameters.Stream == null) { throw new ArgumentNullException("parameters.Stream"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginUpdateGraphAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(parameters.Name); url = url + "/draft/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Stream; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/powershell"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResultResponse result = null; // Deserialize Response result = new LongRunningOperationResultResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ocp-location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("ocp-location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the content of runbook draft identified by runbook name. /// (see http://aka.ms/azureautomationsdk/runbookdraftoperations for /// more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the runbook content operation. /// </returns> public async Task<RunbookContentResponse> ContentAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "ContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/content"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RunbookContentResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookContentResponse(); result.Stream = responseContent; } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the runbook draft identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the get runbook draft operation. /// </returns> public async Task<RunbookDraftGetResponse> GetAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RunbookDraftGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookDraftGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RunbookDraft runbookDraftInstance = new RunbookDraft(); result.RunbookDraft = runbookDraftInstance; JToken inEditValue = responseDoc["inEdit"]; if (inEditValue != null && inEditValue.Type != JTokenType.Null) { bool inEditInstance = ((bool)inEditValue); runbookDraftInstance.InEdit = inEditInstance; } JToken draftContentLinkValue = responseDoc["draftContentLink"]; if (draftContentLinkValue != null && draftContentLinkValue.Type != JTokenType.Null) { ContentLink draftContentLinkInstance = new ContentLink(); runbookDraftInstance.DraftContentLink = draftContentLinkInstance; JToken uriValue = draftContentLinkValue["uri"]; if (uriValue != null && uriValue.Type != JTokenType.Null) { Uri uriInstance = TypeConversion.TryParseUri(((string)uriValue)); draftContentLinkInstance.Uri = uriInstance; } JToken contentHashValue = draftContentLinkValue["contentHash"]; if (contentHashValue != null && contentHashValue.Type != JTokenType.Null) { ContentHash contentHashInstance = new ContentHash(); draftContentLinkInstance.ContentHash = contentHashInstance; JToken algorithmValue = contentHashValue["algorithm"]; if (algorithmValue != null && algorithmValue.Type != JTokenType.Null) { string algorithmInstance = ((string)algorithmValue); contentHashInstance.Algorithm = algorithmInstance; } JToken valueValue = contentHashValue["value"]; if (valueValue != null && valueValue.Type != JTokenType.Null) { string valueInstance = ((string)valueValue); contentHashInstance.Value = valueInstance; } } JToken versionValue = draftContentLinkValue["version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { string versionInstance = ((string)versionValue); draftContentLinkInstance.Version = versionInstance; } } JToken creationTimeValue = responseDoc["creationTime"]; if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null) { DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue); runbookDraftInstance.CreationTime = creationTimeInstance; } JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"]; if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null) { DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue); runbookDraftInstance.LastModifiedTime = lastModifiedTimeInstance; } JToken parametersSequenceElement = ((JToken)responseDoc["parameters"]); if (parametersSequenceElement != null && parametersSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in parametersSequenceElement) { string parametersKey = ((string)property.Name); JObject varToken = ((JObject)property.Value); RunbookParameter runbookParameterInstance = new RunbookParameter(); runbookDraftInstance.Parameters.Add(parametersKey, runbookParameterInstance); JToken typeValue = varToken["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); runbookParameterInstance.Type = typeInstance; } JToken isMandatoryValue = varToken["isMandatory"]; if (isMandatoryValue != null && isMandatoryValue.Type != JTokenType.Null) { bool isMandatoryInstance = ((bool)isMandatoryValue); runbookParameterInstance.IsMandatory = isMandatoryInstance; } JToken positionValue = varToken["position"]; if (positionValue != null && positionValue.Type != JTokenType.Null) { int positionInstance = ((int)positionValue); runbookParameterInstance.Position = positionInstance; } JToken defaultValueValue = varToken["defaultValue"]; if (defaultValueValue != null && defaultValueValue.Type != JTokenType.Null) { string defaultValueInstance = ((string)defaultValueValue); runbookParameterInstance.DefaultValue = defaultValueInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the publish runbook operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> PublishAsync(string resourceGroupName, string automationAccount, RunbookDraftPublishParameters parameters, CancellationToken cancellationToken) { AutomationManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PublishAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse response = await client.RunbookDraft.BeginPublishAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Retrieve the runbook identified by runbook name. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='runbookName'> /// Required. The runbook name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the undoedit runbook operation. /// </returns> public async Task<RunbookDraftUndoEditResponse> UndoEditAsync(string resourceGroupName, string automationAccount, string runbookName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (runbookName == null) { throw new ArgumentNullException("runbookName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("runbookName", runbookName); TracingAdapter.Enter(invocationId, this, "UndoEditAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/runbooks/"; url = url + Uri.EscapeDataString(runbookName); url = url + "/draft/undoEdit"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-01-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RunbookDraftUndoEditResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RunbookDraftUndoEditResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> UpdateAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { AutomationManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Updates the runbook draft with runbookStream as its content. (see /// http://aka.ms/azureautomationsdk/runbookdraftoperations for more /// information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The runbook draft update parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResultResponse> UpdateGraphAsync(string resourceGroupName, string automationAccount, RunbookDraftUpdateParameters parameters, CancellationToken cancellationToken) { AutomationManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateGraphAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse response = await client.RunbookDraft.BeginUpdateAsync(resourceGroupName, automationAccount, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResultResponse result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationResultStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } } }
using System; using System.Linq; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; namespace StructureMap.Testing { [TestFixture] public class BuildSessionTester { #region Setup/Teardown [SetUp] public void SetUp() { } #endregion private void assertActionThrowsErrorCode(int errorCode, Action action) { try { action(); Assert.Fail("Should have thrown StructureMapException"); } catch (StructureMapException ex) { Assert.AreEqual(errorCode, ex.ErrorCode); } } public class WidgetHolder { private readonly IWidget[] _widgets; public WidgetHolder(IWidget[] widgets) { _widgets = widgets; } public IWidget[] Widgets { get { return _widgets; } } } [Test] public void can_get_all_of_a_type_during_object_creation() { var container = new Container(x => { x.For<IWidget>().AddInstances(o => { o.Type<AWidget>(); o.ConstructedBy(() => new ColorWidget("red")); o.ConstructedBy(() => new ColorWidget("blue")); o.ConstructedBy(() => new ColorWidget("green")); }); x.ForConcreteType<TopClass>().Configure.OnCreation( (c, top) => { top.Widgets = c.All<IWidget>().ToArray(); }); }); container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4); } [Test] public void can_get_all_of_a_type_during_object_creation_as_generic_type() { var container = new Container(x => { x.For<IWidget>().AddInstances(o => { o.Type<AWidget>(); o.ConstructedBy(() => new ColorWidget("red")); o.ConstructedBy(() => new ColorWidget("blue")); o.ConstructedBy(() => new ColorWidget("green")); }); x.ForConcreteType<TopClass>().Configure.OnCreation( (c, top) => { top.Widgets = c.All<IWidget>().ToArray(); }); }); container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4); } [Test] public void can_get_all_of_a_type_by_GetAllInstances_during_object_creation_as_generic_type() { var container = new Container(x => { x.For<IWidget>().AddInstances(o => { o.Type<AWidget>(); o.ConstructedBy(() => new ColorWidget("red")); o.ConstructedBy(() => new ColorWidget("blue")); o.ConstructedBy(() => new ColorWidget("green")); }); x.ForConcreteType<TopClass>().Configure.OnCreation( (c, top) => { top.Widgets = c.GetAllInstances<IWidget>().ToArray(); }); }); container.GetInstance<TopClass>().Widgets.Count().ShouldEqual(4); } [Test] public void Get_a_unique_value_for_each_individual_buildsession() { int count = 0; var session = BuildSession.Empty(); var session2 = BuildSession.Empty(); var instance = new LambdaInstance<ColorRule>(() => { count++; return new ColorRule("Red"); }); object result1 = session.FindObject(typeof (ColorRule), instance); object result2 = session.FindObject(typeof (ColorRule), instance); object result3 = session2.FindObject(typeof (ColorRule), instance); object result4 = session2.FindObject(typeof (ColorRule), instance); Assert.AreEqual(2, count); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); Assert.AreSame(result3, result4); } [Test] public void If_no_child_array_is_explicitly_defined_return_all_instances() { IContainer manager = new Container(r => { r.For<IWidget>().AddInstances(x => { x.Object(new ColorWidget("Red")); x.Object(new ColorWidget("Blue")); x.Object(new ColorWidget("Green")); }); }); var holder = manager.GetInstance<WidgetHolder>(); Assert.AreEqual(3, holder.Widgets.Length); } [Test] public void Return_the_same_object_everytime_an_object_is_requested() { int count = 0; var session = BuildSession.Empty(); var instance = new LambdaInstance<ColorRule>(() => { count++; return new ColorRule("Red"); }); object result1 = session.FindObject(typeof (ColorRule), instance); object result2 = session.FindObject(typeof (ColorRule), instance); object result3 = session.FindObject(typeof (ColorRule), instance); object result4 = session.FindObject(typeof (ColorRule), instance); Assert.AreEqual(1, count); Assert.AreSame(result1, result2); Assert.AreSame(result1, result3); Assert.AreSame(result1, result4); } [Test] public void Return_the_same_object_within_a_session_for_the_default_of_a_plugin_type() { int count = 0; var instance = new LambdaInstance<ColorRule>(() => { count++; return new ColorRule("Red"); }); var registry = new Registry(); registry.For<ColorRule>().Use(instance); PluginGraph graph = registry.Build(); var session = BuildSession.ForPluginGraph(graph); object result1 = session.GetInstance(typeof (ColorRule)); object result2 = session.GetInstance(typeof (ColorRule)); object result3 = session.GetInstance(typeof (ColorRule)); object result4 = session.GetInstance(typeof (ColorRule)); Assert.AreEqual(1, count); Assert.AreSame(result1, result2); Assert.AreSame(result1, result3); Assert.AreSame(result1, result4); } [Test] public void Throw_200_When_trying_to_build_an_instance_that_cannot_be_found() { var graph = new RootPipelineGraph(new PluginGraph()); assertActionThrowsErrorCode(200, delegate { var session = new BuildSession(graph); session.CreateInstance(typeof (IGateway), "Gateway that is not configured"); }); } [Test] public void when_building_an_instance_use_the_register_the_stack_frame() { var recordingInstance = new BuildSessionInstance1(); ConfiguredInstance instance = new ConfiguredInstance(typeof (ClassWithRule)).Ctor<Rule>("rule").Is(recordingInstance); var session = BuildSession.Empty(); session.FindObject(typeof (IClassWithRule), instance); recordingInstance.Root.ConcreteType.ShouldEqual(typeof (ClassWithRule)); recordingInstance.Root.RequestedType.ShouldEqual(typeof (IClassWithRule)); recordingInstance.Root.Name.ShouldEqual(instance.Name); recordingInstance.Current.ConcreteType.ShouldEqual(typeof (ColorRule)); recordingInstance.Current.RequestedType.ShouldEqual(typeof (Rule)); recordingInstance.Current.Name.ShouldEqual(recordingInstance.Name); } [Test] public void When_calling_GetInstance_if_no_default_can_be_found_throw_202() { var graph = new RootPipelineGraph(new PluginGraph()); assertActionThrowsErrorCode(202, delegate { var session = new BuildSession(graph); session.GetInstance(typeof (IGateway)); }); } [Test] public void when_retrieving_an_object_by_name() { var red = new ColorService("red"); var green = new ColorService("green"); var graph = new PluginGraph(); var family = graph.Families[typeof (IService)]; family.AddInstance(new ObjectInstance(red).Named("red")); family.AddInstance(new ObjectInstance(green).Named("green")); var session = BuildSession.ForPluginGraph(graph); session.GetInstance<IService>("red").ShouldBeTheSameAs(red); } [Test] public void when_retrieving_an_object_by_nongeneric_type_and_name() { var red = new ColorService("red"); var green = new ColorService("green"); var registry = new Registry(); registry.For<IService>().Add(red).Named("red"); registry.For<IService>().Add(green).Named("green"); var graph = registry.Build(); var session = BuildSession.ForPluginGraph(graph); session.GetInstance(typeof(IService), "red").ShouldBeTheSameAs(red); } [Test] public void when_retrieving_by_try_get_instance_for_instance_that_does_exist() { var theService = new ColorService("red"); var session = BuildSession.Empty(new ExplicitArguments().Set<IService>(theService)); session.TryGetInstance<IService>().ShouldBeTheSameAs(theService); } [Test] public void when_retrieving_by_try_get_named_instance_that_does_exist() { var red = new ColorService("red"); var green = new ColorService("green"); var graph = new PluginGraph(); PluginFamily family = graph.Families[typeof (IService)]; family.AddInstance(new ObjectInstance(red).Named("red")); family.AddInstance(new ObjectInstance(green).Named("green")); var session = BuildSession.ForPluginGraph(graph); session.TryGetInstance<IService>("red").ShouldBeTheSameAs(red); session.TryGetInstance<IService>("green").ShouldBeTheSameAs(green); } [Test] public void when_retrieving_by_try_get_named_instance_that_does_not_exist() { var session = BuildSession.Empty(); session.TryGetInstance<IService>("red").ShouldBeNull(); } [Test] public void when_retrieving_with_try_get_instance_for_instance_that_does_not_exists() { var session = BuildSession.Empty(); session.TryGetInstance<IService>().ShouldBeNull(); } [Test] public void when_retrieving_with_try_get_instance_with_nongeneric_type_that_does_exist() { var theService = new ColorService("red"); var registry = new Registry(); registry.For<IService>().Use(theService); var session = BuildSession.ForPluginGraph(registry.Build()); session.TryGetInstance(typeof(IService)).ShouldBeTheSameAs(theService); } [Test] public void when_retrieving_with_try_get_instance_with_nongeneric_type_that_does_not_exist() { var session = BuildSession.Empty(); session.TryGetInstance(typeof(IService)).ShouldBeNull(); } [Test] public void when_retrieving_by_try_get_named_instance_with_nongeneric_type_that_does_exist() { var red = new ColorService("red"); var green = new ColorService("green"); var registry = new Registry(); registry.For<IService>().Add(red).Named("red"); registry.For<IService>().Add(green).Named("green"); var graph = registry.Build(); var session = BuildSession.ForPluginGraph(graph); session.TryGetInstance(typeof(IService), "red").ShouldBeTheSameAs(red); } [Test] public void when_retrieving_by_try_get_named_instance_with_type_that_does_not_exist() { var session = BuildSession.Empty(); session.TryGetInstance(typeof(IService), "yo").ShouldBeNull(); } [Test] public void Can_get_an_instance_using_the_non_generic_method() { var registry = new Registry(); registry.For<IFooService>().Use<Service>(); var graph = registry.Build(); var session = BuildSession.ForPluginGraph(graph); var instance = session.GetInstance(typeof (IFooService)); instance.ShouldNotBeNull(); instance.ShouldBeOfType<Service>(); } public interface IFooService { } public class Service : IFooService { } } public class TopClass { public TopClass(ClassWithWidget classWithWidget) { } public IWidget[] Widgets { get; set; } } public class ClassWithWidget { public ClassWithWidget(IWidget[] widgets) { } } public interface IClassWithRule { } public class ClassWithRule : IClassWithRule { public ClassWithRule(Rule rule) { } } public class BuildSessionInstance1 : Instance { public BuildFrame Current { get; set; } public BuildFrame Root { get; set; } protected override string getDescription() { return string.Empty; } protected override Type getConcreteType(Type pluginType) { return typeof (ColorRule); } protected override object build(Type pluginType, BuildSession session) { Current = session.BuildStack.Current; Root = session.BuildStack.Root; return new ColorRule("Red"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using Xunit; namespace System.Net.Primitives.PalTests { public class IPAddressPalTests { [Fact] public void IPv4StringToAddress_Valid() { const string AddressString = "127.0.64.255"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(127, bytes[0]); Assert.Equal(0, bytes[1]); Assert.Equal(64, bytes[2]); Assert.Equal(255, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassB() { const string AddressString = "128.64.256"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(128, bytes[0]); Assert.Equal(64, bytes[1]); Assert.Equal(1, bytes[2]); Assert.Equal(0, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassC() { const string AddressString = "192.65536"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(192, bytes[0]); Assert.Equal(1, bytes[1]); Assert.Equal(0, bytes[2]); Assert.Equal(0, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Valid_ClassA() { const string AddressString = "2130706433"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(127, bytes[0]); Assert.Equal(0, bytes[1]); Assert.Equal(0, bytes[2]); Assert.Equal(1, bytes[3]); Assert.Equal(0, port); } [Fact] public void IPv4StringToAddress_Invalid_Empty() { const string AddressString = ""; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv4StringToAddress_Invalid_NotAnAddress() { const string AddressString = "hello, world"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv4StringToAddress_Invalid_Port() { const string AddressString = "127.0.64.255:80"; var bytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port); Assert.True(err != IPAddressPal.SuccessErrorCode || port != 0); } public static object[][] ValidIPv4Addresses = new object[][] { new object[] { new byte[] { 0, 0, 0, 0 }, "0.0.0.0" }, new object[] { new byte[] { 127, 0, 64, 255 }, "127.0.64.255" }, new object[] { new byte[] { 128, 64, 1, 0 }, "128.64.1.0" }, new object[] { new byte[] { 192, 0, 0, 1 }, "192.0.0.1" }, new object[] { new byte[] { 255, 255, 255, 255 }, "255.255.255.255" } }; [Theory, MemberData("ValidIPv4Addresses")] public void IPv4AddressToString_Valid(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(addressString, buffer.ToString()); } [Theory, MemberData("ValidIPv4Addresses")] public void IPv4AddressToString_RoundTrip(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var actualAddressString = buffer.ToString(); Assert.Equal(addressString, actualAddressString); var roundTrippedBytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; err = IPAddressPal.Ipv4StringToAddress(actualAddressString, roundTrippedBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(bytes[0], roundTrippedBytes[0]); Assert.Equal(bytes[1], roundTrippedBytes[1]); Assert.Equal(bytes[2], roundTrippedBytes[2]); Assert.Equal(bytes[3], roundTrippedBytes[3]); Assert.Equal(0, port); } [Theory, MemberData("ValidIPv4Addresses")] public void IPv4StringToAddress_RoundTrip(byte[] bytes, string addressString) { var actualBytes = new byte[IPAddressParser.IPv4AddressBytes]; ushort port; uint err = IPAddressPal.Ipv4StringToAddress(addressString, actualBytes, out port); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(bytes[0], actualBytes[0]); Assert.Equal(bytes[1], actualBytes[1]); Assert.Equal(bytes[2], actualBytes[2]); Assert.Equal(bytes[3], actualBytes[3]); Assert.Equal(0, port); var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN); err = IPAddressPal.Ipv4AddressToString(actualBytes, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var roundTrippedAddressString = buffer.ToString(); Assert.Equal(addressString, roundTrippedAddressString); } [Fact] public void IPv6StringToAddress_Valid_Localhost() { const string AddressString = "::1"; var expectedBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid() { const string AddressString = "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Bracketed() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Port() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:80"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Port_2() { const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_Compressed() { const string AddressString = "2001:db8::1"; var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Valid_IPv4Compatible() { const string AddressString = "::ffff:222.1.41.90"; var expectedBytes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 }; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; Assert.Equal(bytes.Length, expectedBytes.Length); uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < expectedBytes.Length; i++) { Assert.Equal(expectedBytes[i], bytes[i]); } Assert.Equal(0, (int)scope); } [Fact] public void IPv6StringToAddress_Invalid_Empty() { const string AddressString = ""; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_NotAnAddress() { const string AddressString = "hello, world"; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_Port() { const string AddressString = "[2001:db8::1]:xx"; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } [Fact] public void IPv6StringToAddress_Invalid_Compression() { const string AddressString = "2001::db8::1"; var bytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope); Assert.NotEqual(err, IPAddressPal.SuccessErrorCode); } public static object[][] ValidIPv6Addresses = new object[][] { new object[] { new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, "::1" }, new object[] { new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 }, "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1" }, new object[] { new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, "2001:db8::1" }, new object[] { new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 }, "::ffff:222.1.41.90" } }; [Theory, MemberData("ValidIPv6Addresses")] public void IPv6AddressToString_Valid(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); Assert.Equal(addressString, buffer.ToString()); } [Theory, MemberData("ValidIPv6Addresses")] public void IPv6AddressToString_RoundTrip(byte[] bytes, string addressString) { var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var actualAddressString = buffer.ToString(); Assert.Equal(addressString, actualAddressString); var roundTrippedBytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; err = IPAddressPal.Ipv6StringToAddress(actualAddressString, roundTrippedBytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < bytes.Length; i++) { Assert.Equal(bytes[i], roundTrippedBytes[i]); } Assert.Equal(0, (int)scope); } [Theory, MemberData("ValidIPv6Addresses")] public void IPv6StringToAddress_RoundTrip(byte[] bytes, string addressString) { var actualBytes = new byte[IPAddressParser.IPv6AddressBytes]; uint scope; uint err = IPAddressPal.Ipv6StringToAddress(addressString, actualBytes, out scope); Assert.Equal(IPAddressPal.SuccessErrorCode, err); for (int i = 0; i < bytes.Length; i++) { Assert.Equal(bytes[i], actualBytes[i]); } Assert.Equal(0, (int)scope); var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN); err = IPAddressPal.Ipv6AddressToString(actualBytes, 0, buffer); Assert.Equal(IPAddressPal.SuccessErrorCode, err); var roundTrippedAddressString = buffer.ToString(); Assert.Equal(addressString, roundTrippedAddressString); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Toggl.Core.Extensions; using Toggl.Core.Models.Interfaces; using Toggl.Core.UI.Collections; using Toggl.Core.UI.Extensions; using Toggl.Core.UI.ViewModels.MainLog; using Toggl.Core.UI.ViewModels.MainLog.Identity; using Toggl.Shared; using Toggl.Shared.Extensions; using Toggl.Storage; using static Toggl.Core.UI.ViewModels.MainLog.LogItemVisualizationIntent; namespace Toggl.Core.UI.Transformations { using LogGrouping = IGrouping<DateTime, IThreadSafeTimeEntry>; using MainLogSection = AnimatableSectionModel<MainLogSectionViewModel, MainLogItemViewModel, IMainLogKey>; internal sealed class TimeEntriesGroupsFlattening { private delegate IImmutableList<IImmutableList<IThreadSafeTimeEntry>> GroupingStrategy(IEnumerable<IThreadSafeTimeEntry> timeEntries); private readonly ITimeService timeService; private readonly HashSet<GroupId> expandedGroups; private int indexInLog; private DurationFormat durationFormat; public TimeEntriesGroupsFlattening(ITimeService timeService) { this.timeService = timeService; expandedGroups = new HashSet<GroupId>(); } public IImmutableList<MainLogSection> Flatten(IEnumerable<LogGrouping> days, IThreadSafePreferences preferences) { durationFormat = preferences.DurationFormat; indexInLog = 0; return days.Select((day, dayInLog) => { var today = timeService.CurrentDateTime.Date; var sample = day.First().Start.Date; var daysInThePast = (today - sample).Days; var strategy = preferences.CollapseTimeEntries ? (GroupingStrategy)bySimilarTimeEntries : (GroupingStrategy)withJustSingleTimeEntries; return flatten(strategy, dayInLog, daysInThePast)(day); }).ToImmutableList(); } public void ToggleGroupExpansion(GroupId groupId) { if (expandedGroups.Contains(groupId)) { expandedGroups.Remove(groupId); } else { expandedGroups.Add(groupId); } } private Func<LogGrouping, MainLogSection> flatten(GroupingStrategy groupingStrategy, int dayInLog, int daysInThePast) { return day => { var items = groupingStrategy(day); var title = DateToTitleString.Convert(day.Key, timeService.CurrentDateTime); var duration = totalTrackedTime(items).ToFormattedString(durationFormat); return new MainLogSection( new DaySummaryViewModel(day.Key, title, duration), flattenGroups(items, dayInLog, daysInThePast) ); }; } private TimeSpan totalTrackedTime(IImmutableList<IImmutableList<IThreadSafeTimeEntry>> groups) { var trackedSeconds = groups.Sum(group => group.Sum(timeEntry => timeEntry.Duration ?? 0)); return TimeSpan.FromSeconds(trackedSeconds); } private IEnumerable<TimeEntryLogItemViewModel> flattenGroups(IImmutableList<IImmutableList<IThreadSafeTimeEntry>> groups, int dayInLog, int daysInThePast) { return groups.SelectMany(group => flattenGroup(group, dayInLog, daysInThePast)); } private IEnumerable<TimeEntryLogItemViewModel> flattenGroup(IImmutableList<IThreadSafeTimeEntry> group, int dayInLog, int daysInThePast) { var sample = group.First(); var groupId = new GroupId(sample); if (expandedGroups.Contains(groupId)) { if (group.Count > 1) { var headerIndex = indexInLog++; return group .Select(timeEntry => timeEntry.ToViewModel(groupId, GroupItem, durationFormat, indexInLog++, dayInLog, daysInThePast)) .Prepend(expandedHeader(groupId, group, headerIndex, dayInLog, daysInThePast)); } expandedGroups.Remove(groupId); } var item = group.Count == 1 ? sample.ToViewModel(groupId, SingleItem, durationFormat, indexInLog++, dayInLog, daysInThePast) : collapsedHeader(groupId, group, indexInLog++, dayInLog, daysInThePast); return new[] { item }; } private TimeEntryLogItemViewModel collapsedHeader( GroupId groupId, IImmutableList<IThreadSafeTimeEntry> group, int indexInLog, int dayInLog, int daysInThePast) => header(groupId, group, CollapsedGroupHeader, indexInLog, dayInLog, daysInThePast); private TimeEntryLogItemViewModel expandedHeader( GroupId groupId, IImmutableList<IThreadSafeTimeEntry> group, int indexInLog, int dayInLog, int daysInThePast) => header(groupId, group, ExpandedGroupHeader, indexInLog, dayInLog, daysInThePast); private TimeEntryLogItemViewModel header( GroupId groupId, IImmutableList<IThreadSafeTimeEntry> group, LogItemVisualizationIntent visualizationIntent, int indexInLog, int dayInLog, int daysInThePast) { var sample = group.First(); return new TimeEntryLogItemViewModel( groupId: groupId, representedTimeEntriesIds: group.Select(timeEntry => timeEntry.Id).ToArray(), visualizationIntent: visualizationIntent, isBillable: sample.Billable, isActive: sample.Project?.Active ?? true, description: sample.Description, duration: DurationAndFormatToString.Convert( TimeSpan.FromSeconds(group.Sum(timeEntry => timeEntry.Duration ?? 0)), durationFormat), projectName: sample.Project?.DisplayName(), projectColor: sample.Project?.Color, clientName: sample.Project?.Client?.Name, taskName: sample.Task?.Name, hasTags: sample.Tags.Any(), needsSync: group.Any(timeEntry => timeEntry.SyncStatus == SyncStatus.SyncNeeded || timeEntry.SyncStatus == SyncStatus.Syncing), canSync: group.All(timeEntry => timeEntry.SyncStatus != SyncStatus.SyncFailed), isInaccessible: sample.IsInaccessible, indexInLog: indexInLog, dayInLog: dayInLog, daysInThePast: daysInThePast, projectIsPlaceholder: sample.Project?.IsPlaceholder() ?? false, taskIsPlaceholder: sample.Task?.IsPlaceholder() ?? false); } private static IImmutableList<IImmutableList<IThreadSafeTimeEntry>> bySimilarTimeEntries( IEnumerable<IThreadSafeTimeEntry> timeEntries) => timeEntries .GroupBy(timeEntry => timeEntry, new TimeEntriesComparer()) .OrderByDescending(group => group.Max(timeEntry => timeEntry.Start)) .Select(group => group.ToIImmutableList()) .ToImmutableList(); private static IImmutableList<IImmutableList<IThreadSafeTimeEntry>> withJustSingleTimeEntries( IEnumerable<IThreadSafeTimeEntry> timeEntries) => timeEntries .Select(timeEntry => timeEntry.Yield().ToIImmutableList()) .ToImmutableList(); private sealed class TimeEntriesComparer : IEqualityComparer<IThreadSafeTimeEntry> { public bool Equals(IThreadSafeTimeEntry x, IThreadSafeTimeEntry y) => x != null && y != null && x.WorkspaceId == y.WorkspaceId && x.Description == y.Description && x.Project?.Id == y.Project?.Id && x.Task?.Id == y.Task?.Id && x.Billable == y.Billable && haveSameTags(x.TagIds?.ToArray(), y.TagIds?.ToArray()); public int GetHashCode(IThreadSafeTimeEntry timeEntry) { var hashCode = HashCode.Combine( timeEntry.Workspace.Id, timeEntry.Description, timeEntry.Project?.Id, timeEntry.Task?.Id, timeEntry.Billable); var tags = timeEntry.TagIds.OrderBy(id => id); foreach (var tag in tags) { hashCode = HashCode.Combine(hashCode, tag); } return hashCode; } private static bool haveSameTags(long[] a, long[] b) => a?.Length == b?.Length && (a?.OrderBy(id => id).SequenceEqual(b.OrderBy(id => id)) ?? true); } } }
using System; using System.Collections; using NBitcoin.BouncyCastle.Asn1; using NBitcoin.BouncyCastle.Asn1.X9; using NBitcoin.BouncyCastle.Math; using NBitcoin.BouncyCastle.Math.EC; using NBitcoin.BouncyCastle.Math.EC.Endo; using NBitcoin.BouncyCastle.Utilities; using NBitcoin.BouncyCastle.Utilities.Collections; using NBitcoin.BouncyCastle.Utilities.Encoders; namespace NBitcoin.BouncyCastle.Asn1.Sec { public sealed class SecNamedCurves { private SecNamedCurves() { } private static ECCurve ConfigureCurve(ECCurve curve) { return curve; } private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p) { return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create(); } private static BigInteger FromHex(string hex) { return new BigInteger(1, Hex.Decode(hex)); } /* * secp112r1 */ internal class Secp112r1Holder : X9ECParametersHolder { private Secp112r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder(); protected override X9ECParameters CreateParameters() { // p = (2^128 - 3) / 76439 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B"); BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088"); BigInteger b = FromHex("659EF8BA043916EEDE8911702B22"); byte[] S = Hex.Decode("00F50B028E4D696E676875615175290472783FB1"); BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "09487239995A5EE76B55F9C2F098")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "09487239995A5EE76B55F9C2F098" + "A89CE5AF8724C0A23E0E0FF77500")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp112r2 */ internal class Secp112r2Holder : X9ECParametersHolder { private Secp112r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder(); protected override X9ECParameters CreateParameters() { // p = (2^128 - 3) / 76439 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B"); BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C"); BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709"); byte[] S = Hex.Decode("002757A1114D696E6768756151755316C05E0BD4"); BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "4BA30AB5E892B4E1649DD0928643")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "4BA30AB5E892B4E1649DD0928643" + "ADCD46F5882E3747DEF36E956E97")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp128r1 */ internal class Secp128r1Holder : X9ECParametersHolder { private Secp128r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^128 - 2^97 - 1 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3"); byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679"); BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "161FF7528B899B2D0C28607CA52C5B86")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp128r2 */ internal class Secp128r2Holder : X9ECParametersHolder { private Secp128r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder(); protected override X9ECParameters CreateParameters() { // p = 2^128 - 2^97 - 1 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1"); BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D"); byte[] S = Hex.Decode("004D696E67687561517512D8F03431FCE63B88F4"); BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "7B6AA5D85E572983E6FB32A7CDEBC140")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "7B6AA5D85E572983E6FB32A7CDEBC140" + "27B6916A894D3AEE7106FE805FC34B44")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160k1 */ internal class Secp160k1Holder : X9ECParametersHolder { private Secp160k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(7); byte[] S = null; BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16), new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16), new BigInteger[]{ new BigInteger("9162fbe73984472a0a9e", 16), new BigInteger("-96341f1138933bc2f505", 16) }, new BigInteger[]{ new BigInteger("127971af8721782ecffa3", 16), new BigInteger("9162fbe73984472a0a9e", 16) }, new BigInteger("9162fbe73984472a0a9d0590", 16), new BigInteger("96341f1138933bc2f503fd44", 16), 176); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160r1 */ internal class Secp160r1Holder : X9ECParametersHolder { private Secp160r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^31 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345"); BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "4A96B5688EF573284664698968C38BB913CBFC82")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160r2 */ internal class Secp160r2Holder : X9ECParametersHolder { private Secp160r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70"); BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA"); byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751"); BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "52DCB034293A117E1F4FF11B30F7199D3144CE6D")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "52DCB034293A117E1F4FF11B30F7199D3144CE6D" + "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp192k1 */ internal class Secp192k1Holder : X9ECParametersHolder { private Secp192k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(3); byte[] S = null; BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16), new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16), new BigInteger[]{ new BigInteger("71169be7330b3038edb025f1", 16), new BigInteger("-b3fb3400dec5c4adceb8655c", 16) }, new BigInteger[]{ new BigInteger("12511cfe811d0f4e6bc688b4d", 16), new BigInteger("71169be7330b3038edb025f1", 16) }, new BigInteger("71169be7330b3038edb025f1d0f9", 16), new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16), 208); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp192r1 */ internal class Secp192r1Holder : X9ECParametersHolder { private Secp192r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^192 - 2^64 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp224k1 */ internal class Secp224k1Holder : X9ECParametersHolder { private Secp224k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(5); byte[] S = null; BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16), new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16), new BigInteger[]{ new BigInteger("6b8cf07d4ca75c88957d9d670591", 16), new BigInteger("-b8adf1378a6eb73409fa6c9c637d", 16) }, new BigInteger[]{ new BigInteger("1243ae1b4d71613bc9f780a03690e", 16), new BigInteger("6b8cf07d4ca75c88957d9d670591", 16) }, new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16), new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16), 240); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C" + "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp224r1 */ internal class Secp224r1Holder : X9ECParametersHolder { private Secp224r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 - 2^96 + 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp256k1 */ internal class Secp256k1Holder : X9ECParametersHolder { private Secp256k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(7); byte[] S = null; BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16), new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16), new BigInteger[]{ new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16), new BigInteger("-e4437ed6010e88286f547fa90abfe4c3", 16) }, new BigInteger[]{ new BigInteger("114ca50f7a8e2f3f657c1108d9d44cfd8", 16), new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16) }, new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16), new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16), 272); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp256r1 */ internal class Secp256r1Holder : X9ECParametersHolder { private Secp256r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90"); BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp384r1 */ internal class Secp384r1Holder : X9ECParametersHolder { private Secp384r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^384 - 2^128 - 2^96 + 2^32 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC"); BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF"); byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7" + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp521r1 */ internal class Secp521r1Holder : X9ECParametersHolder { private Secp521r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^521 - 1 BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00"); byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA"); BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66" + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect113r1 */ internal class Sect113r1Holder : X9ECParametersHolder { private Sect113r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder(); private const int m = 113; private const int k = 9; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7"); BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723"); byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9"); BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "009D73616F35F4AB1407D73562C10F")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "009D73616F35F4AB1407D73562C10F" + "00A52830277958EE84D1315ED31886")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect113r2 */ internal class Sect113r2Holder : X9ECParametersHolder { private Sect113r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder(); private const int m = 113; private const int k = 9; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7"); BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F"); byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D"); BigInteger n = FromHex("010000000000000108789B2496AF93"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "01A57A6A7B26CA5EF52FCDB8164797")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "01A57A6A7B26CA5EF52FCDB8164797" + "00B3ADC94ED1FE674C06E695BABA1D")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect131r1 */ internal class Sect131r1Holder : X9ECParametersHolder { private Sect131r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder(); private const int m = 131; private const int k1 = 2; private const int k2 = 3; private const int k3 = 8; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8"); BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341"); byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2"); BigInteger n = FromHex("0400000000000000023123953A9464B54D"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "0081BAF91FDF9833C40F9C181343638399")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0081BAF91FDF9833C40F9C181343638399" + "078C6E7EA38C001F73C8134B1B4EF9E150")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect131r2 */ internal class Sect131r2Holder : X9ECParametersHolder { private Sect131r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder(); private const int m = 131; private const int k1 = 2; private const int k2 = 3; private const int k3 = 8; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2"); BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192"); byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3"); BigInteger n = FromHex("0400000000000000016954A233049BA98F"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "0356DCD8F2F95031AD652D23951BB366A8")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0356DCD8F2F95031AD652D23951BB366A8" + "0648F06D867940A5366D9E265DE9EB240F")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163k1 */ internal class Sect163k1Holder : X9ECParametersHolder { private Sect163k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8" + "0289070FB05D38FF58321F2E800536D538CCDAA3D9")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163r1 */ internal class Sect163r1Holder : X9ECParametersHolder { private Sect163r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2"); BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9"); byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "0369979697AB43897789566789567F787A7876A654")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0369979697AB43897789566789567F787A7876A654" + "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163r2 */ internal class Sect163r2Holder : X9ECParametersHolder { private Sect163r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD"); byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268"); BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "03F0EBA16286A2D57EA0991168D4994637E8343E36")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "03F0EBA16286A2D57EA0991168D4994637E8343E36" + "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect193r1 */ internal class Sect193r1Holder : X9ECParametersHolder { private Sect193r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder(); private const int m = 193; private const int k = 15; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01"); BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814"); byte[] S = Hex.Decode("103FAEC74D696E676875615175777FC5B191EF30"); BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1" + "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect193r2 */ internal class Sect193r2Holder : X9ECParametersHolder { private Sect193r2Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder(); private const int m = 193; private const int k = 15; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B"); BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE"); byte[] S = Hex.Decode("10B7B4D696E676875615175137C8A16FD0DA2211"); BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F" + "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect233k1 */ internal class Sect233k1Holder : X9ECParametersHolder { private Sect233k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder(); private const int m = 233; private const int k = 74; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126" + "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect233r1 */ internal class Sect233r1Holder : X9ECParametersHolder { private Sect233r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder(); private const int m = 233; private const int k = 74; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD"); byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3"); BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B" + "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect239k1 */ internal class Sect239k1Holder : X9ECParametersHolder { private Sect239k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder(); private const int m = 239; private const int k = 158; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC" + "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect283k1 */ internal class Sect283k1Holder : X9ECParametersHolder { private Sect283k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder(); private const int m = 283; private const int k1 = 5; private const int k2 = 7; private const int k3 = 12; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836" + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect283r1 */ internal class Sect283r1Holder : X9ECParametersHolder { private Sect283r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder(); private const int m = 283; private const int k1 = 5; private const int k2 = 7; private const int k3 = 12; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5"); byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053" + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect409k1 */ internal class Sect409k1Holder : X9ECParametersHolder { private Sect409k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder(); private const int m = 409; private const int k = 87; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746" + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect409r1 */ internal class Sect409r1Holder : X9ECParametersHolder { private Sect409r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder(); private const int m = 409; private const int k = 87; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F"); byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B"); BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7" + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect571k1 */ internal class Sect571k1Holder : X9ECParametersHolder { private Sect571k1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder(); private const int m = 571; private const int k1 = 2; private const int k2 = 5; private const int k3 = 10; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("02" //+ "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972" + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect571r1 */ internal class Sect571r1Holder : X9ECParametersHolder { private Sect571r1Holder() {} internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder(); private const int m = 571; private const int k1 = 2; private const int k2 = 5; private const int k3 = 10; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A"); byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); //ECPoint G = curve.DecodePoint(Hex.Decode("03" //+ "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19")); ECPoint G = curve.DecodePoint(Hex.Decode("04" + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19" + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B")); return new X9ECParameters(curve, G, n, h, S); } } private static readonly IDictionary objIds = Platform.CreateHashtable(); private static readonly IDictionary curves = Platform.CreateHashtable(); private static readonly IDictionary names = Platform.CreateHashtable(); private static void DefineCurve( string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { objIds.Add(name, oid); names.Add(oid, name); curves.Add(oid, holder); } static SecNamedCurves() { DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance); DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance); DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance); DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance); DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance); DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance); DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance); DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance); DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance); DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance); DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance); DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance); DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance); DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance); DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance); DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance); DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance); DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance); DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance); DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance); DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance); DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance); DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance); DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance); DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance); DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance); DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance); DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance); DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance); DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance); DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance); DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance); DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance); } public static X9ECParameters GetByName( string name) { DerObjectIdentifier oid = (DerObjectIdentifier) objIds[Platform.ToLowerInvariant(name)]; return oid == null ? null : GetByOid(oid); } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters GetByOid( DerObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid]; return holder == null ? null : holder.Parameters; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid( string name) { return (DerObjectIdentifier)objIds[Platform.ToLowerInvariant(name)]; } /** * return the named curve name represented by the given object identifier. */ public static string GetName( DerObjectIdentifier oid) { return (string) names[oid]; } /** * returns an enumeration containing the name strings for curves * contained in this structure. */ public static IEnumerable Names { get { return new EnumerableProxy(objIds.Keys); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Security.Principal; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { // TODO: #2383 - Consolidate the use of the environment variable settings to Common/tests. public class DefaultCredentialsTest { private static string DomainJoinedTestServer => Configuration.Http.DomainJoinedHttpHost; private static bool DomainJoinedTestsEnabled => !string.IsNullOrEmpty(DomainJoinedTestServer); private static bool DomainProxyTestsEnabled => (!string.IsNullOrEmpty(Configuration.Http.DomainJoinedProxyHost)) && DomainJoinedTestsEnabled; private static string s_specificUserName = Configuration.Security.ActiveDirectoryUserName; private static string s_specificPassword = Configuration.Security.ActiveDirectoryUserPassword; private static string s_specificDomain = Configuration.Security.ActiveDirectoryName; private static Uri s_authenticatedServer = new Uri($"http://{DomainJoinedTestServer}/test/auth/negotiate/showidentity.ashx"); // This test endpoint offers multiple schemes, Basic and NTLM, in that specific order. This endpoint // helps test that the client will use the stronger of the server proposed auth schemes and // not the first auth scheme. private static Uri s_multipleSchemesAuthenticatedServer = new Uri($"http://{DomainJoinedTestServer}/test/auth/multipleschemes/showidentity.ashx"); private readonly ITestOutputHelper _output; private readonly NetworkCredential _specificCredential = new NetworkCredential(s_specificUserName, s_specificPassword, s_specificDomain); public DefaultCredentialsTest(ITestOutputHelper output) { _output = output; _output.WriteLine(s_authenticatedServer.ToString()); } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_DefaultValue_Unauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetFalse_Unauthorized(bool useProxy) { var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = false }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetTrue_ConnectAsCurrentIdentity(bool useProxy) { var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = true }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetTrueAndServerOffersMultipleSchemes_Ok(bool useProxy) { var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = true }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_multipleSchemesAuthenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task Credentials_SetToSpecificCredential_ConnectAsSpecificIdentity(bool useProxy) { var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = false, Credentials = _specificCredential }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); VerifyAuthentication(responseBody, true, s_specificDomain + "\\" + s_specificUserName); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task Credentials_SetToWrappedDefaultCredential_ConnectAsCurrentIdentity(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.Credentials = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithNoCredentials_ProxyAuthenticationRequired() { var handler = new HttpClientHandler(); handler.Proxy = new AuthenticatedProxy(null); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithDefaultCredentials_OK() { var handler = new HttpClientHandler(); handler.Proxy = new AuthenticatedProxy(CredentialCache.DefaultCredentials); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithWrappedDefaultCredentials_OK() { ICredentials wrappedCreds = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; var handler = new HttpClientHandler(); handler.Proxy = new AuthenticatedProxy(wrappedCreds); using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } private void VerifyAuthentication(string response, bool authenticated, string user) { // Convert all strings to lowercase to compare. Windows treats domain and username as case-insensitive. response = response.ToLower(); user = user.ToLower(); _output.WriteLine(response); if (!authenticated) { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "false"), "authenticated == false"); } else { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "true"), "authenticated == true"); Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "user", user), $"user == {user}"); } } private class CredentialWrapper : ICredentials { public ICredentials InnerCredentials { get; set; } public NetworkCredential GetCredential(Uri uri, String authType) => InnerCredentials?.GetCredential(uri, authType); } private class AuthenticatedProxy : IWebProxy { ICredentials _credentials; Uri _proxyUri; public AuthenticatedProxy(ICredentials credentials) { _credentials = credentials; string host = Configuration.Http.DomainJoinedProxyHost; Assert.False(string.IsNullOrEmpty(host), "DomainJoinedProxyHost must specify proxy hostname"); string portString = Configuration.Http.DomainJoinedProxyPort; Assert.False(string.IsNullOrEmpty(portString), "DomainJoinedProxyPort must specify proxy port number"); int port; Assert.True(int.TryParse(portString, out port), "DomainJoinedProxyPort must be a valid port number"); _proxyUri = new Uri(string.Format("http://{0}:{1}", host, port)); } public ICredentials Credentials { get { return _credentials; } set { throw new NotImplementedException(); } } public Uri GetProxy(Uri destination) { return _proxyUri; } public bool IsBypassed(Uri host) { return false; } } } }
!# issue 0 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_UNSIGNED 0x66,0x83,0xc0,0x80 == add ax, 0xff80 !# issue 0 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT | CS_OPT_UNSIGNED 0x66,0x83,0xc0,0x80 == addw $0xff80, %ax !# issue 1323 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x70,0x47,0x00 == bx lr ; op_count: 1 ; operands[0].type: REG = lr ; operands[0].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: thumb jump !# issue 1317 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0xd0,0xe8,0x11,0xf0 == tbh [r0, r1, lsl #1] ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = r0 ; operands[0].mem.index: REG = r1 ; operands[0].mem.lshift: 0x1 ; operands[0].access: READ ; Shift: 2 = 1 ; Registers read: r0 r1 ; Groups: thumb2 jump !# issue 1308 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x83,0x3d,0xa1,0x75,0x21,0x00,0x04 == cmp dword ptr [rip + 0x2175a1], 4 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x83 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x3d ; disp: 0x2175a1 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x4 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.base: REG = rip ; operands[0].mem.disp: 0x2175a1 ; operands[0].size: 4 ; operands[0].access: READ ; operands[1].type: IMM = 0x4 ; operands[1].size: 4 ; Registers read: rip ; Registers modified: rflags ; EFLAGS: MOD_AF MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF !# issue 1262 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x95,0x44,0x24,0x5e == setne byte ptr [rsp + 0x5e] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x95 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x44 ; disp: 0x5e ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x5e ; operands[0].size: 1 ; operands[0].access: WRITE ; Registers read: rflags rsp ; EFLAGS: TEST_ZF !# issue 1262 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x94,0x44,0x24,0x1f == sete byte ptr [rsp + 0x1f] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x94 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x44 ; disp: 0x1f ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x1f ; operands[0].size: 1 ; operands[0].access: WRITE ; Registers read: rflags rsp ; EFLAGS: TEST_ZF !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdb,0x7c,0x24,0x40 == fstp xword ptr [rsp + 0x40] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdb 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x7c ; disp: 0x40 ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x40 ; operands[0].size: 10 ; operands[0].access: WRITE ; Registers read: rsp ; Registers modified: fpsw ; FPU_FLAGS: MOD_C1 UNDEF_C0 UNDEF_C2 UNDEF_C3 ; Groups: fpu !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdd,0xd9 == fstp st(1) ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdd 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0xd9 ; disp: 0x0 ; sib: 0x0 ; op_count: 1 ; operands[0].type: REG = st(1) ; operands[0].size: 10 ; operands[0].access: WRITE ; Registers modified: fpsw st(1) ; EFLAGS: MOD_CF PRIOR_SF PRIOR_AF PRIOR_PF !# issue 1255 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0xdf,0x7c,0x24,0x68 == fistp qword ptr [rsp + 0x68] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xdf 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x7c ; disp: 0x68 ; sib: 0x24 ; sib_base: rsp ; sib_scale: 1 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.base: REG = rsp ; operands[0].mem.disp: 0x68 ; operands[0].size: 8 ; operands[0].access: WRITE ; Registers read: rsp ; Registers modified: fpsw ; FPU_FLAGS: RESET_C1 UNDEF_C0 UNDEF_C2 UNDEF_C3 ; Groups: fpu !# issue 1221 !# CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, None 0x0: 0x55,0x48,0x89,0xe5 == call 0x55222794 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x02,0xb6 == tbz x0, #0x20, #0x4000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x04,0xb6 == tbz x0, #0x20, #0xffffffffffff8000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x02,0xb7 == tbnz x0, #0x20, #0x4000 !# issue 1144 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x04,0xb7 == tbnz x0, #0x20, #0xffffffffffff8000 !# issue 826 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0b,0x00,0x00,0x0a == beq #0x34 ; op_count: 1 ; operands[0].type: IMM = 0x34 ; Code condition: 1 ; Registers read: pc ; Registers modified: pc ; Groups: branch_relative arm jump !# issue 1047 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x83,0xe4,0xf0 == andq $0xfffffffffffffff0, %rsp !# issue 959 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xa0,0x28,0x57,0x88,0x7c == mov al, byte ptr [0x7c885728] !# issue 950 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x66,0xa3,0x94,0x90,0x04,0x08 == mov word ptr [0x8049094], ax ; Prefix:0x00 0x00 0x66 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x8049094 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.disp: 0x8049094 ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: REG = ax ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: ax !# issue 938 !# CS_ARCH_MIPS, CS_MODE_MIPS64+CS_MODE_LITTLE_ENDIAN, None 0x0: 0x70,0x00,0xb2,0xff == sd $s2, 0x70($sp) !# issue 915 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xf0,0x0f,0x1f,0x00 == lock nop dword ptr [rax] !# issue 913 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x04,0x10,0x9d,0xe4 == pop {r1} ; op_count: 1 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; Write-back: True ; Registers read: sp ; Registers modified: sp r1 ; Groups: arm !# issue 884 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x64,0x48,0x03,0x04,0x25,0x00,0x00,0x00,0x00 == addq %fs:0, %rax !# issue 872 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xeb,0x3e == bnd jmp 0x41 !# issue 861 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x01,0x81,0xa0,0xfc == stc2 p1, c8, [r0], #4 ; op_count: 4 ; operands[0].type: P-IMM = 1 ; operands[1].type: C-IMM = 8 ; operands[2].type: MEM ; operands[2].mem.base: REG = r0 ; operands[2].access: READ ; operands[3].type: IMM = 0x4 ; Write-back: True ; Registers read: r0 ; Registers modified: r0 ; Groups: prev8 !# issue 852 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x64,0xa3,0x00,0x00,0x00,0x00 == mov dword ptr fs:[0], eax ; Prefix:0x00 0x64 0x00 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.segment: REG = fs ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: REG = eax ; operands[1].size: 4 ; operands[1].access: READ ; Registers read: fs eax !# issue 825 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0xf0,0xa0,0xe1 == mov pc, lr ; op_count: 2 ; operands[0].type: REG = pc ; operands[0].access: WRITE ; operands[1].type: REG = lr ; operands[1].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: arm !# issue 813 !# CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_BIG_ENDIAN, None 0x0: 0xF6,0xC0,0x04,0x01 == movt r4, #0x801 !# issue 809 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_DETAIL 0x0: 0x0f,0x29,0x8d,0xf0,0xfd,0xff,0xff == movaps xmmword ptr [rbp - 0x210], xmm1 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x0f 0x29 0x00 0x00 ; rex: 0x0 ; addr_size: 8 ; modrm: 0x8d ; disp: 0xfffffffffffffdf0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.base: REG = rbp ; operands[0].mem.disp: 0xfffffffffffffdf0 ; operands[0].size: 16 ; operands[0].access: WRITE ; operands[1].type: REG = xmm1 ; operands[1].size: 16 ; operands[1].access: READ ; Registers read: rbp xmm1 ; Groups: sse1 !# issue 807 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x4c,0x0f,0x00,0x80,0x16,0x76,0x8a,0xfe == sldt word ptr [rax - 0x17589ea] !# issue 806 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x0f,0x35 == sysexit !# issue 805 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x4c,0x0f,0xb5,0x80,0x16,0x76,0x8a,0xfe == lgs -0x17589ea(%rax), %r8 !# issue 804 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x66,0x48,0xf3,0xd1,0xc0 == rol $1, %ax !# issue 789 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x8e,0x1e == movw (%rsi), %ds !# issue 767 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0xb1,0xe8,0xfc,0x07 == ldm.w r1!, {r2, r3, r4, r5, r6, r7, r8, sb, sl} ; op_count: 10 ; operands[0].type: REG = r1 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r2 ; operands[1].access: WRITE ; operands[2].type: REG = r3 ; operands[2].access: WRITE ; operands[3].type: REG = r4 ; operands[3].access: WRITE ; operands[4].type: REG = r5 ; operands[4].access: WRITE ; operands[5].type: REG = r6 ; operands[5].access: WRITE ; operands[6].type: REG = r7 ; operands[6].access: WRITE ; operands[7].type: REG = r8 ; operands[7].access: WRITE ; operands[8].type: REG = sb ; operands[8].access: WRITE ; operands[9].type: REG = sl ; operands[9].access: WRITE ; Write-back: True ; Registers read: r1 ; Registers modified: r1 r2 r3 r4 r5 r6 r7 r8 sb sl ; Groups: thumb2 !# issue 760 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x02,0x80,0xbd,0xe8 == pop {r1, pc} ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: REG = pc ; operands[1].access: WRITE ; Registers read: sp ; Registers modified: sp r1 pc ; Groups: arm !# issue 750 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0x00,0x20,0xe9 == stmdb r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ ; operands[1].type: REG = r1 ; operands[2].type: REG = r2 ; operands[3].type: REG = r3 ; Write-back: True ; Registers read: r0 ; Groups: arm !# issue 747 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x0e,0x00,0xb0,0xe8 == ldm r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r1 ; operands[1].access: WRITE ; operands[2].type: REG = r2 ; operands[2].access: WRITE ; operands[3].type: REG = r3 ; operands[3].access: WRITE ; Write-back: True ; Registers read: r0 ; Registers modified: r0 r1 r2 r3 ; Groups: arm !# issue 747 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x0e,0xc8 == ldm r0!, {r1, r2, r3} ; op_count: 4 ; operands[0].type: REG = r0 ; operands[0].access: READ | WRITE ; operands[1].type: REG = r1 ; operands[1].access: WRITE ; operands[2].type: REG = r2 ; operands[2].access: WRITE ; operands[3].type: REG = r3 ; operands[3].access: WRITE ; Write-back: True ; Registers read: r0 ; Registers modified: r0 r1 r2 r3 ; Groups: thumb thumb1only !# issue 746 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x89,0x00,0x2d,0xe9 == push {r0, r3, r7} ; op_count: 3 ; operands[0].type: REG = r0 ; operands[0].access: READ ; operands[1].type: REG = r3 ; operands[1].access: READ ; operands[2].type: REG = r7 ; operands[2].access: READ ; Registers read: sp r0 r3 r7 ; Registers modified: sp ; Groups: arm !# issue 744 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0x02,0x80,0xbd,0xe8 == pop {r1, pc} ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: REG = pc ; operands[1].access: WRITE ; Registers read: sp ; Registers modified: sp r1 pc ; Groups: arm !# issue 741 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x83,0xff,0xf7 == cmp edi, -9 !# issue 717 !# CS_ARCH_X86, CS_MODE_64, CS_OPT_SYNTAX_ATT 0x0: 0x48,0x8b,0x04,0x25,0x00,0x00,0x00,0x00 == movq 0, %rax !# issue 711 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xa3,0x44,0xb0,0x00,0x10 == mov dword ptr [0x1000b044], eax ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xa3 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x1000b044 ; sib: 0x0 ; op_count: 2 ; operands[0].type: MEM ; operands[0].mem.disp: 0x1000b044 ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: REG = eax ; operands[1].size: 4 ; operands[1].access: READ ; Registers read: eax !# issue 613 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xd9,0x74,0x24,0xd8 == fnstenv [rsp - 0x28] !# issue 554 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe7,0x84 == out 0x84, eax !# issue 554 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe5,0x8c == in eax, 0x8c !# issue 545 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x95 == xchg eax, ebp ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x95 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = eax ; operands[0].size: 4 ; operands[0].access: READ | WRITE ; operands[1].type: REG = ebp ; operands[1].size: 4 ; operands[1].access: READ | WRITE ; Registers read: eax ebp ; Registers modified: eax ebp ; Groups: not64bitmode !# issue 544 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xdf,0x30 == fbstp tbyte ptr [eax] !# issue 544 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xdf,0x20 == fbld tbyte ptr [eax] !# issue 541 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x48,0xb8,0x00,0x00,0x00,0x00,0x80,0xf8,0xff,0xff == movabs rax, 0xfffff88000000000 !# issue 499 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x48,0xb8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80 == movabs rax, 0x8000000000000000 !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x18 == lcall [eax] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x28 == ljmp [eax] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0xae,0x04,0x24 == fxsave [esp] !# issue 492 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0xae,0x0c,0x24 == fxrstor [esp] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x05,0xa0,0x90,0x04,0x08 == sgdt [0x80490a0] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x0d,0xa7,0x90,0x04,0x08 == sidt [0x80490a7] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x15,0xa0,0x90,0x04,0x08 == lgdt [0x80490a0] !# issue 470 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x0f,0x01,0x1d,0xa7,0x90,0x04,0x08 == lidt [0x80490a7] !# issue 459 !# CS_ARCH_ARM, CS_MODE_ARM, CS_OPT_DETAIL 0x0: 0xd3,0x20,0x11,0xe1 == ldrsb r2, [r1, -r3] ; op_count: 2 ; operands[0].type: REG = r2 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r1 ; operands[1].mem.index: REG = r3 ; operands[1].mem.scale: -1 ; Subtracted: True ; Registers read: r1 r3 ; Registers modified: r2 ; Groups: arm !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xe8,0x35,0x64 == call 0x6438 !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xe9,0x35,0x64 == jmp 0x6438 !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe8,0x35,0x64,0x93,0x53 == call 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0x66,0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643b !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xe8,0x35,0x64 == call 0x6439 !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe9,0x35,0x64,0x93,0x53 == jmp 0x5393643a !# issue 456 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xe9,0x35,0x64 == jmp 0x6439 !# issue 458 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xA1,0x12,0x34,0x90,0x90 == mov eax, dword ptr [0x90903412] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xa1 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x90903412 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = eax ; operands[0].size: 4 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.disp: 0x90903412 ; operands[1].size: 4 ; operands[1].access: READ ; Registers modified: eax !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6c == repne insb byte ptr es:[edi], dx !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6d == repne insd dword ptr es:[edi], dx !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6e == repne outsb dx, byte ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x6f == repne outsd dx, dword ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xac == repne lodsb al, byte ptr [esi] !# issue 454 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0xad == repne lodsd eax, dword ptr [esi] !# issue 450 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xff,0x2d,0x34,0x35,0x23,0x01 == ljmp [0x1233534] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xff 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x2d ; disp: 0x1233534 ; sib: 0x0 ; op_count: 1 ; operands[0].type: MEM ; operands[0].mem.disp: 0x1233534 ; operands[0].size: 6 ; Groups: jump !# issue 448 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xea,0x12,0x34,0x56,0x78,0x9a,0xbc == ljmp 0xbc9a:0x78563412 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xea 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 2 ; imms[1]: 0xbc9a ; imms[2]: 0x78563412 ; op_count: 2 ; operands[0].type: IMM = 0xbc9a ; operands[0].size: 2 ; operands[1].type: IMM = 0x78563412 ; operands[1].size: 4 ; Groups: not64bitmode jump !# issue 426 !# CS_ARCH_SPARC, CS_MODE_BIG_ENDIAN, None 0x0: 0xbb,0x70,0x00,0x00 == popc %g0, %i5 !# issue 358 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xe8,0xe3,0xf6,0xff,0xff == call 0xfffff6e8 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xe8 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0xfffff6e8 ; op_count: 1 ; operands[0].type: IMM = 0xfffff6e8 ; operands[0].size: 4 ; Registers read: esp eip ; Registers modified: esp ; Groups: call branch_relative not64bitmode !# issue 353 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xe6,0xa2 == out 0xa2, al ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xe6 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0xa2 ; op_count: 2 ; operands[0].type: IMM = 0xa2 ; operands[0].size: 4 ; operands[1].type: REG = al ; operands[1].size: 1 ; operands[1].access: READ ; Registers read: al !# issue 305 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x34,0x8b == xor al, 0x8b !# issue 298 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf3,0x90 == pause !# issue 298 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0x66,0xf3,0xf2,0x0f,0x59,0xff == mulsd xmm7, xmm7 !# issue 298 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xf2,0x66,0x0f,0x59,0xff == mulpd xmm7, xmm7 !# issue 294 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xc1,0xe6,0x08 == shl esi, 8 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xc1 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0xe6 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x8 ; op_count: 2 ; operands[0].type: REG = esi ; operands[0].size: 4 ; operands[0].access: READ | WRITE ; operands[1].type: IMM = 0x8 ; operands[1].size: 1 ; Registers read: esi ; Registers modified: eflags esi ; EFLAGS: MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF UNDEF_AF !# issue 285 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x3c,0x12,0x80 == cmp al, 0x12 ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x3c 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x12 ; op_count: 2 ; operands[0].type: REG = al ; operands[0].size: 1 ; operands[0].access: READ ; operands[1].type: IMM = 0x12 ; operands[1].size: 1 ; Registers read: al ; Registers modified: eflags ; EFLAGS: MOD_AF MOD_CF MOD_SF MOD_ZF MOD_PF MOD_OF !# issue 265 !# CS_ARCH_ARM, CS_MODE_THUMB, CS_OPT_DETAIL 0x0: 0x52,0xf8,0x23,0x30 == ldr.w r3, [r2, r3, lsl #2] ; op_count: 2 ; operands[0].type: REG = r3 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r2 ; operands[1].mem.index: REG = r3 ; operands[1].access: READ ; Shift: 2 = 2 ; Registers read: r2 r3 ; Registers modified: r3 ; Groups: thumb2 !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x0c,0xbf == ite eq !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x17,0x20 == movs r0, #0x17 !# issue 264 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x4f,0xf0,0xff,0x30 == mov.w r0, #-1 !# issue 246 !# CS_ARCH_ARM, CS_MODE_THUMB, None 0x0: 0x52,0xf8,0x23,0xf0 == ldr.w pc, [r2, r3, lsl #2] !# issue 232 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x8e,0x10 == mov ss, word ptr [eax] ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0x8e 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x10 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = ss ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = eax ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: eax ; Registers modified: ss ; Groups: privilege !# issue 231 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0x66,0x6b,0xc0,0x02 == imul ax, ax, 2 ; Prefix:0x00 0x00 0x66 0x00 ; Opcode:0x6b 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0xc0 ; disp: 0x0 ; sib: 0x0 ; imm_count: 1 ; imms[1]: 0x2 ; op_count: 3 ; operands[0].type: REG = ax ; operands[0].size: 2 ; operands[0].access: WRITE ; operands[1].type: REG = ax ; operands[1].size: 2 ; operands[1].access: READ ; operands[2].type: IMM = 0x2 ; operands[2].size: 2 ; Registers read: ax ; Registers modified: eflags ax ; EFLAGS: MOD_CF MOD_SF MOD_OF UNDEF_ZF UNDEF_PF UNDEF_AF !# issue 230 !# CS_ARCH_X86, CS_MODE_32, CS_OPT_DETAIL 0x0: 0xec == in al, dx ; Prefix:0x00 0x00 0x00 0x00 ; Opcode:0xec 0x00 0x00 0x00 ; rex: 0x0 ; addr_size: 4 ; modrm: 0x0 ; disp: 0x0 ; sib: 0x0 ; op_count: 2 ; operands[0].type: REG = al ; operands[0].size: 1 ; operands[0].access: WRITE ; operands[1].type: REG = dx ; operands[1].size: 2 ; operands[1].access: READ ; Registers read: dx ; Registers modified: al !# issue 213 !# CS_ARCH_X86, CS_MODE_16, None 0x0: 0xea,0xaa,0xff,0x00,0xf0 == ljmp 0xf000:0xffaa !# issue 191 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xc5,0xe8,0xc2,0x33,0x9b == vcmpps xmm6, xmm2, xmmword ptr [rbx], 0x9b !# issue 176 !# CS_ARCH_ARM, CS_MODE_ARM, None 0x0: 0xfd,0xff,0xff,0x1a == bne #0xfffffffc !# issue 151 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0x4d,0x8d,0x3d,0x02,0x00,0x00,0x00 == lea r15, [rip + 2] !# issue 151 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xeb,0xb0 == jmp 0xffffffffffffffb2 !# issue 134 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xe7,0x92,0x11,0x80 == ldr r1, [r2, r0, lsl #3] ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = r2 ; operands[1].mem.index: REG = r0 ; operands[1].access: READ ; Shift: 2 = 3 ; Registers read: r2 r0 ; Registers modified: r1 ; Groups: arm !# issue 133 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xed,0xdf,0x2b,0x1b == vldr d18, [pc, #0x6c] ; op_count: 2 ; operands[0].type: REG = d18 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = pc ; operands[1].mem.disp: 0x6c ; operands[1].access: READ ; Registers read: pc ; Registers modified: d18 ; Groups: vfp2 !# issue 132 !# CS_ARCH_ARM, CS_MODE_THUMB | CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0x49,0x19 == ldr r1, [pc, #0x64] ; op_count: 2 ; operands[0].type: REG = r1 ; operands[0].access: WRITE ; operands[1].type: MEM ; operands[1].mem.base: REG = pc ; operands[1].mem.disp: 0x64 ; operands[1].access: READ ; Registers read: pc ; Registers modified: r1 ; Groups: thumb thumb1only !# issue 130 !# CS_ARCH_ARM, CS_MODE_BIG_ENDIAN, CS_OPT_DETAIL 0x0: 0xe1,0xa0,0xf0,0x0e == mov pc, lr ; op_count: 2 ; operands[0].type: REG = pc ; operands[0].access: WRITE ; operands[1].type: REG = lr ; operands[1].access: READ ; Registers read: lr ; Registers modified: pc ; Groups: arm !# issue 85 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0xee,0x3f,0xbf,0x29 == stp w14, w15, [sp, #-8]! !# issue 82 !# CS_ARCH_X86, CS_MODE_64, None 0x0: 0xf2,0x66,0xaf == repne scasw ax, word ptr [rdi] !# issue 35 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xe8,0xc6,0x02,0x00,0x00 == call 0x2cb !# issue 8 !# CS_ARCH_X86, CS_MODE_32, None 0x0: 0xff,0x8c,0xf9,0xff,0xff,0x9b,0xf9 == dec dword ptr [ecx + edi*8 - 0x6640001] !# issue 29 !# CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN, None 0x0: 0x00,0x00,0x00,0x4c == st4 {v0.16b, v1.16b, v2.16b, v3.16b}, [x0]
using System; using System.Collections; using Community.CsharpSqlite; public class SQLiteQuery { private SQLiteDB sqlDb; private Sqlite3.sqlite3 db; private Sqlite3.Vdbe vm; private string[] columnNames; private int[] columnTypes; private int bindIndex; public string[] Names { get { return columnNames; } } public SQLiteQuery(SQLiteDB sqliteDb, string query) { sqlDb = sqliteDb; bindIndex = 1; db = sqliteDb.Connection(); if (Sqlite3.sqlite3_prepare_v2(db, query, query.Length, ref vm, 0) != Sqlite3.SQLITE_OK) { throw new Exception("Error with prepare query! error:" + Sqlite3.sqlite3_errmsg(db)); }; sqlDb.RegisterQuery(this); } public void Reset() { bindIndex = 1; if (Sqlite3.sqlite3_reset(vm) != Sqlite3.SQLITE_OK) { throw new Exception("Error with sqlite3_reset!"); }; } public void Release() { sqlDb.UnregisterQuery(this); if (Sqlite3.sqlite3_reset(vm) != Sqlite3.SQLITE_OK) { throw new Exception("Error with sqlite3_reset!"); }; if (Sqlite3.sqlite3_finalize(vm) != Sqlite3.SQLITE_OK) { throw new Exception("Error with sqlite3_finalize!"); }; } public void Bind(string str) { BindAt(str, -1); } public void BindAt(string str, int bindAt) { if (bindAt == -1) { bindAt = bindIndex++; } if (Sqlite3.sqlite3_bind_text(vm, bindAt, str, -1, null) != Sqlite3.SQLITE_OK) { throw new Exception("SQLite fail to bind string with error: " + Sqlite3.sqlite3_errmsg(db)); }; } public void Bind(int integer) { BindAt(integer, -1); } public void BindAt(int integer, int bindAt) { if (bindAt == -1) { bindAt = bindIndex++; } if (Sqlite3.sqlite3_bind_int(vm, bindAt, integer) != Sqlite3.SQLITE_OK) { throw new Exception("SQLite fail to bind integer with error: " + Sqlite3.sqlite3_errmsg(db)); }; } public void Bind(double real) { BindAt(real, -1); } public void BindAt(double real, int bindAt) { if (bindAt == -1) { bindAt = bindIndex++; } if (Sqlite3.sqlite3_bind_double(vm, bindAt, real) != Sqlite3.SQLITE_OK) { throw new Exception("SQLite fail to bind double with error: " + Sqlite3.sqlite3_errmsg(db)); }; } public void Bind(byte[] blob) { BindAt(blob, -1); } public void BindAt(byte[] blob, int bindAt) { if (bindAt == -1) { bindAt = bindIndex++; } if (Sqlite3.sqlite3_bind_blob(vm, bindAt, blob, blob.Length, null) != Sqlite3.SQLITE_OK) { throw new Exception("SQLite fail to bind blob with error: " + Sqlite3.sqlite3_errmsg(db)); }; } public void BindNull() { BindNullAt(-1); } public void BindNullAt(int bindAt) { if (bindAt == -1) { bindAt = bindIndex++; } if (Sqlite3.sqlite3_bind_null(vm, bindAt) != Sqlite3.SQLITE_OK) { throw new Exception("SQLite fail to bind null error: " + Sqlite3.sqlite3_errmsg(db)); }; } public bool Step() { switch (Sqlite3.sqlite3_step(vm)) { case Sqlite3.SQLITE_DONE: return false; case Sqlite3.SQLITE_ROW: { int columnCount = Sqlite3.sqlite3_column_count(vm); columnNames = new string[columnCount]; columnTypes = new int[columnCount]; try { // reads columns one by one for (int i = 0; i < columnCount; i++) { columnNames[i] = Sqlite3.sqlite3_column_name(vm, i); columnTypes[i] = Sqlite3.sqlite3_column_type(vm, i); } } catch { throw new Exception("SQLite fail to read column's names and types! error: " + Sqlite3.sqlite3_errmsg(db)); } return true; } } throw new Exception("SQLite step fail! error: " + Sqlite3.sqlite3_errmsg(db)); } public bool IsNULL(string field) { int i = GetFieldIndex(field); return Sqlite3.SQLITE_NULL == columnTypes[i]; } public int GetFieldType(string field) { for (int i = 0; i < columnNames.Length; i++) { if (columnNames[i] == field) return columnTypes[i]; } throw new Exception("SQLite unknown field name: " + field); } private int GetFieldIndex(string field) { for (int i = 0; i < columnNames.Length; i++) { if (columnNames[i] == field) return i; } throw new Exception("SQLite unknown field name: " + field); } public string GetString(string field) { int i = GetFieldIndex(field); if (Sqlite3.SQLITE_TEXT == columnTypes[i]) { return Sqlite3.sqlite3_column_text(vm, i); } throw new Exception("SQLite wrong field type (expecting String) : " + field); } public int GetInteger(string field) { int i = GetFieldIndex(field); if (Sqlite3.SQLITE_INTEGER == columnTypes[i]) { return Sqlite3.sqlite3_column_int(vm, i); } throw new Exception("SQLite wrong field type (expecting Integer) : " + field); } public double GetDouble(string field) { int i = GetFieldIndex(field); if (Sqlite3.SQLITE_FLOAT == columnTypes[i]) { return Sqlite3.sqlite3_column_double(vm, i); } throw new Exception("SQLite wrong field type (expecting Double) : " + field); } public byte[] GetBlob(string field) { int i = GetFieldIndex(field); if (Sqlite3.SQLITE_BLOB == columnTypes[i]) { return Sqlite3.sqlite3_column_blob(vm, i); } throw new Exception("SQLite wrong field type (expecting byte[]) : " + field); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; namespace System.Diagnostics { /// <summary> /// Performance Counter component. /// This class provides support for NT Performance counters. /// It handles both the existing counters (accesible by Perf Registry Interface) /// and user defined (extensible) counters. /// This class is a part of a larger framework, that includes the perf dll object and /// perf service. /// </summary> public sealed class PerformanceCounter : Component, ISupportInitialize { private string _machineName; private string _categoryName; private string _counterName; private string _instanceName; private PerformanceCounterInstanceLifetime _instanceLifetime = PerformanceCounterInstanceLifetime.Global; private bool _isReadOnly; private bool _initialized = false; private string _helpMsg = null; private int _counterType = -1; // Cached old sample private CounterSample _oldSample = CounterSample.Empty; // Cached IP Shared Performanco counter private SharedPerformanceCounter _sharedCounter; [ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")] public static int DefaultFileMappingSize = 524288; private Object _instanceLockObject; private Object InstanceLockObject { get { if (_instanceLockObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref _instanceLockObject, o, null); } return _instanceLockObject; } } /// <summary> /// The defaut constructor. Creates the perf counter object /// </summary> public PerformanceCounter() { _machineName = "."; _categoryName = string.Empty; _counterName = string.Empty; _instanceName = string.Empty; _isReadOnly = true; GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) { MachineName = machineName; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = true; Initialize(); GC.SuppressFinalize(this); } internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit) { MachineName = machineName; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = true; _initialized = true; GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object on local machine. /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName) : this(categoryName, counterName, instanceName, true) { } /// <summary> /// Creates the Performance Counter Object on local machine. /// </summary> public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly) { if (!readOnly) { VerifyWriteableCounterAllowed(); } MachineName = "."; CategoryName = categoryName; CounterName = counterName; InstanceName = instanceName; _isReadOnly = readOnly; Initialize(); GC.SuppressFinalize(this); } /// <summary> /// Creates the Performance Counter Object, assumes that it's a single instance /// </summary> public PerformanceCounter(string categoryName, string counterName) : this(categoryName, counterName, true) { } /// <summary> /// Creates the Performance Counter Object, assumes that it's a single instance /// </summary> public PerformanceCounter(string categoryName, string counterName, bool readOnly) : this(categoryName, counterName, "", readOnly) { } /// <summary> /// Returns the performance category name for this performance counter /// </summary> public string CategoryName { get { return _categoryName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (_categoryName == null || !string.Equals(_categoryName, value, StringComparison.OrdinalIgnoreCase)) { _categoryName = value; Close(); } } } /// <summary> /// Returns the description message for this performance counter /// </summary> public string CounterHelp { get { string currentCategoryName = _categoryName; string currentMachineName = _machineName; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); if (_helpMsg == null) _helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName); return _helpMsg; } } /// <summary> /// Sets/returns the performance counter name for this performance counter /// </summary> public string CounterName { get { return _counterName; } set { if (value == null) throw new ArgumentNullException(nameof(value)); if (_counterName == null || !string.Equals(_counterName, value, StringComparison.OrdinalIgnoreCase)) { _counterName = value; Close(); } } } /// <summary> /// Sets/Returns the counter type for this performance counter /// </summary> public PerformanceCounterType CounterType { get { if (_counterType == -1) { string currentCategoryName = _categoryName; string currentMachineName = _machineName; // This is the same thing that NextSample does, except that it doesn't try to get the actual counter // value. If we wanted the counter value, we would need to have an instance name. PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName); _counterType = counterSample._counterType; } return (PerformanceCounterType)_counterType; } } public PerformanceCounterInstanceLifetime InstanceLifetime { get { return _instanceLifetime; } set { if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global) throw new ArgumentOutOfRangeException(nameof(value)); if (_initialized) throw new InvalidOperationException(SR.Format(SR.CantSetLifetimeAfterInitialized)); _instanceLifetime = value; } } /// <summary> /// Sets/returns an instance name for this performance counter /// </summary> public string InstanceName { get { return _instanceName; } set { if (value == null && _instanceName == null) return; if ((value == null && _instanceName != null) || (value != null && _instanceName == null) || !string.Equals(_instanceName, value, StringComparison.OrdinalIgnoreCase)) { _instanceName = value; Close(); } } } /// <summary> /// Returns true if counter is read only (system counter, foreign extensible counter or remote counter) /// </summary> public bool ReadOnly { get { return _isReadOnly; } set { if (value != _isReadOnly) { if (value == false) { VerifyWriteableCounterAllowed(); } _isReadOnly = value; Close(); } } } /// <summary> /// Set/returns the machine name for this performance counter /// </summary> public string MachineName { get { return _machineName; } set { if (!SyntaxCheck.CheckMachineName(value)) throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value)); if (_machineName != value) { _machineName = value; Close(); } } } /// <summary> /// Directly accesses the raw value of this counter. If counter type is of a 32-bit size, it will truncate /// the value given to 32 bits. This can be significantly more performant for scenarios where /// the raw value is sufficient. Note that this only works for custom counters created using /// this component, non-custom counters will throw an exception if this property is accessed. /// </summary> public long RawValue { get { if (ReadOnly) { //No need to initialize or Demand, since NextSample already does. return NextSample().RawValue; } else { Initialize(); return _sharedCounter.Value; } } set { if (ReadOnly) ThrowReadOnly(); Initialize(); _sharedCounter.Value = value; } } /// <summary> /// </summary> public void BeginInit() { Close(); } /// <summary> /// Frees all the resources allocated by this counter /// </summary> public void Close() { _helpMsg = null; _oldSample = CounterSample.Empty; _sharedCounter = null; _initialized = false; _counterType = -1; } /// <summary> /// Frees all the resources allocated for all performance /// counters, frees File Mapping used by extensible counters, /// unloads dll's used to read counters. /// </summary> public static void CloseSharedResources() { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*"); permission.Demand(); PerformanceCounterLib.CloseAllLibraries(); } /// <internalonly/> /// <summary> /// </summary> protected override void Dispose(bool disposing) { // safe to call while finalizing or disposing if (disposing) { //Dispose managed and unmanaged resources Close(); } base.Dispose(disposing); } /// <summary> /// Decrements counter by one using an efficient atomic operation. /// </summary> public long Decrement() { if (ReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.Decrement(); } /// <summary> /// </summary> public void EndInit() { Initialize(); } /// <summary> /// Increments the value of this counter. If counter type is of a 32-bit size, it'll truncate /// the value given to 32 bits. This method uses a mutex to guarantee correctness of /// the operation in case of multiple writers. This method should be used with caution because of the negative /// impact on performance due to creation of the mutex. /// </summary> public long IncrementBy(long value) { if (_isReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.IncrementBy(value); } /// <summary> /// Increments counter by one using an efficient atomic operation. /// </summary> public long Increment() { if (_isReadOnly) ThrowReadOnly(); Initialize(); return _sharedCounter.Increment(); } private void ThrowReadOnly() { throw new InvalidOperationException(SR.Format(SR.ReadOnlyCounter)); } private static void VerifyWriteableCounterAllowed() { if (EnvironmentHelpers.IsAppContainerProcess) { throw new NotSupportedException(SR.Format(SR.PCNotSupportedUnderAppContainer)); } } private void Initialize() { // Keep this method small so the JIT will inline it. if (!_initialized && !DesignMode) { InitializeImpl(); } } /// <summary> /// Intializes required resources /// </summary> private void InitializeImpl() { bool tookLock = false; RuntimeHelpers.PrepareConstrainedRegions(); try { Monitor.Enter(InstanceLockObject, ref tookLock); if (!_initialized) { string currentCategoryName = _categoryName; string currentMachineName = _machineName; if (currentCategoryName == string.Empty) throw new InvalidOperationException(SR.Format(SR.CategoryNameMissing)); if (_counterName == string.Empty) throw new InvalidOperationException(SR.Format(SR.CounterNameMissing)); if (ReadOnly) { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName)) throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName)); PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName)); } if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global) throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessonReadOnly)); _initialized = true; } else { PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Write, currentMachineName, currentCategoryName); permission.Demand(); if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException(SR.Format(SR.RemoteWriting)); if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName)) throw new InvalidOperationException(SR.Format(SR.NotCustomCounter)); // check category type PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName); if (categoryType == PerformanceCounterCategoryType.MultiInstance) { if (string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName)); } else if (categoryType == PerformanceCounterCategoryType.SingleInstance) { if (!string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName)); } if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process) throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessforSingleInstance)); _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); _initialized = true; } } } finally { if (tookLock) Monitor.Exit(InstanceLockObject); } } // Will cause an update, raw value /// <summary> /// Obtains a counter sample and returns the raw value for it. /// </summary> public CounterSample NextSample() { string currentCategoryName = _categoryName; string currentMachineName = _machineName; PerformanceCounterPermission permission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, currentMachineName, currentCategoryName); permission.Demand(); Initialize(); CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName); CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName); _counterType = counterSample._counterType; if (!categorySample._isMultiInstance) { if (_instanceName != null && _instanceName.Length != 0) throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName)); return counterSample.GetSingleValue(); } else { if (_instanceName == null || _instanceName.Length == 0) throw new InvalidOperationException(SR.Format(SR.InstanceNameRequired)); return counterSample.GetInstanceValue(_instanceName); } } /// <summary> /// Obtains a counter sample and returns the calculated value for it. /// NOTE: For counters whose calculated value depend upon 2 counter reads, /// the very first read will return 0.0. /// </summary> public float NextValue() { //No need to initialize or Demand, since NextSample already does. CounterSample newSample = NextSample(); float retVal = 0.0f; retVal = CounterSample.Calculate(_oldSample, newSample); _oldSample = newSample; return retVal; } /// <summary> /// Removes this counter instance from the shared memory /// </summary> public void RemoveInstance() { if (_isReadOnly) throw new InvalidOperationException(SR.Format(SR.ReadOnlyRemoveInstance)); Initialize(); _sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Diagnostics; using System.IO; using System.Linq; using Moq; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Diagnostics; using Avalonia.Input; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Shared.PlatformSupport; using Avalonia.Styling; using Avalonia.Themes.Default; using Avalonia.VisualTree; using Xunit; using Avalonia.Media; using System; using System.Collections.Generic; using Avalonia.Controls.UnitTests; using Avalonia.UnitTests; namespace Avalonia.Layout.UnitTests { public class FullLayoutTests { [Fact] public void Grandchild_Size_Changed() { using (var context = AvaloniaLocator.EnterScope()) { RegisterServices(); Border border; TextBlock textBlock; var window = new Window() { SizeToContent = SizeToContent.WidthAndHeight, Content = border = new Border { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Child = new Border { Child = textBlock = new TextBlock { Width = 400, Height = 400, Text = "Hello World!", }, } } }; window.Show(); window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.Equal(new Size(400, 400), border.Bounds.Size); textBlock.Width = 200; window.LayoutManager.ExecuteLayoutPass(); Assert.Equal(new Size(200, 400), border.Bounds.Size); } } [Fact] public void Test_ScrollViewer_With_TextBlock() { using (var context = AvaloniaLocator.EnterScope()) { RegisterServices(); ScrollViewer scrollViewer; TextBlock textBlock; var window = new Window() { Width = 800, Height = 600, SizeToContent = SizeToContent.WidthAndHeight, Content = scrollViewer = new ScrollViewer { Width = 200, Height = 200, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Content = textBlock = new TextBlock { Width = 400, Height = 400, Text = "Hello World!", }, } }; window.Resources["ScrollBarThickness"] = 10.0; window.Show(); window.LayoutManager.ExecuteInitialLayoutPass(window); Assert.Equal(new Size(800, 600), window.Bounds.Size); Assert.Equal(new Size(200, 200), scrollViewer.Bounds.Size); Assert.Equal(new Point(300, 200), Position(scrollViewer)); Assert.Equal(new Size(400, 400), textBlock.Bounds.Size); var scrollBars = scrollViewer.GetTemplateChildren().OfType<ScrollBar>().ToList(); var presenters = scrollViewer.GetTemplateChildren().OfType<ScrollContentPresenter>().ToList(); Assert.Equal(2, scrollBars.Count); Assert.Single(presenters); var presenter = presenters[0]; Assert.Equal(new Size(190, 190), presenter.Bounds.Size); var horzScroll = scrollBars.Single(x => x.Orientation == Orientation.Horizontal); var vertScroll = scrollBars.Single(x => x.Orientation == Orientation.Vertical); Assert.True(horzScroll.IsVisible); Assert.True(vertScroll.IsVisible); Assert.Equal(new Size(190, 10), horzScroll.Bounds.Size); Assert.Equal(new Size(10, 190), vertScroll.Bounds.Size); Assert.Equal(new Point(0, 190), Position(horzScroll)); Assert.Equal(new Point(190, 0), Position(vertScroll)); } } private static Point Position(IVisual v) { return v.Bounds.Position; } class FormattedTextMock : IFormattedTextImpl { public FormattedTextMock(string text) { Text = text; } public Size Constraint { get; set; } public string Text { get; } public Size Size => new Size(); public void Dispose() { } public IEnumerable<FormattedTextLine> GetLines() => new FormattedTextLine[0]; public TextHitTestResult HitTestPoint(Point point) => new TextHitTestResult(); public Rect HitTestTextPosition(int index) => new Rect(); public IEnumerable<Rect> HitTestTextRange(int index, int length) => new Rect[0]; public Size Measure() => Constraint; } private void RegisterServices() { var globalStyles = new Mock<IGlobalStyles>(); var globalStylesResources = globalStyles.As<IResourceNode>(); var outObj = (object)10; globalStylesResources.Setup(x => x.TryGetResource("FontSizeNormal", out outObj)).Returns(true); var renderInterface = new Mock<IPlatformRenderInterface>(); renderInterface.Setup(x => x.CreateFormattedText( It.IsAny<string>(), It.IsAny<Typeface>(), It.IsAny<TextAlignment>(), It.IsAny<TextWrapping>(), It.IsAny<Size>(), It.IsAny<IReadOnlyList<FormattedTextStyleSpan>>())) .Returns(new FormattedTextMock("TEST")); var streamGeometry = new Mock<IStreamGeometryImpl>(); streamGeometry.Setup(x => x.Open()) .Returns(new Mock<IStreamGeometryContextImpl>().Object); renderInterface.Setup(x => x.CreateStreamGeometry()) .Returns(streamGeometry.Object); var windowImpl = new Mock<IWindowImpl>(); Size clientSize = default(Size); windowImpl.SetupGet(x => x.ClientSize).Returns(() => clientSize); windowImpl.Setup(x => x.Resize(It.IsAny<Size>())).Callback<Size>(s => clientSize = s); windowImpl.Setup(x => x.MaxClientSize).Returns(new Size(1024, 1024)); windowImpl.SetupGet(x => x.Scaling).Returns(1); AvaloniaLocator.CurrentMutable .Bind<IStandardCursorFactory>().ToConstant(new CursorFactoryMock()) .Bind<IAssetLoader>().ToConstant(new AssetLoader()) .Bind<IInputManager>().ToConstant(new Mock<IInputManager>().Object) .Bind<IGlobalStyles>().ToConstant(globalStyles.Object) .Bind<IRuntimePlatform>().ToConstant(new AppBuilder().RuntimePlatform) .Bind<IPlatformRenderInterface>().ToConstant(renderInterface.Object) .Bind<IStyler>().ToConstant(new Styler()) .Bind<IWindowingPlatform>().ToConstant(new Avalonia.Controls.UnitTests.WindowingPlatformMock(() => windowImpl.Object)); var theme = new DefaultTheme(); globalStyles.Setup(x => x.IsStylesInitialized).Returns(true); globalStyles.Setup(x => x.Styles).Returns(theme); } } }
// 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 UnpackLowUInt32() { var test = new SimpleBinaryOpTest__UnpackLowUInt32(); 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__UnpackLowUInt32 { 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(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); 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<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, 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<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__UnpackLowUInt32 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__UnpackLowUInt32 testClass) { fixed (Vector128<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__UnpackLowUInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public SimpleBinaryOpTest__UnpackLowUInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new DataTable(_data1, _data2, new UInt32[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<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_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((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_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((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_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<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(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<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(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<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(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<UInt32>* pClsVar1 = &_clsVar1) fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt32*)(pClsVar1)), Sse2.LoadVector128((UInt32*)(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<UInt32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<UInt32>>(_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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((UInt32*)(_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((UInt32*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((UInt32*)(_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__UnpackLowUInt32(); 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__UnpackLowUInt32(); fixed (Vector128<UInt32>* pFld1 = &test._fld1) fixed (Vector128<UInt32>* pFld2 = &test._fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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<UInt32>* pFld1 = &_fld1) fixed (Vector128<UInt32>* pFld2 = &_fld2) { var result = Sse2.UnpackLow( Sse2.LoadVector128((UInt32*)(pFld1)), Sse2.LoadVector128((UInt32*)(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((UInt32*)(&test._fld1)), Sse2.LoadVector128((UInt32*)(&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<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] 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)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using UnityEditor.Rendering; using UnityEngine; using UnityEngine.Experimental.Rendering.HDPipeline; using UnityEngine.Rendering; using UnityEngine.Experimental.Rendering; using System.Reflection; using System.Linq; namespace UnityEditor.Experimental.Rendering.HDPipeline { internal struct OverridableFrameSettingsArea { static readonly GUIContent overrideTooltip = EditorGUIUtility.TrTextContent("", "Override this setting in component."); static readonly Dictionary<FrameSettingsField, FrameSettingsFieldAttribute> attributes; static Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>> attributesGroup = new Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>>(); FrameSettings defaultFrameSettings; SerializedFrameSettings serializedFrameSettings; static OverridableFrameSettingsArea() { attributes = new Dictionary<FrameSettingsField, FrameSettingsFieldAttribute>(); attributesGroup = new Dictionary<int, IOrderedEnumerable<KeyValuePair<FrameSettingsField, FrameSettingsFieldAttribute>>>(); Type type = typeof(FrameSettingsField); foreach (FrameSettingsField value in Enum.GetValues(type)) { attributes[value] = type.GetField(Enum.GetName(type, value)).GetCustomAttribute<FrameSettingsFieldAttribute>(); } } private struct Field { public FrameSettingsField field; public Func<bool> overrideable; public Func<bool> customOverrideable; public Func<object> customGetter; public Action<object> customSetter; public object overridedDefaultValue; public GUIContent label => EditorGUIUtility.TrTextContent(attributes[field].displayedName); public bool IsOverrideableWithDependencies(SerializedFrameSettings serialized, FrameSettings defaultFrameSettings) { FrameSettingsFieldAttribute attribute = attributes[field]; bool locallyOverrideable = overrideable == null || overrideable(); FrameSettingsField[] dependencies = attribute.dependencies; if (dependencies == null || !locallyOverrideable) return locallyOverrideable; bool dependenciesOverrideable = true; for (int index = dependencies.Length - 1; index >= 0 && dependenciesOverrideable; --index) { FrameSettingsField depency = dependencies[index]; dependenciesOverrideable &= EvaluateBoolWithOverride(depency, this, defaultFrameSettings, serialized, attribute.IsNegativeDependency(depency)); } return dependenciesOverrideable; } } private List<Field> fields; public OverridableFrameSettingsArea(int capacity, FrameSettings defaultFrameSettings, SerializedFrameSettings serializedFrameSettings) { fields = new List<Field>(capacity); this.defaultFrameSettings = defaultFrameSettings; this.serializedFrameSettings = serializedFrameSettings; } public static OverridableFrameSettingsArea GetGroupContent(int groupIndex, FrameSettings defaultFrameSettings, SerializedFrameSettings serializedFrameSettings) { if (!attributesGroup.ContainsKey(groupIndex) || attributesGroup[groupIndex] == null) attributesGroup[groupIndex] = attributes?.Where(pair => pair.Value?.group == groupIndex)?.OrderBy(pair => pair.Value.orderInGroup); if (!attributesGroup.ContainsKey(groupIndex)) throw new ArgumentException("Unknown groupIndex"); var area = new OverridableFrameSettingsArea(attributesGroup[groupIndex].Count(), defaultFrameSettings, serializedFrameSettings); foreach (var field in attributesGroup[groupIndex]) { area.Add(field.Key); } return area; } public void AmmendInfo(FrameSettingsField field, Func<bool> overrideable = null, Func<object> customGetter = null, Action<object> customSetter = null, object overridedDefaultValue = null, Func<bool> customOverrideable = null) { var matchIndex = fields.FindIndex(f => f.field == field); var match = fields[matchIndex]; if (overrideable != null) match.overrideable = overrideable; if (customOverrideable != null) match.customOverrideable = customOverrideable; if (customGetter != null) match.customGetter = customGetter; if (customSetter != null) match.customSetter = customSetter; if (overridedDefaultValue != null) match.overridedDefaultValue = overridedDefaultValue; fields[matchIndex] = match; } static bool EvaluateBoolWithOverride(FrameSettingsField field, Field forField, FrameSettings defaultFrameSettings, SerializedFrameSettings serializedFrameSettings, bool negative) { bool value; if (forField.customOverrideable != null) return forField.customOverrideable() ^ negative; if (serializedFrameSettings.GetOverrides(field)) value = serializedFrameSettings.IsEnabled(field) ?? false; else value = defaultFrameSettings.IsEnabled(field); return value ^ negative; } /// <summary>Add an overrideable field to be draw when Draw(bool) will be called.</summary> /// <param name="serializedFrameSettings">The overrideable property to draw in inspector</param> /// <param name="field">The field drawn</param> /// <param name="overrideable">The enabler will be used to check if this field could be overrided. If null or have a return value at true, it will be overrided.</param> /// <param name="overridedDefaultValue">The value to display when the property is not overrided. If null, use the actual value of it.</param> /// <param name="indent">Add this value number of indent when drawing this field.</param> void Add(FrameSettingsField field, Func<bool> overrideable = null, Func<object> customGetter = null, Action<object> customSetter = null, object overridedDefaultValue = null) => fields.Add(new Field { field = field, overrideable = overrideable, overridedDefaultValue = overridedDefaultValue, customGetter = customGetter, customSetter = customSetter }); public void Draw(bool withOverride) { if (fields == null) throw new ArgumentOutOfRangeException("Cannot be used without using the constructor with a capacity initializer."); if (withOverride & GUI.enabled) OverridesHeaders(); for (int i = 0; i< fields.Count; ++i) DrawField(fields[i], withOverride); } void DrawField(Field field, bool withOverride) { int indentLevel = attributes[field.field].indentLevel; if (indentLevel == 0) --EditorGUI.indentLevel; //alignment provided by the space for override checkbox else { for (int i = indentLevel - 1; i > 0; --i) ++EditorGUI.indentLevel; } bool enabled = field.IsOverrideableWithDependencies(serializedFrameSettings, defaultFrameSettings); withOverride &= enabled & GUI.enabled; bool shouldBeDisabled = withOverride || !enabled || !GUI.enabled; using (new EditorGUILayout.HorizontalScope()) { var overrideRect = GUILayoutUtility.GetRect(15f, 17f, GUILayout.ExpandWidth(false)); //15 = kIndentPerLevel if (withOverride) { bool originalValue = serializedFrameSettings.GetOverrides(field.field); overrideRect.yMin += 4f; EditorGUI.showMixedValue = serializedFrameSettings.HaveMultipleOverride(field.field); bool modifiedValue = GUI.Toggle(overrideRect, originalValue, overrideTooltip, CoreEditorStyles.smallTickbox); EditorGUI.showMixedValue = false; if (originalValue ^ modifiedValue) serializedFrameSettings.SetOverrides(field.field, modifiedValue); shouldBeDisabled = !modifiedValue; } using (new EditorGUI.DisabledScope(shouldBeDisabled)) { EditorGUI.showMixedValue = serializedFrameSettings.HaveMultipleValue(field.field); using (new EditorGUILayout.VerticalScope()) { //the following block will display a default value if provided instead of actual value (case if(true)) if (shouldBeDisabled) { if (field.overridedDefaultValue == null) { switch (attributes[field.field].type) { case FrameSettingsFieldAttribute.DisplayType.BoolAsCheckbox: DrawFieldShape(field.label, defaultFrameSettings.IsEnabled(field.field)); break; case FrameSettingsFieldAttribute.DisplayType.BoolAsEnumPopup: //shame but it is not possible to use Convert.ChangeType to convert int into enum in current C# //rely on string parsing for the moment var oldEnumValue = Enum.Parse(attributes[field.field].targetType, defaultFrameSettings.IsEnabled(field.field) ? "1" : "0"); DrawFieldShape(field.label, oldEnumValue); break; case FrameSettingsFieldAttribute.DisplayType.Others: var oldValue = field.customGetter(); DrawFieldShape(field.label, oldValue); break; default: throw new ArgumentException("Unknown FrameSettingsFieldAttribute"); } } else DrawFieldShape(field.label, field.overridedDefaultValue); } else { switch (attributes[field.field].type) { case FrameSettingsFieldAttribute.DisplayType.BoolAsCheckbox: bool oldBool = serializedFrameSettings.IsEnabled(field.field) ?? false; bool newBool = (bool)DrawFieldShape(field.label, oldBool); if (oldBool ^ newBool) { Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field); serializedFrameSettings.SetEnabled(field.field, newBool); } break; case FrameSettingsFieldAttribute.DisplayType.BoolAsEnumPopup: //shame but it is not possible to use Convert.ChangeType to convert int into enum in current C# //Also, Enum.Equals and Enum operator!= always send true here. As it seams to compare object reference instead of value. var oldBoolValue = serializedFrameSettings.IsEnabled(field.field); int oldEnumIntValue = -1; int newEnumIntValue; object newEnumValue; if (oldBoolValue.HasValue) { var oldEnumValue = Enum.GetValues(attributes[field.field].targetType).GetValue(oldBoolValue.Value ? 1 : 0); newEnumValue = Convert.ChangeType(DrawFieldShape(field.label, oldEnumValue), attributes[field.field].targetType); oldEnumIntValue = ((IConvertible)oldEnumValue).ToInt32(System.Globalization.CultureInfo.CurrentCulture); newEnumIntValue = ((IConvertible)newEnumValue).ToInt32(System.Globalization.CultureInfo.CurrentCulture); } else //in multi edition, do not assume any previous value { newEnumIntValue = EditorGUILayout.Popup(field.label, -1, Enum.GetNames(attributes[field.field].targetType)); newEnumValue = newEnumIntValue < 0 ? null : Enum.GetValues(attributes[field.field].targetType).GetValue(newEnumIntValue); } if (oldEnumIntValue != newEnumIntValue) { Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field); serializedFrameSettings.SetEnabled(field.field, Convert.ToInt32(newEnumValue) == 1); } break; case FrameSettingsFieldAttribute.DisplayType.Others: var oldValue = field.customGetter(); var newValue = DrawFieldShape(field.label, oldValue); if (oldValue != newValue) { Undo.RecordObject(serializedFrameSettings.serializedObject.targetObject, "Changed FrameSettings " + field.field); field.customSetter(newValue); } break; default: throw new ArgumentException("Unknown FrameSettingsFieldAttribute"); } } } EditorGUI.showMixedValue = false; } } if (indentLevel == 0) { ++EditorGUI.indentLevel; } else { for (int i = indentLevel - 1; i > 0; --i) { --EditorGUI.indentLevel; } } } object DrawFieldShape(GUIContent label, object field) { if (field is GUIContent) { EditorGUILayout.LabelField(label, (GUIContent)field); return null; } else if (field is string) return EditorGUILayout.TextField(label, (string)field); else if (field is bool) return EditorGUILayout.Toggle(label, (bool)field); else if (field is int) return EditorGUILayout.IntField(label, (int)field); else if (field is float) return EditorGUILayout.FloatField(label, (float)field); else if (field is Color) return EditorGUILayout.ColorField(label, (Color)field); else if (field is Enum) return EditorGUILayout.EnumPopup(label, (Enum)field); else if (field is LayerMask) return EditorGUILayout.MaskField(label, (LayerMask)field, GraphicsSettings.renderPipelineAsset.renderingLayerMaskNames); else if (field is UnityEngine.Object) return EditorGUILayout.ObjectField(label, (UnityEngine.Object)field, field.GetType(), true); else if (field is SerializedProperty) return EditorGUILayout.PropertyField((SerializedProperty)field, label, includeChildren: true); else { EditorGUILayout.LabelField(label, new GUIContent("Unsupported type")); Debug.LogError("Unsupported format " + field.GetType() + " in OverridableSettingsArea.cs. Please add it!"); return null; } } void OverridesHeaders() { using (new EditorGUILayout.HorizontalScope()) { GUILayoutUtility.GetRect(0f, 17f, GUILayout.ExpandWidth(false)); if (GUILayout.Button(EditorGUIUtility.TrTextContent("All", "Toggle all overrides on. To maximize performances you should only toggle overrides that you actually need."), CoreEditorStyles.miniLabelButton, GUILayout.Width(17f), GUILayout.ExpandWidth(false))) { foreach (var field in fields) { if (field.IsOverrideableWithDependencies(serializedFrameSettings, defaultFrameSettings)) serializedFrameSettings.SetOverrides(field.field, true); } } if (GUILayout.Button(EditorGUIUtility.TrTextContent("None", "Toggle all overrides off."), CoreEditorStyles.miniLabelButton, GUILayout.Width(32f), GUILayout.ExpandWidth(false))) { foreach (var field in fields) { if (field.IsOverrideableWithDependencies(serializedFrameSettings, defaultFrameSettings)) serializedFrameSettings.SetOverrides(field.field, false); } } GUILayout.FlexibleSpace(); } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using DataBoss.Data; namespace DataBoss.DataPackage { public class DataReaderTransform : DbDataReader, ITransformedDataRecord { public static class FieldInfo<T> { public static readonly Type FieldType = typeof(T).TryGetNullableTargetType(out var targetType) ? targetType : typeof(T); public static readonly bool IsNullable = typeof(T).IsNullable(); public static readonly int ColumnSize = DataBossDbType.From(typeof(T)).ColumnSize ?? -1; public static readonly Func<T, bool> IsNull = CreateIsNullMethod(); static Func<T, bool> CreateIsNullMethod() { var p0 = Expression.Parameter(typeof(T)); Expression CreateNullCheck(Expression input) { if (p0.Type.IsNullable()) return Expression.Not(Expression.MakeMemberAccess(input, typeof(T).GetMember("HasValue").Single())); if (p0.Type.IsValueType) return Expression.Constant(false, typeof(bool)); return Expression.ReferenceEqual(input, Expression.Constant(null, p0.Type)); } return Expression.Lambda<Func<T, bool>>(CreateNullCheck(p0), p0).Compile(); } } delegate IFieldAccessor AccessorBuilder(int ordinal, bool allowDBNull, int columnSize); static readonly ConcurrentDictionary<(Type Type, Type ProviderSpecificType), AccessorBuilder> fieldAccessorCtorCache = new(); static IFieldAccessor CreateFieldAccessor(int ordinal, bool isNullable, int columnSize, Type type, Type providerSpecificType) { var ctor = fieldAccessorCtorCache.GetOrAdd((type, providerSpecificType), key => { var ps = Array.ConvertAll( typeof(AccessorBuilder).GetMethod("Invoke").GetParameters(), x => Expression.Parameter(x.ParameterType, x.Name)); var c = typeof(SourceFieldAccessor<,>).MakeGenericType(key.Type, key.ProviderSpecificType).GetConstructor(Array.ConvertAll(ps, x => x.Type)); return Expression.Lambda<AccessorBuilder>(Expression.New(c, ps), ps).Compile(); }); return ctor(ordinal, isNullable, columnSize); } interface IFieldAccessor { bool AllowDBNull { get; } int ColumnSize { get; } Type FieldType { get; } Type ProviderSpecificFieldType { get; } string Name { get; set; } bool IsDBNull(DataReaderTransform record); object GetValue(DataReaderTransform record); object GetProviderSpecificValue(DataReaderTransform record); T GetFieldValue<T>(DataReaderTransform record); } abstract class SourceFieldAccessor : IFieldAccessor { public SourceFieldAccessor(int ordinal, bool allowDBNull, int columnSize) { this.Ordinal = ordinal; this.AllowDBNull = allowDBNull; this.ColumnSize = columnSize; } public bool AllowDBNull { get; } public int ColumnSize { get; } public int Ordinal { get; } public abstract Type FieldType { get; } public abstract Type ProviderSpecificFieldType { get; } public string Name { get; set; } public bool IsDBNull(DataReaderTransform record) => record.inner.IsDBNull(Ordinal); public abstract object GetValue(DataReaderTransform record); public abstract object GetProviderSpecificValue(DataReaderTransform record); public T GetFieldValue<T>(DataReaderTransform record) => record.inner.GetFieldValue<T>(Ordinal); } class SourceFieldAccessor<TField, TProviderType> : SourceFieldAccessor { public SourceFieldAccessor(int ordinal, bool allowDBNull, int columnSize) : base(ordinal, allowDBNull, columnSize) { } public override Type FieldType => FieldInfo<TField>.FieldType; public override Type ProviderSpecificFieldType => typeof(TProviderType); public override object GetValue(DataReaderTransform record) => GetFieldValue<TField>(record); public override object GetProviderSpecificValue(DataReaderTransform record) => GetFieldValue<TProviderType>(record); } abstract class UserFieldAccessor<TField> : IFieldAccessor { TField currentValue; bool isDirty; public UserFieldAccessor() { this.isDirty = true; } public virtual bool AllowDBNull => FieldInfo<TField>.IsNullable; public int ColumnSize => FieldInfo<TField>.ColumnSize; public Type FieldType => FieldInfo<TField>.FieldType; public Type ProviderSpecificFieldType => FieldType; public string Name { get; set; } public T GetFieldValue<T>(DataReaderTransform record) => (T)(object)GetCurrentValue(record); public object GetValue(DataReaderTransform record) { var value = GetCurrentValue(record); return FieldInfo<TField>.IsNull(value) ? DBNull.Value : value; } public object GetProviderSpecificValue(DataReaderTransform record) => GetValue(record); public bool IsDBNull(DataReaderTransform record) => AllowDBNull && FieldInfo<TField>.IsNull(GetCurrentValue(record)); TField GetCurrentValue(DataReaderTransform record) { if (isDirty) { currentValue = GetRecordValue(record); isDirty = false; } return currentValue; } protected abstract TField GetRecordValue(DataReaderTransform record); public void Dirty() { isDirty = true; } } class FieldTransform<T> : UserFieldAccessor<T> { readonly Func<ITransformedDataRecord, T> transform; public FieldTransform(Func<ITransformedDataRecord, T> transform) { this.transform = transform; } protected override T GetRecordValue(DataReaderTransform record) => transform(record); } class FieldTransform<TField, T> : UserFieldAccessor<T> { readonly IFieldAccessor source; readonly Func<TField, T> transform; readonly bool allowDBNull; public FieldTransform(IFieldAccessor source, Func<TField, T> transform, bool allowDBNull) { this.source = source; this.transform = transform; this.allowDBNull = allowDBNull; } public override bool AllowDBNull => allowDBNull; protected override T GetRecordValue(DataReaderTransform record) => transform(source.GetFieldValue<TField>(record)); } interface IRecordTransform { void Reset(); } class RecordTransform<TRecord, T> : UserFieldAccessor<T>, IRecordTransform { Func<IDataReader, TRecord> readRecord; readonly Func<TRecord, T> selector; public RecordTransform(Func<TRecord, T> selector) { this.selector = selector; } protected override T GetRecordValue(DataReaderTransform record) => selector(ReadRecord(record)); TRecord ReadRecord(DataReaderTransform reader) { if(readRecord == null) { var self = reader.fields.IndexOf(this); var fields = FieldMap.Create(reader.AsDbDataReader(), x => x.Ordinal < self || reader.fields[x.Ordinal] is SourceFieldAccessor); readRecord = ConverterFactory.Default.BuildConverter<IDataReader, TRecord>(fields).Compiled; } return readRecord(reader); } void IRecordTransform.Reset() { readRecord = null; } } readonly DbDataReader inner; readonly List<IFieldAccessor> fields = new(); Action onRead; public DataReaderTransform(IDataReader inner) : this(inner.AsDbDataReader()) { } public DataReaderTransform(DbDataReader inner) { this.inner = inner; var schema = inner.GetDataReaderSchemaTable(); var sourceFields = new IFieldAccessor[schema.Count]; for(var i = 0; i != schema.Count; ++i) { var field = schema[i]; var accessor = CreateFieldAccessor( field.Ordinal, field.AllowDBNull, field.ColumnSize ?? -1, field.DataType, field.ProviderSpecificDataType); accessor.Name = field.ColumnName; sourceFields[field.Ordinal] = accessor; } this.fields.AddRange(sourceFields); } public IDataRecord Source => inner; public DataReaderTransform Add<T>(string name, Func<ITransformedDataRecord, T> getValue) { fields.Add(Bind(new FieldTransform<T>(getValue) { Name = name })); return this; } public DataReaderTransform Add<T>(int ordinal, string name, Func<ITransformedDataRecord, T> getValue) { fields.Insert(ordinal, Bind(new FieldTransform<T>(getValue) { Name = name })); return this; } public DataReaderTransform Add<TRecord, T>(string name, Func<TRecord, T> selector) { fields.Add(Bind(new RecordTransform<TRecord, T>(selector) { Name = name })); return this; } public DataReaderTransform Add<TRecord, T>(int ordinal, string name, Func<TRecord, T> selector) { fields.Insert(ordinal, Bind(new RecordTransform<TRecord, T>(selector) { Name = name })); return this; } public DataReaderTransform Remove(string name) { fields.RemoveAll(x => x.Name == name); return this; } public DataReaderTransform Transform<T>(string name, Func<ITransformedDataRecord, T> transform) { fields[GetOrdinal(name)] = Bind(new FieldTransform<T>(transform) { Name = name }); return this; } public DataReaderTransform Transform<TField, T>(string name, Func<TField, T> transform) { var o = GetOrdinal(name); return Transform(name, o, fields[o], transform); } public DataReaderTransform Transform<TField, T>(int ordinal, Func<TField, T> transform) => Transform(GetName(ordinal), ordinal, fields[ordinal], transform); DataReaderTransform Transform<TField, T>(string name, int ordinal, IFieldAccessor source, Func<TField, T> transform) { var allowDBNull = FieldInfo<TField>.IsNullable ? FieldInfo<T>.IsNullable : FieldInfo<T>.IsNullable || source.AllowDBNull; fields[ordinal] = Bind(new FieldTransform<TField, T>(source, transform, allowDBNull) { Name = name }); return this; } IFieldAccessor Bind<T>(UserFieldAccessor<T> accessor) { onRead += accessor.Dirty; return accessor; } public DataReaderTransform Set<T>(string name, Func<ITransformedDataRecord, T> getValue) { var n = fields.FindIndex(x => x.Name == name); return n == -1 ? Add(name, getValue) : Transform(name, getValue); } public DataReaderTransform Rename(string from, string to) { var o = GetOrdinal(from); fields[o].Name = to; ResetRecordFields(); return this; } void ResetRecordFields() { foreach (var x in fields.OfType<IRecordTransform>()) x.Reset(); } public override T GetFieldValue<T>(int i) => fields[i].GetFieldValue<T>(this); public override object GetValue(int i) => fields[i].GetValue(this); public override object GetProviderSpecificValue(int i) => fields[i].GetProviderSpecificValue(this); public override object this[int i] => GetValue(i); public override object this[string name] => GetValue(GetOrdinal(name)); public override int Depth => inner.Depth; public override bool IsClosed => inner.IsClosed; public override int RecordsAffected => inner.RecordsAffected; public override int FieldCount => fields.Count; public override bool HasRows => throw new NotSupportedException(); public override void Close() => inner.Close(); protected override void Dispose(bool disposing) { if(disposing) inner.Dispose(); } public override Type GetFieldType(int i) => fields[i].FieldType; public override Type GetProviderSpecificFieldType(int i) => fields[i].ProviderSpecificFieldType; public override bool GetBoolean(int i) => GetFieldValue<bool>(i); public override byte GetByte(int i) => GetFieldValue<byte>(i); public override char GetChar(int i) => GetFieldValue<char>(i); public override DateTime GetDateTime(int i) => GetFieldValue<DateTime>(i); public override decimal GetDecimal(int i) => GetFieldValue<decimal>(i); public override double GetDouble(int i) => GetFieldValue<double>(i); public override float GetFloat(int i) => GetFieldValue<float>(i); public override Guid GetGuid(int i) => GetFieldValue<Guid>(i); public override short GetInt16(int i) => GetFieldValue<short>(i); public override int GetInt32(int i) => GetFieldValue<int>(i); public override long GetInt64(int i) => GetFieldValue<long>(i); public override string GetString(int i) => GetFieldValue<string>(i); public override int GetValues(object[] values) { var n = Math.Min(FieldCount, values.Length); for (var i = 0; i != n; ++i) values[i] = GetValue(i); return n; } public override string GetName(int i) => fields[i].Name; public override int GetOrdinal(string name) => fields.FindIndex(x => x.Name == name); public override DataTable GetSchemaTable() { var schema = new DataReaderSchemaTable(); for (var i = 0; i != FieldCount; ++i) { var item = fields[i]; schema.Add(item.Name, i, item.FieldType, item.AllowDBNull, item.ColumnSize, providerSpecificDataType: item.ProviderSpecificFieldType); } return schema.ToDataTable(); } public override string GetDataTypeName(int i) => DataBossDbType.From(GetFieldType(i)).TypeName; public override bool IsDBNull(int i) => fields[i].IsDBNull(this); public override bool NextResult() => false; public override bool Read() { onRead?.Invoke(); return inner.Read(); } public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) => throw new NotSupportedException(); public override long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) => throw new NotSupportedException(); public override IEnumerator GetEnumerator() => new DataReaderEnumerator(this); } public static class DataReaderTransformExtensions { public static DbDataReader WithTransform(this IDataReader self, Action<DataReaderTransform> defineTransfrom) { var r = new DataReaderTransform(self); defineTransfrom(r); return r; } public static DataReaderTransform SpecifyDateTimeKind(this DataReaderTransform self, DateTimeKind kind) { for(var i = 0; i != self.FieldCount; ++i) { if (self.GetFieldType(i) == typeof(DateTime)) self.Transform(i, (DateTime x) => DateTime.SpecifyKind(x, kind)); } return self; } } }
using System; using System.Diagnostics; using HANDLE = System.IntPtr; using System.Text; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_CORE //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ const int SQLITE_CORE = 1; #endif //#include "sqlite3ext.h" //#include "sqliteInt.h" //#include <string.h> #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #if !SQLITE_ENABLE_COLUMN_METADATA //# define sqlite3_column_database_name 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name 0 //# define sqlite3_column_origin_name16 0 //# define sqlite3_table_column_metadata 0 #endif //#if SQLITE_OMIT_AUTHORIZATION //# define sqlite3_set_authorizer 0 //#endif #if !NO_SQLITE_OMIT_UTF16 //# define sqlite3_bind_text16 0 //# define sqlite3_collation_needed16 0 //# define sqlite3_column_decltype16 0 //# define sqlite3_column_name16 0 //# define sqlite3_column_text16 0 //# define sqlite3_complete16 0 //# define sqlite3_create_collation16 0 //# define sqlite3_create_function16 0 //# define sqlite3_errmsg16 0 static string sqlite3_errmsg16( sqlite3 db ) { return ""; } //# define sqlite3_open16 0 //# define sqlite3_prepare16 0 //# define sqlite3_prepare16_v2 0 //# define sqlite3_result_error16 0 //# define sqlite3_result_text16 0 static void sqlite3_result_text16( sqlite3_context pCtx, string z, int n, dxDel xDel ) { } //# define sqlite3_result_text16be 0 //# define sqlite3_result_text16le 0 //# define sqlite3_value_text16 0 //# define sqlite3_value_text16be 0 //# define sqlite3_value_text16le 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name16 0 #endif #if SQLITE_OMIT_COMPLETE //# define sqlite3_complete 0 //# define sqlite3_complete16 0 #endif #if SQLITE_OMIT_DECLTYPE //# define sqlite3_column_decltype16 0 //# define sqlite3_column_decltype 0 #endif #if SQLITE_OMIT_PROGRESS_CALLBACK //# define sqlite3_progress_handler 0 static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if SQLITE_OMIT_VIRTUALTABLE //# define sqlite3_create_module 0 //# define sqlite3_create_module_v2 0 //# define sqlite3_declare_vtab 0 #endif //#if SQLITE_OMIT_SHARED_CACHE //# define sqlite3_enable_shared_cache 0 //#endif #if SQLITE_OMIT_TRACE //# define sqlite3_profile 0 //# define sqlite3_trace 0 #endif #if !NO_SQLITE_OMIT_GET_TABLE //# define //sqlite3_free_table 0 //# define sqlite3_get_table 0 static public int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ ref int pnColumn, /* Number of result columns written here */ ref string pzErrmsg /* Error msg written here */ ) { return 0; } #endif //#if SQLITE_OMIT_INCRBLOB //#define sqlite3_bind_zeroblob 0 //#define sqlite3_blob_bytes 0 //#define sqlite3_blob_close 0 //#define sqlite3_blob_open 0 //#define sqlite3_blob_read 0 //#define sqlite3_blob_write 0 //#endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ public class sqlite3_api_routines { public sqlite3 context_db_handle; }; static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); //{ // sqlite3_aggregate_context, #if NOT_SQLITE_OMIT_DEPRECATED //#if !SQLITE_OMIT_DEPRECATED / sqlite3_aggregate_count, #else // 0, #endif // sqlite3_bind_blob, // sqlite3_bind_double, // sqlite3_bind_int, // sqlite3_bind_int64, // sqlite3_bind_null, // sqlite3_bind_parameter_count, // sqlite3_bind_parameter_index, // sqlite3_bind_parameter_name, // sqlite3_bind_text, // sqlite3_bind_text16, // sqlite3_bind_value, // sqlite3_busy_handler, // sqlite3_busy_timeout, // sqlite3_changes, // sqlite3_close, // sqlite3_collation_needed, // sqlite3_collation_needed16, // sqlite3_column_blob, // sqlite3_column_bytes, // sqlite3_column_bytes16, // sqlite3_column_count, // sqlite3_column_database_name, // sqlite3_column_database_name16, // sqlite3_column_decltype, // sqlite3_column_decltype16, // sqlite3_column_double, // sqlite3_column_int, // sqlite3_column_int64, // sqlite3_column_name, // sqlite3_column_name16, // sqlite3_column_origin_name, // sqlite3_column_origin_name16, // sqlite3_column_table_name, // sqlite3_column_table_name16, // sqlite3_column_text, // sqlite3_column_text16, // sqlite3_column_type, // sqlite3_column_value, // sqlite3_commit_hook, // sqlite3_complete, // sqlite3_complete16, // sqlite3_create_collation, // sqlite3_create_collation16, // sqlite3_create_function, // sqlite3_create_function16, // sqlite3_create_module, // sqlite3_data_count, // sqlite3_db_handle, // sqlite3_declare_vtab, // sqlite3_enable_shared_cache, // sqlite3_errcode, // sqlite3_errmsg, // sqlite3_errmsg16, // sqlite3_exec, #if NOT_SQLITE_OMIT_DEPRECATED //#if !SQLITE_OMIT_DEPRECATED //sqlite3_expired, #else //0, #endif // sqlite3_finalize, // //sqlite3_free, // //sqlite3_free_table, // sqlite3_get_autocommit, // sqlite3_get_auxdata, // sqlite3_get_table, // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ // sqlite3_interrupt, // sqlite3_last_insert_rowid, // sqlite3_libversion, // sqlite3_libversion_number, // sqlite3_malloc, // sqlite3_mprintf, // sqlite3_open, // sqlite3_open16, // sqlite3_prepare, // sqlite3_prepare16, // sqlite3_profile, // sqlite3_progress_handler, // sqlite3_realloc, // sqlite3_reset, // sqlite3_result_blob, // sqlite3_result_double, // sqlite3_result_error, // sqlite3_result_error16, // sqlite3_result_int, // sqlite3_result_int64, // sqlite3_result_null, // sqlite3_result_text, // sqlite3_result_text16, // sqlite3_result_text16be, // sqlite3_result_text16le, // sqlite3_result_value, // sqlite3_rollback_hook, // sqlite3_set_authorizer, // sqlite3_set_auxdata, // sqlite3_snprintf, // sqlite3_step, // sqlite3_table_column_metadata, #if NOT_SQLITE_OMIT_DEPRECATED //#if !SQLITE_OMIT_DEPRECATED //sqlite3_thread_cleanup, #else // 0, #endif // sqlite3_total_changes, // sqlite3_trace, #if NOT_SQLITE_OMIT_DEPRECATED //#if !SQLITE_OMIT_DEPRECATED //sqlite3_transfer_bindings, #else // 0, #endif // sqlite3_update_hook, // sqlite3_user_data, // sqlite3_value_blob, // sqlite3_value_bytes, // sqlite3_value_bytes16, // sqlite3_value_double, // sqlite3_value_int, // sqlite3_value_int64, // sqlite3_value_numeric_type, // sqlite3_value_text, // sqlite3_value_text16, // sqlite3_value_text16be, // sqlite3_value_text16le, // sqlite3_value_type, // sqlite3_vmprintf, // /* // ** The original API set ends here. All extensions can call any // ** of the APIs above provided that the pointer is not NULL. But // ** before calling APIs that follow, extension should check the // ** sqlite3_libversion_number() to make sure they are dealing with // ** a library that is new enough to support that API. // ************************************************************************* // */ // sqlite3_overload_function, // /* // ** Added after 3.3.13 // */ // sqlite3_prepare_v2, // sqlite3_prepare16_v2, // sqlite3_clear_bindings, // /* // ** Added for 3.4.1 // */ // sqlite3_create_module_v2, // /* // ** Added for 3.5.0 // */ // sqlite3_bind_zeroblob, // sqlite3_blob_bytes, // sqlite3_blob_close, // sqlite3_blob_open, // sqlite3_blob_read, // sqlite3_blob_write, // sqlite3_create_collation_v2, // sqlite3_file_control, // sqlite3_memory_highwater, // sqlite3_memory_used, #if SQLITE_MUTEX_OMIT // 0, // 0, // 0, // 0, // 0, #else // sqlite3MutexAlloc, // sqlite3_mutex_enter, // sqlite3_mutex_free, // sqlite3_mutex_leave, // sqlite3_mutex_try, #endif // sqlite3_open_v2, // sqlite3_release_memory, // sqlite3_result_error_nomem, // sqlite3_result_error_toobig, // sqlite3_sleep, // sqlite3_soft_heap_limit, // sqlite3_vfs_find, // sqlite3_vfs_register, // sqlite3_vfs_unregister, // /* // ** Added for 3.5.8 // */ // sqlite3_threadsafe, // sqlite3_result_zeroblob, // sqlite3_result_error_code, // sqlite3_test_control, // sqlite3_randomness, // sqlite3_context_db_handle, // /* // ** Added for 3.6.0 // */ // sqlite3_extended_result_codes, // sqlite3_limit, // sqlite3_next_stmt, // sqlite3_sql, // sqlite3_status, // /* // ** Added for 3.7.4 // */ // sqlite3_backup_finish, // sqlite3_backup_init, // sqlite3_backup_pagecount, // sqlite3_backup_remaining, // sqlite3_backup_step, //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS // sqlite3_compileoption_get, // sqlite3_compileoption_used, //#else // 0, // 0, //#endif // sqlite3_create_function_v2, // sqlite3_db_config, // sqlite3_db_mutex, // sqlite3_db_status, // sqlite3_extended_errcode, // sqlite3_log, // sqlite3_soft_heap_limit64, // sqlite3_sourceid, // sqlite3_stmt_status, // sqlite3_strnicmp, //#if SQLITE_ENABLE_UNLOCK_NOTIFY // sqlite3_unlock_notify, //#else // 0, //#endif //#if !SQLITE_OMIT_WAL // sqlite3_wal_autocheckpoint, // sqlite3_wal_checkpoint, // sqlite3_wal_hook, //#else // 0, // 0, // 0, //#endif //}; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { sqlite3_vfs pVfs = db.pVfs; HANDLE handle; dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines); StringBuilder zErrmsg = new StringBuilder( 100 ); //object aHandle; const int nMsg = 300; if ( pzErrMsg != null ) pzErrMsg = null; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call sqlite3_enable_load_extension() to turn on extension ** loading. Otherwise you get the following error. */ if ( ( db.flags & SQLITE_LoadExtension ) == 0 ) { //if( pzErrMsg != null){ pzErrMsg = sqlite3_mprintf( "not authorized" ); //} return SQLITE_ERROR; } if ( zProc == null || zProc == "" ) { zProc = "sqlite3_extension_init"; } handle = sqlite3OsDlOpen( pVfs, zFile ); if ( handle == IntPtr.Zero ) { // if( pzErrMsg ){ pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); //if( zErrmsg !=null){ sqlite3_snprintf( nMsg, zErrmsg, "unable to open shared library [%s]", zFile ); sqlite3OsDlError( pVfs, nMsg - 1, zErrmsg.ToString() ); return SQLITE_ERROR; } //xInit = (int()(sqlite3*,char**,const sqlite3_api_routines)) // sqlite3OsDlSym(pVfs, handle, zProc); xInit = (dxInit)sqlite3OsDlSym( pVfs, handle, ref zProc ); Debugger.Break(); // TODO -- //if( xInit==0 ){ // if( pzErrMsg ){ // *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); // if( zErrmsg ){ // sqlite3_snprintf(nMsg, zErrmsg, // "no entry point [%s] in shared library [%s]", zProc,zFile); // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); // } // sqlite3OsDlClose(pVfs, handle); // } // return SQLITE_ERROR; // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ //// if( pzErrMsg !=null){ // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); // //} // sqlite3DbFree(db,ref zErrmsg); // sqlite3OsDlClose(pVfs, ref handle); // return SQLITE_ERROR; // } // /* Append the new shared library handle to the db.aExtension array. */ // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); // if( aHandle==null ){ // return SQLITE_NOMEM; // } // if( db.nExtension>0 ){ // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); // } // sqlite3DbFree(db,ref db.aExtension); // db.aExtension = aHandle; // db.aExtension[db.nExtension++] = handle; return SQLITE_OK; } static public int sqlite3_load_extension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { int rc; sqlite3_mutex_enter( db.mutex ); rc = sqlite3LoadExtension( db, zFile, zProc, ref pzErrMsg ); rc = sqlite3ApiExit( db, rc ); sqlite3_mutex_leave( db.mutex ); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ static void sqlite3CloseExtensions( sqlite3 db ) { int i; Debug.Assert( sqlite3_mutex_held( db.mutex ) ); for ( i = 0; i < db.nExtension; i++ ) { sqlite3OsDlClose( db.pVfs, (HANDLE)db.aExtension[i] ); } sqlite3DbFree( db, ref db.aExtension ); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ static public int sqlite3_enable_load_extension( sqlite3 db, int onoff ) { sqlite3_mutex_enter( db.mutex ); if ( onoff != 0 ) { db.flags |= SQLITE_LoadExtension; } else { db.flags &= ~SQLITE_LoadExtension; } sqlite3_mutex_leave( db.mutex ); return SQLITE_OK; } #endif //* SQLITE_OMIT_LOAD_EXTENSION */ /* ** The auto-extension code added regardless of whether or not extension ** loading is supported. We need a dummy sqlite3Apis pointer for that ** code if regular extension loading is not available. This is that ** dummy pointer. */ #if SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines sqlite3Apis = null; #endif /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ //typedef struct sqlite3AutoExtList sqlite3AutoExtList; public class sqlite3AutoExtList { public int nExt = 0; /* Number of entries in aExt[] */ public dxInit[] aExt = null; /* Pointers to the extension init functions */ public sqlite3AutoExtList( int nExt, dxInit[] aExt ) { this.nExt = nExt; this.aExt = aExt; } } static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList( 0, null ); /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) //# define wsdAutoext x[0] #else //# define wsdAutoextInit static void wsdAutoextInit() { } //# define wsdAutoext sqlite3Autoext static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ static int sqlite3_auto_extension( dxInit xInit ) { int rc = SQLITE_OK; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if ( rc != 0 ) { return rc; } else #endif { int i; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); for ( i = 0; i < wsdAutoext.nExt; i++ ) { if ( wsdAutoext.aExt[i] == xInit ) break; } //if( i==wsdAutoext.nExt ){ // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); // void **aNew; // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); // if( aNew==0 ){ // rc = SQLITE_NOMEM; // }else{ Array.Resize( ref wsdAutoext.aExt, wsdAutoext.nExt + 1 );// wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; //} sqlite3_mutex_leave( mutex ); Debug.Assert( ( rc & 0xff ) == rc ); return rc; } } /* ** Reset the automatic extension loading mechanism. */ static void sqlite3_reset_auto_extension() { #if !SQLITE_OMIT_AUTOINIT if ( sqlite3_initialize() == SQLITE_OK ) #endif { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif wsdAutoextInit(); sqlite3_mutex_enter( mutex ); #if SQLITE_OMIT_WSD //sqlite3_free( ref wsdAutoext.aExt ); wsdAutoext.aExt = null; wsdAutoext.nExt = 0; #else //sqlite3_free( ref sqlite3Autoext.aExt ); sqlite3Autoext.aExt = null; sqlite3Autoext.nExt = 0; #endif sqlite3_mutex_leave( mutex ); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ static void sqlite3AutoLoadExtensions( sqlite3 db ) { int i; bool go = true; dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines); wsdAutoextInit(); #if SQLITE_OMIT_WSD if ( wsdAutoext.nExt == 0 ) #else if ( sqlite3Autoext.nExt == 0 ) #endif { /* Common case: early out without every having to acquire a mutex */ return; } for ( i = 0; go; i++ ) { string zErrmsg = ""; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter( mutex ); if ( i >= wsdAutoext.nExt ) { xInit = null; go = false; } else { xInit = (dxInit) wsdAutoext.aExt[i]; } sqlite3_mutex_leave( mutex ); zErrmsg = ""; if ( xInit != null && xInit( db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis ) != 0 ) { sqlite3Error( db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg ); go = false; } sqlite3DbFree( db, ref zErrmsg ); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Providers.Streams.Common; using Orleans.Runtime; namespace Orleans.Streams { internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener { private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5); private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap; private readonly string streamProviderName; private readonly IStreamProviderRuntime providerRuntime; private readonly IStreamPubSub pubSub; private readonly PersistentStreamProviderConfig config; private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications. private readonly LoggerImpl logger; private int latestRingNotificationSequenceNumber; private int latestCommandNumber; private IQueueAdapter queueAdapter; private readonly IQueueAdapterCache queueAdapterCache; private readonly IStreamQueueBalancer queueBalancer; private readonly IQueueAdapterFactory adapterFactory; private PersistentStreamProviderState managerState; private readonly IDisposable queuePrintTimer; private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } } internal PersistentStreamPullingManager( GrainId id, string strProviderName, IStreamProviderRuntime runtime, IStreamPubSub streamPubSub, IQueueAdapterFactory adapterFactory, IStreamQueueBalancer streamQueueBalancer, PersistentStreamProviderConfig config) : base(id, runtime.ExecutingSiloAddress) { if (string.IsNullOrWhiteSpace(strProviderName)) { throw new ArgumentNullException("strProviderName"); } if (runtime == null) { throw new ArgumentNullException("runtime", "IStreamProviderRuntime runtime reference should not be null"); } if (streamPubSub == null) { throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null"); } if (streamQueueBalancer == null) { throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null"); } queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>(); streamProviderName = strProviderName; providerRuntime = runtime; pubSub = streamPubSub; this.config = config; nonReentrancyGuarantor = new AsyncSerialExecutor(); latestRingNotificationSequenceNumber = 0; latestCommandNumber = 0; queueBalancer = streamQueueBalancer; this.adapterFactory = adapterFactory; queueAdapterCache = adapterFactory.GetQueueAdapterCache(); logger = LogManager.GetLogger(GetType().Name + "-" + streamProviderName, LoggerType.Provider); Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count); queuePrintTimer = base.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD); } public Task Initialize(Immutable<IQueueAdapter> qAdapter) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); Log(ErrorCode.PersistentStreamPullingManager_02, "Init."); // Remove cast once we cleanup queueAdapter = qAdapter.Value; var meAsQueueBalanceListener = this.AsReference<IStreamQueueBalanceListener>(); queueBalancer.SubscribeToQueueDistributionChangeEvents(meAsQueueBalanceListener); List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues))); managerState = PersistentStreamProviderState.Initialized; return TaskDone.Done; } public async Task Stop() { await StopAgents(); if (queuePrintTimer != null) { queuePrintTimer.Dispose(); } } public async Task StartAgents() { managerState = PersistentStreamProviderState.AgentsStarted; List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues)); await AddNewQueues(myQueues, true); Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents."); } public async Task StopAgents() { managerState = PersistentStreamProviderState.AgentsStopped; List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList(); Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove)); await RemoveQueues(queuesToRemove); Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents."); } #region Management of queues /// <summary> /// Actions to take when the queue distribution changes due to a failure or a join. /// Since this pulling manager is system target and queue distribution change notifications /// are delivered to it as grain method calls, notifications are not reentrant. To simplify /// notification handling we execute them serially, in a non-reentrant way. We also supress /// and don't execute an older notification if a newer one was already delivered. /// </summary> public Task QueueDistributionChangeNotification() { latestRingNotificationSequenceNumber++; int notificationSeqNumber = latestRingNotificationSequenceNumber; Log(ErrorCode.PersistentStreamPullingManager_04, "Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState); if (managerState == PersistentStreamProviderState.AgentsStopped) { return TaskDone.Done; // if agents not running, no need to rebalance the queues among them. } return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous notification since already got a newer range update notification. if (notificationSeqNumber < latestRingNotificationSequenceNumber) { Log(ErrorCode.PersistentStreamPullingManager_05, "Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " + "(already have notification number {1}).", notificationSeqNumber, latestRingNotificationSequenceNumber); return TaskDone.Done; } if (managerState == PersistentStreamProviderState.AgentsStopped) { return TaskDone.Done; // if agents not running, no need to rebalance the queues among them. } return QueueDistributionChangeNotification(notificationSeqNumber); }); } private async Task QueueDistributionChangeNotification(int notificationSeqNumber) { HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet(); Log(ErrorCode.PersistentStreamPullingManager_06, "Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues)); try { Task t1 = AddNewQueues(currentQueues, false); List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList(); Task t2 = RemoveQueues(queuesToRemove); await Task.WhenAll(t1, t2); } finally { Log(ErrorCode.PersistentStreamPullingManager_16, "Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } /// <summary> /// Take responsibility for a set of new queues that were assigned to me via a new range. /// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents. /// ERROR HANDLING: /// The responsibility to handle initialization and shutdown failures is inside the Agents code. /// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded. /// Same applies to shutdown. /// </summary> /// <param name="myQueues"></param> /// <param name="failOnInit"></param> /// <returns></returns> private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit) { // Create agents for queues in range that we don't yet have. // First create them and store in local queuesToAgentsMap. // Only after that Initialize them all. var agents = new List<PersistentStreamPullingAgent>(); foreach (var queueId in myQueues.Where(queueId => !queuesToAgentsMap.ContainsKey(queueId))) { try { var agentId = GrainId.NewSystemTargetGrainIdByTypeCode(Constants.PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE); var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, providerRuntime, pubSub, queueId, config); providerRuntime.RegisterSystemTarget(agent); queuesToAgentsMap.Add(queueId, agent); agents.Add(agent); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc); // What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down. // If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers. if (failOnInit) throw; } } try { var initTasks = new List<Task>(); foreach (var agent in agents) { initTasks.Add(InitAgent(agent)); } await Task.WhenAll(initTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } private async Task InitAgent(PersistentStreamPullingAgent agent) { // Init the agent only after it was registered locally. var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); var queueAdapterCacheAsImmutable = queueAdapterCache != null ? queueAdapterCache.AsImmutable() : new Immutable<IQueueAdapterCache>(null); IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(agent.QueueId); // Need to call it as a grain reference. var task = OrleansTaskExtentions.SafeExecute(() => agentGrainRef.Initialize(queueAdapter.AsImmutable(), queueAdapterCacheAsImmutable, deliveryFailureHandler.AsImmutable())); await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId)); } private async Task RemoveQueues(List<QueueId> queuesToRemove) { if (queuesToRemove.Count == 0) { return; } // Stop the agents that for queues that are not in my range anymore. var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count); Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString())); var removeTasks = new List<Task>(); foreach (var queueId in queuesToRemove) { PersistentStreamPullingAgent agent; if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue; agents.Add(agent); queuesToAgentsMap.Remove(queueId); var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown); task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11, String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId)); removeTasks.Add(task); } try { await Task.WhenAll(removeTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } foreach (var agent in agents) { try { providerRuntime.UnRegisterSystemTarget(agent); } catch (Exception exc) { Log(ErrorCode.PersistentStreamPullingManager_12, "Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message); } } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } #endregion public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg) { latestCommandNumber++; int commandSeqNumber = latestCommandNumber; try { Log(ErrorCode.PersistentStreamPullingManager_13, String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.", command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState)); switch (command) { case PersistentStreamProviderCommand.StartAgents: case PersistentStreamProviderCommand.StopAgents: await QueueCommandForExecution(command, commandSeqNumber); return null; case PersistentStreamProviderCommand.GetAgentsState: return managerState; case PersistentStreamProviderCommand.GetNumberRunningAgents: return NumberRunningAgents; default: throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command)); } } finally { Log(ErrorCode.PersistentStreamPullingManager_15, String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.", command, commandSeqNumber, managerState, NumberRunningAgents)); } } // Start and Stop commands are composite commands that take multiple turns. // Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification. // Therefore, we serialize them all via the same nonReentrancyGuarantor. private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber) { return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous command since already got a newer command. if (commandSeqNumber < latestCommandNumber) { Log(ErrorCode.PersistentStreamPullingManager_15, "Skipping execution of command number {0} since already received a later command (already have command number {1}).", commandSeqNumber, latestCommandNumber); return TaskDone.Done; } switch (command) { case PersistentStreamProviderCommand.StartAgents: return StartAgents(); case PersistentStreamProviderCommand.StopAgents: return StopAgents(); default: throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command)); } }); } private static string PrintQueues(ICollection<QueueId> myQueues) { return Utils.EnumerableToString(myQueues, q => q.ToString()); } // Just print our queue assignment periodicaly, for easy monitoring. private Task AsyncTimerCallback(object state) { Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint, "I am responsible for a total of {0} queues on stream provider {1}: {2}.", NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys)); return TaskDone.Done; } private void Log(ErrorCode logCode, string format, params object[] args) { logger.LogWithoutBulkingAndTruncating(Severity.Info, logCode, format, args); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.IO; using System.Net.Http; using System.Runtime; using System.Threading.Tasks; using System.Xml; public static class ByteStreamMessage { public static Message CreateMessage(Stream stream) { if (stream == null) { throw FxTrace.Exception.ArgumentNull("stream"); } return CreateMessage(stream, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } public static Message CreateMessage(ArraySegment<byte> buffer) { return CreateMessage(buffer, null); } public static Message CreateMessage(ArraySegment<byte> buffer, BufferManager bufferManager) { if (buffer.Array == null) { throw FxTrace.Exception.ArgumentNull("buffer.Array", SR.ArgumentPropertyShouldNotBeNullError("buffer.Array")); } ByteStreamBufferedMessageData data = new ByteStreamBufferedMessageData(buffer, bufferManager); return CreateMessage(data, XmlDictionaryReaderQuotas.Max, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { return new InternalByteStreamMessage(stream, quotas, moveBodyReaderToContent); } internal static Message CreateMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas) { return new InternalByteStreamMessage(httpRequestMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas) { return new InternalByteStreamMessage(httpResponseMessage, quotas, true); // moveBodyReaderToContent is true, for consistency with the other implementations of Message (including the Message base class itself) } internal static Message CreateMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { return new InternalByteStreamMessage(bufferedMessageData, quotas, moveBodyReaderToContent); } internal static bool IsInternalByteStreamMessage(Message message) { Fx.Assert(message != null, "message should not be null"); return message is InternalByteStreamMessage; } class InternalByteStreamMessage : Message { BodyWriter bodyWriter; MessageHeaders headers; MessageProperties properties; XmlByteStreamReader reader; /// <summary> /// If set to true, OnGetReaderAtBodyContents() calls MoveToContent() on the reader before returning it. /// If set to false, the reader is positioned on None, just before the root element of the body message. /// </summary> /// <remarks> /// We use this flag to preserve compatibility between .net 4.0 (or previous) and .net 4.5 (or later). /// /// In .net 4.0: /// - WebMessageEncodingBindingElement uses a raw encoder, different than ByteStreamMessageEncoder. /// - ByteStreamMessageEncodingBindingElement uses the ByteStreamMessageEncoder. /// - When the WebMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns /// an XmlDictionaryReader positioned initially on content (the root element of the xml); that's because MoveToContent() is called /// on the reader before it's returned. /// - When the ByteStreamMessageEncodingBindingElement is used, the Message.GetReaderAtBodyContents() method returns an /// XmlDictionaryReader positioned initially on None (just before the root element). /// /// In .net 4.5: /// - Both WebMessageEncodingBindingElement and ByteStreamMessageEncodingBindingElement use the ByteStreamMessageEncoder. /// - So we need the ByteStreamMessageEncoder to call MoveToContent() when used by WebMessageEncodingBindingElement, and not do so /// when used by the ByteStreamMessageEncodingBindingElement. /// - Preserving the compatibility with 4.0 is important especially because 4.5 is an in-place upgrade of 4.0. /// /// See 252277 @ CSDMain for other info. /// </remarks> bool moveBodyReaderToContent; public InternalByteStreamMessage(ByteStreamBufferedMessageData bufferedMessageData, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = new BufferedBodyWriter(bufferedMessageData); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = new XmlBufferedByteStreamReader(bufferedMessageData, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(Stream stream, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(stream); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(stream, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(HttpRequestMessage httpRequestMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null."); // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(httpRequestMessage); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(httpRequestMessage, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public InternalByteStreamMessage(HttpResponseMessage httpResponseMessage, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null."); // Assign both writer and reader here so that we can CreateBufferedCopy without the need to // abstract between a streamed or buffered message. We're protected here by the state on Message // preventing both a read/write on the same stream. quotas = ByteStreamMessageUtility.EnsureQuotas(quotas); this.bodyWriter = StreamedBodyWriter.Create(httpResponseMessage); this.headers = new MessageHeaders(MessageVersion.None); this.properties = new MessageProperties(); this.reader = XmlStreamedByteStreamReader.Create(httpResponseMessage, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } InternalByteStreamMessage(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) { this.headers = new MessageHeaders(headers); this.properties = new MessageProperties(properties); this.bodyWriter = new BufferedBodyWriter(messageData); this.reader = new XmlBufferedByteStreamReader(messageData, quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; } public override MessageHeaders Headers { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return this.headers; } } public override bool IsEmpty { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return false; } } public override bool IsFault { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return false; } } public override MessageProperties Properties { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return this.properties; } } public override MessageVersion Version { get { if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return MessageVersion.None; } } protected override void OnBodyToString(XmlDictionaryWriter writer) { if (this.bodyWriter.IsBuffered) { bodyWriter.WriteBodyContents(writer); } else { writer.WriteString(SR.MessageBodyIsStream); } } protected override void OnClose() { Exception ex = null; try { base.OnClose(); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } ex = e; } try { if (properties != null) { properties.Dispose(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ex == null) { ex = e; } } try { if (reader != null) { reader.Close(); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ex == null) { ex = e; } } if (ex != null) { throw FxTrace.Exception.AsError(ex); } this.bodyWriter = null; } protected override MessageBuffer OnCreateBufferedCopy(int maxBufferSize) { BufferedBodyWriter bufferedBodyWriter; if (this.bodyWriter.IsBuffered) { // Can hand this off in buffered case without making a new one. bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter; } else { bufferedBodyWriter = (BufferedBodyWriter)this.bodyWriter.CreateBufferedCopy(maxBufferSize); } // Protected by Message state to be called only once. this.bodyWriter = null; return new ByteStreamMessageBuffer(bufferedBodyWriter.MessageData, this.headers, this.properties, this.reader.Quotas, this.moveBodyReaderToContent); } protected override T OnGetBody<T>(XmlDictionaryReader reader) { Fx.Assert(reader is XmlByteStreamReader, "reader should be XmlByteStreamReader"); if (this.IsDisposed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } Type typeT = typeof(T); if (typeof(Stream) == typeT) { Stream stream = (reader as XmlByteStreamReader).ToStream(); reader.Close(); return (T)(object)stream; } else if (typeof(byte[]) == typeT) { byte[] buffer = (reader as XmlByteStreamReader).ToByteArray(); reader.Close(); return (T)(object)buffer; } throw FxTrace.Exception.AsError( new NotSupportedException(SR.ByteStreamMessageGetTypeNotSupported(typeT.FullName))); } protected override XmlDictionaryReader OnGetReaderAtBodyContents() { XmlDictionaryReader r = this.reader; this.reader = null; if ((r != null) && this.moveBodyReaderToContent) { r.MoveToContent(); } return r; } protected override IAsyncResult OnBeginWriteMessage(XmlDictionaryWriter writer, AsyncCallback callback, object state) { WriteMessagePreamble(writer); return new OnWriteMessageAsyncResult(writer, this, callback, state); } protected override void OnEndWriteMessage(IAsyncResult result) { OnWriteMessageAsyncResult.End(result); } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { this.bodyWriter.WriteBodyContents(writer); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return this.bodyWriter.BeginWriteBodyContents(writer, callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { this.bodyWriter.EndWriteBodyContents(result); } class OnWriteMessageAsyncResult : AsyncResult { InternalByteStreamMessage message; XmlDictionaryWriter writer; public OnWriteMessageAsyncResult(XmlDictionaryWriter writer, InternalByteStreamMessage message, AsyncCallback callback, object state) : base(callback, state) { this.message = message; this.writer = writer; IAsyncResult result = this.message.OnBeginWriteBodyContents(this.writer, PrepareAsyncCompletion(HandleWriteBodyContents), this); bool completeSelf = SyncContinue(result); if (completeSelf) { this.Complete(true); } } static bool HandleWriteBodyContents(IAsyncResult result) { OnWriteMessageAsyncResult thisPtr = (OnWriteMessageAsyncResult)result.AsyncState; thisPtr.message.OnEndWriteBodyContents(result); thisPtr.message.WriteMessagePostamble(thisPtr.writer); return true; } public static void End(IAsyncResult result) { AsyncResult.End<OnWriteMessageAsyncResult>(result); } } class BufferedBodyWriter : BodyWriter { ByteStreamBufferedMessageData bufferedMessageData; public BufferedBodyWriter(ByteStreamBufferedMessageData bufferedMessageData) : base(true) { this.bufferedMessageData = bufferedMessageData; } internal ByteStreamBufferedMessageData MessageData { get { return bufferedMessageData; } } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { // Never called because when copying a Buffered message, we simply hand off the existing BodyWriter // to the new message. Fx.Assert(false, "This is never called"); return null; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); writer.WriteBase64(this.bufferedMessageData.Buffer.Array, this.bufferedMessageData.Buffer.Offset, this.bufferedMessageData.Buffer.Count); writer.WriteEndElement(); } } abstract class StreamedBodyWriter : BodyWriter { private StreamedBodyWriter() : base(false) { } public static StreamedBodyWriter Create(Stream stream) { return new StreamBasedStreamedBodyWriter(stream); } public static StreamedBodyWriter Create(HttpRequestMessage httpRequestMessage) { return new HttpRequestMessageStreamedBodyWriter(httpRequestMessage); } public static StreamedBodyWriter Create(HttpResponseMessage httpResponseMessage) { return new HttpResponseMessageStreamedBodyWriter(httpResponseMessage); } // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once) protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { using (BufferManagerOutputStream bufferedStream = new BufferManagerOutputStream(SR.MaxReceivedMessageSizeExceeded("{0}"), maxBufferSize)) { using (XmlDictionaryWriter writer = new XmlByteStreamWriter(bufferedStream, true)) { OnWriteBodyContents(writer); writer.Flush(); int size; byte[] bytesArray = bufferedStream.ToArray(out size); ByteStreamBufferedMessageData bufferedMessageData = new ByteStreamBufferedMessageData(new ArraySegment<byte>(bytesArray, 0, size)); return new BufferedBodyWriter(bufferedMessageData); } } } // OnCreateBufferedCopy / OnWriteBodyContents can only be called once - protected by state on Message (either copied or written once) protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); writer.WriteValue(new ByteStreamStreamProvider(this.GetStream())); writer.WriteEndElement(); } protected override IAsyncResult OnBeginWriteBodyContents(XmlDictionaryWriter writer, AsyncCallback callback, object state) { return new WriteBodyContentsAsyncResult(writer, this.GetStream(), callback, state); } protected override void OnEndWriteBodyContents(IAsyncResult result) { WriteBodyContentsAsyncResult.End(result); } protected abstract Stream GetStream(); class ByteStreamStreamProvider : IStreamProvider { Stream stream; internal ByteStreamStreamProvider(Stream stream) { this.stream = stream; } public Stream GetStream() { return stream; } public void ReleaseStream(Stream stream) { //Noop } } class WriteBodyContentsAsyncResult : AsyncResult { XmlDictionaryWriter writer; public WriteBodyContentsAsyncResult(XmlDictionaryWriter writer, Stream stream, AsyncCallback callback, object state) : base(callback, state) { this.writer = writer; this.writer.WriteStartElement(ByteStreamMessageUtility.StreamElementName, string.Empty); IAsyncResult result = this.writer.WriteValueAsync(new ByteStreamStreamProvider(stream)).AsAsyncResult(PrepareAsyncCompletion(HandleWriteBodyContents), this); bool completeSelf = SyncContinue(result); // Note: The current task implementation hard codes the "IAsyncResult.CompletedSynchronously" property to false, so this fast path will never // be hit, and we will always hop threads. CSDMain #210220 if (completeSelf) { this.Complete(true); } } static bool HandleWriteBodyContents(IAsyncResult result) { // If result is a task, we need to get the result so that exceptions are bubbled up in case the task is faulted. Task t = result as Task; if (t != null) { t.GetAwaiter().GetResult(); } WriteBodyContentsAsyncResult thisPtr = (WriteBodyContentsAsyncResult)result.AsyncState; thisPtr.writer.WriteEndElement(); return true; } public static void End(IAsyncResult result) { AsyncResult.End<WriteBodyContentsAsyncResult>(result); } } class StreamBasedStreamedBodyWriter : StreamedBodyWriter { private Stream stream; public StreamBasedStreamedBodyWriter(Stream stream) { this.stream = stream; } protected override Stream GetStream() { return this.stream; } } class HttpRequestMessageStreamedBodyWriter : StreamedBodyWriter { private HttpRequestMessage httpRequestMessage; public HttpRequestMessageStreamedBodyWriter(HttpRequestMessage httpRequestMessage) { Fx.Assert(httpRequestMessage != null, "The 'httpRequestMessage' parameter should not be null."); this.httpRequestMessage = httpRequestMessage; } protected override Stream GetStream() { HttpContent content = this.httpRequestMessage.Content; if (content != null) { return content.ReadAsStreamAsync().Result; } return new MemoryStream(EmptyArray<byte>.Instance); } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { HttpContent content = this.httpRequestMessage.Content; if (content != null) { content.LoadIntoBufferAsync(maxBufferSize).Wait(); } return base.OnCreateBufferedCopy(maxBufferSize); } } class HttpResponseMessageStreamedBodyWriter : StreamedBodyWriter { private HttpResponseMessage httpResponseMessage; public HttpResponseMessageStreamedBodyWriter(HttpResponseMessage httpResponseMessage) { Fx.Assert(httpResponseMessage != null, "The 'httpResponseMessage' parameter should not be null."); this.httpResponseMessage = httpResponseMessage; } protected override Stream GetStream() { HttpContent content = this.httpResponseMessage.Content; if (content != null) { return content.ReadAsStreamAsync().Result; } return new MemoryStream(EmptyArray<byte>.Instance); } protected override BodyWriter OnCreateBufferedCopy(int maxBufferSize) { HttpContent content = this.httpResponseMessage.Content; if (content != null) { content.LoadIntoBufferAsync(maxBufferSize).Wait(); } return base.OnCreateBufferedCopy(maxBufferSize); } } } class ByteStreamMessageBuffer : MessageBuffer { bool closed; MessageHeaders headers; ByteStreamBufferedMessageData messageData; MessageProperties properties; XmlDictionaryReaderQuotas quotas; bool moveBodyReaderToContent; object thisLock = new object(); public ByteStreamMessageBuffer(ByteStreamBufferedMessageData messageData, MessageHeaders headers, MessageProperties properties, XmlDictionaryReaderQuotas quotas, bool moveBodyReaderToContent) : base() { this.messageData = messageData; this.headers = new MessageHeaders(headers); this.properties = new MessageProperties(properties); this.quotas = new XmlDictionaryReaderQuotas(); quotas.CopyTo(this.quotas); this.moveBodyReaderToContent = moveBodyReaderToContent; this.messageData.Open(); } public override int BufferSize { get { return this.messageData.Buffer.Count; } } object ThisLock { get { return this.thisLock; } } public override void Close() { lock (ThisLock) { if (!closed) { closed = true; this.headers = null; if (properties != null) { properties.Dispose(); properties = null; } this.messageData.Close(); this.messageData = null; this.quotas = null; } } } public override Message CreateMessage() { lock (ThisLock) { if (closed) { throw FxTrace.Exception.ObjectDisposed(SR.ObjectDisposed("message")); } return new InternalByteStreamMessage(this.messageData, this.headers, this.properties, this.quotas, this.moveBodyReaderToContent); } } } } } }
#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.Xml; using System.Collections; using System.IO; using System.Reflection; using System.Threading; using log4net.Appender; using log4net.Util; using log4net.Repository; namespace log4net.Config { /// <summary> /// Use this class to initialize the log4net environment using an Xml tree. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// Configures a <see cref="ILoggerRepository"/> using an Xml tree. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> [Obsolete("Use XmlConfigurator instead of DOMConfigurator")] public sealed class DOMConfigurator { #region Private Instance Constructors /// <summary> /// Private constructor /// </summary> private DOMConfigurator() { } #endregion Protected Instance Constructors #region Configure static methods /// <summary> /// Automatically configures the log4net system based on the /// application's configuration settings. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure() { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly())); } /// <summary> /// Automatically configures the <see cref="ILoggerRepository"/> using settings /// stored in the application's configuration file. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Each application has a configuration file. This has the /// same name as the application with '.config' appended. /// This file is XML and calling this function prompts the /// configurator to look in that file for a section called /// <c>log4net</c> that contains the configuration data. /// </remarks> /// <param name="repository">The repository to configure.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository) { XmlConfigurator.Configure(repository); } /// <summary> /// Configures log4net using a <c>log4net</c> element /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </remarks> /// <param name="element">The element to parse.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(XmlElement element) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), element); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified XML /// element. /// </summary> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// Loads the log4net configuration from the XML element /// supplied as <paramref name="element"/>. /// </remarks> /// <param name="repository">The repository to configure.</param> /// <param name="element">The element to parse.</param> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, XmlElement element) { XmlConfigurator.Configure(repository, element); } /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(FileInfo configFile) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); } /// <summary> /// Configures log4net using the specified configuration file. /// </summary> /// <param name="configStream">A stream to load the XML configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the log4net configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(Stream configStream) { XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), configStream); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The log4net configuration file can possible be specified in the application's /// configuration file (either <c>MyAppName.exe.config</c> for a /// normal application on <c>Web.config</c> for an ASP.NET application). /// </para> /// <example> /// The following example configures log4net using a configuration file, of which the /// location is stored in the application's configuration file : /// </example> /// <code lang="C#"> /// using log4net.Config; /// using System.IO; /// using System.Configuration; /// /// ... /// /// DOMConfigurator.Configure(new FileInfo(ConfigurationSettings.AppSettings["log4net-config-file"])); /// </code> /// <para> /// In the <c>.config</c> file, the path to the log4net can be specified like this : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="log4net-config-file" value="log.config"/> /// </appSettings> /// </configuration> /// </code> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, FileInfo configFile) { XmlConfigurator.Configure(repository, configFile); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the specified configuration /// file. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configStream">The stream to load the XML configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration data must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// Note that this method will NOT close the stream parameter. /// </para> /// </remarks> [Obsolete("Use XmlConfigurator.Configure instead of DOMConfigurator.Configure")] static public void Configure(ILoggerRepository repository, Stream configStream) { XmlConfigurator.Configure(repository, configStream); } #endregion Configure static methods #region ConfigureAndWatch static methods #if (!NETCF && !SSCLI) /// <summary> /// Configures log4net using the file specified, monitors the file for changes /// and reloads the configuration if a change is detected. /// </summary> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="Configure(FileInfo)"/> [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] static public void ConfigureAndWatch(FileInfo configFile) { XmlConfigurator.ConfigureAndWatch(LogManager.GetRepository(Assembly.GetCallingAssembly()), configFile); } /// <summary> /// Configures the <see cref="ILoggerRepository"/> using the file specified, /// monitors the file for changes and reloads the configuration if a change /// is detected. /// </summary> /// <param name="repository">The repository to configure.</param> /// <param name="configFile">The XML file to load the configuration from.</param> /// <remarks> /// <para> /// <b>DOMConfigurator is obsolete. Use XmlConfigurator instead of DOMConfigurator.</b> /// </para> /// <para> /// The configuration file must be valid XML. It must contain /// at least one element called <c>log4net</c> that holds /// the configuration data. /// </para> /// <para> /// The configuration file will be monitored using a <see cref="FileSystemWatcher"/> /// and depends on the behavior of that class. /// </para> /// <para> /// For more information on how to configure log4net using /// a separate configuration file, see <see cref="Configure(FileInfo)"/>. /// </para> /// </remarks> /// <seealso cref="Configure(FileInfo)"/> [Obsolete("Use XmlConfigurator.ConfigureAndWatch instead of DOMConfigurator.ConfigureAndWatch")] static public void ConfigureAndWatch(ILoggerRepository repository, FileInfo configFile) { XmlConfigurator.ConfigureAndWatch(repository, configFile); } #endif #endregion ConfigureAndWatch static methods } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Eto.Drawing; using s = SharpDX; using sd = SharpDX.Direct2D1; using sw = SharpDX.DirectWrite; #if WINFORMS using Eto.WinForms.Drawing; #else using Windows.Globalization.Fonts; #endif namespace Eto.Direct2D.Drawing { /// <summary> /// Handler for <see cref="IFont"/> /// </summary> /// <copyright>(c) 2013 by Vivek Jhaveri</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class FontHandler : WidgetHandler<sw.Font, Font>, Font.IHandler #if WINFORMS , IWindowsFontSource #endif { sw.TextFormat textFormat; public sw.TextFormat TextFormat { get { if (textFormat == null) { textFormat = new sw.TextFormat( SDFactory.DirectWriteFactory, Control.FontFamily.FamilyNames.GetString(0), FontCollection, Control.Weight, Control.Style, Control.Stretch, Size * 96.0f / 72.0f // convert from points to pixels. (The documentation says device-independent pixels.) ); } return textFormat; } } public void Create(FontFamily family, float size, FontStyle style, FontDecoration decoration) { this.family = family; Size = size; FontStyle = style; FontDecoration = decoration; sw.FontStyle fontStyle; sw.FontWeight fontWeight; Conversions.Convert(style, out fontStyle, out fontWeight); var familyHandler = (FontFamilyHandler)family.Handler; Control = familyHandler.Control.GetFirstMatchingFont(fontWeight, sw.FontStretch.Normal, fontStyle); } #if !WINFORMS static LanguageFontGroup languageFontGroup = new LanguageFontGroup("en"); // TODO: add Eto support for other locales. #endif public void Create(SystemFont systemFont, float? size, FontDecoration decoration) { #if WINFORMS var sdfont = Eto.WinForms.WinConversions.ToSD(systemFont); Create(sdfont.Name, size ?? sdfont.SizeInPoints, FontStyle.None, decoration); #else var familyName = "Segoe UI"; var sizeInPoints = size ?? 12f; var fontStyle = FontStyle.None; // TODO: map the systemfont and default size to a family name and font size. // See: http://msdn.microsoft.com/en-us/library/windows/apps/hh700394.aspx switch (systemFont) { case SystemFont.Default: case SystemFont.Bold: case SystemFont.TitleBar: case SystemFont.ToolTip: case SystemFont.Label: case SystemFont.MenuBar: case SystemFont.Menu: case SystemFont.Message: case SystemFont.Palette: case SystemFont.StatusBar: default: break; } Create(familyName, sizeInPoints, fontStyle, decoration); #endif } public void Create(FontTypeface typeface, float size, FontDecoration decoration) { family = typeface.Family; this.typeface = typeface; var typefaceHandler = (FontTypefaceHandler)typeface.Handler; Control = typefaceHandler.Font; FontStyle = Control.ToEtoStyle(); FontDecoration = decoration; Size = size; } void Create(string familyName, float sizeInPoints, FontStyle style, FontDecoration decoration) { Size = sizeInPoints; FontStyle = style; FontDecoration = decoration; int index; if (FontCollection.FindFamilyName(familyName, out index)) { sw.FontStyle fontStyle; sw.FontWeight fontWeight; Conversions.Convert(style, out fontStyle, out fontWeight); Control = FontCollection.GetFontFamily(index).GetFirstMatchingFont(fontWeight, sw.FontStretch.Normal, fontStyle); } } static sw.FontCollection fontCollection; public static sw.FontCollection FontCollection { get { return fontCollection = fontCollection ?? SDFactory.DirectWriteFactory.GetSystemFontCollection(checkForUpdates: false); } } public static sw.FontFamily GetFontFamily(string familyName) { sw.FontFamily result = null; int index; if (FontHandler.FontCollection.FindFamilyName(familyName, out index)) result = FontHandler.FontCollection.GetFontFamily(index); return result; } protected override void Dispose(bool disposing) { if (textFormat != null) { textFormat.Dispose(); textFormat = null; } base.Dispose(disposing); } FontFamily family; public FontFamily Family { get { return family ?? (family = new FontFamily(new FontFamilyHandler(Control.FontFamily))); } } public string FamilyName { get { return Family.Name; } } public FontStyle FontStyle { get; private set; } public FontDecoration FontDecoration { get; private set; } /// <summary> /// The size in points. /// </summary> public float Size { get; private set; } FontTypeface typeface; public FontTypeface Typeface { get { return typeface ?? (typeface = new FontTypeface(Family, new FontTypefaceHandler(Control))); } } public float XHeight { get { return Size * Control.Metrics.XHeight / Control.Metrics.DesignUnitsPerEm; } } public float Ascent { get { return Size * Control.Metrics.Ascent / Control.Metrics.DesignUnitsPerEm; } } public float Descent { get { return Size * Control.Metrics.Descent / Control.Metrics.DesignUnitsPerEm; } } public float LineHeight { get { return Ascent + Descent + Size * Control.Metrics.LineGap / Control.Metrics.DesignUnitsPerEm; } } public float Leading { get { return LineHeight - (Ascent + Descent);} } public float Baseline { get { return Ascent; } } #if WINFORMS public System.Drawing.Font GetFont() { var familyName = Control.FontFamily.FamilyNames.GetString(0); var style = Eto.WinForms.WinConversions.ToSD(FontStyle) | Eto.WinForms.WinConversions.ToSD(FontDecoration); return new System.Drawing.Font(familyName, Size, style); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableDictionaryTest : ImmutableDictionaryTestBase { [Fact] public void AddExistingKeySameValueTest() { AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft"); AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void AddExistingKeyDifferentValueTest() { AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void UnorderedChangeTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("Johnny")); Assert.False(map.ContainsKey("johnny")); var newMap = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, newMap.Count); Assert.True(newMap.ContainsKey("Johnny")); Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive } [Fact] public void ToSortedTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); var sortedMap = map.ToImmutableSortedDictionary(StringComparer.Ordinal); Assert.Equal(sortedMap.Count, map.Count); CollectionAssertAreEquivalent<KeyValuePair<string, string>>(sortedMap.ToList(), map.ToList()); } [Fact] public void SetItemUpdateEqualKeyTest() { var map = Empty<string, int>().WithComparers(StringComparer.OrdinalIgnoreCase) .SetItem("A", 1); map = map.SetItem("a", 2); Assert.Equal("a", map.Keys.Single()); } /// <summary> /// Verifies that the specified value comparer is applied when /// checking for equality. /// </summary> [Fact] public void SetItemUpdateEqualKeyWithValueEqualityByComparer() { var map = Empty<string, CaseInsensitiveString>().WithComparers(StringComparer.OrdinalIgnoreCase, new MyStringOrdinalComparer()); string key = "key"; var value1 = "Hello"; var value2 = "hello"; map = map.SetItem(key, new CaseInsensitiveString(value1)); map = map.SetItem(key, new CaseInsensitiveString(value2)); Assert.Equal(value2, map[key].Value); Assert.Same(map, map.SetItem(key, new CaseInsensitiveString(value2))); } [Fact] public override void EmptyTest() { base.EmptyTest(); this.EmptyTestHelperHash(Empty<int, bool>(), 5); } [Fact] public void ContainsValueTest() { this.ContainsValueTestHelper(ImmutableDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper()); } [Fact] public void ContainsValue_NoSuchValue_ReturnsFalse() { ImmutableDictionary<int, string> dictionary = new Dictionary<int, string> { { 1, "a" }, { 2, "b" } }.ToImmutableDictionary(); Assert.False(dictionary.ContainsValue("c")); Assert.False(dictionary.ContainsValue(null)); } [Fact] public void EnumeratorWithHashCollisionsTest() { var emptyMap = Empty<int, GenericParameterHelper>(new BadHasher<int>()); this.EnumeratorTestHelper(emptyMap); } [Fact] public void Create() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; var dictionary = ImmutableDictionary.Create<string, string>(); Assert.Equal(0, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.Create<string, string>(keyComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.Create(keyComparer, valueComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(pairs); Assert.Equal(1, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(keyComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableDictionary.CreateRange(keyComparer, valueComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void ToImmutableDictionary() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; ImmutableDictionary<string, string> dictionary = pairs.ToImmutableDictionary(); Assert.Equal(1, dictionary.Count); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(keyComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant()); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(EqualityComparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); var list = new int[] { 1, 2 }; var intDictionary = list.ToImmutableDictionary(n => (double)n); Assert.Equal(1, intDictionary[1.0]); Assert.Equal(2, intDictionary[2.0]); Assert.Equal(2, intDictionary.Count); var stringIntDictionary = list.ToImmutableDictionary(n => n.ToString(), StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, stringIntDictionary.KeyComparer); Assert.Equal(1, stringIntDictionary["1"]); Assert.Equal(2, stringIntDictionary["2"]); Assert.Equal(2, intDictionary.Count); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableDictionary<int, int>(null)); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => list.ToImmutableDictionary<int, int, int>(null, v => v)); AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => list.ToImmutableDictionary<int, int, int>(k => k, null)); list.ToDictionary(k => k, v => v, null); // verifies BCL behavior is to not throw. list.ToImmutableDictionary(k => k, v => v, null, null); } [Fact] public void ToImmutableDictionaryOptimized() { var dictionary = ImmutableDictionary.Create<string, string>(); var result = dictionary.ToImmutableDictionary(); Assert.Same(dictionary, result); var cultureComparer = StringComparer.CurrentCulture; result = dictionary.WithComparers(cultureComparer, StringComparer.OrdinalIgnoreCase); Assert.Same(cultureComparer, result.KeyComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, result.ValueComparer); } [Fact] public void WithComparers() { var map = ImmutableDictionary.Create<string, string>().Add("a", "1").Add("B", "1"); Assert.Same(EqualityComparer<string>.Default, map.KeyComparer); Assert.True(map.ContainsKey("a")); Assert.False(map.ContainsKey("A")); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); var cultureComparer = StringComparer.CurrentCulture; map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(cultureComparer, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersCollisions() { // First check where collisions have matching values. var map = ImmutableDictionary.Create<string, string>() .Add("a", "1").Add("A", "1"); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(1, map.Count); Assert.True(map.ContainsKey("a")); Assert.Equal("1", map["a"]); // Now check where collisions have conflicting values. map = ImmutableDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3"); Assert.Throws<ArgumentException>(null, () => map.WithComparers(StringComparer.OrdinalIgnoreCase)); // Force all values to be considered equal. map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(EverythingEqual<string>.Default, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("b")); } [Fact] public void CollisionExceptionMessageContainsKey() { var map = ImmutableDictionary.Create<string, string>() .Add("firstKey", "1").Add("secondKey", "2"); var exception = Assert.Throws<ArgumentException>(null, () => map.Add("firstKey", "3")); Assert.Contains("firstKey", exception.Message); } [Fact] public void WithComparersEmptyCollection() { var map = ImmutableDictionary.Create<string, string>(); Assert.Same(EqualityComparer<string>.Default, map.KeyComparer); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); } [Fact] public void GetValueOrDefaultOfIImmutableDictionary() { IImmutableDictionary<string, int> empty = ImmutableDictionary.Create<string, int>(); IImmutableDictionary<string, int> populated = ImmutableDictionary.Create<string, int>().Add("a", 5); Assert.Equal(0, empty.GetValueOrDefault("a")); Assert.Equal(1, empty.GetValueOrDefault("a", 1)); Assert.Equal(5, populated.GetValueOrDefault("a")); Assert.Equal(5, populated.GetValueOrDefault("a", 1)); } [Fact] public void GetValueOrDefaultOfConcreteType() { var empty = ImmutableDictionary.Create<string, int>(); var populated = ImmutableDictionary.Create<string, int>().Add("a", 5); Assert.Equal(0, empty.GetValueOrDefault("a")); Assert.Equal(1, empty.GetValueOrDefault("a", 1)); Assert.Equal(5, populated.GetValueOrDefault("a")); Assert.Equal(5, populated.GetValueOrDefault("a", 1)); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableDictionary.Create<int, int>().Add(5, 3); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableDictionary.Create<int, int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableDictionary.Create<string, int>()); object rootNode = DebuggerAttributes.GetFieldValue(ImmutableDictionary.Create<string, string>(), "_root"); DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode); } [Fact] public void Clear_NoComparer_ReturnsEmptyWithoutComparer() { ImmutableDictionary<string, int> dictionary = new Dictionary<string, int> { { "a", 1 } }.ToImmutableDictionary(); Assert.Same(ImmutableDictionary<string, int>.Empty, dictionary.Clear()); Assert.NotEmpty(dictionary); } [Fact] public void Clear_HasComparer_ReturnsEmptyWithOriginalComparer() { ImmutableDictionary<string, int> dictionary = new Dictionary<string, int> { { "a", 1 } }.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase); ImmutableDictionary<string, int> clearedDictionary = dictionary.Clear(); Assert.NotSame(ImmutableDictionary<string, int>.Empty, clearedDictionary.Clear()); Assert.NotEmpty(dictionary); clearedDictionary = clearedDictionary.Add("a", 1); Assert.True(clearedDictionary.ContainsKey("A")); } protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() { return ImmutableDictionaryTest.Empty<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableDictionary.Create<string, TValue>(comparer); } protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableDictionary<TKey, TValue>)dictionary).ValueComparer; } internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableDictionary<TKey, TValue>)dictionary).Root; } protected void ContainsValueTestHelper<TKey, TValue>(ImmutableDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsValue(value)); Assert.True(map.Add(key, value).ContainsValue(value)); } private static ImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IEqualityComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { return ImmutableDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } private void EmptyTestHelperHash<TKey, TValue>(IImmutableDictionary<TKey, TValue> empty, TKey someKey) { Assert.Same(EqualityComparer<TKey>.Default, ((IHashKeyCollection<TKey>)empty).KeyComparer); } /// <summary> /// An ordinal comparer for case-insensitive strings. /// </summary> private class MyStringOrdinalComparer : EqualityComparer<CaseInsensitiveString> { public override bool Equals(CaseInsensitiveString x, CaseInsensitiveString y) { return StringComparer.Ordinal.Equals(x.Value, y.Value); } public override int GetHashCode(CaseInsensitiveString obj) { return StringComparer.Ordinal.GetHashCode(obj.Value); } } /// <summary> /// A string-wrapper that considers equality based on case insensitivity. /// </summary> private class CaseInsensitiveString { public CaseInsensitiveString(string value) { Value = value; } public string Value { get; private set; } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(this.Value); } public override bool Equals(object obj) { return StringComparer.OrdinalIgnoreCase.Equals(this.Value, ((CaseInsensitiveString)obj).Value); } } } }
using System; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace WindowFinder { [DefaultEvent("WindowHandleChanged")] [ToolboxBitmap(typeof(ResourceFinder), "WindowFinder.Resources.WindowFinder.bmp")] [Designer(typeof(WindowFinderDesigner))] public sealed partial class WindowFinder : UserControl { /// <summary> /// Initializes a new instance of the <see cref="WindowFinder"/> class. /// </summary> public WindowFinder() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); SetStyle(ControlStyles.FixedWidth, true); SetStyle(ControlStyles.FixedHeight, true); SetStyle(ControlStyles.StandardClick, false); SetStyle(ControlStyles.StandardDoubleClick, false); SetStyle(ControlStyles.Selectable, false); picTarget.Size = new Size(31, 28); Size = picTarget.Size; } #region Public Properties /// <summary> /// Called when the WindowHandle property is changed. /// </summary> public event EventHandler WindowHandleChanged; /// <summary> /// Handle of the window found. /// </summary> [Browsable(false)] public IntPtr WindowHandle { get { return windowHandle; } } /// <summary> /// Handle text of the window found. /// </summary> [Browsable(false)] public string WindowHandleText { get { return windowHandleText; } } /// <summary> /// Class of the window found. /// </summary> [Browsable(false)] public string WindowClass { get { return windowClass; } } /// <summary> /// Text of the window found. /// </summary> [Browsable(false)] public string WindowText { get { return windowText; } } /// <summary> /// Whether or not the found window is unicode. /// </summary> [Browsable(false)] public bool IsWindowUnicode { get { return isWindowUnicode; } } /// <summary> /// Whether or not the found window is unicode, via text. /// </summary> [Browsable(false)] public string WindowCharset { get { return windowCharset; } } #endregion #region Event Handler Methods /// <summary> /// Handles the Load event of the WindowFinder control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void WindowFinder_Load(object sender, System.EventArgs e) { this.Size = picTarget.Size; try { // Load cursors Assembly assembly = Assembly.GetExecutingAssembly(); cursorTarget = new Cursor(assembly.GetManifestResourceStream("WindowFinder.curTarget.cur")); bitmapFind = new Bitmap(assembly.GetManifestResourceStream("WindowFinder.bmpFind.bmp")); bitmapFinda = new Bitmap(assembly.GetManifestResourceStream("WindowFinder.bmpFinda.bmp")); } catch(Exception x) { // Show error MessageBox.Show(this, "Failed to load resources.\n\n" + x.ToString(), "WindowFinder"); // Attempt to use backup cursor if(cursorTarget == null) cursorTarget = Cursors.Cross; } // Set default values picTarget.Image = bitmapFind; } /// <summary> /// Handles the MouseDown event of the picTarget control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> private void picTarget_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // Set capture image and cursor picTarget.Image = bitmapFinda; picTarget.Cursor = cursorTarget; // Set capture Win32.SetCapture(picTarget.Handle); // Begin targeting isTargeting = true; targetWindow = IntPtr.Zero; // Show info TODO: Put into function for mousemove & mousedown SetWindowHandle(picTarget.Handle); } /// <summary> /// Handles the MouseMove event of the picTarget control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> private void picTarget_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { IntPtr hWnd; IntPtr hTemp; Win32.POINTAPI pt; // TODO: Draw border around EVERY window pt.x = e.X; pt.y = e.Y; Win32.ClientToScreen(picTarget.Handle, ref pt); // Make sure targeting before highlighting windows if(!isTargeting) return; // Get screen coords from client coords and window handle hWnd = Win32.WindowFromPoint(picTarget.Handle, e.X, e.Y); // Get real window if(hWnd != IntPtr.Zero) { hTemp = IntPtr.Zero; while(true) { Win32.MapWindowPoints(hTemp, hWnd, ref pt, 1); hTemp = (IntPtr)Win32.ChildWindowFromPoint(hWnd, pt.x, pt.y); if(hTemp == IntPtr.Zero) break; if(hWnd == hTemp) break; hWnd = hTemp; } /* TODO: Work with ALL windows Win32.ScreenToClient(hWnd, ref pt); Win32.MapWindowPoints(IntPtr.Zero, hWnd, ref pt, 2); if ((hTemp = (IntPtr)Win32.ChildWindowFromPoint(hWnd, pt.x, pt.y)) != IntPtr.Zero) { hWnd = hTemp; } // */ } // Get owner while((hTemp = Win32.GetParent(hWnd)) != IntPtr.Zero) hWnd = hTemp; // Show info SetWindowHandle(hWnd); // Highlight valid window HighlightValidWindow(hWnd, this.Handle); } /// <summary> /// Handles the MouseUp event of the picTarget control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> private void picTarget_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { IntPtr hWnd; IntPtr hTemp; // End targeting isTargeting = false; // Unhighlight window if(targetWindow != IntPtr.Zero) Win32.HighlightWindow(targetWindow); targetWindow = IntPtr.Zero; // Reset capture image and cursor picTarget.Cursor = Cursors.Default; picTarget.Image = bitmapFind; // Get screen coords from client coords and window handle hWnd = Win32.WindowFromPoint(picTarget.Handle, e.X, e.Y); // Get owner while((hTemp = Win32.GetParent(hWnd)) != IntPtr.Zero) hWnd = hTemp; SetWindowHandle(hWnd); // Release capture Win32.SetCapture(IntPtr.Zero); } #endregion #region Public Methods /// <summary> /// Sets the window handle if handle is a valid window. /// </summary> /// <param name="handle">The handle to set to.</param> public void SetWindowHandle(IntPtr handle) { if((Win32.IsWindow(handle) == 0) || (Win32.IsRelativeWindow(handle, this.Handle, true))) { // Clear window information windowHandle = IntPtr.Zero; windowHandleText = string.Empty; windowClass = string.Empty; windowText = string.Empty; isWindowUnicode = false; windowCharset = string.Empty; } else { // Set window information windowHandle = handle; windowHandleText = Convert.ToString(handle.ToInt32(), 16).ToUpper().PadLeft(8, '0'); windowClass = Win32.GetClassName(handle); windowText = Win32.GetWindowText(handle); isWindowUnicode = Win32.IsWindowUnicode(handle) != 0; windowCharset = ((isWindowUnicode) ? ("Unicode") : ("Ansi")); } if(WindowHandleChanged != null) WindowHandleChanged(this, EventArgs.Empty); } #endregion #region Helper Methods /// <summary> /// Highlights the specified window, but only if it is a valid window in relation to the specified owner window. /// </summary> private void HighlightValidWindow(IntPtr hWnd, IntPtr hOwner) { // Check for valid highlight if(targetWindow == hWnd) return; // Check for relative if(Win32.IsRelativeWindow(hWnd, hOwner, true)) { // Unhighlight last window if(targetWindow != IntPtr.Zero) { Win32.HighlightWindow(targetWindow); targetWindow = IntPtr.Zero; } return; } // Unhighlight last window Win32.HighlightWindow(targetWindow); // Set as current target targetWindow = hWnd; // Highlight window Win32.HighlightWindow(hWnd); } #endregion private bool isTargeting = false; private Cursor cursorTarget = null; private Bitmap bitmapFind = null; private Bitmap bitmapFinda = null; private IntPtr targetWindow = IntPtr.Zero; private IntPtr windowHandle = IntPtr.Zero; private string windowHandleText = string.Empty; private string windowClass = string.Empty; private string windowText = string.Empty; private bool isWindowUnicode = false; private string windowCharset = string.Empty; } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Configuration; using System.Globalization; using System.Text.RegularExpressions; using System.Web; using System.Web.Routing; using Subtext.Extensibility; using Subtext.Extensibility.Interfaces; using Subtext.Framework.Components; using Subtext.Framework.Properties; using Subtext.Framework.Web; namespace Subtext.Framework.Routing { public class UrlHelper { protected UrlHelper() { } public UrlHelper(RequestContext context, RouteCollection routes) { RequestContext = context ?? new RequestContext(new HttpContextWrapper(System.Web.HttpContext.Current), new RouteData()); Routes = routes ?? RouteTable.Routes; } public HttpContextBase HttpContext { get { return RequestContext.HttpContext; } } protected RequestContext RequestContext { get; private set; } public RouteCollection Routes { get; private set; } public virtual VirtualPath AppRoot() { return new VirtualPath(GetNormalizedAppPath()); } private string GetNormalizedAppPath() { string appRoot = HttpContext.Request.ApplicationPath; if(!appRoot.EndsWith("/")) { appRoot += "/"; } return appRoot; } public virtual VirtualPath CommentUpdateStatus() { return GetVirtualPath("comments-admin", new RouteValueDictionary {{"action", "updatestatus"}, {"controller", "comment"}}); } public virtual VirtualPath CommentDestroy() { return GetVirtualPath("comments-admin", new RouteValueDictionary { { "action", "destroy" }, { "controller", "comment" } }); } public virtual VirtualPath FeedbackUrl(FeedbackItem comment) { if(comment == null) { throw new ArgumentNullException("comment"); } if(comment.FeedbackType == FeedbackType.ContactPage || comment.Entry == null) { return null; } string entryUrl = EntryUrl(comment.Entry); if(string.IsNullOrEmpty(entryUrl)) { return null; } return string.Format("{0}#{1}", entryUrl, comment.Id); } public virtual VirtualPath EntryUrl(IEntryIdentity entry) { return EntryUrl(entry, null); } public virtual VirtualPath EntryUrl(IEntryIdentity entry, Blog entryBlog) { if(entry == null) { throw new ArgumentNullException("entry"); } if(entry.PostType == PostType.None) { throw new ArgumentException(Resources.Argument_EntryMustHaveValidPostType, "entry"); } if(NullValue.IsNull(entry.Id)) { return null; } string routeName; var routeValues = new RouteValueDictionary(); if(entry.PostType == PostType.BlogPost) { #if DEBUG var blogEntry = entry as Entry; if(blogEntry != null && blogEntry.IsActive && blogEntry.DateSyndicated.Year == 1) { throw new InvalidOperationException("DateSyndicated was not properly set."); } #endif routeValues.Add("year", entry.DateSyndicated.ToString("yyyy", CultureInfo.InvariantCulture)); routeValues.Add("month", entry.DateSyndicated.ToString("MM", CultureInfo.InvariantCulture)); routeValues.Add("day", entry.DateSyndicated.ToString("dd", CultureInfo.InvariantCulture)); routeName = "entry-"; } else { routeName = "article-"; } if(string.IsNullOrEmpty(entry.EntryName)) { routeValues.Add("id", entry.Id); routeName += "by-id"; } else { routeValues.Add("slug", entry.EntryName); routeName += "by-slug"; } if(entryBlog != null) { routeValues.Add("subfolder", entryBlog.Subfolder); } VirtualPathData virtualPath = Routes.GetVirtualPath(RequestContext, routeName, routeValues); if(virtualPath != null) { return virtualPath.VirtualPath; } return null; } private static string NormalizeFileName(string filename) { if(filename.StartsWith("/")) { return filename.Substring(1); } return filename; } private string GetImageDirectoryTildePath(Blog blog) { string host = blog.Host.Replace(":", "_").Replace(".", "_"); string appPath = GetNormalizedAppPath().Replace(".", "_"); string subfolder = String.IsNullOrEmpty(blog.Subfolder) ? String.Empty : blog.Subfolder + "/"; return string.Format("~/images/{0}{1}{2}", host, appPath, subfolder); } private string GetImageTildePath(Blog blog, string filename) { return GetImageDirectoryTildePath(blog) + NormalizeFileName(filename); } private string GetGalleryImageTildePath(Image image, string filename) { return string.Format("{0}{1}/{2}", GetImageDirectoryTildePath(image.Blog), image.CategoryID, filename); } /// <summary> /// Returns the URL for an image that was uploaded to a blog via MetaWeblog API. The image /// is not associated with an image gallery. /// </summary> /// <param name="blog"></param> /// <param name="filename"></param> /// <returns></returns> public virtual VirtualPath ImageUrl(Blog blog, string filename) { return ResolveUrl(GetImageTildePath(blog, filename)); } /// <summary> /// Returns the URL for a system image that's directly in the images directory. /// </summary> /// <param name="filename"></param> /// <returns></returns> public virtual VirtualPath ImageUrl(string filename) { return ResolveUrl(string.Format("~/images/{0}", filename)); } /// <summary> /// Returns the direct URL to an image within a gallery. /// </summary> /// <param name="image"></param> /// <returns></returns> public virtual VirtualPath GalleryImageUrl(Image image) { return GalleryImageUrl(image, image.OriginalFile); } public VirtualPath GalleryImageUrl(Image image, string fileName) { if(image == null) { throw new ArgumentNullException("image"); } if(!String.IsNullOrEmpty(image.Url)) { return ResolveUrl(image.Url + fileName); } return ResolveUrl(GetGalleryImageTildePath(image, fileName)); } public virtual VirtualPath ImageDirectoryUrl(Blog blog) { return ResolveUrl(GetImageDirectoryTildePath(blog)); } /// <summary> /// Returns the physical gallery path for the specified category. /// </summary> public virtual string GalleryDirectoryPath(Blog blog, int categoryId) { string path = ImageGalleryDirectoryUrl(blog, categoryId); return HttpContext.Server.MapPath(path); } public virtual string ImageDirectoryPath(Blog blog) { return HttpContext.Server.MapPath(ImageDirectoryUrl(blog)); } /// <summary> /// Returns the URL to a page that displays an image within a gallery. /// </summary> /// <param name="image"></param> /// <returns></returns> public virtual VirtualPath GalleryImagePageUrl(Image image) { if(image == null) { throw new ArgumentNullException("image"); } var routeValues = GetRouteValuesWithSubfolder(image.Blog.Subfolder) ?? new RouteValueDictionary(); routeValues.Add("id", image.ImageID); return GetVirtualPath("gallery-image", routeValues); } public virtual VirtualPath ImageGalleryDirectoryUrl(Blog blog, int galleryId) { var image = new Image {Blog = blog, CategoryID = galleryId}; string imageUrl = GalleryImageUrl(image, string.Empty); if(!imageUrl.EndsWith("/")) { imageUrl += "/"; } return imageUrl; } public virtual VirtualPath GalleryUrl(int id) { return GetVirtualPath("gallery", new RouteValueDictionary{{"id", id}}); } public virtual VirtualPath GalleryUrl(Image image) { var routeValues = GetRouteValuesWithSubfolder(image.Blog.Subfolder) ?? new RouteValueDictionary(); routeValues.Add("id", image.CategoryID); return GetVirtualPath("gallery", routeValues); } public virtual VirtualPath AggBugUrl(int id) { return GetVirtualPath("aggbug", new RouteValueDictionary { { "id", id } }); } public virtual VirtualPath ResolveUrl(string virtualPath) { return RequestContext.HttpContext.ExpandTildePath(virtualPath); } public virtual VirtualPath BlogUrl() { string vp = GetVirtualPath("root", null); return BlogUrl(vp); } public virtual VirtualPath BlogUrl(Blog blog) { if(String.IsNullOrEmpty(blog.Subfolder)) { return BlogUrl(); } string vp = GetVirtualPath("root", GetRouteValuesWithSubfolder(blog.Subfolder)); return BlogUrl(vp); } private static VirtualPath BlogUrl(string virtualPath) { if(!(virtualPath ?? string.Empty).EndsWith("/")) { virtualPath += "/"; } if(!HttpRuntime.UsingIntegratedPipeline) { virtualPath += "default.aspx"; } return virtualPath; } public virtual VirtualPath ContactFormUrl() { return GetVirtualPath("contact", null); } public virtual VirtualPath SearchPageUrl() { return GetVirtualPath("search", null); } public virtual VirtualPath SearchPageUrl(string keywords) { return GetVirtualPath("search", new { q = keywords }); } public virtual VirtualPath MonthUrl(DateTime dateTime) { var routeValues = new RouteValueDictionary { { "year", dateTime.ToString("yyyy", CultureInfo.InvariantCulture) }, { "month", dateTime.ToString("MM", CultureInfo.InvariantCulture) } }; return GetVirtualPath("entries-by-month", routeValues); } public virtual VirtualPath CommentApiUrl(int entryId) { return GetVirtualPath("comment-api", new RouteValueDictionary { { "id", entryId } }); } public virtual VirtualPath CommentRssUrl(int entryId) { return GetVirtualPath("comment-rss", new RouteValueDictionary { { "id", entryId } }); } public virtual VirtualPath TrackbacksUrl(int entryId) { return GetVirtualPath("trackbacks", new RouteValueDictionary { { "id", entryId } }); } public virtual VirtualPath CategoryUrl(Category category) { var routeValues = new RouteValueDictionary {{"slug", category.Id}, {"categoryType", "category"}}; return GetVirtualPath("category", routeValues); } public virtual VirtualPath CategoryRssUrl(Category category) { return GetVirtualPath("rss", new RouteValueDictionary {{"catId", category.Id}}); } /// <summary> /// Returns the url for all posts on the day specified by the date /// </summary> /// <param name="date"></param> /// <returns></returns> public virtual VirtualPath DayUrl(DateTime date) { var routeValues = new RouteValueDictionary { { "year", date.ToString("yyyy", CultureInfo.InvariantCulture) }, { "month", date.ToString("MM", CultureInfo.InvariantCulture) }, { "day", date.ToString("dd", CultureInfo.InvariantCulture) } }; return GetVirtualPath("entries-by-day", routeValues); } /// <summary> /// Returns the url for all posts on the day specified by the date /// </summary> public virtual Uri RssUrl(Blog blog) { if(blog.RssProxyEnabled) { return RssProxyUrl(blog); } RouteValueDictionary routeValues = GetRouteValuesWithSubfolder(blog.Subfolder); return GetVirtualPath("rss", routeValues).ToFullyQualifiedUrl(blog); } /// <summary> /// Returns the url for all posts on the day specified by the date /// </summary> public virtual Uri AtomUrl(Blog blog) { if(blog.RssProxyEnabled) { return RssProxyUrl(blog); } return GetVirtualPath("atom", null).ToFullyQualifiedUrl(blog); } public virtual Uri RssProxyUrl(Blog blog) { //TODO: Store this in db. string feedburnerUrl = ConfigurationManager.AppSettings["FeedBurnerUrl"]; feedburnerUrl = String.IsNullOrEmpty(feedburnerUrl) ? "http://feedproxy.google.com/" : feedburnerUrl; return new Uri(new Uri(feedburnerUrl), blog.RssProxyUrl); } public virtual VirtualPath GetVirtualPath(string routeName, object routeValues) { RouteValueDictionary routeValueDictionary = null; if(routeValues is RouteValueDictionary) { routeValueDictionary = (RouteValueDictionary)routeValues; } if(routeValues != null) { routeValueDictionary = new RouteValueDictionary(routeValues); } return GetVirtualPath(routeName, routeValueDictionary); } public virtual VirtualPath GetVirtualPath(string routeName, RouteValueDictionary routeValues) { VirtualPathData virtualPath = Routes.GetVirtualPath(RequestContext, routeName, routeValues); if(virtualPath == null) { return null; } return virtualPath.VirtualPath; } public virtual VirtualPath LoginUrl() { return LoginUrl(null); } public virtual VirtualPath LoginUrl(string returnUrl) { RouteValueDictionary routeValues = null; if(!String.IsNullOrEmpty(returnUrl)) { routeValues = new RouteValueDictionary {{"ReturnUrl", returnUrl}}; } return GetVirtualPath("login", routeValues); } public virtual VirtualPath LogoutUrl() { return GetVirtualPath("logout", null); } public virtual VirtualPath ArchivesUrl() { return GetVirtualPath("archives", null); } public virtual VirtualPath AdminUrl(string path) { return AdminUrl(path, null); } public virtual VirtualPath AdminUrl(string path, object routeValues) { RouteValueDictionary routeValueDict = (routeValues as RouteValueDictionary) ?? new RouteValueDictionary(routeValues); return AdminUrl(path, routeValueDict); } public virtual VirtualPath HostAdminUrl(string path) { return ResolveUrl(string.Format("~/hostadmin/{0}", EnsureDefaultAspx(path))); } public virtual VirtualPath AdminUrl(string path, RouteValueDictionary routeValues) { return GetUrl("admin", path, routeValues); } private VirtualPath GetUrl(string directory, string path, RouteValueDictionary routeValues) { routeValues = routeValues ?? new RouteValueDictionary(); if(!HttpRuntime.UsingIntegratedPipeline) { path = EnsureDefaultAspx(path); } else { path = EnsureTrailingSlash(path); } routeValues.Add("pathinfo", path); return GetVirtualPath(directory, routeValues); } private static string EnsureDefaultAspx(string path) { if(!path.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) { if(path.Length > 0 && !path.EndsWith("/", StringComparison.Ordinal)) { path += "/"; } path += "default.aspx"; } return path; } private static string EnsureTrailingSlash(string path) { if(!path.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase) && !path.EndsWith("/", StringComparison.Ordinal)) { return path + "/"; } return path; } public virtual VirtualPath AdminRssUrl(string feedName) { return GetVirtualPath("admin-rss", new RouteValueDictionary{{"feedName", feedName}}); } public virtual Uri MetaWeblogApiUrl(Blog blog) { VirtualPath vp = GetVirtualPath("metaweblogapi", null); return vp.ToFullyQualifiedUrl(blog); } public virtual Uri RsdUrl(Blog blog) { VirtualPath vp = GetVirtualPath("rsd", null); return vp.ToFullyQualifiedUrl(blog); } public virtual VirtualPath WlwManifestUrl() { VirtualPath vp = GetVirtualPath("wlwmanifest", null); return vp; } public virtual VirtualPath OpenSearchDescriptorUrl() { VirtualPath vp = GetVirtualPath("opensearchdesc", null); return vp; } public virtual VirtualPath CustomCssUrl() { return GetVirtualPath("customcss", null); } public virtual VirtualPath EditIconUrl() { return AppRoot() + "images/icons/edit.gif"; } public virtual VirtualPath TagUrl(string tagName) { return GetVirtualPath("tag", new RouteValueDictionary{{"tag", tagName.Replace("#", "{:#:}")}}); } public virtual VirtualPath TagCloudUrl() { return GetVirtualPath("tag-cloud", null); } public virtual VirtualPath IdenticonUrl(int code) { return GetVirtualPath("identicon", new RouteValueDictionary{{"code", code}}); } private static RouteValueDictionary GetRouteValuesWithSubfolder(string subfolder) { if(String.IsNullOrEmpty(subfolder)) { return null; } return new RouteValueDictionary {{"subfolder", subfolder}}; } public virtual VirtualPath Logout() { return GetVirtualPath("logout", new RouteValueDictionary {{"action", "logout"}, {"controller", "account"}}); } // Code inspidered from this article: http://dotnetperls.com/google-query public static string ExtractKeywordsFromReferrer(Uri referrer, Uri currentPath) { if(referrer.Host == currentPath.Host) return string.Empty; string u = referrer.OriginalString.ToLower(); //This looks for parameters named q (Google, Bing, possibly others) int start = u.IndexOf("&q=", StringComparison.Ordinal); int length = 3; if (start == -1) { start = u.IndexOf("q=", StringComparison.Ordinal); length = 2; } //This looks for parameters named p (Yahoo) if (start == -1) { start = u.IndexOf("p=", StringComparison.Ordinal); length = 2; } //Nothing found if (start == -1) { return string.Empty; } //Get Keywords start += length; int end = u.IndexOf('&', start); if (end == -1) { end = u.Length; } string sub = u.Substring(start, end - start); string result = HttpUtility.UrlDecode(sub); result = StripUnwantedClauses(result); return result; } private static string StripUnwantedClauses(string result) { Regex regex = new Regex(@"(^|\s)site:http(s?)://[\w|.|/|?]*(\s|$)", RegexOptions.IgnoreCase | RegexOptions.Compiled); return regex.Replace(result, ""); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // DateTimeFormatInfoScanner // // Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse() // // The data includes: // // DateWords: such as "de" used in es-ES (Spanish) LongDatePattern. // Postfix: such as "ta" used in fi-FI after the month name. // // This class is shared among mscorlib.dll and sysglobl.dll. // Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between // methods for mscorlib.dll and sysglobl.dll. // //////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Text; namespace System.Globalization { // // from LocaleEx.txt header // //; IFORMATFLAGS //; Parsing/formatting flags. internal enum FORMATFLAGS { None = 0x00000000, UseGenitiveMonth = 0x00000001, UseLeapYearMonth = 0x00000002, UseSpacesInMonthNames = 0x00000004, UseHebrewParsing = 0x00000008, UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names. UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers. } internal enum CalendarId : ushort { UNINITIALIZED_VALUE = 0, GREGORIAN = 1, // Gregorian (localized) calendar GREGORIAN_US = 2, // Gregorian (U.S.) calendar JAPAN = 3, // Japanese Emperor Era calendar /* SSS_WARNINGS_OFF */ TAIWAN = 4, // Taiwan Era calendar /* SSS_WARNINGS_ON */ KOREA = 5, // Korean Tangun Era calendar HIJRI = 6, // Hijri (Arabic Lunar) calendar THAI = 7, // Thai calendar HEBREW = 8, // Hebrew (Lunar) calendar GREGORIAN_ME_FRENCH = 9, // Gregorian Middle East French calendar GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar GREGORIAN_XLIT_FRENCH = 12, // Note that all calendars after this point are MANAGED ONLY for now. JULIAN = 13, JAPANESELUNISOLAR = 14, CHINESELUNISOLAR = 15, SAKA = 16, // reserved to match Office but not implemented in our code LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code KOREANLUNISOLAR = 20, TAIWANLUNISOLAR = 21, PERSIAN = 22, UMALQURA = 23, LAST_CALENDAR = 23 // Last calendar ID } internal class DateTimeFormatInfoScanner { // Special prefix-like flag char in DateWord array. // Use char in PUA area since we won't be using them in real data. // The char used to tell a read date word or a month postfix. A month postfix // is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI. // In this case, it will be stored as "\xfffeta" in the date word array. internal const char MonthPostfixChar = '\xe000'; // Add ignorable symbol in a DateWord array. // hu-HU has: // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd // long date pattern: yyyy. MMMM d. // Here, "." is the date separator (derived from short date pattern). However, // "." also appear at the end of long date pattern. In this case, we just // "." as ignorable symbol so that the DateTime.Parse() state machine will not // treat the additional date separator at the end of y,m,d pattern as an error // condition. internal const char IgnorableSymbolChar = '\xe001'; // Known CJK suffix internal const String CJKYearSuff = "\u5e74"; internal const String CJKMonthSuff = "\u6708"; internal const String CJKDaySuff = "\u65e5"; internal const String KoreanYearSuff = "\ub144"; internal const String KoreanMonthSuff = "\uc6d4"; internal const String KoreanDaySuff = "\uc77c"; internal const String KoreanHourSuff = "\uc2dc"; internal const String KoreanMinuteSuff = "\ubd84"; internal const String KoreanSecondSuff = "\ucd08"; internal const String CJKHourSuff = "\u6642"; internal const String ChineseHourSuff = "\u65f6"; internal const String CJKMinuteSuff = "\u5206"; internal const String CJKSecondSuff = "\u79d2"; // The collection fo date words & postfix. internal List<string> m_dateWords = new List<string>(); // Hashtable for the known words. private static volatile Dictionary<string, string> s_knownWords; static Dictionary<string, string> KnownWords { get { if (s_knownWords == null) { Dictionary<string, string> temp = new Dictionary<string, string>(); // Add known words into the hash table. // Skip these special symbols. temp.Add("/", String.Empty); temp.Add("-", String.Empty); temp.Add(".", String.Empty); // Skip known CJK suffixes. temp.Add(CJKYearSuff, String.Empty); temp.Add(CJKMonthSuff, String.Empty); temp.Add(CJKDaySuff, String.Empty); temp.Add(KoreanYearSuff, String.Empty); temp.Add(KoreanMonthSuff, String.Empty); temp.Add(KoreanDaySuff, String.Empty); temp.Add(KoreanHourSuff, String.Empty); temp.Add(KoreanMinuteSuff, String.Empty); temp.Add(KoreanSecondSuff, String.Empty); temp.Add(CJKHourSuff, String.Empty); temp.Add(ChineseHourSuff, String.Empty); temp.Add(CJKMinuteSuff, String.Empty); temp.Add(CJKSecondSuff, String.Empty); s_knownWords = temp; } return (s_knownWords); } } //////////////////////////////////////////////////////////////////////////// // // Parameters: // pattern: The pattern to be scanned. // currentIndex: the current index to start the scan. // // Returns: // Return the index with the first character that is a letter, which will // be the start of a date word. // Note that the index can be pattern.Length if we reach the end of the string. // //////////////////////////////////////////////////////////////////////////// internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex) { while (currentIndex < pattern.Length) { char ch = pattern[currentIndex]; if (ch == '\\') { // Escaped character. Look ahead one character. currentIndex++; if (currentIndex < pattern.Length) { ch = pattern[currentIndex]; if (ch == '\'') { // Skip the leading single quote. We will // stop at the first letter. continue; } // Fall thru to check if this is a letter. } else { // End of string break; } } if (Char.IsLetter(ch) || ch == '\'' || ch == '.') { break; } // Skip the current char since it is not a letter. currentIndex++; } return (currentIndex); } //////////////////////////////////////////////////////////////////////////// // // A helper to add the found date word or month postfix into ArrayList for date words. // // Parameters: // formatPostfix: What kind of postfix this is. // Possible values: // null: This is a regular date word // "MMMM": month postfix // word: The date word or postfix to be added. // //////////////////////////////////////////////////////////////////////////// internal void AddDateWordOrPostfix(String formatPostfix, String str) { if (str.Length > 0) { // Some cultures use . like an abbreviation if (str.Equals(".")) { AddIgnorableSymbols("."); return; } String words; if (KnownWords.TryGetValue(str, out words) == false) { if (m_dateWords == null) { m_dateWords = new List<string>(); } if (formatPostfix == "MMMM") { // Add the word into the ArrayList as "\xfffe" + real month postfix. String temp = MonthPostfixChar + str; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); } } else { if (!m_dateWords.Contains(str)) { m_dateWords.Add(str); } if (str[str.Length - 1] == '.') { // Old version ignore the trialing dot in the date words. Support this as well. String strWithoutDot = str.Substring(0, str.Length - 1); if (!m_dateWords.Contains(strWithoutDot)) { m_dateWords.Add(strWithoutDot); } } } } } } //////////////////////////////////////////////////////////////////////////// // // Scan the pattern from the specified index and add the date word/postfix // when appropriate. // // Parameters: // pattern: The pattern to be scanned. // index: The starting index to be scanned. // formatPostfix: The kind of postfix to be scanned. // Possible values: // null: This is a regular date word // "MMMM": month postfix // // //////////////////////////////////////////////////////////////////////////// internal int AddDateWords(String pattern, int index, String formatPostfix) { // Skip any whitespaces so we will start from a letter. int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index); if (newIndex != index && formatPostfix != null) { // There are whitespaces. This will not be a postfix. formatPostfix = null; } index = newIndex; // This is the first char added into dateWord. // Skip all non-letter character. We will add the first letter into DateWord. StringBuilder dateWord = new StringBuilder(); // We assume that date words should start with a letter. // Skip anything until we see a letter. while (index < pattern.Length) { char ch = pattern[index]; if (ch == '\'') { // We have seen the end of quote. Add the word if we do not see it before, // and break the while loop. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); index++; break; } else if (ch == '\\') { // // Escaped character. Look ahead one character // // Skip escaped backslash. index++; if (index < pattern.Length) { dateWord.Append(pattern[index]); index++; } } else if (Char.IsWhiteSpace(ch)) { // Found a whitespace. We have to add the current date word/postfix. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); if (formatPostfix != null) { // Done with postfix. The rest will be regular date word. formatPostfix = null; } // Reset the dateWord. dateWord.Length = 0; index++; } else { dateWord.Append(ch); index++; } } return (index); } //////////////////////////////////////////////////////////////////////////// // // A simple helper to find the repeat count for a specified char. // //////////////////////////////////////////////////////////////////////////// internal static int ScanRepeatChar(String pattern, char ch, int index, out int count) { count = 1; while (++index < pattern.Length && pattern[index] == ch) { count++; } // Return the updated position. return (index); } //////////////////////////////////////////////////////////////////////////// // // Add the text that is a date separator but is treated like ignroable symbol. // E.g. // hu-HU has: // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd // long date pattern: yyyy. MMMM d. // Here, "." is the date separator (derived from short date pattern). However, // "." also appear at the end of long date pattern. In this case, we just // "." as ignorable symbol so that the DateTime.Parse() state machine will not // treat the additional date separator at the end of y,m,d pattern as an error // condition. // //////////////////////////////////////////////////////////////////////////// internal void AddIgnorableSymbols(String text) { if (m_dateWords == null) { // Create the date word array. m_dateWords = new List<string>(); } // Add the ignorable symbol into the ArrayList. String temp = IgnorableSymbolChar + text; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); } } // // Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen. // private enum FoundDatePattern { None = 0x0000, FoundYearPatternFlag = 0x0001, FoundMonthPatternFlag = 0x0002, FoundDayPatternFlag = 0x0004, FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag; } // Check if we have found all of the year/month/day pattern. private FoundDatePattern _ymdFlags = FoundDatePattern.None; //////////////////////////////////////////////////////////////////////////// // // Given a date format pattern, scan for date word or postfix. // // A date word should be always put in a single quoted string. And it will // start from a letter, so whitespace and symbols will be ignored before // the first letter. // // Examples of date word: // 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy // "\x0443." in bg-BG: dd.M.yyyy '\x0433.' // // Example of postfix: // month postfix: // "ta" in fi-FI: d. MMMM'ta 'yyyy // Currently, only month postfix is supported. // // Usage: // Always call this with Framework-style pattern, instead of Windows style pattern. // Windows style pattern uses '' for single quote, while .NET uses \' // //////////////////////////////////////////////////////////////////////////// internal void ScanDateWord(String pattern) { // Check if we have found all of the year/month/day pattern. _ymdFlags = FoundDatePattern.None; int i = 0; while (i < pattern.Length) { char ch = pattern[i]; int chCount; switch (ch) { case '\'': // Find a beginning quote. Search until the end quote. i = AddDateWords(pattern, i + 1, null); break; case 'M': i = ScanRepeatChar(pattern, 'M', i, out chCount); if (chCount >= 4) { if (i < pattern.Length && pattern[i] == '\'') { i = AddDateWords(pattern, i + 1, "MMMM"); } } _ymdFlags |= FoundDatePattern.FoundMonthPatternFlag; break; case 'y': i = ScanRepeatChar(pattern, 'y', i, out chCount); _ymdFlags |= FoundDatePattern.FoundYearPatternFlag; break; case 'd': i = ScanRepeatChar(pattern, 'd', i, out chCount); if (chCount <= 2) { // Only count "d" & "dd". // ddd, dddd are day names. Do not count them. _ymdFlags |= FoundDatePattern.FoundDayPatternFlag; } break; case '\\': // Found a escaped char not in a quoted string. Skip the current backslash // and its next character. i += 2; break; case '.': if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag) { // If we find a dot immediately after the we have seen all of the y, m, d pattern. // treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for // more details. AddIgnorableSymbols("."); _ymdFlags = FoundDatePattern.None; } i++; break; default: if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch)) { // We are not seeing "." after YMD. Clear the flag. _ymdFlags = FoundDatePattern.None; } // We are not in quote. Skip the current character. i++; break; } } } //////////////////////////////////////////////////////////////////////////// // // Given a DTFI, get all of the date words from date patterns and time patterns. // //////////////////////////////////////////////////////////////////////////// internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) { // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix. String[] datePatterns = dtfi.GetAllDateTimePatterns('D'); int i; // Scan the long date patterns for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the short date patterns datePatterns = dtfi.GetAllDateTimePatterns('d'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the YearMonth patterns. datePatterns = dtfi.GetAllDateTimePatterns('y'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the month/day pattern ScanDateWord(dtfi.MonthDayPattern); // Scan the long time patterns. datePatterns = dtfi.GetAllDateTimePatterns('T'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the short time patterns. datePatterns = dtfi.GetAllDateTimePatterns('t'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } String[] result = null; if (m_dateWords != null && m_dateWords.Count > 0) { result = new String[m_dateWords.Count]; for (i = 0; i < m_dateWords.Count; i++) { result[i] = m_dateWords[i]; } } return (result); } //////////////////////////////////////////////////////////////////////////// // // Scan the month names to see if genitive month names are used, and return // the format flag. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) { // If we have different names in regular and genitive month names, use genitive month flag. return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames)) ? FORMATFLAGS.UseGenitiveMonth : 0); } //////////////////////////////////////////////////////////////////////////// // // Scan the month names to see if spaces are used or start with a digit, and return the format flag // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) { FORMATFLAGS formatFlags = 0; formatFlags |= (ArrayElementsBeginWithDigit(monthNames) || ArrayElementsBeginWithDigit(genitveMonthNames) || ArrayElementsBeginWithDigit(abbrevMonthNames) || ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames) ? FORMATFLAGS.UseDigitPrefixInTokens : 0); formatFlags |= (ArrayElementsHaveSpace(monthNames) || ArrayElementsHaveSpace(genitveMonthNames) || ArrayElementsHaveSpace(abbrevMonthNames) || ArrayElementsHaveSpace(genetiveAbbrevMonthNames) ? FORMATFLAGS.UseSpacesInMonthNames : 0); return (formatFlags); } //////////////////////////////////////////////////////////////////////////// // // Scan the day names and set the correct format flag. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames) { return ((ArrayElementsHaveSpace(dayNames) || ArrayElementsHaveSpace(abbrevDayNames)) ? FORMATFLAGS.UseSpacesInDayNames : 0); } //////////////////////////////////////////////////////////////////////////// // // Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID) { return (calID == (int)CalendarId.HEBREW ? FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0); } //----------------------------------------------------------------------------- // EqualStringArrays // compares two string arrays and return true if all elements of the first // array equals to all elmentsof the second array. // otherwise it returns false. //----------------------------------------------------------------------------- private static bool EqualStringArrays(string[] array1, string[] array2) { // Shortcut if they're the same array if (array1 == array2) { return true; } // This is effectively impossible if (array1.Length != array2.Length) { return false; } // Check each string for (int i = 0; i < array1.Length; i++) { if (!array1[i].Equals(array2[i])) { return false; } } return true; } //----------------------------------------------------------------------------- // ArrayElementsHaveSpace // It checks all input array elements if any of them has space character // returns true if found space character in one of the array elements. // otherwise returns false. //----------------------------------------------------------------------------- private static bool ArrayElementsHaveSpace(string[] array) { for (int i = 0; i < array.Length; i++) { // it is faster to check for space character manually instead of calling IndexOf // so we don't have to go to native code side. for (int j = 0; j < array[i].Length; j++) { if (Char.IsWhiteSpace(array[i][j])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////// // // Check if any element of the array start with a digit. // //////////////////////////////////////////////////////////////////////////// private static bool ArrayElementsBeginWithDigit(string[] array) { for (int i = 0; i < array.Length; i++) { // it is faster to check for space character manually instead of calling IndexOf // so we don't have to go to native code side. if (array[i].Length > 0 && array[i][0] >= '0' && array[i][0] <= '9') { int index = 1; while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9') { // Skip other digits. index++; } if (index == array[i].Length) { return (false); } if (index == array[i].Length - 1) { // Skip known CJK month suffix. // CJK uses month name like "1\x6708", since \x6708 is a known month suffix, // we don't need the UseDigitPrefixInTokens since it is slower. switch (array[i][index]) { case '\x6708': // CJKMonthSuff case '\xc6d4': // KoreanMonthSuff return (false); } } if (index == array[i].Length - 4) { // Skip known CJK month suffix. // Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'" // instead of just "1\x6708" if (array[i][index] == '\'' && array[i][index + 1] == ' ' && array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'') { return (false); } } return (true); } } return false; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using Newtonsoft.Json; namespace AFNN { using static Math; public class NeuralNetwork { private delegate void PrepEventHandler(bool Preperation); private delegate void StepEventHandler(ref ListDictionary Neurons, ref ListDictionary InputData); private event StepEventHandler Step; private event PrepEventHandler Prep; private ListDictionary Neurons { get; set; } private ListDictionary InputData { get; set; } private List<int> InputNeurons { get; set; } private List<int> OutputNeurons { get; set; } public double LearningParameter { get; set; } public double MaxError { get; set; } private IThreshold Threshold { get; set; } #region Constructors public NeuralNetwork(int Neurons, IThreshold Threshold, IList<int> OutputNeurons, IList<int> InputNeurons, double LearningParameter, double MaxError) { this.OutputNeurons = (List<int>)OutputNeurons; this.InputNeurons = (List<int>)InputNeurons; this.LearningParameter = LearningParameter; this.Threshold = Threshold; this.MaxError = MaxError; Parallel.For(0, Neurons, I => { Neuron N = new Neuron(I, Threshold); Prep += new PrepEventHandler(N.Prep); Step += new StepEventHandler(N.IaF); this.Neurons.Add(I, N); }); } public NeuralNetwork(double[,] WeightMatrix, IThreshold Threshold, IList<int> OutputNeurons, IList<int> InputNeurons, double LearningParameter, double MaxError) { this.OutputNeurons = (List<int>)OutputNeurons; this.InputNeurons = (List<int>)InputNeurons; this.LearningParameter = LearningParameter; this.Threshold = Threshold; this.MaxError = MaxError; int n = WeightMatrix.GetLength(0); if (n.Equals(WeightMatrix.GetLength(1))) { Parallel.For(0, n, I => { Neuron N = new Neuron(I, Threshold); Prep += new PrepEventHandler(N.Prep); Step += new StepEventHandler(N.IaF); for (int i = 0; i < n; i++) { if (WeightMatrix[i, I] != 0) { N.Weights.Add(i, WeightMatrix[i, I]); } } this.Neurons.Add(I, N); }); } else { throw new ArgumentException(); } } #endregion public void ComputeStep(ListDictionary InputData = null) { ListDictionary _InputData = InputData ?? this.InputData; ListDictionary _Neurons = Neurons; Step(ref _Neurons, ref _InputData); Prep(true); } public void ComputeStepParallel(ListDictionary InputData = null) { ListDictionary _InputData = InputData ?? this.InputData; ListDictionary _Neurons = Neurons; Parallel.ForEach((StepEventHandler[])Step.GetInvocationList(), e => e.Invoke(ref _Neurons, ref _InputData)); Parallel.ForEach((PrepEventHandler[])Prep.GetInvocationList(), e => e.Invoke(true)); } public void TrainStep(ListDictionary RequestedResult, ListDictionary InputData, int Cycles = 1) { ListDictionary _InputData = InputData ?? this.InputData; ListDictionary _Neurons = Neurons; Step(ref _Neurons, ref _InputData); Prep(false); List<int> Processed = new List<int>(OutputNeurons); Queue<int> NeuronQ = new Queue<int>(OutputNeurons); double delta = 0; int I = 0; while (NeuronQ.Any()) { I = NeuronQ.Dequeue(); if (RequestedResult.Contains(I) && Abs((double)RequestedResult[I] - ((Neuron)Neurons[I]).R1) > MaxError) { foreach (int i in ((Neuron)Neurons[I]).Weights.Keys) { delta = ((Neuron)Neurons[I]).Threshold.Derivative(((Neuron)Neurons[I]).R0 * ((Neuron)Neurons[I]).Weights[i]) * ((double)RequestedResult[I] - ((Neuron)Neurons[I]).R1); ((Neuron)Neurons[I]).Weights[i] += LearningParameter * delta * ((Neuron)Neurons[I]).R1; ((Neuron)Neurons[I]).R0 += ((Neuron)Neurons[I]).Weights[i] * delta; if (!Processed.Contains(i)) { NeuronQ.Enqueue(i); Processed.Add(i); } } } else { foreach (int i in ((Neuron)Neurons[I]).Weights.Keys) { delta = ((Neuron)Neurons[I]).Threshold.Derivative(((Neuron)Neurons[I]).R0 * ((Neuron)Neurons[I]).Weights[i]) * ((Neuron)Neurons[I]).R0; ((Neuron)Neurons[I]).Weights[i] += LearningParameter * delta * ((Neuron)Neurons[I]).R1; ((Neuron)Neurons[I]).R0 += ((Neuron)Neurons[I]).Weights[i] * delta; if (!Processed.Contains(i)) { NeuronQ.Enqueue(i); Processed.Add(i); } } } } Prep(true); } public void TrainStepParallel(ListDictionary RequestedResult, ListDictionary InputData, int Cycles = 1) { ListDictionary _InputData = InputData ?? this.InputData; ListDictionary _Neurons = Neurons; Parallel.ForEach((StepEventHandler[])Step.GetInvocationList(), e => e.Invoke(ref _Neurons, ref _InputData)); Parallel.ForEach((PrepEventHandler[])Prep.GetInvocationList(), e => e.Invoke(false)); List<int> Processed = new List<int>(OutputNeurons); Queue<int> Neuron0 = new Queue<int>(OutputNeurons); Queue<int> Neuron1 = new Queue<int>(); double delta = 0; while (Neuron0.Any()) { Parallel.For(0, Neuron0.Count, n => { int I = Neuron0.Dequeue(); if (RequestedResult.Contains(I) && Abs((double)RequestedResult[I] - ((Neuron)Neurons[I]).R1) > MaxError) { foreach (int i in ((Neuron)Neurons[I]).Weights.Keys) { delta = ((Neuron)Neurons[I]).Threshold.Derivative(((Neuron)Neurons[I]).R0 * ((Neuron)Neurons[I]).Weights[i]) * ((double)RequestedResult[I] - ((Neuron)Neurons[I]).R1); ((Neuron)Neurons[I]).Weights[i] += LearningParameter * delta * ((Neuron)Neurons[I]).R1; ((Neuron)Neurons[I]).R0 += ((Neuron)Neurons[I]).Weights[i] * delta; if (!Processed.Contains(i)) { Neuron1.Enqueue(i); Processed.Add(i); } } } else { foreach (int i in ((Neuron)Neurons[I]).Weights.Keys) { delta = ((Neuron)Neurons[I]).Threshold.Derivative(((Neuron)Neurons[I]).R0 * ((Neuron)Neurons[I]).Weights[i]) * ((Neuron)Neurons[I]).R0; ((Neuron)Neurons[I]).Weights[i] += LearningParameter * delta * ((Neuron)Neurons[I]).R1; ((Neuron)Neurons[I]).R0 += ((Neuron)Neurons[I]).Weights[i] * delta; if (!Processed.Contains(i)) { Neuron1.Enqueue(i); Processed.Add(i); } } } }); Neuron0 = Neuron1; } Parallel.ForEach((PrepEventHandler[])Prep.GetInvocationList(), e => e.Invoke(true)); } #region Maintenance public void AddNeuron(double BiasValue, Dictionary<int, double> Weights, IThreshold Threshold = null) { int I = Neurons.Count; while (Neurons.Contains(I)) { I++; }; Neuron N = new Neuron(I, Threshold); N.Threshold = Threshold ?? this.Threshold; N.Weights = Weights; Neurons.Add(I, N); Prep += new PrepEventHandler(N.Prep); Step += new StepEventHandler(N.IaF); } public void RemoveNeuron(int ID) { Prep -= ((Neuron)Neurons[ID]).Prep; Step -= ((Neuron)Neurons[ID]).IaF; Neurons.Remove(ID); Neurons.Values.OfType<Neuron>() .Where(e => e.Weights.ContainsKey(ID)) .AsParallel().ForAll(e => { e.Weights.Remove(ID); }); } public void Reduce() { Parallel.ForEach(Neurons.Keys.OfType<int>(), I => { ((Neuron)Neurons[I]).Weights.Where(e => e.Value.Equals(0)).Select(e => e.Key).ToList().ForEach(e => { ((Neuron)Neurons[I]).Weights.Remove(e); }); }); } #endregion #region Output public List<double> GetListOutput() { List<double> Output = new List<double>(OutputNeurons.Count); foreach (int i in OutputNeurons) { Output.Add(((Neuron)Neurons[i]).R0); } return Output; } public double[] GetArrayOutput() { double[] Output = new double[OutputNeurons.Count]; for (int i = 0; i < OutputNeurons.Count; i++) { Output[i] = ((Neuron)Neurons[OutputNeurons[i]]).R0; } return Output; } #endregion } public class Neuron { public int ID { get; set; } public double BV { get; set; } = 0; public double R0 { get; set; } = 0; public double R1 { get; set; } = 0; public IThreshold Threshold { get; set; } public Dictionary<int, double> Weights { get; set; } = new Dictionary<int, double>(); public Neuron(int ID, IThreshold Threshold) { this.Threshold = Threshold; this.ID = ID; } public void IaF(ref ListDictionary Neurons, ref ListDictionary InputData) { R1 = BV + ((double)InputData[ID]); foreach (KeyValuePair<int, double> e in Weights) { R1 += ((Neuron)Neurons[e.Key]).R0 * e.Value; } R1 = Threshold.Function(R1); } public void Prep(bool Preperation) { R0 = Preperation ? R1 : 0; } public override string ToString() { return JsonConvert.SerializeObject(this); } } public interface IThreshold { double Function(double X); double Derivative(double X); } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Diagnostics; using System.Globalization; using System.Text; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.Internal.Web.Utils; namespace Microsoft.AspNet.Razor.Text { public struct TextChange { private string _newText; private string _oldText; /// <summary> /// Constructor for changes where the position hasn't moved (primarily for tests) /// </summary> internal TextChange(int position, int oldLength, ITextBuffer oldBuffer, int newLength, ITextBuffer newBuffer) : this(position, oldLength, oldBuffer, position, newLength, newBuffer) { } public TextChange(int oldPosition, int oldLength, ITextBuffer oldBuffer, int newPosition, int newLength, ITextBuffer newBuffer) : this() { if (oldPosition < 0) { throw new ArgumentOutOfRangeException("oldPosition", string.Format(CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0)); } if (newPosition < 0) { throw new ArgumentOutOfRangeException("newPosition", string.Format(CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0)); } if (oldLength < 0) { throw new ArgumentOutOfRangeException("oldLength", string.Format(CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0)); } if (newLength < 0) { throw new ArgumentOutOfRangeException("newLength", string.Format(CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0)); } if (oldBuffer == null) { throw new ArgumentNullException("oldBuffer"); } if (newBuffer == null) { throw new ArgumentNullException("newBuffer"); } OldPosition = oldPosition; NewPosition = newPosition; OldLength = oldLength; NewLength = newLength; NewBuffer = newBuffer; OldBuffer = oldBuffer; } public int OldPosition { get; private set; } public int NewPosition { get; private set; } public int OldLength { get; private set; } public int NewLength { get; private set; } public ITextBuffer NewBuffer { get; private set; } public ITextBuffer OldBuffer { get; private set; } /// <remark> /// Note: This property is not thread safe, and will move position on the textbuffer while being read. /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access /// to ITextBuffer to be thread safe. /// </remark> public string OldText { get { if (_oldText == null && OldBuffer != null) { _oldText = GetText(OldBuffer, OldPosition, OldLength); } return _oldText; } } /// <remark> /// Note: This property is not thread safe, and will move position on the textbuffer while being read. /// https://aspnetwebstack.codeplex.com/workitem/1317, tracks making this immutable and improving the access /// to ITextBuffer to be thread safe. /// </remark> public string NewText { get { if (_newText == null) { _newText = GetText(NewBuffer, NewPosition, NewLength); } return _newText; } } public bool IsInsert { get { return OldLength == 0 && NewLength > 0; } } public bool IsDelete { get { return OldLength > 0 && NewLength == 0; } } public bool IsReplace { get { return OldLength > 0 && NewLength > 0; } } public override bool Equals(object obj) { if (!(obj is TextChange)) { return false; } TextChange change = (TextChange)obj; return (change.OldPosition == OldPosition) && (change.NewPosition == NewPosition) && (change.OldLength == OldLength) && (change.NewLength == NewLength) && OldBuffer.Equals(change.OldBuffer) && NewBuffer.Equals(change.NewBuffer); } public string ApplyChange(string content, int changeOffset) { int changeRelativePosition = OldPosition - changeOffset; Debug.Assert(changeRelativePosition >= 0); return content.Remove(changeRelativePosition, OldLength) .Insert(changeRelativePosition, NewText); } /// <summary> /// Applies the text change to the content of the span and returns the new content. /// This method doesn't update the span content. /// </summary> public string ApplyChange(Span span) { return ApplyChange(span.Content, span.Start.AbsoluteIndex); } public override int GetHashCode() { return OldPosition ^ NewPosition ^ OldLength ^ NewLength ^ NewBuffer.GetHashCode() ^ OldBuffer.GetHashCode(); } public override string ToString() { return String.Format(CultureInfo.CurrentCulture, "({0}:{1}) \"{3}\" -> ({0}:{2}) \"{4}\"", OldPosition, OldLength, NewLength, OldText, NewText); } /// <summary> /// Removes a common prefix from the edit to turn IntelliSense replacements into insertions where possible /// </summary> /// <returns>A normalized text change</returns> public TextChange Normalize() { if (OldBuffer != null && IsReplace && NewLength > OldLength && NewText.StartsWith(OldText, StringComparison.Ordinal) && NewPosition == OldPosition) { // Normalize the change into an insertion of the uncommon suffix (i.e. strip out the common prefix) return new TextChange(oldPosition: OldPosition + OldLength, oldLength: 0, oldBuffer: OldBuffer, newPosition: OldPosition + OldLength, newLength: NewLength - OldLength, newBuffer: NewBuffer); } return this; } private static string GetText(ITextBuffer buffer, int position, int length) { // Optimization for the common case of one char inserts, in this case we don't even need to seek the buffer. if (length == 0) { return String.Empty; } int oldPosition = buffer.Position; try { buffer.Position = position; // Optimization for the common case of one char inserts, in this case we seek the buffer. if (length == 1) { return ((char)buffer.Read()).ToString(); } else { var builder = new StringBuilder(); for (int i = 0; i < length; i++) { char c = (char)buffer.Read(); builder.Append(c); // This check is probably not necessary, will revisit when fixing https://aspnetwebstack.codeplex.com/workitem/1317 if (Char.IsHighSurrogate(c)) { builder.Append((char)buffer.Read()); } } return builder.ToString(); } } finally { buffer.Position = oldPosition; } } public static bool operator ==(TextChange left, TextChange right) { return left.Equals(right); } public static bool operator !=(TextChange left, TextChange right) { return !left.Equals(right); } } }
//============================================================================= // System : Sandcastle Help File Builder // File : TopicEditorWindow.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 11/10/2009 // Note : Copyright 2008-2009, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the form used to edit the conceptual topic files. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.7 05/10/2008 EFW Created the code // 1.8.0.0 07/26/2008 EFW Reworked for use with the new project format //============================================================================= using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Windows.Forms; using SandcastleBuilder.Gui.Properties; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.ConceptualContent; using SandcastleBuilder.Utils.Design; using ICSharpCode.TextEditor; using ICSharpCode.TextEditor.Actions; using WeifenLuo.WinFormsUI.Docking; namespace SandcastleBuilder.Gui.ContentEditors { /// <summary> /// This form is used to edit a conceptual topic file. /// </summary> public partial class TopicEditorWindow : BaseContentEditor { #region Private data members //===================================================================== private ToolStripMenuItem lastAction; #endregion #region Properties //===================================================================== /// <summary> /// This returns the filename /// </summary> public string Filename { get { return this.ToolTipText; } } #endregion #region Constructor //===================================================================== /// <summary> /// Constructor /// </summary> /// <param name="filename">The filename to load</param> public TopicEditorWindow(string filename) { string ext; InitializeComponent(); // Connect the drag and drop events to the text area TextArea area = editor.ActiveTextAreaControl.TextArea; area.AllowDrop = true; area.DragEnter += new DragEventHandler(editor_DragEnter); area.DragDrop += new DragEventHandler(editor_DragDrop); editor.DragDrop += new DragEventHandler(editor_DragDrop); editor.PerformFindText += new EventHandler(editor_PerformFindText); editor.PerformReplaceText += new EventHandler(editor_PerformReplaceText); editor.TextEditorProperties.Font = Settings.Default.TextEditorFont; editor.TextEditorProperties.ShowLineNumbers = Settings.Default.ShowLineNumbers; try { editor.LoadFile(filename); ext = Path.GetExtension(filename).ToLower( CultureInfo.InvariantCulture); if(ext == ".aml" || ext == ".topic" || ext == ".snippets" || ext == ".tokens" || ext == ".content") editor.SetHighlighting("XML"); editor.TextChanged += new EventHandler(editor_TextChanged); this.Text = Path.GetFileName(filename); this.ToolTipText = filename; } catch(Exception ex) { this.Text = this.ToolTipText = "N/A"; MessageBox.Show("Unable to load file '" + filename + "'. Reason: " + ex.Message, "Topic Editor", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #endregion #region Method overrides //===================================================================== /// <inheritdoc /> public override bool CanClose { get { if(!this.IsDirty) return true; DialogResult dr = MessageBox.Show("Do you want to save your " + "changes to '" + this.ToolTipText + "? Click YES to " + "to save them, NO to discard them, or CANCEL to stay " + "here and make further changes.", "Topic Editor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3); if(dr == DialogResult.Cancel) return false; if(dr == DialogResult.Yes) { this.Save(); if(this.IsDirty) return false; } else this.IsDirty = false; // Don't ask again return true; } } /// <inheritdoc /> public override bool CanSaveContent { get { return true; } } /// <inheritdoc /> public override bool IsContentDocument { get { return true; } } /// <inheritdoc /> public override bool Save() { try { Cursor.Current = Cursors.WaitCursor; if(this.IsDirty) { editor.SaveFile(this.ToolTipText); this.Text = Path.GetFileName(this.ToolTipText); this.IsDirty = false; } return true; } catch(Exception ex) { MessageBox.Show("Unable to save file. Reason: " + ex.Message, "Topic Editor", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } finally { Cursor.Current = Cursors.Default; } } /// <inheritdoc /> public override bool SaveAs() { using(SaveFileDialog dlg = new SaveFileDialog()) { dlg.Title = "Save Content File As"; dlg.Filter = "Project Files (*.aml, *.htm*, *.css, *.js, " + "*.content, *.sitemap, *.snippets, *.tokens)|*.aml;" + "*.htm*;*.css;*.js;*.content;*.sitemap;*.tokens;" + "*.snippets|Content Files (*.aml, *.htm*)|*.aml;*.htm*|" + "Content Layout Files (*.content, *.sitemap)|" + "*.content;*.sitemap|All Files (*.*)|*.*"; dlg.DefaultExt = Path.GetExtension(this.ToolTipText); dlg.InitialDirectory = Directory.GetCurrentDirectory(); if(dlg.ShowDialog() == DialogResult.OK) return this.Save(dlg.FileName); } return false; } #endregion #region Helper methods //===================================================================== /// <summary> /// Update the font used based on the selected user settings /// </summary> public void UpdateFont() { editor.TextEditorProperties.Font = Settings.Default.TextEditorFont; editor.TextEditorProperties.ShowLineNumbers = Settings.Default.ShowLineNumbers; } /// <summary> /// Track the last used insert action and update the toolbar button /// </summary> /// <param name="element">The last used element</param> private void TrackLastInsertedElement(ToolStripMenuItem element) { if(element == null) element = miAlert; if(element != lastAction) { lastAction = element; tsbInsertElement.Text = lastAction.Text; tsbInsertElement.ToolTipText = lastAction.ToolTipText; } } /// <summary> /// Insert a link to a topic /// </summary> /// <param name="extension">The extension of the file in which the /// link is being inserted.</param> /// <param name="topic">The topic for which to create a link</param> /// <remarks>If dropped inside some selected text, the link will /// wrap the selected text.</remarks> private void InsertTopicLink(string extension, Topic topic) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = String.Empty; if(extension == ".htm" || extension == ".html") ContentEditorControl.InsertString(textArea, topic.ToAnchor(selectedText)); else ContentEditorControl.InsertString(textArea, topic.ToLink(selectedText)); } /// <summary> /// Insert a link to a site map table of contents entry (HTML only) /// </summary> /// <param name="extension">The extension of the file in which the /// link is being inserted.</param> /// <param name="tocEntry">The TOC entry for which to create a link</param> /// <remarks>If dropped inside some selected text, the link will /// wrap the selected text.</remarks> private void InsertTocLink(string extension, TocEntry tocEntry) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = String.Empty; if(extension == ".htm" || extension == ".html") ContentEditorControl.InsertString(textArea, tocEntry.ToAnchor(selectedText)); else ContentEditorControl.InsertString(textArea, tocEntry.Title); // Not supported in MAML topics } /// <summary> /// Save the topic to a new filename /// </summary> /// <param name="filename">The new filename</param> /// <returns>True if saved successfully, false if not</returns> /// <overloads>There are two overloads for this method</overloads> public bool Save(string filename) { this.Text = Path.GetFileName(filename); this.ToolTipText = filename; this.IsDirty = true; return this.Save(); } /// <summary> /// Paste text from the clipboard into the editor /// </summary> public void PasteFromClipboard() { editor.Execute(new PasteSpecial(editor)); } #endregion #region General event handlers //===================================================================== /// <summary> /// Mark the file as dirty when the text changes /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void editor_TextChanged(object sender, EventArgs e) { if(!this.IsDirty) { this.IsDirty = true; this.Text += "*"; } } /// <summary> /// This is overriden to prompt to save changes if necessary /// </summary> /// <param name="e">The event arguments</param> protected override void OnClosing(CancelEventArgs e) { e.Cancel = !this.CanClose; base.OnClosing(e); } #endregion #region Editor drag and drop handlers //===================================================================== /// <summary> /// This displays the drop cursor when the mouse drags into /// the editor. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void editor_DragEnter(object sender, DragEventArgs e) { if(e.Data.GetDataPresent(typeof(ImageReference)) || e.Data.GetDataPresent(typeof(Token)) || e.Data.GetDataPresent(typeof(Topic)) || e.Data.GetDataPresent(typeof(TocEntry)) || e.Data.GetDataPresent(typeof(CodeReference)) || e.Data.GetDataPresent(typeof(CodeEntityReference))) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.None; } /// <summary> /// This handles the drop operation for the editor /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void editor_DragDrop(object sender, DragEventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; DataObject data = e.Data as DataObject; ImageReference ir; CodeReference cr; CodeEntityReference cer; Token token; Topic topic; TocEntry tocEntry; string extension = Path.GetExtension(this.ToolTipText).ToLower( CultureInfo.InvariantCulture); if(data == null) return; // Images have multiple link formats so a context menu is used // to let the user pick a format. if(data.GetDataPresent(typeof(ImageReference))) { if(extension == ".htm" || extension == ".html") { ir = data.GetData(typeof(ImageReference)) as ImageReference; if(ir != null) ContentEditorControl.InsertString(textArea, ir.ToImageLink()); } else { cmsDropImage.Tag = data.GetData(typeof(ImageReference)); cmsDropImage.Show(e.X, e.Y); } return; } // Everything else is fairly simple. Topic links will wrap the // selected text if dropped inside it. if(data.GetDataPresent(typeof(Token))) { token = data.GetData(typeof(Token)) as Token; if(token != null) ContentEditorControl.InsertString(textArea, token.ToToken()); } else if(data.GetDataPresent(typeof(CodeReference))) { cr = data.GetData(typeof(CodeReference)) as CodeReference; if(cr != null) ContentEditorControl.InsertString(textArea, cr.ToCodeReference()); } else if(data.GetDataPresent(typeof(CodeEntityReference))) { cer = data.GetData(typeof(CodeEntityReference)) as CodeEntityReference; if(cer != null) if(extension == ".htm" || extension == ".html") ContentEditorControl.InsertString(textArea, cer.ToSee()); else ContentEditorControl.InsertString(textArea, cer.ToCodeEntityReference()); } else if(data.GetDataPresent(typeof(Topic))) { topic = data.GetData(typeof(Topic)) as Topic; // Topic links can wrap selected text if(topic != null) this.InsertTopicLink(extension, topic); } else if(data.GetDataPresent(typeof(TocEntry))) { tocEntry = data.GetData(typeof(TocEntry)) as TocEntry; // Topic links can wrap selected text if(tocEntry != null) this.InsertTocLink(extension, tocEntry); } } /// <summary> /// Insert a media link into the document /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void MediaLinkItem_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; ImageReference ir = cmsDropImage.Tag as ImageReference; if(ir != null) if(sender == miMediaLink) ContentEditorControl.InsertString(textArea, ir.ToMediaLink()); else if(sender == miMediaLinkInline) ContentEditorControl.InsertString(textArea, ir.ToMediaLinkInline()); else ContentEditorControl.InsertString(textArea, ir.ToExternalLink()); } #endregion #region Toolbar event handlers //===================================================================== // NOTE: Each method calls editor.Focus() to refocus the editor // control. If not done, the cursor occasionally disappears if the // toolbar buttons are clicked or double-clicked in a certain way. // Usually it's after using the "para" toolbar dropdown. /// <summary> /// Insert a basic element such as legacyBold, legacyItalic, etc. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event element</param> private void insertElement_Click(object sender, EventArgs e) { ToolStripItem item = sender as ToolStripItem; editor.Execute(new InsertElement(item.Text)); editor.Focus(); this.TrackLastInsertedElement(sender as ToolStripMenuItem); } /// <summary> /// Insert a list element /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void insertList_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; string style; if(sender == tsbListBullet) style = "bullet"; else style = "ordered"; ContentEditorControl.InsertString(textArea, "\r\n<list class=\"" + style + "\">\r\n" + " <listItem>Item 1</listItem>\r\n <listItem>Item 2" + "</listItem>\r\n</list>\r\n"); editor.Focus(); } /// <summary> /// Insert a table element /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbTable_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; ContentEditorControl.InsertString(textArea, "\r\n<table>\r\n <tableHeader>\r\n " + "<row>\r\n <entry>Header 1</entry>\r\n <entry>" + "Header 2</entry>\r\n </row>\r\n </tableHeader>\r\n " + "<row>\r\n <entry>Column 1</entry>\r\n <entry>" + "Column 2</entry>\r\n </row>\r\n</table>\r\n"); editor.Focus(); } /// <summary> /// Insert a link to an in-page address attribute value /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbLocalLink_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = "inner text"; ContentEditorControl.InsertString(textArea, "<link xlink:href=\"#addr\">" + selectedText + "</link>"); textArea.Caret.Column -= 7; editor.Focus(); } /// <summary> /// Insert an external link /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbExternalLink_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = "link text"; ContentEditorControl.InsertString(textArea, "<externalLink>\r\n<linkText>" + selectedText + "</linkText>\r\n<linkAlternateText>Optional alternate text" + "</linkAlternateText>\r\n<linkUri>http://www.url.com" + "</linkUri>\r\n<linkTarget>_blank</linkTarget>\r\n" + "</externalLink>\r\n"); editor.Focus(); } /// <summary> /// Perform the action associated with the last insert item used /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbInsertElement_ButtonClick(object sender, EventArgs e) { if(lastAction != null) lastAction.PerformClick(); else miAlert.PerformClick(); } /// <summary> /// Insert an alert element /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void miAlert_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; int offset = textArea.Caret.Offset; string selectedText; if(textArea.SelectionManager.HasSomethingSelected && textArea.SelectionManager.SelectionCollection[0].ContainsOffset(offset)) selectedText = textArea.SelectionManager.SelectionCollection[0].SelectedText; else selectedText = "Alert text"; ContentEditorControl.InsertString(textArea, "\r\n<alert class=\"note\">\r\n <para>" + selectedText + "</para>\r\n</alert>\r\n"); editor.Focus(); this.TrackLastInsertedElement(sender as ToolStripMenuItem); } /// <summary> /// Insert a code element /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void miCode_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; ContentEditorControl.InsertString(textArea, "\r\n<code " + "language=\"cs\">\r\n/// Code\r\n</code>\r\n"); editor.Focus(); this.TrackLastInsertedElement(sender as ToolStripMenuItem); } /// <summary> /// Insert a definition table /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void miDefinitionTable_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; ContentEditorControl.InsertString(textArea, "\r\n<definitionTable>\r\n" + " <definedTerm>Term 1</definedTerm>\r\n <definition>" + "Definition 1</definition>\r\n <definedTerm>Term 2" + "</definedTerm>\r\n <definition>Definition 2</definition>" + "\r\n</definitionTable>"); editor.Focus(); this.TrackLastInsertedElement(sender as ToolStripMenuItem); } /// <summary> /// Insert a section /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void miSection_Click(object sender, EventArgs e) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; ContentEditorControl.InsertString(textArea, "\r\n<section address=\"optionalAddress\">\r\n" + " <title>Title</title>\r\n <content>\r\n <para>Content " + "goes here</para>\r\n </content>\r\n</section>\r\n"); editor.Focus(); this.TrackLastInsertedElement(sender as ToolStripMenuItem); } /// <summary> /// HTML encode any currently selected text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbHtmlEncode_Click(object sender, EventArgs e) { editor.Execute(new HtmlEncode()); editor.Focus(); } /// <summary> /// Cut text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbCutText_Click(object sender, EventArgs e) { editor.Execute(new Cut()); editor.Focus(); } /// <summary> /// Cut text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbCopyText_Click(object sender, EventArgs e) { editor.Execute(new Copy()); editor.Focus(); } /// <summary> /// Paste text /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbPasteText_Click(object sender, EventArgs e) { this.PasteFromClipboard(); editor.Focus(); } /// <summary> /// Undo editor change /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbUndo_Click(object sender, EventArgs e) { editor.Undo(); editor.Focus(); } /// <summary> /// Redo editor change /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void tsbRedo_Click(object sender, EventArgs e) { editor.Redo(); editor.Focus(); } #endregion #region Find and Replace methods //===================================================================== /// <summary> /// This handles the Perform Find Text event /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void editor_PerformFindText(object sender, EventArgs e) { FindAndReplaceWindow findWindow = null; foreach(IDockContent content in this.DockPanel.Contents) { findWindow = content as FindAndReplaceWindow; if(findWindow != null) break; } if(findWindow != null && findWindow.Visible) { if(!findWindow.ShowReplaceControls(false) && !String.IsNullOrEmpty(findWindow.FindText)) { if(!this.FindText(findWindow.FindText, findWindow.CaseSensitive)) MessageBox.Show("The specified text was not found", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else findWindow.Activate(); } else if(findWindow == null) { findWindow = new FindAndReplaceWindow(); findWindow.Show(this.DockPanel); } else { findWindow.Activate(); findWindow.ShowReplaceControls(false); } } /// <summary> /// This handles the Perform Replace Text event /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void editor_PerformReplaceText(object sender, EventArgs e) { FindAndReplaceWindow findWindow = null; foreach(IDockContent content in this.DockPanel.Contents) { findWindow = content as FindAndReplaceWindow; if(findWindow != null) break; } if(findWindow != null && findWindow.Visible) { if(findWindow.ShowReplaceControls(true) && !String.IsNullOrEmpty(findWindow.FindText)) this.ReplaceText(findWindow.FindText, findWindow.ReplaceWith, findWindow.CaseSensitive); else findWindow.Activate(); } else if(findWindow == null) { findWindow = new FindAndReplaceWindow(); findWindow.Show(this.DockPanel); findWindow.ShowReplaceControls(true); } else { findWindow.Activate(); findWindow.ShowReplaceControls(true); } } /// <summary> /// Find the specified text in the editor /// </summary> /// <param name="textToFind">The text to find</param> /// <param name="caseSensitive">True to do a case-sensitive search /// or false to do a case-insensitive search</param> /// <returns>True if the text is found, false if not</returns> public bool FindText(string textToFind, bool caseSensitive) { TextLocation start, end; TextArea textArea = editor.ActiveTextAreaControl.TextArea; StringComparison comparisonType = (caseSensitive) ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; string text = textArea.Document.GetText(0, textArea.Document.TextLength); int pos, offset = textArea.Caret.Offset; if(textToFind == null) textToFind = String.Empty; pos = text.IndexOf(textToFind, offset, comparisonType); if(pos == -1 && offset != 0) pos = text.IndexOf(textToFind, 0, offset, comparisonType); if(pos != -1) { start = textArea.Document.OffsetToPosition(pos); end = textArea.Document.OffsetToPosition(pos + textToFind.Length); textArea.Caret.Position = end; textArea.SelectionManager.SetSelection(start, end); this.Activate(); return true; } return false; } /// <summary> /// Find and replace the next occurrence of the specified text in the /// editor. /// </summary> /// <param name="textToFind">The text to find</param> /// <param name="replaceWith">The replacement text</param> /// <param name="caseSensitive">True to do a case-sensitive search /// or false to do a case-insensitive search</param> /// <returns>True if the text is found and replaced, false if not</returns> public bool ReplaceText(string textToFind, string replaceWith, bool caseSensitive) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; StringComparison comparisonType = (caseSensitive) ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase; string text = textArea.Document.GetText(0, textArea.Document.TextLength); int offset; if(textToFind == null) textToFind = String.Empty; if(replaceWith == null) replaceWith = String.Empty; // If the cursor is sitting at the end of the find text, replace // the instance at the cursor. offset = textArea.Caret.Offset - textToFind.Length; if(offset >= 0 && String.Compare(text, offset, textToFind, 0, textToFind.Length, comparisonType) == 0) { textArea.Document.Replace(offset, textToFind.Length, replaceWith); textArea.Caret.Position = textArea.Document.OffsetToPosition( offset + replaceWith.Length); } // Find the next occurence, if any return this.FindText(textToFind, caseSensitive); } /// <summary> /// Find and replace all occurrences of the specified text in the /// editor. /// </summary> /// <param name="textToFind">The text to find</param> /// <param name="replaceWith">The replacement text</param> /// <param name="caseSensitive">True to do a case-sensitive search /// or false to do a case-insensitive search</param> /// <returns>True if replacements were made, false if not</returns> public bool ReplaceAll(string textToFind, string replaceWith, bool caseSensitive) { TextArea textArea = editor.ActiveTextAreaControl.TextArea; bool nextFound; int offset; textArea.Caret.Position = textArea.Document.OffsetToPosition(0); if(!this.FindText(textToFind, caseSensitive)) return false; offset = textArea.Caret.Offset; do { nextFound = this.ReplaceText(textToFind, replaceWith, caseSensitive); } while(offset < textArea.Caret.Offset && nextFound); return true; } #endregion } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Linq; namespace XenAdmin.Dialogs { public partial class VIFDialog : XenDialogBase { private readonly VIF ExistingVif; private readonly int Device; private readonly bool allowSriov; public VIFDialog(IXenConnection connection, VIF existingVif, int device, bool allowSriov = false) : base(connection) { InitializeComponent(); CueBannersManager.SetWatermark(promptTextBoxMac, "aa:bb:cc:dd:ee:ff"); ExistingVif = existingVif; Device = device; this.allowSriov = allowSriov; if (ExistingVif != null) { Text = Messages.VIRTUAL_INTERFACE_PROPERTIES; buttonOk.Text = Messages.OK; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); LoadNetworks(); LoadDetails(); ValidateInput(); } private void LoadDetails() { // Check if vSwitch Controller is configured for the pool (CA-46299) Pool pool = Helpers.GetPoolOfOne(connection); var vSwitchController = !Helpers.StockholmOrGreater(connection) && pool != null && pool.vSwitchController(); if (vSwitchController) { tableLayoutPanel3.Enabled = checkboxQoS.Enabled = checkboxQoS.Checked = false; tableLayoutPanelInfo.Visible = true; } else { if (ExistingVif == null) { promptTextBoxQoS.Text = ""; checkboxQoS.Checked = false; } else { promptTextBoxQoS.Text = ExistingVif.LimitString(); checkboxQoS.Checked = ExistingVif.qos_algorithm_type == VIF.RATE_LIMIT_QOS_VALUE; } tableLayoutPanel3.Enabled = checkboxQoS.Enabled = true; tableLayoutPanelInfo.Visible = false; } if (ExistingVif == null) { radioButtonAutogenerate.Checked = true; return; } foreach (NetworkComboBoxItem item in comboBoxNetwork.Items) { if (item.Network != null && item.Network.opaque_ref == ExistingVif.network.opaque_ref) comboBoxNetwork.SelectedItem = item; } promptTextBoxMac.Text = ExistingVif.MAC; if (!string.IsNullOrEmpty(ExistingVif.MAC)) radioButtonMac.Checked = true; else radioButtonAutogenerate.Checked = true; } private void ValidateInput() { string error; if (!IsValidNetwork(out error) || !IsValidMAc(out error) || !IsValidQoSLimit(out error)) { buttonOk.Enabled = false; if (string.IsNullOrEmpty(error)) { tableLayoutPanelError.Visible = false; } else { tableLayoutPanelError.Visible = true; pictureBoxError.Image = Images.StaticImages._000_error_h32bit_16; labelError.Text = error; } } else { buttonOk.Enabled = true; tableLayoutPanelError.Visible = false; } } private bool IsValidNetwork(out string error) { error = Messages.SELECT_NETWORK_TOOLTIP; return comboBoxNetwork.SelectedItem is NetworkComboBoxItem item && item.Network != null; } private bool IsValidMAc(out string error) { error = null; if (!radioButtonMac.Checked) return true; if (string.IsNullOrWhiteSpace(promptTextBoxMac.Text)) return false; error = Messages.MAC_INVALID; return Helpers.IsValidMAC(promptTextBoxMac.Text); } private bool IsValidQoSLimit(out string error) { error = null; if (!checkboxQoS.Checked) return true; if (string.IsNullOrWhiteSpace(promptTextBoxQoS.Text)) return false; error = Messages.ENTER_VALID_QOS; if (int.TryParse(promptTextBoxQoS.Text, out var result)) return result > 0; return false; } private void LoadNetworks() { List<XenAPI.Network> networks = new List<XenAPI.Network>(connection.Cache.Networks); networks.Sort(); foreach (XenAPI.Network network in networks) { if (!network.Show(Properties.Settings.Default.ShowHiddenVMs) || network.IsSlave() || (network.IsSriov() && !allowSriov)) continue; comboBoxNetwork.Items.Add(new NetworkComboBoxItem(network)); } if (comboBoxNetwork.Items.Count == 0) { comboBoxNetwork.Items.Add(new NetworkComboBoxItem(null)); } comboBoxNetwork.SelectedIndex = 0; } private XenAPI.Network SelectedNetwork => (comboBoxNetwork.SelectedItem as NetworkComboBoxItem)?.Network; private string SelectedMac => radioButtonAutogenerate.Checked ? "" : promptTextBoxMac.Text; public VIF NewVif() { var vif = new VIF(); vif.Connection = connection; vif.network = new XenRef<XenAPI.Network>(SelectedNetwork.opaque_ref); vif.MAC = SelectedMac; vif.device = Device.ToString(); if (checkboxQoS.Checked) vif.qos_algorithm_type = VIF.RATE_LIMIT_QOS_VALUE; // preserve this param even if we have decided not to turn on qos if (!string.IsNullOrWhiteSpace(promptTextBoxQoS.Text)) vif.qos_algorithm_params = new Dictionary<string, string> {{VIF.KBPS_QOS_PARAMS_KEY, promptTextBoxQoS.Text}}; return vif; } /// <summary> /// Retrieves the new settings as a vif object. You will need to set the VM field to use these settings in a vif action /// </summary> /// <returns></returns> public VIF GetNewSettings() { var newVif = new VIF(); if (ExistingVif != null) newVif.UpdateFrom(ExistingVif); newVif.network = new XenRef<XenAPI.Network>(SelectedNetwork.opaque_ref); newVif.MAC = SelectedMac; newVif.device = Device.ToString(); if (checkboxQoS.Checked) { newVif.qos_algorithm_type = VIF.RATE_LIMIT_QOS_VALUE; } else if (ExistingVif != null && ExistingVif.qos_algorithm_type == VIF.RATE_LIMIT_QOS_VALUE) { newVif.qos_algorithm_type = ""; } // else ... we leave it alone. Currently we only deal with "ratelimit" and "", don't overwrite the field if it's something else // preserve this param even if we turn off qos if (!string.IsNullOrEmpty(promptTextBoxQoS.Text)) newVif.qos_algorithm_params = new Dictionary<string, string> { { VIF.KBPS_QOS_PARAMS_KEY, promptTextBoxQoS.Text } }; return newVif; } private bool MACAddressHasChanged() { if (ExistingVif == null) return true; return promptTextBoxMac.Text != ExistingVif.MAC; } private bool ChangesHaveBeenMade { get { if (ExistingVif == null) return true; if (ExistingVif.network.opaque_ref != SelectedNetwork.opaque_ref) return true; if (ExistingVif.MAC != SelectedMac) return true; if (ExistingVif.device != Device.ToString()) return true; if (ExistingVif.qos_algorithm_type == VIF.RATE_LIMIT_QOS_VALUE) { if (!checkboxQoS.Checked) return true; if (ExistingVif.qos_algorithm_params[VIF.KBPS_QOS_PARAMS_KEY] != promptTextBoxQoS.Text) return true; } else if (string.IsNullOrEmpty(ExistingVif.qos_algorithm_type)) { if (checkboxQoS.Checked) return true; } return false; } } #region Control event handlers private void VIFDialog_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.Cancel) return; if (MACAddressHasChanged()) foreach (var xenConnection in ConnectionsManager.XenConnectionsCopy.Where(c => c.IsConnected)) { foreach (VIF vif in xenConnection.Cache.VIFs) { var vm = xenConnection.Resolve(vif.VM); if (vif != ExistingVif && vif.MAC == SelectedMac && vm != null && vm.is_a_real_vm()) { using (var dlg = new WarningDialog(string.Format(Messages.PROBLEM_MAC_ADDRESS_IS_DUPLICATE, SelectedMac, vm.NameWithLocation()), ThreeButtonDialog.ButtonYes, new ThreeButtonDialog.TBDButton(Messages.NO_BUTTON_CAPTION, DialogResult.No, selected: true)) {WindowTitle = Messages.PROBLEM_MAC_ADDRESS_IS_DUPLICATE_TITLE}) { e.Cancel = dlg.ShowDialog(this) == DialogResult.No; return; } } } } if (!ChangesHaveBeenMade) DialogResult = DialogResult.Cancel; } private void comboBoxNetwork_SelectedIndexChanged(object sender, EventArgs e) { ValidateInput(); } private void radioButtonAutogenerate_CheckedChanged(object sender, EventArgs e) { if (radioButtonAutogenerate.Checked) ValidateInput(); } private void radioButtonMac_CheckedChanged(object sender, EventArgs e) { if (radioButtonMac.Checked) ValidateInput(); } private void promptTextBoxMac_Enter(object sender, EventArgs e) { radioButtonMac.Checked = true; ValidateInput(); } private void promptTextBoxMac_TextChanged(object sender, EventArgs e) { ValidateInput(); } private void checkboxQoS_CheckedChanged(object sender, EventArgs e) { ValidateInput(); } private void promptTextBoxQoS_TextChanged(object sender, EventArgs e) { ValidateInput(); } private void promptTextBoxQoS_Enter(object sender, EventArgs e) { checkboxQoS.Checked = true; ValidateInput(); } #endregion internal override string HelpName => ExistingVif == null ? "VIFDialog" : "EditVmNetworkSettingsDialog"; } public class NetworkComboBoxItem : IEquatable<NetworkComboBoxItem> { public XenAPI.Network Network; public NetworkComboBoxItem(XenAPI.Network network) { Network = network; } public override string ToString() { return Network == null ? Messages.NONE : Helpers.GetName(Network); } public bool Equals(NetworkComboBoxItem other) { if (Network == null) return other.Network == null; return Network.Equals(other.Network); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; #if ! __UNIFIED__ using MonoTouch.Foundation; using MonoTouch.UIKit; #else using Foundation; using UIKit; #endif using MonoTouch.Dialog; using Xamarin.Media; using Xamarin.Social.Services; namespace Xamarin.Social.Sample.iOS { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { UIWindow window; DialogViewController dialog; #region Fields private static FacebookService mFacebook; private static FlickrService mFlickr; private static TwitterService mTwitter; private static Twitter5Service mTwitter5; #endregion public static FacebookService Facebook { get { if (mFacebook == null) { mFacebook = new FacebookService() { ClientId = "App ID/API Key from https://developers.facebook.com/apps", RedirectUrl = new Uri ("Redirect URL from https://developers.facebook.com/apps") }; } return mFacebook; } } public static FlickrService Flickr { get { if (mFlickr == null) { mFlickr = new FlickrService() { ConsumerKey = "Key from http://www.flickr.com/services/apps/by/me", ConsumerSecret = "Secret from http://www.flickr.com/services/apps/by/me", }; } return mFlickr; } } public static TwitterService Twitter { get { if (mTwitter == null) { mTwitter = new TwitterService { ConsumerKey = "Consumer key from https://dev.twitter.com/apps", ConsumerSecret = "Consumer secret from https://dev.twitter.com/apps", CallbackUrl = new Uri ("Callback URL from https://dev.twitter.com/apps") }; } return mTwitter; } } public static Twitter5Service Twitter5 { get { if (mTwitter5 == null) { mTwitter5 = new Twitter5Service(); } return mTwitter5; } } private void Share (Service service, StringElement button) { Item item = new Item { Text = "I'm sharing great things using Xamarin!", Links = new List<Uri> { new Uri ("http://xamarin.com"), }, }; UIViewController vc = service.GetShareUI (item, shareResult => { dialog.DismissViewController (true, null); button.GetActiveCell().TextLabel.Text = service.Title + " shared: " + shareResult; }); dialog.PresentViewController (vc, true, null); } private void ShowMessage(string Message) { var msgView = new UIAlertView("Error", Message,null,"OK", null); msgView.Show(); } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { var root = new RootElement ("Xamarin.Social Sample"); var section = new Section ("Services"); var facebookButton = new StringElement ("Share with Facebook"); facebookButton.Tapped += delegate { try { Share (Facebook, facebookButton); } catch (Exception ex) { ShowMessage("Facebook: " + ex.Message); } }; section.Add (facebookButton); var twitterButton = new StringElement ("Share with Twitter"); twitterButton.Tapped += delegate { try { Share (Twitter, twitterButton); } catch (Exception ex) { ShowMessage("Twitter: " + ex.Message); } }; section.Add (twitterButton); var twitter5Button = new StringElement ("Share with built-in Twitter"); twitter5Button.Tapped += delegate { try { Share (Twitter5, twitter5Button); } catch (Exception ex) { ShowMessage("Twitter5: " +ex.Message); } }; section.Add (twitter5Button); var flickr = new StringElement ("Share with Flickr"); flickr.Tapped += () => { var picker = new MediaPicker(); // Set breakpoint here picker.PickPhotoAsync().ContinueWith (t => { if (t.IsCanceled) return; var item = new Item ("I'm sharing great things using Xamarin!") { Images = new[] { new ImageData (t.Result.Path) } }; Console.WriteLine ("Picked image {0}", t.Result.Path); UIViewController viewController = Flickr.GetShareUI (item, shareResult => { dialog.DismissViewController (true, null); flickr.GetActiveCell().TextLabel.Text = "Flickr shared: " + shareResult; }); dialog.PresentViewController (viewController, true, null); }, TaskScheduler.FromCurrentSynchronizationContext()); }; section.Add (flickr); root.Add (section); dialog = new DialogViewController (root); window = new UIWindow (UIScreen.MainScreen.Bounds); window.RootViewController = new UINavigationController (dialog); window.MakeKeyAndVisible (); return true; } // This is the main entry point of the application. static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } } }