context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//------------------------------------------------------------------------------ // <copyright file="CachedPathData.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web { using System.Collections; using System.Configuration; using System.Configuration.Internal; using System.Globalization; using System.Security.Principal; using System.Threading; using System.Web.Security; using System.Web.SessionState; using System.Web.Configuration; using System.Web.Caching; using System.Web.Hosting; using System.Web.Util; using System.Web.UI; using System.Security.Permissions; // Data about a path that is cached across requests class CachedPathData { internal const int FInited = 0x0001; internal const int FCompletedFirstRequest = 0x0002; internal const int FExists = 0x0004; internal const int FOwnsConfigRecord = 0x0010; // is this the highest ancestor pointing to the config record? internal const int FClosed = 0x0020; // Has item been closed already? internal const int FCloseNeeded = 0x0040; // Should we close? internal const int FAnonymousAccessChecked = 0x0100; internal const int FAnonymousAccessAllowed = 0x0200; static CacheItemRemovedCallback s_callback = new CacheItemRemovedCallback(CachedPathData.OnCacheItemRemoved); // initialize the URL metadata cache expiration here, just in case there's an issue with HttpRuntime.HostingInit private static TimeSpan s_urlMetadataSlidingExpiration = HostingEnvironmentSection.DefaultUrlMetadataSlidingExpiration; private static bool s_doNotCacheUrlMetadata = false; private static int s_appConfigPathLength = 0; #pragma warning disable 0649 SafeBitVector32 _flags; #pragma warning restore 0649 string _configPath; VirtualPath _virtualPath; string _physicalPath; RuntimeConfig _runtimeConfig; HandlerMappingMemo _handlerMemo; // // Constructor // internal CachedPathData(string configPath, VirtualPath virtualPath, string physicalPath, bool exists) { // Guarantee that we return a non-null config record // if an error occurs during initialization. _runtimeConfig = RuntimeConfig.GetErrorRuntimeConfig(); _configPath = configPath; _virtualPath = virtualPath; _physicalPath = physicalPath; _flags[FExists] = exists; // VSWhidbey 607683: Config loading for web app has a dependency on CachedPathData. // On the other hand, Config also has a dependency on Uri class which has // a new static constructor that calls config, and eventually to CachedPathData again. // We need a dummy reference to Uri class so the static constructor would be involved // first to initialize config. string dummy = System.Uri.SchemeDelimiter; } // // Called by HttpRuntime.HostingInit to initialize UrlMetadataSlidingExpiration // static internal void InitializeUrlMetadataSlidingExpiration(HostingEnvironmentSection section) { TimeSpan slidingExp = section.UrlMetadataSlidingExpiration; if (slidingExp == TimeSpan.Zero) { // a value of TimeSpan.Zero means don't cache // this "feature" was added for Bing, because they // have scenarios where the same URL is never seen twice s_doNotCacheUrlMetadata = true; } else if (slidingExp == TimeSpan.MaxValue) { // a value of TimeSpan.MaxValue means use Cache.NoSlidingExpiration, // which is how CachedPathData used to be cached, so this effectively // reverts to v2.0 behavior for caching CachedPathData s_urlMetadataSlidingExpiration = Cache.NoSlidingExpiration; s_doNotCacheUrlMetadata = false; } else { // anything in between means cache with that sliding expiration s_urlMetadataSlidingExpiration = slidingExp; s_doNotCacheUrlMetadata = false; } } // // Get CachedPathData for the machine.config level // static internal CachedPathData GetMachinePathData() { return GetConfigPathData(WebConfigurationHost.MachineConfigPath); } // // Get CachedPathData for the root web.config path // static internal CachedPathData GetRootWebPathData() { return GetConfigPathData(WebConfigurationHost.RootWebConfigPath); } // // Get CachedPathData for the application. // static internal CachedPathData GetApplicationPathData() { if (!HostingEnvironment.IsHosted) { return GetRootWebPathData(); } return GetConfigPathData(HostingEnvironment.AppConfigPath); } // // Get CachedPathData for a virtual path. // The path may be supplied by user code, so check that it is valid. // static internal CachedPathData GetVirtualPathData(VirtualPath virtualPath, bool permitPathsOutsideApp) { if (!HostingEnvironment.IsHosted) { return GetRootWebPathData(); } // Make sure it's not relative if (virtualPath != null) { virtualPath.FailIfRelativePath(); } // Check if the path is within the application. if (virtualPath == null || !virtualPath.IsWithinAppRoot) { if (permitPathsOutsideApp) { return GetApplicationPathData(); } else { throw new ArgumentException(SR.GetString(SR.Cross_app_not_allowed, (virtualPath != null) ? virtualPath.VirtualPathString : "null")); } } // Construct a configPath based on the unvalidated virtualPath. string configPath = WebConfigurationHost.GetConfigPathFromSiteIDAndVPath(HostingEnvironment.SiteID, virtualPath); // Pass the virtualPath to GetConfigPathData to validate in the case where the // CachedPathData for the unsafeConfigPath is not found. return GetConfigPathData(configPath); } // Dev10 862204: AppDomain does not restart when the application's web.config is touched 2 minutes after the last request static private bool IsCachedPathDataRemovable(string configPath) { // have we initialized yet? if (s_appConfigPathLength == 0) { // when hosted use AppConfigPath, otherwise use RootWebConfigPath s_appConfigPathLength = (HostingEnvironment.IsHosted) ? HostingEnvironment.AppConfigPath.Length : WebConfigurationHost.RootWebConfigPath.Length; } // Only config paths beneath the application config path can be removed from the cache. return (configPath.Length > s_appConfigPathLength); } // Example of configPath = "machine/webroot/1/fxtest/sub/foo.aspx" // The configPath parameter must be lower case. static private CachedPathData GetConfigPathData(string configPath) { Debug.Assert(ConfigPathUtility.IsValid(configPath), "ConfigPathUtility.IsValid(configPath)"); Debug.Assert(configPath == configPath.ToLower(CultureInfo.InvariantCulture), "configPath == configPath.ToLower(CultureInfo.InvariantCulture)"); bool exists = false; bool isDirectory = false; bool isRemovable = IsCachedPathDataRemovable(configPath); // if the sliding expiration is zero, we won't cache it unless it is a configPath for root web.config or above if (isRemovable && DoNotCacheUrlMetadata) { string pathSiteID = null; VirtualPath virtualFilePath = null; string physicalFilePath = null; WebConfigurationHost.GetSiteIDAndVPathFromConfigPath(configPath, out pathSiteID, out virtualFilePath); physicalFilePath = GetPhysicalPath(virtualFilePath); string parentConfigPath = ConfigPathUtility.GetParent(configPath); CachedPathData pathParentData = GetConfigPathData(parentConfigPath); if (!String.IsNullOrEmpty(physicalFilePath)) { FileUtil.PhysicalPathStatus(physicalFilePath, false, false, out exists, out isDirectory); } CachedPathData pathData = new CachedPathData(configPath, virtualFilePath, physicalFilePath, exists); pathData.Init(pathParentData); return pathData; } // // First, see if the CachedPathData is in the cache. // we don't use Add for this lookup, as doing so requires // creating a CacheDependency, which can be slow as it may hit // the filesystem. // string key = CreateKey(configPath); CacheInternal cacheInternal = HttpRuntime.CacheInternal; CachedPathData data = (CachedPathData) cacheInternal.Get(key); // if found, return the data if (data != null) { data.WaitForInit(); return data; } // WOS bool cacheEntryIsNotRemovable = false; // if not found, try to add it string siteID = null; VirtualPath virtualPath = null; CachedPathData parentData = null; CacheDependency dependency = null; string physicalPath = null; string[] fileDependencies = null; string[] cacheItemDependencies = null; if (WebConfigurationHost.IsMachineConfigPath(configPath)) { cacheEntryIsNotRemovable = true; } else { // Make sure we have the parent data so we can create a dependency on the parent. // The parent dependency will ensure that configuration data in the parent // will be referenced by a cache hit on the child. (see UtcUpdateUsageRecursive in Cache.cs) string parentConfigPath = ConfigPathUtility.GetParent(configPath); parentData = GetConfigPathData(parentConfigPath); string parentKey = CreateKey(parentConfigPath); cacheItemDependencies = new string[1] {parentKey}; if (!WebConfigurationHost.IsVirtualPathConfigPath(configPath)) { // assume hardcoded levels above the path, such as root web.config, exist cacheEntryIsNotRemovable = true; } else { cacheEntryIsNotRemovable = !isRemovable; WebConfigurationHost.GetSiteIDAndVPathFromConfigPath(configPath, out siteID, out virtualPath); physicalPath = GetPhysicalPath(virtualPath); // Add a dependency on the path itself, if it is a file, // to handle the case where a file is deleted and replaced // with a directory of the same name. if (!String.IsNullOrEmpty(physicalPath)) { FileUtil.PhysicalPathStatus(physicalPath, false, false, out exists, out isDirectory); if (exists && !isDirectory) { fileDependencies = new string[1] {physicalPath}; } } } try { dependency = new CacheDependency(0, fileDependencies, cacheItemDependencies); } catch { // CacheDependency ctor could fail because of bogus file path // and it is ok not to watch those } } // Try to add the CachedPathData to the cache. CachedPathData dataAdd = null; bool isDataCreator = false; bool initCompleted = false; CacheItemPriority priority = cacheEntryIsNotRemovable ? CacheItemPriority.NotRemovable : CacheItemPriority.Normal; TimeSpan slidingExpiration = cacheEntryIsNotRemovable ? Cache.NoSlidingExpiration : UrlMetadataSlidingExpiration; try { using (dependency) { dataAdd = new CachedPathData(configPath, virtualPath, physicalPath, exists); try { } finally { data = (CachedPathData) cacheInternal.UtcAdd(key, dataAdd, dependency, Cache.NoAbsoluteExpiration, slidingExpiration, priority, s_callback); if (data == null) { isDataCreator = true; } } } // If another thread added it first, return the data if (!isDataCreator) { data.WaitForInit(); return data; } // This thread is the creator of the CachedPathData, initialize it lock (dataAdd) { try { dataAdd.Init(parentData); initCompleted = true; } finally { // free waiters dataAdd._flags[FInited] = true; // Wake up waiters. Monitor.PulseAll(dataAdd); if (dataAdd._flags[FCloseNeeded]) { // If we have received a call back to close, then lets // make sure that our config object is cleaned up dataAdd.Close(); } } } } finally { // All the work in this finally block is for the case where we're the // creator of the CachedPathData. if (isDataCreator) { // if (!dataAdd._flags[FInited]) { lock (dataAdd) { // free waiters dataAdd._flags[FInited] = true; // Wake up waiters. Monitor.PulseAll(dataAdd); if (dataAdd._flags[FCloseNeeded]) { // If we have received a call back to close, then lets // make sure that our config object is cleaned up dataAdd.Close(); } } } // // Even though there is a try/catch handler surrounding the call to Init, // a ThreadAbortException can still cause the handler to be bypassed. // // If there is an error, either a thread abort or an error in the config // file itself, we do want to leave the item cached for a short period // so that we do not revisit the error and potentially reparse the config file // on every request. // // The reason we simply do not leave the item in the cache forever is that the // problem that caused the configuration exception may be fixed without touching // the config file in a way that causes a file change notification (for example, an // acl change in a parent directory, or a change of path mapping in the metabase). // // NOTE: It is important to reinsert the item into the cache AFTER dropping // the lock on dataAdd, in order to prevent the possibility of deadlock. // Debug.Assert(dataAdd._flags[FInited], "_flags[FInited]"); if (!initCompleted || (dataAdd.ConfigRecord != null && dataAdd.ConfigRecord.HasInitErrors)) { // // Create a new dependency object as the old one cannot be reused. // Do not include a file dependency if initialization could not be completed, // as invoking the file system could lead to further errors during a thread abort. // if (dependency != null) { if (!initCompleted) { dependency = new CacheDependency(0, null, cacheItemDependencies); } else { dependency = new CacheDependency(0, fileDependencies, cacheItemDependencies); } } using (dependency) { cacheInternal.UtcInsert(key, dataAdd, dependency, DateTime.UtcNow.AddSeconds(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, s_callback); } } } } return dataAdd; } // Ensure that the physical path does not look suspicious (MSRC 5556). static private string GetPhysicalPath(VirtualPath virtualPath) { string physicalPath = null; try { physicalPath = virtualPath.MapPathInternal(true); } catch (HttpException e) { // // Treat exceptions that are thrown because the path is suspicious // as "404 Not Found" exceptions. Implementations of MapPath // will throw HttpException with no error code if the path is // suspicious. // if (e.GetHttpCode() == 500) { throw new HttpException(404, String.Empty); } else { throw; } } // // Throw "404 Not Found" if the path is suspicious and // the implementation of MapPath has not already done so. // FileUtil.CheckSuspiciousPhysicalPath(physicalPath); return physicalPath; } // Remove CachedPathData when the first request for the path results in a // 400 range error. We need to remove all data up the path to account for // virtual files. // An example of a 400 range error is "path not found". static internal void RemoveBadPathData(CachedPathData pathData) { CacheInternal cacheInternal = HttpRuntime.CacheInternal; string configPath = pathData._configPath; string key = CreateKey(configPath); while (pathData != null && !pathData.CompletedFirstRequest && !pathData.Exists) { cacheInternal.Remove(key); configPath = ConfigPathUtility.GetParent(configPath); if (configPath == null) break; key = CreateKey(configPath); pathData = (CachedPathData) cacheInternal.Get(key); } } // Mark CachedPathData as completed when the first request for the path results in a // status outside the 400 range. We need to mark all data up the path to account for // virtual files. static internal void MarkCompleted(CachedPathData pathData) { CacheInternal cacheInternal = HttpRuntime.CacheInternal; string configPath = pathData._configPath; do { pathData.CompletedFirstRequest = true; configPath = ConfigPathUtility.GetParent(configPath); if (configPath == null) break; string key = CreateKey(configPath); pathData = (CachedPathData) cacheInternal.Get(key); } while (pathData != null && !pathData.CompletedFirstRequest); } // Close // // Close the object. This does not mean it can not be used anymore, // it just means that the cleanup as been done, so we don't have // to worry about closing it anymore // void Close() { // Only close if we are propertly initialized if (_flags[FInited]) { // Only close if we haven't already closed if (_flags.ChangeValue(FClosed, true)) { // Remove the config record if we own it // N.B. ConfigRecord.Remove is safe to call more than once. if (_flags[FOwnsConfigRecord]) { ConfigRecord.Remove(); } } } } // OnCacheItemRemoved // // Notification the items has been removed from the cache. Flag // the item to be cleaned up, and then try cleanup // static void OnCacheItemRemoved(string key, object value, CacheItemRemovedReason reason) { CachedPathData data = (CachedPathData) value; data._flags[FCloseNeeded] = true; data.Close(); } static string CreateKey(string configPath) { Debug.Assert(configPath == configPath.ToLower(CultureInfo.InvariantCulture), "configPath == configPath.ToLower(CultureInfo.InvariantCulture)"); return CacheInternal.PrefixPathData + configPath; } // Initialize the data void Init(CachedPathData parentData) { // Note that _runtimeConfig will be set to the singleton instance of ErrorRuntimeConfig // if a ThreadAbortException is thrown during this method. Debug.Assert(_runtimeConfig == RuntimeConfig.GetErrorRuntimeConfig(), "_runtimeConfig == RuntimeConfig.GetErrorRuntimeConfig()"); if (!HttpConfigurationSystem.UseHttpConfigurationSystem) { // // configRecord may legitimately be null if we are not using the HttpConfigurationSystem. // _runtimeConfig = null; } else { IInternalConfigRecord configRecord = HttpConfigurationSystem.GetUniqueConfigRecord(_configPath); Debug.Assert(configRecord != null, "configRecord != null"); if (configRecord.ConfigPath.Length == _configPath.Length) { // // The config is unique to this path, so this make this record the owner of the config. // _flags[FOwnsConfigRecord] = true; _runtimeConfig = new RuntimeConfig(configRecord); } else { // // The config record is the same as an ancestor's, so use the parent's RuntimeConfig. // Debug.Assert(parentData != null, "parentData != null"); _runtimeConfig = parentData._runtimeConfig; } } } void WaitForInit() { // Wait for the data to be initialized. if (!_flags[FInited]) { lock (this) { if (!_flags[FInited]) { Monitor.Wait(this); } } } } // Ensure that Request.PhysicalPath is valid (canonical, not too long, and contains valid characters). // The work is done by CheckSuspiciousPhysicalPath, but as a perf optimization, we can compare // Request.PhysicalPath with the cached path result. The cached path result is validated before // it is cached. As long as the cached path result is identical to Request.PhysicalPath, we don't // have to call CheckSuspiciousPhysicalPath again. internal void ValidatePath(String physicalPath) { if (String.IsNullOrEmpty(_physicalPath) && String.IsNullOrEmpty(physicalPath)) { return; } if (!String.IsNullOrEmpty(_physicalPath) && !String.IsNullOrEmpty(physicalPath)) { if (_physicalPath.Length == physicalPath.Length) { // if identical, we don't have to call CheckSuspiciousPhysicalPath if (0 == String.Compare(_physicalPath, 0, physicalPath, 0, physicalPath.Length, StringComparison.OrdinalIgnoreCase)) { return; } } else if (_physicalPath.Length - physicalPath.Length == 1) { // if they differ by a trailing slash, we shouldn't call CheckSuspiciousPhysicalPath again if (_physicalPath[_physicalPath.Length-1] == System.IO.Path.DirectorySeparatorChar && (0 == String.Compare(_physicalPath, 0, physicalPath, 0, physicalPath.Length, StringComparison.OrdinalIgnoreCase))) { return; } } else if (physicalPath.Length - _physicalPath.Length == 1) { // if they differ by a trailing slash, we shouldn't call CheckSuspiciousPhysicalPath again if (physicalPath[physicalPath.Length-1] == System.IO.Path.DirectorySeparatorChar && (0 == String.Compare(_physicalPath, 0, physicalPath, 0, _physicalPath.Length, StringComparison.OrdinalIgnoreCase))) { return; } } } // If we're here, the paths were different, which normally should not happen. Debug.Assert(false, "ValidatePath optimization failed: Request.PhysicalPath=" + physicalPath + "; _physicalPath=" + _physicalPath); FileUtil.CheckSuspiciousPhysicalPath(physicalPath); } internal bool CompletedFirstRequest { get {return _flags[FCompletedFirstRequest];} set { _flags[FCompletedFirstRequest] = value; } } internal VirtualPath Path { get {return _virtualPath;} } internal string PhysicalPath { get { return _physicalPath; } } internal bool AnonymousAccessChecked { get { return _flags[FAnonymousAccessChecked]; } set { _flags[FAnonymousAccessChecked] = value; } } internal bool AnonymousAccessAllowed { get { return _flags[FAnonymousAccessAllowed]; } set { _flags[FAnonymousAccessAllowed] = value; } } internal bool Exists { get {return _flags[FExists];} } internal HandlerMappingMemo CachedHandler { get {return _handlerMemo;} set {_handlerMemo = value;} } internal IInternalConfigRecord ConfigRecord { get { // _runtimeConfig may be null if we are not using the HttpConfigurationSystem. return (_runtimeConfig != null) ? _runtimeConfig.ConfigRecord : null; } } internal RuntimeConfig RuntimeConfig { get { return _runtimeConfig; } } // Any time we cache metadata for the URL, we should use this // sliding expiration, unless DoNotCacheUrlMetadata is true. // This is currently used by CachedPathData, MapPathBasedVirtualPathProvider, // FileAuthorizationModule, ProcessHostMapPath and MetabaseServerConfig. internal static TimeSpan UrlMetadataSlidingExpiration { get { return s_urlMetadataSlidingExpiration; } } // if true, do not cache at all. internal static bool DoNotCacheUrlMetadata { get { return s_doNotCacheUrlMetadata; } } } }
using SwitchAppDesign.AniListAPI.v2.Types; using System.Collections.Generic; using SwitchAppDesign.AniListAPI.v2.Graph.Common; using SwitchAppDesign.AniListAPI.v2.Graph.Types; namespace SwitchAppDesign.AniListAPI.v2.Graph.Fields { /// <summary> /// All available media list query fields. /// </summary> public class MediaListQueryFields { private readonly List<AniListQueryType> _allowedQueryTypes; private readonly AniListQueryType _queryType; internal MediaListQueryFields(AniListQueryType queryType) { _queryType = queryType; _allowedQueryTypes = new List<AniListQueryType> {AniListQueryType.MediaList}; } /// <summary> /// The id of the user /// </summary> public GraphQueryField IdQueryField() { return new GraphQueryField("id", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The id of the user owner of the list entry /// </summary> public GraphQueryField UserIdQueryField() { return new GraphQueryField("userId", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The id of the media /// </summary> public GraphQueryField MediaIdQueryField() { return new GraphQueryField("mediaId", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The watching/reading status /// </summary> public GraphQueryField StatusQueryField() { return new GraphQueryField("status", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The score of the entry /// </summary> public GraphQueryField ScoreQueryField() { return new GraphQueryField("score", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The amount of episodes/chapters consumed by the user /// </summary> public GraphQueryField ProgressQueryField() { return new GraphQueryField("progress", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The amount of volumes read by the user /// </summary> public GraphQueryField ProgressVolumesQueryField() { return new GraphQueryField("progressVolumes", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The amount of times the user has rewatched/read the media /// </summary> public GraphQueryField RepeatQueryField() { return new GraphQueryField("repeat", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// Priority of planning /// </summary> public GraphQueryField PriorityQueryField() { return new GraphQueryField("priority", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// If the entry should only be visible to authenticated user /// </summary> public GraphQueryField _privateQueryField() { return new GraphQueryField("_private", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// Text notes /// </summary> public GraphQueryField NotesQueryField() { return new GraphQueryField("notes", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// If the entry shown be hidden from non-custom lists /// </summary> public GraphQueryField HiddenFromStatusListsQueryField() { return new GraphQueryField("hiddenFromStatusLists", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// Map of booleans for which custom lists the entry are in /// </summary> public GraphQueryField CustomListsQueryField() { return new GraphQueryField("customLists", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// Map of advanced scores with name keys /// </summary> public GraphQueryField AdvancedScoresQueryField() { return new GraphQueryField("advancedScores", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// When the entry was started by the user /// </summary> public GraphQueryField StartedAtQueryField() { return new GraphQueryField("startedAt", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// When the entry was completed by the user /// </summary> public GraphQueryField CompletedAtQueryField() { return new GraphQueryField("completedAt", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// When the entry data was last updated /// </summary> public GraphQueryField UpdatedAtQueryField() { return new GraphQueryField("updatedAt", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// When the entry data was created /// </summary> public GraphQueryField CreatedAtQueryField() { return new GraphQueryField("createdAt", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The id of the media /// </summary> public GraphQueryField MediaQueryField() { return new GraphQueryField("media", GetType(), _queryType, InitilizeDefaultFieldRules()); } /// <summary> /// The id of the user owner of the list entry /// </summary> public GraphQueryField UserQueryField() { return new GraphQueryField("user", GetType(), _queryType, InitilizeDefaultFieldRules()); } private FieldRules InitilizeDefaultFieldRules(bool authenticationRequired = false) { return new FieldRules(authenticationRequired, _allowedQueryTypes); } } }
using ATL.Logging; using System; using System.IO; using static ATL.AudioData.AudioDataManager; using static ATL.ChannelsArrangements; namespace ATL.AudioData.IO { /// <summary> /// Class for WavPack files manipulation (extension : .WV) /// </summary> class WAVPack : IAudioDataIO { private int formatTag; private int version; private ChannelsArrangement channelsArrangement; private int bits; private string encoder; private long tagSize; private long samples; private long bSamples; private int sampleRate; private double bitrate; private double duration; private int codecFamily; private SizeInfo sizeInfo; private readonly string filePath; /* public int FormatTag { get { return formatTag; } } public int Version { get { return version; } } public int Bits { get { return bits; } } public long Samples { get { return samples; } } public long BSamples { get { return bSamples; } } public double CompressionRation { get { return getCompressionRatio(); } } public String Encoder { get { return encoder; } } */ private class wavpack_header3 { public char[] ckID = new char[4]; public uint ckSize; public ushort version; public ushort bits; public ushort flags; public ushort shift; public uint total_samples; public uint crc; public uint crc2; public char[] extension = new char[4]; public byte extra_bc; public char[] extras = new char[3]; public void Reset() { Array.Clear(ckID, 0, 4); ckSize = 0; version = 0; bits = 0; flags = 0; shift = 0; total_samples = 0; crc = 0; crc2 = 0; Array.Clear(extension, 0, 4); extra_bc = 0; Array.Clear(extras, 0, 3); } } private class wavpack_header4 { public char[] ckID = new char[4]; public uint ckSize; public ushort version; public byte track_no; public byte index_no; public uint total_samples; public uint block_index; public uint block_samples; public uint flags; public uint crc; public void Reset() { Array.Clear(ckID, 0, 4); ckSize = 0; version = 0; track_no = 0; index_no = 0; total_samples = 0; block_index = 0; block_samples = 0; flags = 0; crc = 0; } } private struct fmt_chunk { public ushort wformattag; public ushort wchannels; public uint dwsamplespersec; public uint dwavgbytespersec; public ushort wblockalign; public ushort wbitspersample; } private class riff_chunk { public char[] id = new char[4]; public uint size; public void Reset() { Array.Clear(id, 0, 3); size = 0; } } //version 3 flags private const int MONO_FLAG_v3 = 1; // not stereo private const int FAST_FLAG_v3 = 2; // non-adaptive predictor and stereo mode //private const int RAW_FLAG_v3 = 4; // raw mode (no .wav header) //private const int CALC_NOISE_v3 = 8; // calc noise in lossy mode (no longer stored) private const int HIGH_FLAG_v3 = 0x10; // high quality mode (all modes) //private const int BYTES_3_v3 = 0x20; // files have 3-byte samples //private const int OVER_20_v3 = 0x40; // samples are over 20 bits private const int WVC_FLAG_v3 = 0x80; // create/use .wvc (no longer stored) //private const int LOSSY_SHAPE_v3 = 0x100; // noise shape (lossy mode only) //private const int VERY_FAST_FLAG_v3 = 0x200; // double fast (no longer stored) private const int NEW_HIGH_FLAG_v3 = 0x400; // new high quality mode (lossless only) //private const int CANCEL_EXTREME_v3 = 0x800; // cancel EXTREME_DECORR //private const int CROSS_DECORR_v3 = 0x1000; // decorrelate chans (with EXTREME_DECORR flag) //private const int NEW_DECORR_FLAG_v3 = 0x2000; // new high-mode decorrelator //private const int JOINT_STEREO_v3 = 0x4000; // joint stereo (lossy and high lossless) private const int EXTREME_DECORR_v3 = 0x8000; // extra decorrelation (+ enables other flags) private static readonly int[] sample_rates = new int[15] { 6000, 8000, 9600, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 }; // ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES public int SampleRate { get { return sampleRate; } } public bool IsVBR { get { return false; } } public int CodecFamily { get { return codecFamily; } } public string FileName { get { return filePath; } } public double BitRate { get { return bitrate; } } public double Duration { get { return duration; } } public ChannelsArrangement ChannelsArrangement { get { return channelsArrangement; } } public bool IsMetaSupported(int metaDataType) { return (metaDataType == MetaDataIOFactory.TAG_APE); } // ---------- CONSTRUCTORS & INITIALIZERS private void resetData() { duration = 0; bitrate = 0; codecFamily = AudioDataIOFactory.CF_LOSSLESS; tagSize = 0; formatTag = 0; sampleRate = 0; bits = 0; version = 0; encoder = ""; samples = 0; bSamples = 0; } public WAVPack(string filePath) { this.filePath = filePath; resetData(); } // ---------- SUPPORT METHODS /* unused for now * public String getChannelMode() { switch( channels ) { case 1: return "Mono"; case 2: return "Stereo"; default : return "Surround"; } } private double getCompressionRatio() { if (isValid) return (double)sizeInfo.FileSize / (samples * (channels * bits / 8) + 44) * 100; else return 0; } */ public bool Read(BinaryReader source, SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams) { char[] marker = new char[4]; bool result = false; this.sizeInfo = sizeInfo; resetData(); source.BaseStream.Seek(0, SeekOrigin.Begin); marker = source.ReadChars(4); source.BaseStream.Seek(0, SeekOrigin.Begin); if (StreamUtils.StringEqualsArr("RIFF", marker)) { result = _ReadV3(source); } else { if (StreamUtils.StringEqualsArr("wvpk", marker)) { result = _ReadV4(source); } } return result; } private bool _ReadV4(BinaryReader r) { wavpack_header4 wvh4 = new wavpack_header4(); byte[] EncBuf = new byte[4096]; int tempo; byte encoderbyte; bool result = false; wvh4.Reset(); wvh4.ckID = r.ReadChars(4); wvh4.ckSize = r.ReadUInt32(); wvh4.version = r.ReadUInt16(); wvh4.track_no = r.ReadByte(); wvh4.index_no = r.ReadByte(); wvh4.total_samples = r.ReadUInt32(); wvh4.block_index = r.ReadUInt32(); wvh4.block_samples = r.ReadUInt32(); wvh4.flags = r.ReadUInt32(); wvh4.crc = r.ReadUInt32(); if (StreamUtils.StringEqualsArr("wvpk", wvh4.ckID)) // wavpack header found -- TODO handle exceptions better { result = true; version = (wvh4.version >> 8); channelsArrangement = ChannelsArrangements.GuessFromChannelNumber((int)(2 - (wvh4.flags & 4))); bits = (int)((wvh4.flags & 3) * 16); // bytes stored flag samples = wvh4.total_samples; bSamples = wvh4.block_samples; sampleRate = (int)((wvh4.flags & (0x1F << 23)) >> 23); if ((sampleRate > 14) || (sampleRate < 0)) { sampleRate = 44100; } else { sampleRate = sample_rates[sampleRate]; } if (8 == (wvh4.flags & 8)) // hybrid flag { encoder = "hybrid lossy"; codecFamily = AudioDataIOFactory.CF_LOSSY; } else { //if (2 == (wvh4.flags & 2) ) { // lossless flag encoder = "lossless"; codecFamily = AudioDataIOFactory.CF_LOSSLESS; } /* if ((wvh4.flags & 0x20) > 0) // MODE_HIGH { FEncoder = FEncoder + " (high)"; end else if ((wvh4.flags & 0x40) > 0) // MODE_FAST { FEncoder = FEncoder + " (fast)"; } */ duration = (double)wvh4.total_samples * 1000.0 / sampleRate; if (duration > 0) bitrate = (sizeInfo.FileSize - tagSize) * 8 / (double)(samples * 1000.0 / (double)sampleRate); Array.Clear(EncBuf, 0, 4096); EncBuf = r.ReadBytes(4096); for (tempo = 0; tempo < 4096; tempo++) { if (0x65 == EncBuf[tempo]) { if (0x02 == EncBuf[tempo + 1]) { encoderbyte = EncBuf[tempo + 2]; switch (encoderbyte) { case 8: encoder = encoder + " (high)"; break; case 0: encoder = encoder + " (normal)"; break; case 2: encoder = encoder + " (fast)"; break; case 6: encoder = encoder + " (very fast)"; break; } break; } } } } return result; } private bool _ReadV3(BinaryReader r) { riff_chunk chunk = new riff_chunk(); char[] wavchunk = new char[4]; fmt_chunk fmt; bool hasfmt; long fpos; wavpack_header3 wvh3 = new wavpack_header3(); bool result = false; hasfmt = false; // read and evaluate header chunk.Reset(); chunk.id = r.ReadChars(4); chunk.size = r.ReadUInt32(); wavchunk = r.ReadChars(4); if (!StreamUtils.StringEqualsArr("WAVE", wavchunk)) return result; // start looking for chunks chunk.Reset(); while (r.BaseStream.Position < r.BaseStream.Length) { chunk.id = r.ReadChars(4); chunk.size = r.ReadUInt32(); if (chunk.size <= 0) break; fpos = r.BaseStream.Position; if (StreamUtils.StringEqualsArr("fmt ", chunk.id)) // Format chunk found read it { if (chunk.size >= 16/*sizeof(fmt_chunk)*/ ) { fmt.wformattag = r.ReadUInt16(); fmt.wchannels = r.ReadUInt16(); fmt.dwsamplespersec = r.ReadUInt32(); fmt.dwavgbytespersec = r.ReadUInt32(); fmt.wblockalign = r.ReadUInt16(); fmt.wbitspersample = r.ReadUInt16(); hasfmt = true; result = true; formatTag = fmt.wformattag; channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(fmt.wchannels); sampleRate = (int)fmt.dwsamplespersec; bits = fmt.wbitspersample; bitrate = (double)fmt.dwavgbytespersec * 8; } else { break; } } else { if ((StreamUtils.StringEqualsArr("data", chunk.id)) && hasfmt) { wvh3.Reset(); wvh3.ckID = r.ReadChars(4); wvh3.ckSize = r.ReadUInt32(); wvh3.version = r.ReadUInt16(); wvh3.bits = r.ReadUInt16(); wvh3.flags = r.ReadUInt16(); wvh3.shift = r.ReadUInt16(); wvh3.total_samples = r.ReadUInt32(); wvh3.crc = r.ReadUInt32(); wvh3.crc2 = r.ReadUInt32(); wvh3.extension = r.ReadChars(4); wvh3.extra_bc = r.ReadByte(); wvh3.extras = r.ReadChars(3); if (StreamUtils.StringEqualsArr("wvpk", wvh3.ckID)) // wavpack header found { result = true; version = wvh3.version; channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(2 - (wvh3.flags & 1)); samples = wvh3.total_samples; codecFamily = AudioDataIOFactory.CF_LOSSLESS; // Encoder guess if (wvh3.bits > 0) { if ((wvh3.flags & NEW_HIGH_FLAG_v3) > 0) { encoder = "hybrid"; if ((wvh3.flags & WVC_FLAG_v3) > 0) { encoder += " lossless"; } else { encoder += " lossy"; codecFamily = AudioDataIOFactory.CF_LOSSY; } if ((wvh3.flags & EXTREME_DECORR_v3) > 0) encoder = encoder + " (high)"; } else { if ((wvh3.flags & (HIGH_FLAG_v3 | FAST_FLAG_v3)) == 0) { encoder = (wvh3.bits + 3).ToString() + "-bit lossy"; codecFamily = AudioDataIOFactory.CF_LOSSY; } else { encoder = (wvh3.bits + 3).ToString() + "-bit lossy"; codecFamily = AudioDataIOFactory.CF_LOSSY; if ((wvh3.flags & HIGH_FLAG_v3) > 0) { encoder += " high"; } else { encoder += " fast"; } } } } else { if ((wvh3.flags & HIGH_FLAG_v3) == 0) { encoder = "lossless (fast mode)"; } else { if ((wvh3.flags & EXTREME_DECORR_v3) > 0) { encoder = "lossless (high mode)"; } else { encoder = "lossless"; } } } if (sampleRate <= 0) sampleRate = 44100; duration = (double)wvh3.total_samples * 1000.0 / sampleRate; if (duration > 0) bitrate = 8.0 * (sizeInfo.FileSize - tagSize - (double)wvh3.ckSize) / duration; } break; } else // not a wv file { break; } } } // while return result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// SubscriptionInMethodOperations operations. /// </summary> internal partial class SubscriptionInMethodOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInMethodOperations { /// <summary> /// Initializes a new instance of the SubscriptionInMethodOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubscriptionInMethodOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// This should appear as a method parameter, use value '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostMethodLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = null, client-side validation should prevent you from /// making this call /// </summary> /// <param name='subscriptionId'> /// This should appear as a method parameter, use value null, client-side /// validation should prvenet the call /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostMethodLocalNullWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// Should appear as a method parameter -use value '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostPathLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostPathLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// The subscriptionId, which appears in the path, the value is always /// '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostSwaggerLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass(typeof(global::android.widget.CursorAdapter_))] public abstract partial class CursorAdapter : android.widget.BaseAdapter, Filterable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CursorAdapter() { InitJNI(); } protected CursorAdapter(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _init11106; protected virtual void init(android.content.Context arg0, android.database.Cursor arg1, bool arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter._init11106, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._init11106, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _onContentChanged11107; protected virtual void onContentChanged() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter._onContentChanged11107); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._onContentChanged11107); } internal static global::MonoJavaBridge.MethodId _getCount11108; public override int getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.CursorAdapter._getCount11108); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getCount11108); } internal static global::MonoJavaBridge.MethodId _getItem11109; public override global::java.lang.Object getItem(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getItem11109, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getItem11109, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _getItemId11110; public override long getItemId(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.widget.CursorAdapter._getItemId11110, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getItemId11110, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFilter11111; public virtual global::android.widget.Filter getFilter() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getFilter11111)) as android.widget.Filter; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getFilter11111)) as android.widget.Filter; } internal static global::MonoJavaBridge.MethodId _hasStableIds11112; public override bool hasStableIds() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.CursorAdapter._hasStableIds11112); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._hasStableIds11112); } internal static global::MonoJavaBridge.MethodId _getView11113; public override global::android.view.View getView(int arg0, android.view.View arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getView11113, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getView11113, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _getCursor11114; public virtual global::android.database.Cursor getCursor() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getCursor11114)) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getCursor11114)) as android.database.Cursor; } internal static global::MonoJavaBridge.MethodId _getDropDownView11115; public override global::android.view.View getDropDownView(int arg0, android.view.View arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getDropDownView11115, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getDropDownView11115, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _newView11116; public abstract global::android.view.View newView(android.content.Context arg0, android.database.Cursor arg1, android.view.ViewGroup arg2); internal static global::MonoJavaBridge.MethodId _newDropDownView11117; public virtual global::android.view.View newDropDownView(android.content.Context arg0, android.database.Cursor arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._newDropDownView11117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._newDropDownView11117, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _bindView11118; public abstract void bindView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2); internal static global::MonoJavaBridge.MethodId _changeCursor11119; public virtual void changeCursor(android.database.Cursor arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter._changeCursor11119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._changeCursor11119, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _convertToString11120; public virtual global::java.lang.CharSequence convertToString(android.database.Cursor arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._convertToString11120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._convertToString11120, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _runQueryOnBackgroundThread11121; public virtual global::android.database.Cursor runQueryOnBackgroundThread(java.lang.CharSequence arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._runQueryOnBackgroundThread11121, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.database.Cursor>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._runQueryOnBackgroundThread11121, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.Cursor; } public android.database.Cursor runQueryOnBackgroundThread(string arg0) { return runQueryOnBackgroundThread((global::java.lang.CharSequence)(global::java.lang.String)arg0); } internal static global::MonoJavaBridge.MethodId _getFilterQueryProvider11122; public virtual global::android.widget.FilterQueryProvider getFilterQueryProvider() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.FilterQueryProvider>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter._getFilterQueryProvider11122)) as android.widget.FilterQueryProvider; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.widget.FilterQueryProvider>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._getFilterQueryProvider11122)) as android.widget.FilterQueryProvider; } internal static global::MonoJavaBridge.MethodId _setFilterQueryProvider11123; public virtual void setFilterQueryProvider(android.widget.FilterQueryProvider arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter._setFilterQueryProvider11123, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._setFilterQueryProvider11123, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _CursorAdapter11124; public CursorAdapter(android.content.Context arg0, android.database.Cursor arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._CursorAdapter11124, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _CursorAdapter11125; public CursorAdapter(android.content.Context arg0, android.database.Cursor arg1, bool arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.CursorAdapter.staticClass, global::android.widget.CursorAdapter._CursorAdapter11125, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.CursorAdapter.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorAdapter")); global::android.widget.CursorAdapter._init11106 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "init", "(Landroid/content/Context;Landroid/database/Cursor;Z)V"); global::android.widget.CursorAdapter._onContentChanged11107 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "onContentChanged", "()V"); global::android.widget.CursorAdapter._getCount11108 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getCount", "()I"); global::android.widget.CursorAdapter._getItem11109 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getItem", "(I)Ljava/lang/Object;"); global::android.widget.CursorAdapter._getItemId11110 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getItemId", "(I)J"); global::android.widget.CursorAdapter._getFilter11111 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getFilter", "()Landroid/widget/Filter;"); global::android.widget.CursorAdapter._hasStableIds11112 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "hasStableIds", "()Z"); global::android.widget.CursorAdapter._getView11113 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.CursorAdapter._getCursor11114 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getCursor", "()Landroid/database/Cursor;"); global::android.widget.CursorAdapter._getDropDownView11115 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getDropDownView", "(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.CursorAdapter._newView11116 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "newView", "(Landroid/content/Context;Landroid/database/Cursor;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.CursorAdapter._newDropDownView11117 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "newDropDownView", "(Landroid/content/Context;Landroid/database/Cursor;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.CursorAdapter._bindView11118 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "bindView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;)V"); global::android.widget.CursorAdapter._changeCursor11119 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "changeCursor", "(Landroid/database/Cursor;)V"); global::android.widget.CursorAdapter._convertToString11120 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "convertToString", "(Landroid/database/Cursor;)Ljava/lang/CharSequence;"); global::android.widget.CursorAdapter._runQueryOnBackgroundThread11121 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "runQueryOnBackgroundThread", "(Ljava/lang/CharSequence;)Landroid/database/Cursor;"); global::android.widget.CursorAdapter._getFilterQueryProvider11122 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "getFilterQueryProvider", "()Landroid/widget/FilterQueryProvider;"); global::android.widget.CursorAdapter._setFilterQueryProvider11123 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "setFilterQueryProvider", "(Landroid/widget/FilterQueryProvider;)V"); global::android.widget.CursorAdapter._CursorAdapter11124 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "<init>", "(Landroid/content/Context;Landroid/database/Cursor;)V"); global::android.widget.CursorAdapter._CursorAdapter11125 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter.staticClass, "<init>", "(Landroid/content/Context;Landroid/database/Cursor;Z)V"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.CursorAdapter))] public sealed partial class CursorAdapter_ : android.widget.CursorAdapter { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CursorAdapter_() { InitJNI(); } internal CursorAdapter_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _newView11126; public override global::android.view.View newView(android.content.Context arg0, android.database.Cursor arg1, android.view.ViewGroup arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter_._newView11126, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.CursorAdapter_.staticClass, global::android.widget.CursorAdapter_._newView11126, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.view.View; } internal static global::MonoJavaBridge.MethodId _bindView11127; public override void bindView(android.view.View arg0, android.content.Context arg1, android.database.Cursor arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter_._bindView11127, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.CursorAdapter_.staticClass, global::android.widget.CursorAdapter_._bindView11127, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.CursorAdapter_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/CursorAdapter")); global::android.widget.CursorAdapter_._newView11126 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter_.staticClass, "newView", "(Landroid/content/Context;Landroid/database/Cursor;Landroid/view/ViewGroup;)Landroid/view/View;"); global::android.widget.CursorAdapter_._bindView11127 = @__env.GetMethodIDNoThrow(global::android.widget.CursorAdapter_.staticClass, "bindView", "(Landroid/view/View;Landroid/content/Context;Landroid/database/Cursor;)V"); } } }
//------------------------------------------------------------------------------------------ // helpers.cs // Helper functions used in the experimental DXAI system. // https://github.com/Ragora/T2-DXAI.git // // Copyright (c) 2015 Robert MacGregor // This software is licensed under the MIT license. // Refer to LICENSE.txt for more information. //------------------------------------------------------------------------------------------ function sameSide(%p1, %p2, %a, %b) { %cp1 = vectorCross(vectorSub(%b, %a), vectorSub(%p1, %a)); %cp2 = vectorCross(vectorSub(%b, %a), vectorSub(%p2, %a)); if (vectorDot(%cp1, %cp2) >= 0) return true; return false; } //------------------------------------------------------------------------------------------ // Description: Returns whether or not the given point resides inside of the triangle // denoted by points %a, %b and %c. // Param %point: The point to test. // Param %a: One point of the triangle. // Param %b: One point of the triangle. // Param %c: One point of the triangle. // Return: A boolean representing whether or not the given point resides inside of the // triangle. //------------------------------------------------------------------------------------------ function pointInTriangle(%point, %a, %b, %c) { if (sameSide(%point, %a, %b, %c) && sameSide(%point, %b, %a, %c) && sameSide(%point, %c, %a, %b)) return true; return false; } function Player::getXFacing(%this) { %forward = %this.getForwardVector(); return mAtan(getWord(%forward, 1), getWord(%forward, 0)); } //------------------------------------------------------------------------------------------ // Description: Calculates all the points of the given client's view cone given a maximum // view distance and returns them in a long string. // Param %distance: The distance of their view cone. // Return: A string in the following format: // "OriginX OriginY OriginZ Outer1X Outer1Y Outer1Z Outer2X Outer2Y Outer2Z UpperX UpperY UpperZ // LowerX LowerY LowerZ" // // TODO: Return in a faster-to-read format: Could try as static GVar names // as the game's scripting environment for the gameplay is single threaded // and it probably does a hash to store the values. // FIXME: The horizontal view cones may be all that's necessary. A player // height check could be used to help alleviate computational complexity. //------------------------------------------------------------------------------------------ function GameConnection::calculateViewCone(%this, %distance) { if (!isObject(%this.player) || %this.player.getState() !$= "Move") return -1; %xFacing = %this.player.getXFacing(); %coneOrigin = %this.player.getMuzzlePoint($WeaponSlot); %halfView = %this.fieldOfView / 2; %cos = mCos(%halfView); %sin = mSin(%halfView); // Translate the horizontal points %viewConeClockwisePoint = vectorAdd(%coneOrigin, vectorScale(%cos SPC -%sin SPC "0", %this.viewDistance)); %viewConeCounterClockwisePoint = vectorAdd(%coneOrigin, vectorScale(%cos SPC -%sin SPC "0", %this.viewDistance)); // Translate the upper and lower points %halfDistance = vectorDist(%viewConeCounterClockwisePoint, %viewConeClockwisePoint) / 2; %viewConeUpperPoint = vectorAdd(%coneOrigin, "0 0" SPC %halfDistance); %viewConeLowerPoint = vectorAdd(%coneOrigin, "0 0" SPC -%halfDistance); return %coneOrigin SPC %viewConeClockwisePoint SPC %viewConeCounterClockwisePoint SPC %viewConeUpperPoint SPC %viewConeLowerPoint; } //------------------------------------------------------------------------------------------ // Description: Returns a SimSet of all contained object ID's inside of the given SimSet, // including those in child SimGroup and SimSet instances. // Return: The ID of the SimSet that contains all child objects that are not containers // themselves. //------------------------------------------------------------------------------------------ function SimSet::recurse(%this, %result) { if (!isObject(%result)) %result = new SimSet(); for (%iteration = 0; %iteration < %this.getCount(); %iteration++) { %current = %this.getObject(%iteration); if (%current.getClassName() $= "SimGroup" || %current.getClassName() $= "SimSet") %current.recurse(%result); else %result.add(%current); } return %result; } //------------------------------------------------------------------------------------------ // Description: Returns the closest friendly inventory station to the given client. // Return: The object ID of the inventory station determined to be the closest to this // client. // // TODO: Use the nav graph to estimate an actual distance? // FIXME: Return *working* stations only. //------------------------------------------------------------------------------------------ function GameConnection::getClosestInventory(%this) { if (!isObject(%this.player)) return -1; %group = nameToID("Team" @ %this.team); if (!isObject(%group)) return -1; %teamObjects = %group.recurse(); %closestInventory = -1; %closestInventoryDistance = 9999; for (%iteration = 0; %iteration < %teamObjects.getCount(); %iteration++) { %current = %teamObjects.getObject(%iteration); if (%current.getClassName() $= "StaticShape" && %current.getDatablock().getName() $= "StationInventory") { %inventoryDistance = vectorDist(%current.getPosition(), %this.player.getPosition()); if (%inventoryDistance < %closestInventoryDistance) { %closestInventoryDistance = %inventoryDistance; %closestInventory = %current; } } } %teamObjects.delete(); return %closestInventory; } function Player::getFacingAngle(%this) { %vector = vectorNormalize(%this.getMuzzleVector($WeaponSlot)); return mAtan(getWord(%vector, 1), getWord(%vector, 0)); } function Player::getViewConeIntersection(%this, %target, %maxDistance, %viewAngle) { %myPosition = %this.getPosition(); %targetPosition = %target.getPosition(); if (vectorDist(%myPosition, %targetPosition) > %maxDistance) return false; %offset = vectorNormalize(vectorSub(%targetPosition, %myPosition)); %enemyAngle = mAtan(getWord(%offset, 1), getWord(%offset, 0)); %myAngle = %this.getFacingAngle(); %angle = %enemyAngle - %myAngle; %viewMax = %viewAngle / 2; %viewMin = -(%viewAngle / 2); if (%angle >= %viewMin && %angle <= %viewMax) return true; return false; } function Player::getPackName(%this) { %item = %this.getMountedImage(2).item; if (!isObject(%item)) return ""; return %item.getName(); } function Player::canSeeObject(%this, %target, %maxDistance, %viewAngle) { if (%target.isCloaked() || !%this.getViewConeIntersection(%target, %maxDistance, %viewAngle)) return false; %coneOrigin = %this.getPosition(); // Try to raycast the object %rayCast = containerRayCast(%coneOrigin, %target.getWorldBoxCenter(), $TypeMasks::AllObjectType, %this); %hitObject = getWord(%raycast, 0); // Since the engine doesn't do raycasts against projectiles & items correctly, we just check if the bot // hit -nothing- when doing the raycast rather than checking for a hit against the object %workaroundTypes = $TypeMasks::ProjectileObjectType | $TypeMasks::ItemObjectType; if (%hitObject == %target || (%target.getType() & %workaroundTypes && !isObject(%hitObject))) return true; return false; } function Precipitation::isCloaked(%this) { return false; } function LinearProjectile::isCloaked(%this) { return false; } function LinearFlareProjectile::isCloaked(%this) { return false; } function GrenadeProjectile::isCloaked(%this) { return false; } function SniperProjectile::isCloaked(%this) { return false; } function Player::getBackwardsVector(%this) { return vectorScale(%this.getForwardVector(), -1); } //------------------------------------------------------------------------------------------ // Description: Calculates a list of objects that can be seen by the given client using // distance & field of view values passed in for evaluation. // Param %typeMask: The typemask of all objects to consider. // Param %distance: The maximum distance to project our view cone checks out to. // Param %performLOSTest: A boolean representing whether or not found objects should be // verified using a raycast test. If you cannot draw a line from the player to the potential // target, then it the potential target is discarded. // Return: A SimSet of objects that can be seen by the given client. //------------------------------------------------------------------------------------------ function GameConnection::getObjectsInViewcone(%this, %typeMask, %distance, %performLOSTest) { // FIXME: Radians if (%this.fieldOfView < 0 || %this.fieldOfView > 3.14) { %this.fieldOfView = $DXAPI::Bot::DefaultFieldOfView; error("DXAI: Bad field of view value! (" @ %this @ ".fieldOfView > 3.14 || " @ %this @ ".fieldOfView < 0)"); } if (%this.viewDistance <= 0) { %this.viewDistance = $DXAPI::Bot::DefaultViewDistance; error("DXAI: Bad view distance value! (" @ %this @ ".viewDistance <= 0)"); } if (%distance $= "") %distance = %this.viewDistance; %result = new SimSet(); %coneOrigin = %this.player.getPosition(); // Doing a radius search should hopefully be faster than iterating over all objects in MissionCleanup. // Even if the game did that internally it's definitely faster than doing it in TS InitContainerRadiusSearch(%coneOrigin, %distance, %typeMask); while((%currentObject = containerSearchNext()) != 0) { if (%currentObject == %this || !isObject(%currentObject) || containerSearchCurrRadDamageDist() > %distance || %currentObject.isCloaked()) continue; // Check if the object is within both the horizontal and vertical triangles representing our view cone if (%currentObject.getType() & %typeMask && %this.player.getViewConeIntersection(%currentObject, %distance, %this.fieldOfView)) if (!%performLOSTest || %this.player.canSeeObject(%currentObject, %distance, %this.fieldOfView)) %result.add(%currentObject); } return %result; } //------------------------------------------------------------------------------------------ // Description: Gets a random position somewhere within %distance of the given position. // Param %position: The position to generate a new position around. // Param %distance: The maximum distance the new position may be // Param %raycast: A boolean representing whether or not a raycast should be made from // %position to the randomly chosen location to stop on objects that may be in the way. // This is useful for grabbing positions indoors. //------------------------------------------------------------------------------------------ function getRandomPosition(%position, %distance, %raycast) { // First, we determine a random direction vector %direction = vectorNormalize(getRandom(0, 10000) SPC getRandom(0, 10000) SPC getRandom(0, 10000)); // Return the scaled result %result = vectorAdd(%position, vectorScale(%direction, getRandom(0, %distance))); if (!%raycast) return %result; %rayCast = containerRayCast(%position, %result, $TypeMasks::InteriorObjectType | $TypeMasks::StaticShapeObjectType, 0); %result = getWords(%raycast, 1, 3); return %result; } //------------------------------------------------------------------------------------------ // Description: Gets a random position somewhere within %distance of the given position // relative to the terrain object using getTerrainHeight. This is faster to use than // getRandomPosition with the raycast setting if all that is necessary is generating a // position relative to the terrain object. // Param %position: The position to generate a new position around. // Param %distance: The maximum distance the new position may be //------------------------------------------------------------------------------------------ function getRandomPositionOnTerrain(%position, %distance) { %result = getRandomPosition(%position, %distance); return setWord(%result, 2, getTerrainHeight(%result)); } function getRandomPositionInInterior(%position, %distance) { %firstPass = getRandomPosition(%position, %distance, true); %rayCast = containerRayCast(%position, vectorAdd(%position, "0 0 -9000"), $TypeMasks::InteriorObjectType | $TypeMasks::StaticShapeObjectType, 0); if (%rayCast == -1) return %firstPass; return getWords(%raycast, 1, 3); } function getRandomFloat(%min, %max) { return %min + (getRandom() * (%max - %min)); } //------------------------------------------------------------------------------------------ // Description: Multiplies two vectors together and returns the result. // Param %vec1: The first vector to multiply. // Param %vec2: The second vector to multiply. // Return: The product of the multiplication. //------------------------------------------------------------------------------------------ function vectorMult(%vec1, %vec2) { return (getWord(%vec1, 0) * getWord(%vec2, 0)) SPC (getWord(%vec1, 1) * getWord(%vec2, 1)) SPC (getWord(%vec1, 2) * getWord(%vec2, 2)); } function listStuckBots() { for (%iteration = 0; %iteration < ClientGroup.getCount(); %iteration++) { %client = ClientGroup.getObject(%iteration); if (%client.isAIControlled() && %client.isPathCorrecting) error(%client); } } // If the map editor was instantiated, this will prevent a little bit // of console warnings function Terraformer::getType(%this) { return 0; } // Dummy ScriptObject methods to silence console warnings when testing the runtime // environment; this may not silence for all mods but it should help. $DXAI::System::RuntimeDummy = new ScriptObject(RuntimeDummy) { class = "RuntimeDummy"; }; function RuntimeDummy::addTask() { } function RuntimeDummy::reset() { } $TypeMasks::InteractiveObjectType = $TypeMasks::PlayerObjectType | $TypeMasks::VehicleObjectType | $TypeMasks::WaterObjectType | $TypeMasks::ProjectileObjectType | $TypeMasks::ItemObjectType | $TypeMasks::CorpseObjectType; $TypeMasks::UnInteractiveObjectType = $TypeMasks::StaticObjectType | $TypeMasks::TerrainObjectType | $TypeMasks::InteriorObjectType | $TypeMasks::StaticTSObjectType | $TypeMasks::StaticRenderedObjectType; $TypeMasks::BaseAssetObjectType = $TypeMasks::ForceFieldObjectType | $TypeMasks::TurretObjectType | $TypeMasks::SensorObjectType | $TypeMasks::StationObjectType | $TypeMasks::GeneratorObjectType; $TypeMasks::GameSupportObjectType = $TypeMasks::TriggerObjectType | $TypeMasks::MarkerObjectType | $TypeMasks::CameraObjectType | $TypeMasks::VehicleBlockerObjectType | $TypeMasks::PhysicalZoneObjectType; $TypeMasks::GameContentObjectType = $TypeMasks::ExplosionObjectType | $TypeMasks::CorpseObjectType | $TypeMasks::DebrisObjectType; $TypeMasks::DefaultLOSObjectType = $TypeMasks::TerrainObjectType | $TypeMasks::InteriorObjectType | $TypeMasks::StaticObjectType; $TypeMasks::AllObjectType = -1;
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Orleans.Runtime; using LogLevel = Microsoft.Extensions.Logging.LogLevel; // // Number of #ifs can be reduced (or removed), once we separate test projects by feature/area, otherwise we are ending up with ambigous types and build errors. // #if ORLEANS_CLUSTERING namespace Orleans.Clustering.AzureStorage #elif ORLEANS_PERSISTENCE namespace Orleans.Persistence.AzureStorage #elif ORLEANS_REMINDERS namespace Orleans.Reminders.AzureStorage #elif ORLEANS_STREAMING namespace Orleans.Streaming.AzureStorage #elif ORLEANS_EVENTHUBS namespace Orleans.Streaming.EventHubs #elif TESTER_AZUREUTILS namespace Orleans.Tests.AzureUtils #elif ORLEANS_TRANSACTIONS namespace Orleans.Transactions.AzureStorage #else // No default namespace intentionally to cause compile errors if something is not defined #endif { /// <summary> /// Utility class to encapsulate row-based access to Azure table storage. /// </summary> /// <remarks> /// These functions are mostly intended for internal usage by Orleans runtime, but due to certain assembly packaging constraints this class needs to have public visibility. /// </remarks> /// <typeparam name="T">Table data entry used by this table / manager.</typeparam> public class AzureTableDataManager<T> where T : class, ITableEntity, new() { /// <summary> Name of the table this instance is managing. </summary> public string TableName { get; private set; } /// <summary> Logger for this table manager instance. </summary> protected internal ILogger Logger { get; private set; } /// <summary> Connection string for the Azure storage account used to host this table. </summary> protected string ConnectionString { get; set; } private CloudTable tableReference; public CloudTable Table => tableReference; #if !ORLEANS_TRANSACTIONS private readonly CounterStatistic numServerBusy = CounterStatistic.FindOrCreate(StatisticNames.AZURE_SERVER_BUSY, true); #endif /// <summary> /// Constructor /// </summary> /// <param name="tableName">Name of the table to be connected to.</param> /// <param name="storageConnectionString">Connection string for the Azure storage account used to host this table.</param> /// <param name="loggerFactory">Logger factory to use.</param> public AzureTableDataManager(string tableName, string storageConnectionString, ILoggerFactory loggerFactory) { Logger = loggerFactory.CreateLogger<AzureTableDataManager<T>>(); TableName = tableName; ConnectionString = storageConnectionString; AzureStorageUtils.ValidateTableName(tableName); } /// <summary> /// Connects to, or creates and initializes a new Azure table if it does not already exist. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task InitTableAsync() { const string operation = "InitTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didCreate = await tableRef.CreateIfNotExistsAsync(); Logger.Info((int)Utilities.ErrorCode.AzureTable_01, "{0} Azure storage table {1}", (didCreate ? "Created" : "Attached to"), TableName); CloudTableClient tableOperationsClient = GetCloudTableOperationsClient(); tableReference = tableOperationsClient.GetTableReference(TableName); } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_02, $"Could not initialize connection to storage table {TableName}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task DeleteTableAsync() { const string operation = "DeleteTable"; var startTime = DateTime.UtcNow; try { CloudTableClient tableCreationClient = GetCloudTableCreationClient(); CloudTable tableRef = tableCreationClient.GetTableReference(TableName); bool didDelete = await tableRef.DeleteIfExistsAsync(); if (didDelete) { Logger.Info((int)Utilities.ErrorCode.AzureTable_03, "Deleted Azure storage table {0}", TableName); } } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_04, "Could not delete storage table {0}", exc); throw; } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes all entities the Azure table. /// </summary> /// <returns>Completion promise for this operation.</returns> public async Task ClearTableAsync() { IEnumerable<Tuple<T,string>> items = await ReadAllTableEntriesAsync(); IEnumerable<Task> work = items.GroupBy(item => item.Item1.PartitionKey) .SelectMany(partition => partition.ToBatch(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) .Select(batch => DeleteTableEntriesAsync(batch.ToList())); await Task.WhenAll(work); } /// <summary> /// Create a new data entry in the Azure table (insert new, not update existing). /// Fails if the data already exists. /// </summary> /// <param name="data">Data to be inserted into the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> CreateTableEntryAsync(T data) { const string operation = "CreateTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Creating {0} table entry: {1}", TableName, data); try { // WAS: // svc.AddObject(TableName, data); // SaveChangesOptions.None try { // Presumably FromAsync(BeginExecute, EndExecute) has a slightly better performance then CreateIfNotExistsAsync. var opResult = await tableReference.ExecuteAsync(TableOperation.Insert(data)); return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a data entry in the Azure table: creates a new one if does not exists or overwrites (without eTag) an already existing version (the "update in place" semantics). /// </summary> /// <param name="data">Data to be inserted or replaced in the table.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpsertTableEntryAsync(T data) { const string operation = "UpsertTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, null); // svc.UpdateObject(data); // SaveChangesOptions.ReplaceOnUpdate, var opResult = await tableReference.ExecuteAsync(TableOperation.InsertOrReplace(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_06, $"Intermediate error upserting entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Merges a data entry in the Azure table. /// </summary> /// <param name="data">Data to be merged in the table.</param> /// <param name="eTag">ETag to apply.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> internal async Task<string> MergeTableEntryAsync(T data, string eTag) { const string operation = "MergeTableEntry"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} entry {1} into table {2}", operation, data, TableName); try { try { // WAS: // svc.AttachTo(TableName, data, ANY_ETAG); // svc.UpdateObject(data); data.ETag = eTag; // Merge requires an ETag (which may be the '*' wildcard). var opResult = await tableReference.ExecuteAsync(TableOperation.Merge(data)); return opResult.Etag; } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_07, $"Intermediate error merging entry {(data == null ? "null" : data.ToString())} to the table {TableName}", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Updates a data entry in the Azure table: updates an already existing data in the table, by using eTag. /// Fails if the data does not already exist or of eTag does not match. /// </summary> /// <param name="data">Data to be updated into the table.</param> /// /// <param name="dataEtag">ETag to use.</param> /// <returns>Value promise with new Etag for this data entry after completing this storage operation.</returns> public async Task<string> UpdateTableEntryAsync(T data, string dataEtag) { const string operation = "UpdateTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { try { data.ETag = dataEtag; var opResult = await tableReference.ExecuteAsync(TableOperation.Replace(data)); //The ETag of data is needed in further operations. return opResult.Etag; } catch (Exception exc) { CheckAlertWriteError(operation, data, null, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Deletes an already existing data in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="data">Data entry to be deleted from the table.</param> /// <param name="eTag">ETag to use.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntryAsync(T data, string eTag) { const string operation = "DeleteTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} entry {2}", operation, TableName, data); try { data.ETag = eTag; try { await tableReference.ExecuteAsync(TableOperation.Delete(data)); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_08, $"Intermediate error deleting entry {data} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read a single table entry from the storage table. /// </summary> /// <param name="partitionKey">The partition key for the entry.</param> /// <param name="rowKey">The row key for the entry.</param> /// <returns>Value promise for tuple containing the data entry and its corresponding etag.</returns> public async Task<Tuple<T, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey) { const string operation = "ReadSingleTableEntryAsync"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} partitionKey {2} rowKey = {3}", operation, TableName, partitionKey, rowKey); T retrievedResult = default(T); try { try { string queryString = TableQueryFilterBuilder.MatchPartitionKeyAndRowKeyFilter(partitionKey, rowKey); var query = new TableQuery<T>().Where(queryString); TableQuerySegment<T> segment = await tableReference.ExecuteQuerySegmentedAsync(query, null); retrievedResult = segment.Results.SingleOrDefault(); } catch (StorageException exception) { if (!AzureStorageUtils.TableStorageDataNotFound(exception)) throw; } //The ETag of data is needed in further operations. if (retrievedResult != null) return new Tuple<T, string>(retrievedResult, retrievedResult.ETag); if (Logger.IsEnabled(LogLevel.Debug)) Logger.Debug("Could not find table entry for PartitionKey={0} RowKey={1}", partitionKey, rowKey); return null; // No data } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read all entries in one partition of the storage table. /// NOTE: This could be an expensive and slow operation for large table partitions! /// </summary> /// <param name="partitionKey">The key for the partition to be searched.</param> /// <returns>Enumeration of all entries in the specified table partition.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesForPartitionAsync(string partitionKey) { string query = TableQuery.GenerateFilterCondition(nameof(ITableEntity.PartitionKey), QueryComparisons.Equal, partitionKey); return ReadTableEntriesAndEtagsAsync(query); } /// <summary> /// Read all entries in the table. /// NOTE: This could be a very expensive and slow operation for large tables! /// </summary> /// <returns>Enumeration of all entries in the table.</returns> public Task<IEnumerable<Tuple<T, string>>> ReadAllTableEntriesAsync() { return ReadTableEntriesAndEtagsAsync(null); } /// <summary> /// Deletes a set of already existing data entries in the table, by using eTag. /// Fails if the data does not already exist or if eTag does not match. /// </summary> /// <param name="collection">Data entries and their corresponding etags to be deleted from the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task DeleteTableEntriesAsync(IReadOnlyCollection<Tuple<T, string>> collection) { const string operation = "DeleteTableEntries"; var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Deleting {0} table entries: {1}", TableName, Utils.EnumerableToString(collection)); if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk delete - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } try { var entityBatch = new TableBatchOperation(); foreach (var tuple in collection) { // WAS: // svc.AttachTo(TableName, tuple.Item1, tuple.Item2); // svc.DeleteObject(tuple.Item1); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, T item = tuple.Item1; item.ETag = tuple.Item2; entityBatch.Delete(item); } try { await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_08, $"Intermediate error deleting entries {Utils.EnumerableToString(collection)} from the table {TableName}.", exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Read data entries and their corresponding eTags from the Azure table. /// </summary> /// <param name="filter">Filter string to use for querying the table and filtering the results.</param> /// <returns>Enumeration of entries in the table which match the query condition.</returns> public async Task<IEnumerable<Tuple<T, string>>> ReadTableEntriesAndEtagsAsync(string filter) { const string operation = "ReadTableEntriesAndEtags"; var startTime = DateTime.UtcNow; try { TableQuery<T> cloudTableQuery = filter == null ? new TableQuery<T>() : new TableQuery<T>().Where(filter); try { Func<Task<List<T>>> executeQueryHandleContinuations = async () => { TableQuerySegment<T> querySegment = null; var list = new List<T>(); //ExecuteSegmentedAsync not supported in "WindowsAzure.Storage": "7.2.1" yet while (querySegment == null || querySegment.ContinuationToken != null) { querySegment = await tableReference.ExecuteQuerySegmentedAsync(cloudTableQuery, querySegment?.ContinuationToken); list.AddRange(querySegment); } return list; }; #if !ORLEANS_TRANSACTIONS IBackoffProvider backoff = new FixedBackoff(AzureTableDefaultPolicies.PauseBetweenTableOperationRetries); List<T> results = await AsyncExecutorWithRetries.ExecuteWithRetries( counter => executeQueryHandleContinuations(), AzureTableDefaultPolicies.MaxTableOperationRetries, (exc, counter) => AzureStorageUtils.AnalyzeReadException(exc.GetBaseException(), counter, TableName, Logger), AzureTableDefaultPolicies.TableOperationTimeout, backoff); #else List<T> results = await executeQueryHandleContinuations(); #endif // Data was read successfully if we got to here return results.Select(i => Tuple.Create(i, i.ETag)).ToList(); } catch (Exception exc) { // Out of retries... var errorMsg = $"Failed to read Azure storage table {TableName}: {exc.Message}"; if (!AzureStorageUtils.TableStorageDataNotFound(exc)) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_09, errorMsg, exc); } throw new OrleansException(errorMsg, exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } /// <summary> /// Inserts a set of new data entries into the table. /// Fails if the data does already exists. /// </summary> /// <param name="collection">Data entries to be inserted into the table.</param> /// <returns>Completion promise for this storage operation.</returns> public async Task BulkInsertTableEntries(IReadOnlyCollection<T> collection) { const string operation = "BulkInsertTableEntries"; if (collection == null) throw new ArgumentNullException("collection"); if (collection.Count > AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS) { throw new ArgumentOutOfRangeException("collection", collection.Count, "Too many rows for bulk update - max " + AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS); } if (collection.Count == 0) { return; } var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("Bulk inserting {0} entries to {1} table", collection.Count, TableName); try { // WAS: // svc.AttachTo(TableName, entry); // svc.UpdateObject(entry); // SaveChangesOptions.None | SaveChangesOptions.Batch, // SaveChangesOptions.None == Insert-or-merge operation, SaveChangesOptions.Batch == Batch transaction // http://msdn.microsoft.com/en-us/library/hh452241.aspx var entityBatch = new TableBatchOperation(); foreach (T entry in collection) { entityBatch.Insert(entry); } try { // http://msdn.microsoft.com/en-us/library/hh452241.aspx await tableReference.ExecuteBatchAsync(entityBatch); } catch (Exception exc) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_37, $"Intermediate error bulk inserting {collection.Count} entries in the table {TableName}", exc); } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> InsertTwoTableEntriesConditionallyAsync(T data1, T data2, string data2Etag) { const string operation = "InsertTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} into table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AddObject(TableName, data); // --- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); entityBatch.Add(TableOperation.Insert(data1)); data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } internal async Task<Tuple<string, string>> UpdateTwoTableEntriesConditionallyAsync(T data1, string data1Etag, T data2, string data2Etag) { const string operation = "UpdateTableEntryConditionally"; string data2Str = (data2 == null ? "null" : data2.ToString()); var startTime = DateTime.UtcNow; if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("{0} table {1} data1 {2} data2 {3}", operation, TableName, data1, data2Str); try { try { // WAS: // Only AddObject, do NOT AttachTo. If we did both UpdateObject and AttachTo, it would have been equivalent to InsertOrReplace. // svc.AttachTo(TableName, data, dataEtag); // svc.UpdateObject(data); // ---- // svc.AttachTo(TableName, tableVersion, tableVersionEtag); // svc.UpdateObject(tableVersion); // SaveChangesOptions.ReplaceOnUpdate | SaveChangesOptions.Batch, // EntityDescriptor dataResult = svc.GetEntityDescriptor(data); // return dataResult.ETag; var entityBatch = new TableBatchOperation(); data1.ETag = data1Etag; entityBatch.Add(TableOperation.Replace(data1)); if (data2 != null && data2Etag != null) { data2.ETag = data2Etag; entityBatch.Add(TableOperation.Replace(data2)); } var opResults = await tableReference.ExecuteBatchAsync(entityBatch); //The batch results are returned in order of execution, //see reference at https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.cloudtable.executebatch.aspx. //The ETag of data is needed in further operations. return new Tuple<string, string>(opResults[0].Etag, opResults[1].Etag); } catch (Exception exc) { CheckAlertWriteError(operation, data1, data2Str, exc); throw; } } finally { CheckAlertSlowAccess(startTime, operation); } } // Utility methods private CloudTableClient GetCloudTableOperationsClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient operationsClient = storageAccount.CreateCloudTableClient(); operationsClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableOperationRetryPolicy; operationsClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableOperationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value operationsClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return operationsClient; } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_17, "Error creating CloudTableOperationsClient.", exc); throw; } } private CloudTableClient GetCloudTableCreationClient() { try { CloudStorageAccount storageAccount = AzureStorageUtils.GetCloudStorageAccount(ConnectionString); CloudTableClient creationClient = storageAccount.CreateCloudTableClient(); creationClient.DefaultRequestOptions.RetryPolicy = AzureTableDefaultPolicies.TableCreationRetryPolicy; creationClient.DefaultRequestOptions.ServerTimeout = AzureTableDefaultPolicies.TableCreationTimeout; // Values supported can be AtomPub, Json, JsonFullMetadata or JsonNoMetadata with Json being the default value creationClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.JsonNoMetadata; return creationClient; } catch (Exception exc) { Logger.Error((int)Utilities.ErrorCode.AzureTable_18, "Error creating CloudTableCreationClient.", exc); throw; } } private void CheckAlertWriteError(string operation, object data1, string data2, Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if(AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus) && AzureStorageUtils.IsContentionError(httpStatusCode)) { // log at Verbose, since failure on conditional is not not an error. Will analyze and warn later, if required. if(Logger.IsEnabled(LogLevel.Debug)) Logger.Debug((int)Utilities.ErrorCode.AzureTable_13, $"Intermediate Azure table write error {operation} to table {TableName} data1 {(data1 ?? "null")} data2 {(data2 ?? "null")}", exc); } else { Logger.Error((int)Utilities.ErrorCode.AzureTable_14, $"Azure table access write error {operation} to table {TableName} entry {data1}", exc); } } private void CheckAlertSlowAccess(DateTime startOperation, string operation) { var timeSpan = DateTime.UtcNow - startOperation; if (timeSpan > AzureTableDefaultPolicies.TableOperationTimeout) { Logger.Warn((int)Utilities.ErrorCode.AzureTable_15, "Slow access to Azure Table {0} for {1}, which took {2}.", TableName, operation, timeSpan); } } /// <summary> /// Helper functions for building table queries. /// </summary> private class TableQueryFilterBuilder { /// <summary> /// Builds query string to match partitionkey /// </summary> /// <param name="partitionKey"></param> /// <returns></returns> public static string MatchPartitionKeyFilter(string partitionKey) { return TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey); } /// <summary> /// Builds query string to match rowkey /// </summary> /// <param name="rowKey"></param> /// <returns></returns> public static string MatchRowKeyFilter(string rowKey) { return TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey); } /// <summary> /// Builds a query string that matches a specific partitionkey and rowkey. /// </summary> /// <param name="partitionKey"></param> /// <param name="rowKey"></param> /// <returns></returns> public static string MatchPartitionKeyAndRowKeyFilter(string partitionKey, string rowKey) { return TableQuery.CombineFilters(MatchPartitionKeyFilter(partitionKey), TableOperators.And, MatchRowKeyFilter(rowKey)); } } } internal static class TableDataManagerInternalExtensions { internal static IEnumerable<IEnumerable<TItem>> ToBatch<TItem>(this IEnumerable<TItem> source, int size) { using (IEnumerator<TItem> enumerator = source.GetEnumerator()) while (enumerator.MoveNext()) yield return Take(enumerator, size); } private static IEnumerable<TItem> Take<TItem>(IEnumerator<TItem> source, int size) { int i = 0; do yield return source.Current; while (++i < size && source.MoveNext()); } } }
using System; using System.Globalization; using System.Linq; using NetGore.Collections; // ReSharper disable MemberCanBeMadeStatic.Global namespace NetGore { /// <summary> /// Provides parsing for values while forcing them to use the specified culture. /// </summary> public class Parser { const NumberStyles _nsByte = NumberStyles.Integer; const DateTimeStyles _nsDateTime = DateTimeStyles.None; const NumberStyles _nsDecimal = NumberStyles.Number; const NumberStyles _nsDouble = NumberStyles.Float | NumberStyles.AllowThousands; const NumberStyles _nsFloat = NumberStyles.Float | NumberStyles.AllowThousands; const NumberStyles _nsInt = NumberStyles.Integer; const NumberStyles _nsLong = NumberStyles.Integer; const NumberStyles _nsSByte = NumberStyles.Integer; const NumberStyles _nsShort = NumberStyles.Integer; const NumberStyles _nsUInt = NumberStyles.Integer; const NumberStyles _nsULong = NumberStyles.Integer; const NumberStyles _nsUShort = NumberStyles.Integer; /// <summary> /// The cache of <see cref="Parser"/>s for <see cref="CultureInfo"/>s. /// </summary> static readonly ICache<CultureInfo, Parser> _parserCache = new ThreadSafeHashCache<CultureInfo, Parser>(x => new Parser(x, x.NumberFormat, x.DateTimeFormat)); static readonly Parser _parserCurrent; static readonly Parser _parserInvariant; readonly CultureInfo _culture; readonly DateTimeFormatInfo _dateTimeInfo; readonly NumberFormatInfo _info; /// <summary> /// Initializes the <see cref="Parser"/> class. /// </summary> static Parser() { _parserCurrent = new Parser(CultureInfo.CurrentCulture, NumberFormatInfo.CurrentInfo, DateTimeFormatInfo.CurrentInfo); _parserInvariant = new Parser(CultureInfo.InvariantCulture, NumberFormatInfo.InvariantInfo, DateTimeFormatInfo.InvariantInfo); } /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> /// <param name="culture">The culture information.</param> /// <param name="info">The number format information.</param> /// <param name="dateTimeInfo">The date and time format information.</param> /// <exception cref="ArgumentNullException"><paramref name="culture" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="info" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="dateTimeInfo" /> is <c>null</c>.</exception> Parser(CultureInfo culture, NumberFormatInfo info, DateTimeFormatInfo dateTimeInfo) { if (culture == null) throw new ArgumentNullException("culture"); if (info == null) throw new ArgumentNullException("info"); if (dateTimeInfo == null) throw new ArgumentNullException("dateTimeInfo"); _culture = culture; _info = info; _dateTimeInfo = dateTimeInfo; } /// <summary> /// Gets the CultureInfo used for this Parser. /// </summary> public CultureInfo CultureInfo { get { return _culture; } } /// <summary> /// Gets the Parser for the current culture. /// </summary> public static Parser Current { get { return _parserCurrent; } } /// <summary> /// Gets the Parser for an invariant culture. /// </summary> public static Parser Invariant { get { return _parserInvariant; } } /// <summary> /// Gets the NumberFormatInfo used for this Parser. /// </summary> public NumberFormatInfo NumberFormatInfo { get { return _info; } } /// <summary> /// Gets the <see cref="Parser"/> for a given <see cref="CultureInfo"/>. /// </summary> /// <param name="ci">The <see cref="CultureInfo"/> to get the <see cref="Parser"/> for.</param> /// <returns>A <see cref="Parser"/> for the given <paramref name="ci"/>. If the <paramref name="ci"/> is null, returns the /// <see cref="Parser"/> for the invariant culture.</returns> public static Parser FromCulture(CultureInfo ci) { if (ci == null || ci == CultureInfo.InvariantCulture) return Invariant; if (ci == CultureInfo.CurrentCulture) return Current; return _parserCache[ci]; } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public bool ParseBool(string s) { return bool.Parse(s); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public byte ParseByte(string s) { return byte.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public char ParseChar(string s) { return char.Parse(s); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTime ParseDateTime(string s) { return DateTime.Parse(s, _dateTimeInfo); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="format">A format specifier that defines the required format of <paramref name="s"/>.</param> /// <returns> /// The <paramref name="s"/> parsed to the desired type. /// </returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTime ParseDateTimeExact(string s, string format) { return DateTime.ParseExact(s, format, _dateTimeInfo); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="formats">An array of allowable formats of <paramref name="s"/>.</param> /// <returns> /// The <paramref name="s"/> parsed to the desired type. /// </returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTime ParseDateTimeExact(string s, string[] formats) { return DateTime.ParseExact(s, formats, _dateTimeInfo, _nsDateTime); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTimeOffset ParseDateTimeOffset(string s) { return DateTimeOffset.Parse(s, _dateTimeInfo); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="format">A format specifier that defines the required format of <paramref name="s"/>.</param> /// <returns> /// The <paramref name="s"/> parsed to the desired type. /// </returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTimeOffset ParseDateTimeOffsetExact(string s, string format) { return DateTimeOffset.ParseExact(s, format, _dateTimeInfo); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="formats">An array of allowable formats of <paramref name="s"/>.</param> /// <returns> /// The <paramref name="s"/> parsed to the desired type. /// </returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public DateTimeOffset ParseDateTimeOffsetExact(string s, string[] formats) { return DateTimeOffset.ParseExact(s, formats, _dateTimeInfo, _nsDateTime); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public decimal ParseDecimal(string s) { return decimal.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public double ParseDouble(string s) { return double.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public float ParseFloat(string s) { return float.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public int ParseInt(string s) { return int.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public long ParseLong(string s) { return long.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public sbyte ParseSByte(string s) { return sbyte.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public short ParseShort(string s) { return short.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public TimeSpan ParseTimeSpan(string s) { return TimeSpan.Parse(s); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public uint ParseUInt(string s) { return uint.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public ulong ParseULong(string s) { return ulong.Parse(s, _info); } /// <summary> /// Converts a string to the specified type. /// </summary> /// <param name="s">The string to parse.</param> /// <returns>The <paramref name="s"/> parsed to the desired type.</returns> /// <exception cref="System.ArgumentNullException"><paramref name="s"/> is null.</exception> /// <exception cref="System.FormatException"><paramref name="s"/> cannot be parsed to the desired type.</exception> public ushort ParseUShort(string s) { return ushort.Parse(s, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(bool value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(byte value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(byte value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(sbyte value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(sbyte value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(short value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(short value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(ushort value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(ushort value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(int value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(int value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(uint value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(uint value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(long value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(long value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(ulong value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(ulong value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(float value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(float value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(double value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(double value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(decimal value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(decimal value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="f">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="f"/>.</returns> public string ToString(IFormattable f, string format) { return f.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(DateTime value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(DateTime value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(DateTimeOffset value) { return value.ToString(_info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <param name="format">A string that represents the format to convert to.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(DateTimeOffset value, string format) { return value.ToString(format, _info); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(TimeSpan value) { return value.ToString(); } /// <summary> /// Gets the string representation of the given type and value. /// </summary> /// <param name="value">The value to get the string representation for.</param> /// <returns>The string representation of the given <paramref name="value"/>.</returns> public string ToString(char value) { return value.ToString(_info); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out bool value) { return bool.TryParse(s, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out char value) { return char.TryParse(s, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out TimeSpan value) { return TimeSpan.TryParse(s, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out byte value) { return byte.TryParse(s, _nsByte, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out DateTime value) { return DateTime.TryParse(s, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="format">A format specifier that defines the required format of <paramref name="s"/>.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, string format, out DateTime value) { return DateTime.TryParseExact(s, format, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="formats">An array of allowable formats of <paramref name="s"/>.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, string[] formats, out DateTime value) { return DateTime.TryParseExact(s, formats, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out DateTimeOffset value) { return DateTimeOffset.TryParse(s, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="format">A format specifier that defines the required format of <paramref name="s"/>.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, string format, out DateTimeOffset value) { return DateTimeOffset.TryParseExact(s, format, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="formats">An array of allowable formats of <paramref name="s"/>.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, string[] formats, out DateTimeOffset value) { return DateTimeOffset.TryParseExact(s, formats, _dateTimeInfo, _nsDateTime, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out decimal value) { return decimal.TryParse(s, _nsDecimal, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out double value) { return double.TryParse(s, _nsDouble, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out float value) { return float.TryParse(s, _nsFloat, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out int value) { return int.TryParse(s, _nsInt, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out long value) { return long.TryParse(s, _nsLong, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out sbyte value) { return sbyte.TryParse(s, _nsSByte, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out short value) { return short.TryParse(s, _nsShort, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out uint value) { return uint.TryParse(s, _nsUInt, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out ulong value) { return ulong.TryParse(s, _nsULong, _info, out value); } /// <summary> /// Converts a string to the specified type and returns a boolean representing if the conversion was successful. /// </summary> /// <param name="s">The string to parse.</param> /// <param name="value">When this method returns true, contains the result of <paramref name="s"/> converted /// to the desired type.</param> /// <returns>True if value was converted successfully; otherwise, false.</returns> public bool TryParse(string s, out ushort value) { return ushort.TryParse(s, _nsUShort, _info, out value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; using Microsoft.Xunit.Performance; namespace System.Text.Primitives.Tests { public partial class PrimitiveParserPerfTests { [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private static void BaselineSimpleByteStarToUInt64(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; ulong.TryParse(text, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private static void BaselineByteStarToUInt64(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; ulong.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private static void BaselineByteStarToUInt64Hex(string text) { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; ulong.TryParse(text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt64(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; PrimitiveParser.InvariantUtf8.TryParseUInt64(utf8ByteStar, length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt64_BytesConsumed(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt64(utf8ByteStar, length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt64(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; PrimitiveParser.InvariantUtf8.TryParseUInt64(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("2134567890")] // standard parse [InlineData("18446744073709551615")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt64_BytesConsumed(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; int bytesConsumed; PrimitiveParser.InvariantUtf8.TryParseUInt64(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt64Hex(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt64(utf8ByteStar, length, out value); DoNotIgnore(value, 0); } } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteStarToUInt64Hex_BytesConsumed(string text) { int length = text.Length; byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); foreach (var iteration in Benchmark.Iterations) { fixed (byte* utf8ByteStar = utf8ByteArray) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt64(utf8ByteStar, length, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt64Hex(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt64(utf8ByteSpan, out value); DoNotIgnore(value, 0); } } } } [Benchmark] [InlineData("abcdef")] // standard parse [InlineData("ffffffffffffffff")] // max value [InlineData("0")] // min value private unsafe static void PrimitiveParserByteSpanToUInt64Hex_BytesConsumed(string text) { byte[] utf8ByteArray = Text.Encoding.UTF8.GetBytes(text); ReadOnlySpan<byte> utf8ByteSpan = new ReadOnlySpan<byte>(utf8ByteArray); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < LoadIterations; i++) { ulong value; int bytesConsumed; PrimitiveParser.InvariantUtf8.Hex.TryParseUInt64(utf8ByteSpan, out value, out bytesConsumed); DoNotIgnore(value, bytesConsumed); } } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedSessionEntityTypesClientSnippets { /// <summary>Snippet for ListSessionEntityTypes</summary> public void ListSessionEntityTypesRequestObject() { // Snippet: ListSessionEntityTypes(ListSessionEntityTypesRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) ListSessionEntityTypesRequest request = new ListSessionEntityTypesRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypes(request); // Iterate over all response items, lazily performing RPCs as required foreach (SessionEntityType item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSessionEntityTypesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionEntityTypesAsync</summary> public async Task ListSessionEntityTypesRequestObjectAsync() { // Snippet: ListSessionEntityTypesAsync(ListSessionEntityTypesRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) ListSessionEntityTypesRequest request = new ListSessionEntityTypesRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), }; // Make the request PagedAsyncEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SessionEntityType item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionEntityTypesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionEntityTypes</summary> public void ListSessionEntityTypes() { // Snippet: ListSessionEntityTypes(string, string, int?, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypes(parent); // Iterate over all response items, lazily performing RPCs as required foreach (SessionEntityType item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSessionEntityTypesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionEntityTypesAsync</summary> public async Task ListSessionEntityTypesAsync() { // Snippet: ListSessionEntityTypesAsync(string, string, int?, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; // Make the request PagedAsyncEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SessionEntityType item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionEntityTypesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionEntityTypes</summary> public void ListSessionEntityTypesResourceNames() { // Snippet: ListSessionEntityTypes(SessionName, string, int?, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypes(parent); // Iterate over all response items, lazily performing RPCs as required foreach (SessionEntityType item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListSessionEntityTypesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListSessionEntityTypesAsync</summary> public async Task ListSessionEntityTypesResourceNamesAsync() { // Snippet: ListSessionEntityTypesAsync(SessionName, string, int?, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); // Make the request PagedAsyncEnumerable<ListSessionEntityTypesResponse, SessionEntityType> response = sessionEntityTypesClient.ListSessionEntityTypesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((SessionEntityType item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListSessionEntityTypesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (SessionEntityType item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<SessionEntityType> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (SessionEntityType item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetSessionEntityType</summary> public void GetSessionEntityTypeRequestObject() { // Snippet: GetSessionEntityType(GetSessionEntityTypeRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) GetSessionEntityTypeRequest request = new GetSessionEntityTypeRequest { SessionEntityTypeName = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"), }; // Make the request SessionEntityType response = sessionEntityTypesClient.GetSessionEntityType(request); // End snippet } /// <summary>Snippet for GetSessionEntityTypeAsync</summary> public async Task GetSessionEntityTypeRequestObjectAsync() { // Snippet: GetSessionEntityTypeAsync(GetSessionEntityTypeRequest, CallSettings) // Additional: GetSessionEntityTypeAsync(GetSessionEntityTypeRequest, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) GetSessionEntityTypeRequest request = new GetSessionEntityTypeRequest { SessionEntityTypeName = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"), }; // Make the request SessionEntityType response = await sessionEntityTypesClient.GetSessionEntityTypeAsync(request); // End snippet } /// <summary>Snippet for GetSessionEntityType</summary> public void GetSessionEntityType() { // Snippet: GetSessionEntityType(string, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/entityTypes/[ENTITY_TYPE]"; // Make the request SessionEntityType response = sessionEntityTypesClient.GetSessionEntityType(name); // End snippet } /// <summary>Snippet for GetSessionEntityTypeAsync</summary> public async Task GetSessionEntityTypeAsync() { // Snippet: GetSessionEntityTypeAsync(string, CallSettings) // Additional: GetSessionEntityTypeAsync(string, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/entityTypes/[ENTITY_TYPE]"; // Make the request SessionEntityType response = await sessionEntityTypesClient.GetSessionEntityTypeAsync(name); // End snippet } /// <summary>Snippet for GetSessionEntityType</summary> public void GetSessionEntityTypeResourceNames() { // Snippet: GetSessionEntityType(SessionEntityTypeName, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionEntityTypeName name = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"); // Make the request SessionEntityType response = sessionEntityTypesClient.GetSessionEntityType(name); // End snippet } /// <summary>Snippet for GetSessionEntityTypeAsync</summary> public async Task GetSessionEntityTypeResourceNamesAsync() { // Snippet: GetSessionEntityTypeAsync(SessionEntityTypeName, CallSettings) // Additional: GetSessionEntityTypeAsync(SessionEntityTypeName, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionEntityTypeName name = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"); // Make the request SessionEntityType response = await sessionEntityTypesClient.GetSessionEntityTypeAsync(name); // End snippet } /// <summary>Snippet for CreateSessionEntityType</summary> public void CreateSessionEntityTypeRequestObject() { // Snippet: CreateSessionEntityType(CreateSessionEntityTypeRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) CreateSessionEntityTypeRequest request = new CreateSessionEntityTypeRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), SessionEntityType = new SessionEntityType(), }; // Make the request SessionEntityType response = sessionEntityTypesClient.CreateSessionEntityType(request); // End snippet } /// <summary>Snippet for CreateSessionEntityTypeAsync</summary> public async Task CreateSessionEntityTypeRequestObjectAsync() { // Snippet: CreateSessionEntityTypeAsync(CreateSessionEntityTypeRequest, CallSettings) // Additional: CreateSessionEntityTypeAsync(CreateSessionEntityTypeRequest, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) CreateSessionEntityTypeRequest request = new CreateSessionEntityTypeRequest { ParentAsSessionName = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"), SessionEntityType = new SessionEntityType(), }; // Make the request SessionEntityType response = await sessionEntityTypesClient.CreateSessionEntityTypeAsync(request); // End snippet } /// <summary>Snippet for CreateSessionEntityType</summary> public void CreateSessionEntityType() { // Snippet: CreateSessionEntityType(string, SessionEntityType, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = sessionEntityTypesClient.CreateSessionEntityType(parent, sessionEntityType); // End snippet } /// <summary>Snippet for CreateSessionEntityTypeAsync</summary> public async Task CreateSessionEntityTypeAsync() { // Snippet: CreateSessionEntityTypeAsync(string, SessionEntityType, CallSettings) // Additional: CreateSessionEntityTypeAsync(string, SessionEntityType, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/agent/sessions/[SESSION]"; SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = await sessionEntityTypesClient.CreateSessionEntityTypeAsync(parent, sessionEntityType); // End snippet } /// <summary>Snippet for CreateSessionEntityType</summary> public void CreateSessionEntityTypeResourceNames() { // Snippet: CreateSessionEntityType(SessionName, SessionEntityType, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = sessionEntityTypesClient.CreateSessionEntityType(parent, sessionEntityType); // End snippet } /// <summary>Snippet for CreateSessionEntityTypeAsync</summary> public async Task CreateSessionEntityTypeResourceNamesAsync() { // Snippet: CreateSessionEntityTypeAsync(SessionName, SessionEntityType, CallSettings) // Additional: CreateSessionEntityTypeAsync(SessionName, SessionEntityType, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionName parent = SessionName.FromProjectSession("[PROJECT]", "[SESSION]"); SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = await sessionEntityTypesClient.CreateSessionEntityTypeAsync(parent, sessionEntityType); // End snippet } /// <summary>Snippet for UpdateSessionEntityType</summary> public void UpdateSessionEntityTypeRequestObject() { // Snippet: UpdateSessionEntityType(UpdateSessionEntityTypeRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) UpdateSessionEntityTypeRequest request = new UpdateSessionEntityTypeRequest { SessionEntityType = new SessionEntityType(), UpdateMask = new FieldMask(), }; // Make the request SessionEntityType response = sessionEntityTypesClient.UpdateSessionEntityType(request); // End snippet } /// <summary>Snippet for UpdateSessionEntityTypeAsync</summary> public async Task UpdateSessionEntityTypeRequestObjectAsync() { // Snippet: UpdateSessionEntityTypeAsync(UpdateSessionEntityTypeRequest, CallSettings) // Additional: UpdateSessionEntityTypeAsync(UpdateSessionEntityTypeRequest, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) UpdateSessionEntityTypeRequest request = new UpdateSessionEntityTypeRequest { SessionEntityType = new SessionEntityType(), UpdateMask = new FieldMask(), }; // Make the request SessionEntityType response = await sessionEntityTypesClient.UpdateSessionEntityTypeAsync(request); // End snippet } /// <summary>Snippet for UpdateSessionEntityType</summary> public void UpdateSessionEntityType1() { // Snippet: UpdateSessionEntityType(SessionEntityType, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = sessionEntityTypesClient.UpdateSessionEntityType(sessionEntityType); // End snippet } /// <summary>Snippet for UpdateSessionEntityTypeAsync</summary> public async Task UpdateSessionEntityType1Async() { // Snippet: UpdateSessionEntityTypeAsync(SessionEntityType, CallSettings) // Additional: UpdateSessionEntityTypeAsync(SessionEntityType, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionEntityType sessionEntityType = new SessionEntityType(); // Make the request SessionEntityType response = await sessionEntityTypesClient.UpdateSessionEntityTypeAsync(sessionEntityType); // End snippet } /// <summary>Snippet for UpdateSessionEntityType</summary> public void UpdateSessionEntityType2() { // Snippet: UpdateSessionEntityType(SessionEntityType, FieldMask, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionEntityType sessionEntityType = new SessionEntityType(); FieldMask updateMask = new FieldMask(); // Make the request SessionEntityType response = sessionEntityTypesClient.UpdateSessionEntityType(sessionEntityType, updateMask); // End snippet } /// <summary>Snippet for UpdateSessionEntityTypeAsync</summary> public async Task UpdateSessionEntityType2Async() { // Snippet: UpdateSessionEntityTypeAsync(SessionEntityType, FieldMask, CallSettings) // Additional: UpdateSessionEntityTypeAsync(SessionEntityType, FieldMask, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionEntityType sessionEntityType = new SessionEntityType(); FieldMask updateMask = new FieldMask(); // Make the request SessionEntityType response = await sessionEntityTypesClient.UpdateSessionEntityTypeAsync(sessionEntityType, updateMask); // End snippet } /// <summary>Snippet for DeleteSessionEntityType</summary> public void DeleteSessionEntityTypeRequestObject() { // Snippet: DeleteSessionEntityType(DeleteSessionEntityTypeRequest, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) DeleteSessionEntityTypeRequest request = new DeleteSessionEntityTypeRequest { SessionEntityTypeName = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"), }; // Make the request sessionEntityTypesClient.DeleteSessionEntityType(request); // End snippet } /// <summary>Snippet for DeleteSessionEntityTypeAsync</summary> public async Task DeleteSessionEntityTypeRequestObjectAsync() { // Snippet: DeleteSessionEntityTypeAsync(DeleteSessionEntityTypeRequest, CallSettings) // Additional: DeleteSessionEntityTypeAsync(DeleteSessionEntityTypeRequest, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) DeleteSessionEntityTypeRequest request = new DeleteSessionEntityTypeRequest { SessionEntityTypeName = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"), }; // Make the request await sessionEntityTypesClient.DeleteSessionEntityTypeAsync(request); // End snippet } /// <summary>Snippet for DeleteSessionEntityType</summary> public void DeleteSessionEntityType() { // Snippet: DeleteSessionEntityType(string, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/entityTypes/[ENTITY_TYPE]"; // Make the request sessionEntityTypesClient.DeleteSessionEntityType(name); // End snippet } /// <summary>Snippet for DeleteSessionEntityTypeAsync</summary> public async Task DeleteSessionEntityTypeAsync() { // Snippet: DeleteSessionEntityTypeAsync(string, CallSettings) // Additional: DeleteSessionEntityTypeAsync(string, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/agent/sessions/[SESSION]/entityTypes/[ENTITY_TYPE]"; // Make the request await sessionEntityTypesClient.DeleteSessionEntityTypeAsync(name); // End snippet } /// <summary>Snippet for DeleteSessionEntityType</summary> public void DeleteSessionEntityTypeResourceNames() { // Snippet: DeleteSessionEntityType(SessionEntityTypeName, CallSettings) // Create client SessionEntityTypesClient sessionEntityTypesClient = SessionEntityTypesClient.Create(); // Initialize request argument(s) SessionEntityTypeName name = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"); // Make the request sessionEntityTypesClient.DeleteSessionEntityType(name); // End snippet } /// <summary>Snippet for DeleteSessionEntityTypeAsync</summary> public async Task DeleteSessionEntityTypeResourceNamesAsync() { // Snippet: DeleteSessionEntityTypeAsync(SessionEntityTypeName, CallSettings) // Additional: DeleteSessionEntityTypeAsync(SessionEntityTypeName, CancellationToken) // Create client SessionEntityTypesClient sessionEntityTypesClient = await SessionEntityTypesClient.CreateAsync(); // Initialize request argument(s) SessionEntityTypeName name = SessionEntityTypeName.FromProjectSessionEntityType("[PROJECT]", "[SESSION]", "[ENTITY_TYPE]"); // Make the request await sessionEntityTypesClient.DeleteSessionEntityTypeAsync(name); // End snippet } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Net; using SharpSvn; namespace VersionOne.ServiceHost.SubversionServices { public class SvnInformation { public readonly string Url; public readonly string Root; public readonly string Path; public SvnInformation(string url, string root, string path) { Url = url; Root = root; Path = path; } } public class SvnConnector : IDisposable { private readonly SvnClient client = new SvnClient(); private SvnInformation svnInfo; public SvnConnector() { MethodInfo mi = client.GetType().GetProperty("AdministrativeDirectoryName").GetSetMethod(true); mi.Invoke(null, new object[] { "_svn" }); } public void SetAuthentication(string username, string password) { client.Authentication.ClearAuthenticationCache(); client.Authentication.Clear(); client.Authentication.DefaultCredentials = new NetworkCredential(username, password); } public string GetRepositoryUuid(string url) { try { Guid uuid; bool result = client.TryGetRepositoryId(new Uri(url), out uuid); if(!result) { OnError(new InvalidOperationException("The url " + url + " is not valid repository path.")); } return uuid.ToString(); } catch(Exception ex) { OnError(ex); } return null; } public SvnInformation GetSvnInformation(string url) { ReadSvnInformation(url); return svnInfo; } private void ReadSvnInformation(string url) { try { client.Info(new SvnUriTarget(url, SvnRevision.Head), InfoReceiver); } catch (Exception ex) { OnError(ex); } } private void InfoReceiver(object sender, SvnInfoEventArgs e) { svnInfo = new SvnInformation(e.Uri.ToString(), e.RepositoryRoot.ToString(), e.Path); } public void Poke(string url, int revision) { try { client.Log(new Uri(url), new SvnLogArgs(new SvnRevisionRange(new SvnRevision(revision), SvnRevision.Head)), LogHandler); } catch (Exception ex) { OnError(ex); } } private void LogHandler(object sender, SvnLogEventArgs e) { try { List<string> filesChanged = new List<string>(); ChangeSetDictionary changedItems = new ChangeSetDictionary(); if(e.ChangedPaths == null) { return; } foreach (SvnChangeItem item in e.ChangedPaths) { filesChanged.Add(item.Path); changedItems.Add(item.Path, new ChangedPathInfo(item)); } int revision = Convert.ToInt32(e.Revision); OnChangeSet(revision, e.Author, e.Time, e.LogMessage, filesChanged, changedItems); } catch(Exception ex) { OnError(ex); } } private static SvnUriTarget CreateSvnUriTarget(string uriString, int revision) { Uri uri = new Uri(uriString); SvnUriTarget target = new SvnUriTarget(uri, new SvnRevision(revision)); return target; } private static SvnUriTarget CreateSvnUriTarget(string uriString, SvnRevision revision) { Uri uri = new Uri(uriString); SvnUriTarget target = new SvnUriTarget(uri, revision); return target; } public RevisionPropertyCollection GetRevisionProperties(string url) { return GetRevisionProperties(url, SvnRevision.Head); } public RevisionPropertyCollection GetRevisionProperties(string url, int revision) { return GetRevisionProperties(url, new SvnRevision(revision)); } private RevisionPropertyCollection GetRevisionProperties(string url, SvnRevision revision) { try { SvnPropertyCollection propertyCollection; //client.GetRevisionPropertyList(CreateSvnUriTarget(url, revision), out propertyCollection); client.GetRevisionPropertyList(CreateSvnUriTarget(url, revision), out propertyCollection); RevisionPropertyCollection revisionPropertyCollection = new RevisionPropertyCollection((int)revision.Revision); foreach (SvnPropertyValue value in propertyCollection) { revisionPropertyCollection.Add(value.Key, value.StringValue); } return revisionPropertyCollection; } catch(Exception ex) { OnError(ex); } return null; } public int SetRevisionProperty(string path, int revision, string propname, string propval) { try { client.SetRevisionProperty(CreateSvnUriTarget(path, revision), propname, propval); } catch(Exception ex) { OnError(ex); } return int.MinValue; } public PropertiesCollection GetProperies(string target, bool recurse) { return GetProperties(target, SvnRevision.None, recurse); } public PropertiesCollection GetProperies(string target, int asOfRevision, bool recurse) { return GetProperties(target, new SvnRevision(asOfRevision), recurse); } private PropertiesCollection GetProperties(string target, SvnRevision asOfRevision, bool recurse) { try { PropertiesCollection result = new PropertiesCollection(); Collection<SvnPropertyListEventArgs> output; SvnPropertyListArgs args = new SvnPropertyListArgs(); args.Revision = asOfRevision; args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children; client.GetPropertyList(new Uri(target), args, out output); foreach (SvnPropertyListEventArgs eventArgs in output) { Dictionary<string, string> properties = new Dictionary<string, string>(eventArgs.Properties.Count); foreach (SvnPropertyValue value in eventArgs.Properties) { properties.Add(value.Key, value.StringValue); } result.Add(eventArgs.Path, properties); } return result; } catch(Exception ex) { OnError(ex); } return null; } public void SaveProperty(string propertyName, string value, string target, bool recursive, bool skipChecks) { try { SvnSetPropertyArgs args = new SvnSetPropertyArgs(); args.SkipChecks = skipChecks; args.Depth = recursive ? SvnDepth.Infinity : SvnDepth.Children; client.SetProperty(target, propertyName, value, args); } catch (Exception ex) { OnError(ex); } } public int Checkout(string repoUrl, string workingPath, bool recurse, bool ignoreExternals) { return Checkout(repoUrl, workingPath, new SvnRevision(SvnRevisionType.Head), recurse, ignoreExternals); } public int Checkout(string repoUrl, string workingPath, int revision, bool recurse, bool ignoreExternals) { return Checkout(repoUrl, workingPath, new SvnRevision(revision), recurse, ignoreExternals); } private int Checkout(string repoUrl, string workingPath, SvnRevision revision, bool recurse, bool ignoreExternals) { try { SvnCheckOutArgs args = new SvnCheckOutArgs(); args.Revision = revision; args.IgnoreExternals = ignoreExternals; args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children; SvnUpdateResult result; client.CheckOut(new Uri(repoUrl), workingPath, args, out result); return (int)result.Revision; } catch (Exception ex) { OnError(ex); } return int.MinValue; } public void Cleanup(string workingPath) { try { client.CleanUp(workingPath); } catch (Exception ex) { OnError(ex); } } public int Commit(ICollection<string> targets, bool recurse, bool keepLocks, string logMessage) { try { SvnCommitArgs args = new SvnCommitArgs(); args.Depth = SvnDepth.Infinity; args.KeepLocks = true; args.LogMessage = logMessage; SvnCommitResult result; client.Commit(targets, args, out result); OnCommitted((int)result.Revision, result.Author, result.Time); return (int)result.Revision; } catch (Exception ex) { OnError(ex); } return int.MinValue; } #region Events private void OnChangeSet(int revision, string author, DateTime time, string message, List<string> changed, ChangeSetDictionary changedPathInfos) { if (_revision != null) _revision(this, new RevisionArgs(revision, author, time, message, changed, changedPathInfos)); } private event EventHandler<RevisionArgs> _revision; public event EventHandler<RevisionArgs> Revision { add { _revision += value; } remove { _revision -= value; } } public class RevisionArgs : EventArgs { public readonly int Revision; public readonly string Author; public readonly DateTime Time; public readonly string Message; public readonly List<string> Changed; public readonly ChangeSetDictionary ChangePathInfos; public RevisionArgs(int revision, string author, DateTime time, string message, List<string> changed, ChangeSetDictionary changedPathInfos) { Revision = revision; Author = author; Time = time; Message = message; Changed = changed; ChangePathInfos = changedPathInfos; } } private void OnError(Exception ex) { if (_error != null) _error(this, new SvnExceptionEventArgs(ex)); } private event EventHandler<SvnExceptionEventArgs> _error; public event EventHandler<SvnExceptionEventArgs> Error { add { _error += value; } remove { _error -= value; } } private void OnCommitted(int revision, string author, DateTime time) { if (_committed != null) _committed(this, new CommitEventArgs(revision, author, time)); } private event EventHandler<CommitEventArgs> _committed; public event EventHandler<CommitEventArgs> Committed { add { _committed += value; } remove { _committed -= value; } } public class CommitEventArgs : EventArgs { public readonly int Revision; public readonly string Author; public readonly DateTime Time; public CommitEventArgs(int revision, string author, DateTime time) { Revision = revision; Author = author; Time = time; } } #endregion #region Dispose Pattern public void Dispose() { Dispose(true); } //True if disposal is deterministic, meaning we should dispose managed objects. private void Dispose(bool deterministic) { client.Dispose(); } ~SvnConnector() { // When we are GC'd, we don't dispose managed objects - we let the GC handle that Dispose(false); } #endregion } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_105 : MapLoop { public M_105() : base(null) { Content.AddRange(new MapBaseEntity[] { new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new LUI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, }); } //1000 public class L_AMT : MapLoop { public L_AMT(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new PDL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //2000 public class L_NM1 : MapLoop { public L_NM1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3000 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4000 public class L_HL : MapLoop { public L_HL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NM1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_EFI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4100 public class L_LM_1 : MapLoop { public L_LM_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4200 public class L_NM1_1 : MapLoop { public L_NM1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NM1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NX1() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new LUI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TPB() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_AMT_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NX2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4210 public class L_AMT_1 : MapLoop { public L_AMT_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //4220 public class L_NX2 : MapLoop { public L_NX2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NX2() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //4230 public class L_REF : MapLoop { public L_REF(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4240 public class L_LX : MapLoop { public L_LX(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new MTX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4250 public class L_LM_2 : MapLoop { public L_LM_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new L_LQ(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4251 public class L_LQ : MapLoop { public L_LQ(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LQ() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new NX2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PDL() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new CDS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new MTX() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_REF_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4252 public class L_REF_1 : MapLoop { public L_REF_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //4300 public class L_EFI : MapLoop { public L_EFI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Text; using System.Windows.Forms; using System.Media; using System.Runtime.InteropServices; using System.IO; using Org.Vesic.WinForms; namespace Amnesty_Hypercube { public partial class Form3 : Form { Form1 widgetManager; FormState formState = new FormState(); ArrayList blotters = new ArrayList(); SoundPlayer playSound = new SoundPlayer(Amnesty_Hypercube.Properties.Resources.Welcome); SoundPlayer enterSound = new SoundPlayer(Amnesty_Hypercube.Properties.Resources.Enter); SoundPlayer clickSound = new SoundPlayer(Amnesty_Hypercube.Properties.Resources.Click); String home = null; public enum GalleryModes : int { galleryLibrary = 10, galleryCubes = 20, galleryProviders = 30, galleryBrowser = 40, galleryHelp = 50, galleryWelcome = 60 }; public enum ProviderPresets : int { presetAll = 1000, presetLibraries = 1001, presetGames = 1002, presetVideo = 1003, presetPhotos = 1004, presetMusic = 1005, presetOther = 1006 }; [Flags] internal enum WindowStyles : int { ExToolWindow = 0x00000080, ExAppWindow = 0x00040000 }; GalleryModes galleryMode; ProviderPresets providerPreset = ProviderPresets.presetAll; Button presetButton; delegate void SetImageCallback(string key, Image image); bool isInGallery = false; /* internal struct Margins { public int Left, Right, Top, Bottom; } [DllImport("dwmapi.dll")] static extern void DwmIsCompositionEnabled(ref bool pfEnabled); [DllImport("dwmapi.dll")] static extern void DwmExtendFrameIntoClientArea(System.IntPtr hWnd, ref Margins pMargins); */ public Form3() { InitializeComponent(); playSound.Load(); enterSound.Load(); clickSound.Load(); SetupButton( button1, Amnesty_Hypercube.Properties.Resources.Close, Amnesty_Hypercube.Properties.Resources.CloseDown, Amnesty_Hypercube.Properties.Resources.CloseOver); SetupButton( button2, Amnesty_Hypercube.Properties.Resources.Down, Amnesty_Hypercube.Properties.Resources.DownDown, Amnesty_Hypercube.Properties.Resources.DownOver); SetupButton( button3, Amnesty_Hypercube.Properties.Resources.Up, Amnesty_Hypercube.Properties.Resources.UpDown, Amnesty_Hypercube.Properties.Resources.UpOver); SetupButton( button4, Amnesty_Hypercube.Properties.Resources.PreAll, Amnesty_Hypercube.Properties.Resources.PreAllDown, Amnesty_Hypercube.Properties.Resources.PreAllOver); presetButton = button4; button4.Tag = "<disabled>"; button4.ImageIndex = 1; SetupButton( button5, Amnesty_Hypercube.Properties.Resources.PreDirectory, Amnesty_Hypercube.Properties.Resources.PreDirectoryDown, Amnesty_Hypercube.Properties.Resources.PreDirectoryOver); SetupButton( button6, Amnesty_Hypercube.Properties.Resources.PreGames, Amnesty_Hypercube.Properties.Resources.PreGamesDown, Amnesty_Hypercube.Properties.Resources.PreGamesOver); SetupButton( button7, Amnesty_Hypercube.Properties.Resources.PreVideo, Amnesty_Hypercube.Properties.Resources.PreVideoDown, Amnesty_Hypercube.Properties.Resources.PreVideoOver); SetupButton( button8, Amnesty_Hypercube.Properties.Resources.PrePhotos, Amnesty_Hypercube.Properties.Resources.PrePhotosDown, Amnesty_Hypercube.Properties.Resources.PrePhotosOver); SetupButton( button9, Amnesty_Hypercube.Properties.Resources.PreMusic, Amnesty_Hypercube.Properties.Resources.PreMusicDown, Amnesty_Hypercube.Properties.Resources.PreMusicOver); SetupButton( button10, Amnesty_Hypercube.Properties.Resources.PreOther, Amnesty_Hypercube.Properties.Resources.PreOtherDown, Amnesty_Hypercube.Properties.Resources.PreOtherOver); SetupButton( button11, Amnesty_Hypercube.Properties.Resources.Providers, Amnesty_Hypercube.Properties.Resources.ProvidersDown, Amnesty_Hypercube.Properties.Resources.ProvidersOver); SetupButton( button12, Amnesty_Hypercube.Properties.Resources.Back, Amnesty_Hypercube.Properties.Resources.BackDown, Amnesty_Hypercube.Properties.Resources.BackOver); SetupButton( button13, Amnesty_Hypercube.Properties.Resources.Forward, Amnesty_Hypercube.Properties.Resources.ForwardDown, Amnesty_Hypercube.Properties.Resources.ForwardOver); button11.Bounds = button4.Bounds; button12.Bounds = button5.Bounds; button13.Bounds = button6.Bounds; extendedWebBrowser1.StartNewWindow += new EventHandler<ExtendedWebBrowser2.BrowserExtendedNavigatingEventArgs>(extendedWebBrowser1_StartNewWindow); listView1.SelectedIndexChanged += new EventHandler(listView1_SelectedIndexChanged); this.TransparencyKey = Color.FromArgb(254, 255, 254); this.BackColor = Color.FromArgb(254, 255, 254); Rectangle screen = Screen.PrimaryScreen.Bounds; screen.Y = screen.Height; this.Bounds = screen; Rectangle frame = screen; frame.Inflate(-100, -100); if (screen.Width > screen.Height) frame.Width = (screen.Width + screen.Height) / 2; else if (screen.Height > screen.Height) frame.Height = (screen.Width + screen.Height) / 2; if (frame.Width < 832) frame.Width = 832; Rectangle newFrame = panel1.Bounds; newFrame.Inflate(frame.Width - newFrame.Width, frame.Height - newFrame.Height); panel1.Bounds = newFrame; foreach (Screen s in Screen.AllScreens) { Form5 blotter = new Form5(); blotter.Bounds = s.Bounds; blotter.Opacity = .40; blotter.BackColor = Color.Black; blotters.Add(blotter); if (s.Equals(Screen.PrimaryScreen)) this.Owner = blotter; } this.DoubleBuffered = true; this.Show(); //InitializeGlass(); } void extendedWebBrowser1_StartNewWindow(object sender, ExtendedWebBrowser2.BrowserExtendedNavigatingEventArgs e) { if (galleryMode == GalleryModes.galleryHelp) { if (isInGallery) CloseGallery(); if (widgetManager.isInHypercube) widgetManager.CloseCube(); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.Verb = "open"; p.StartInfo.FileName = e.Url.ToString(); p.Start(); } e.Cancel = true; } public void SetWidgetManager(Form1 set) { widgetManager = set; listView1.LargeImageList = widgetManager.images; } public void SetHome(string set) { home = set; } public void SetGalleryTitle(string set) { label1.Text = set; } public GalleryModes GetGalleryMode() { return galleryMode; } public void OpenGallery(GalleryModes mode) { if (isInGallery) return; isInGallery = true; SetupGallery(mode); foreach (Form5 f in blotters) { f.DoShow(); } Rectangle screen = Screen.PrimaryScreen.Bounds; if (this.Bounds.Y != screen.Y) this.Bounds = screen; else { this.Show(); } formState.MaximizeTop(this); //this.Show(); //formState.MaximizeTop(this); } public void SetupGallery(GalleryModes mode) { button2.Hide(); button3.Hide(); button4.Hide(); button5.Hide(); button6.Hide(); button7.Hide(); button8.Hide(); button9.Hide(); button10.Hide(); button11.Hide(); button12.Hide(); button13.Hide(); extendedWebBrowser1.Hide(); extendedWebBrowser1.DocumentText = ""; listView1.Hide(); galleryMode = mode; switch (mode) { case GalleryModes.galleryLibrary: SetGalleryTitle(Amnesty_Hypercube.Properties.Resources.WidgetGallery); SetupGalleryLibrary(); break; case GalleryModes.galleryCubes: SetGalleryTitle(Amnesty_Hypercube.Properties.Resources.CubeGallery); SetupGalleryCubes(); break; case GalleryModes.galleryProviders: button4.Show(); button5.Show(); button6.Show(); button7.Show(); button8.Show(); button9.Show(); button10.Show(); SetupGalleryProviders(); break; case GalleryModes.galleryBrowser: button11.Show(); button12.Show(); button13.Show(); if (home != null) extendedWebBrowser1.Navigate(home); extendedWebBrowser1.Show(); extendedWebBrowser1.Focus(); break; case GalleryModes.galleryHelp: SetGalleryTitle(Amnesty_Hypercube.Properties.Resources.InfoCenter); extendedWebBrowser1.Navigate("http://www.amnestywidgets.com/hypercube/wininfo/home.html"); extendedWebBrowser1.Show(); extendedWebBrowser1.Focus(); break; case GalleryModes.galleryWelcome: SetGalleryTitle(Amnesty_Hypercube.Properties.Resources.WelcomeTitle); extendedWebBrowser1.Navigate("http://www.amnestywidgets.com/hypercube/wininfo/welcome.html"); extendedWebBrowser1.Show(); extendedWebBrowser1.Focus(); if (Amnesty_Hypercube.Properties.Settings.Default.PrefUISound) playSound.Play(); break; } this.Refresh(); } void SetupGalleryLibrary() { listView1.Items.Clear(); DataTable wtable = widgetManager.widgets.Tables["Widgets"]; IEnumerator enumerator = wtable.Rows.GetEnumerator(); while (enumerator.MoveNext()) { DataRow row = (DataRow)enumerator.Current; string identifier = (string)row["Identifier"]; string title = (string)row["Title"]; int imageIndex = widgetManager.images.Images.IndexOfKey("DEFAULT(LargeGear)"); String imageKey = String.Format("WIDGET({0})", identifier); if (listView1.LargeImageList.Images.ContainsKey(imageKey)) imageIndex = listView1.LargeImageList.Images.IndexOfKey(imageKey); else { object imageObject = widgetManager.GetInfoForWidget(identifier, "Image"); if (imageObject != null) { Image image = null; if (imageObject.Equals(DBNull.Value) == false) { try { String i = (String)imageObject; byte[] ibuffer = Convert.FromBase64String(i); image = new Bitmap(new MemoryStream(ibuffer)); } catch { image = null; } } if (image != null) { image = widgetManager.flipper.FlipImage(image); SetImage(imageKey, image); if (listView1.LargeImageList.Images.ContainsKey(imageKey)) imageIndex = listView1.LargeImageList.Images.IndexOfKey(imageKey); } } } listView1.Items.Add(identifier, title, imageIndex); } listView1.Show(); listView1.Focus(); } void SetupGalleryCubes() { listView1.Items.Clear(); string path = widgetManager.GetUserDataPath(); string[] dirs = System.IO.Directory.GetDirectories(path); foreach (string dir in dirs) { if (dir.EndsWith(".cube") && dir.EndsWith("\\_Desktop.cube") == false) { int index = dir.LastIndexOf("\\") + 1; string key = dir.Substring(index, dir.Length - (index + 5)); string title = null; if (key.StartsWith("_")) title = key.Substring(1); else title = key; if(key.StartsWith("_Cube")) { string suffix = key.Substring(5); title = String.Format("{0} {1}", Amnesty_Hypercube.Properties.Resources.CubeTitle, suffix); } int imageIndex = listView1.LargeImageList.Images.IndexOfKey("DEFAULT(LargeCube)"); listView1.Items.Add(key, title, imageIndex); } } listView1.Show(); listView1.Focus(); } ArrayList FilteredProviders() { ArrayList filtered = new ArrayList(widgetManager.providers.Count); IDictionaryEnumerator enumerator = widgetManager.providers.GetEnumerator(); while (enumerator.MoveNext()) { string identifier = (string)enumerator.Key; bool add = true; if (widgetManager.providersHidden.Contains(identifier)) add = false; if (providerPreset != ProviderPresets.presetAll && widgetManager.tags != null) { string tags = (string)widgetManager.tags[identifier]; switch (providerPreset) { case ProviderPresets.presetLibraries: if (tags.Contains("library") == false) add = false; break; case ProviderPresets.presetGames: if (tags.Contains("games") == false) add = false; break; case ProviderPresets.presetVideo: if (tags.Contains("video") == false) add = false; break; case ProviderPresets.presetPhotos: if (tags.Contains("photos") == false) add = false; break; case ProviderPresets.presetMusic: if (tags.Contains("music") == false) add = false; break; case ProviderPresets.presetOther: if (tags.Contains("custom") == false) add = false; break; } } if(add) filtered.Add(identifier); } return filtered; } void SetupGalleryProviders() { listView1.Items.Clear(); int featuredCount = 0; int ix = -1; ArrayList filtered = FilteredProviders(); foreach (string identifier in filtered) { string title = " " + (string) widgetManager.providers[identifier]; if(widgetManager.providersFeatured.Contains(identifier)) { int imageIndex = listView1.LargeImageList.Images.IndexOfKey("DEFAULT(LargeWorld)"); String imageKey = String.Format("PROVIDER({0})", identifier); if (listView1.LargeImageList.Images.ContainsKey(imageKey)) imageIndex = listView1.LargeImageList.Images.IndexOfKey(imageKey); listView1.Items.Add(identifier, title, imageIndex); featuredCount++; } } foreach (string identifier in filtered) { string title = (string) widgetManager.providers[identifier]; if(widgetManager.providersFeatured.Contains(identifier) == false) { int imageIndex = listView1.LargeImageList.Images.IndexOfKey("DEFAULT(LargeWorld)"); String imageKey = String.Format("PROVIDER({0})", identifier); if (listView1.LargeImageList.Images.ContainsKey(imageKey)) imageIndex = listView1.LargeImageList.Images.IndexOfKey(imageKey); ListViewItem i = listView1.Items.Add(identifier, title, imageIndex); if(ix == -1) ix = i.Position.X - listView1.TileSize.Width; } } if (featuredCount > 0) { int imageIndex = listView1.LargeImageList.Images.IndexOfKey("DEFAULT(Blank)"); int area = (listView1.Bounds.Width - 20) - ix; int mod = area % listView1.TileSize.Width; area -= mod; int padding = area / listView1.TileSize.Width; while (padding > 0) { ListViewItem j = listView1.Items.Add("<ignore>", " zzz", imageIndex); j.ForeColor = panel1.BackColor; padding--; } } string presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetAll; switch (providerPreset) { case ProviderPresets.presetLibraries: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetLibraries; break; case ProviderPresets.presetGames: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetGames; break; case ProviderPresets.presetVideo: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetVideo; break; case ProviderPresets.presetPhotos: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetPhotos; break; case ProviderPresets.presetMusic: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetMusic; break; case ProviderPresets.presetOther: presetTitle = Amnesty_Hypercube.Properties.Resources.TipPresetOther; break; } String galleryTitle = String.Format("{0} > {1}", Amnesty_Hypercube.Properties.Resources.ProviderGallery, presetTitle); SetGalleryTitle(galleryTitle); listView1.Show(); listView1.Focus(); } void GalleryLibraryAction(String key) { widgetManager.DoLibraryAction(key); } void GalleryCubeAction(String key) { widgetManager.DoCubeAction(key); } void GalleryProviderAction(String key, String title) { home = String.Format("http://www.amnestywidgets.com/hypercube/providers/pages/{0}.html", key); bool spoofFlag = false; if (widgetManager.providersSpoofed.Contains(key)) spoofFlag = true; label1.Text = String.Format("{0} > {1}", Amnesty_Hypercube.Properties.Resources.ProviderGallery, title); SetupGallery(GalleryModes.galleryBrowser); } public void CloseGallery() { if (isInGallery == false) return; isInGallery = false; if(galleryMode == GalleryModes.galleryBrowser) extendedWebBrowser1.DocumentText = ""; DataTable itable = widgetManager.instances.Tables["Widgets"]; IEnumerator enumerator = itable.Rows.GetEnumerator(); while (enumerator.MoveNext()) { DataRow row = (DataRow)enumerator.Current; Widget w = (Widget)row["Widget"]; w.SetGallery(false); w.ResetOptionLevel(); } formState.Restore(this); this.Hide(); foreach (Form5 f in blotters) { f.DoHide(); } widgetManager.CloseGallery(); } public void SetImage(string key, Image image) { if (listView1.InvokeRequired) { SetImageCallback d = new SetImageCallback(SetImage); this.Invoke(d, new object[] { key, image }); } else widgetManager.images.Images.Add(key, image); } void SetupButton(Button button, Image i1, Image i2, Image i3) { button.Click += new EventHandler(button_Click); ImageList b = new ImageList(); b.ImageSize = new Size(48, 48); b.ColorDepth = ColorDepth.Depth32Bit; b.Images.Add(i1); b.Images.Add(i2); b.Images.Add(i3); button.ImageList = b; button.ImageIndex = 0; button.MouseEnter += new EventHandler(button_MouseEnter); button.MouseLeave += new EventHandler(button_MouseLeave); button.MouseDown += new MouseEventHandler(button_MouseDown); button.MouseUp += new MouseEventHandler(button_MouseUp); button.Tag = null; } void button_MouseEnter(object sender, EventArgs e) { Button b = (Button)sender; if (b.Tag != null) return; if (Amnesty_Hypercube.Properties.Settings.Default.PrefUISound) enterSound.Play(); b.ImageIndex = 2; } void button_MouseLeave(object sender, EventArgs e) { Button b = (Button)sender; if (b.Tag != null) return; b.ImageIndex = 0; } void button_MouseDown(object sender, MouseEventArgs e) { Button b = (Button)sender; if (b.Tag != null) return; b.ImageIndex = 1; } void button_MouseUp(object sender, MouseEventArgs e) { Button b = (Button)sender; if (b.Tag != null) return; b.ImageIndex = 0; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= (int)WindowStyles.ExToolWindow; return cp; } } void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0 && listView1.Visible) { String key = (String)listView1.SelectedItems[0].Name; String title = (String)listView1.SelectedItems[0].Text; listView1.SelectedItems.Clear(); if (key.Equals("<ignore>")) return; if (Amnesty_Hypercube.Properties.Settings.Default.PrefUISound) clickSound.Play(); switch (galleryMode) { case GalleryModes.galleryLibrary: GalleryLibraryAction(key); break; case GalleryModes.galleryCubes: GalleryCubeAction(key); break; case GalleryModes.galleryProviders: GalleryProviderAction(key, title); break; } } } private void button_Click(object sender, EventArgs e) { Button b = (Button)sender; if (b.Tag != null) return; if (Amnesty_Hypercube.Properties.Settings.Default.PrefUISound) clickSound.Play(); bool updateGallery = false; if (sender.Equals(button1)) CloseGallery(); else if (sender.Equals(button4)) { providerPreset = ProviderPresets.presetAll; updateGallery = true; } else if (sender.Equals(button5)) { providerPreset = ProviderPresets.presetLibraries; updateGallery = true; } else if (sender.Equals(button6)) { providerPreset = ProviderPresets.presetGames; updateGallery = true; } else if (sender.Equals(button7)) { providerPreset = ProviderPresets.presetVideo; updateGallery = true; } else if (sender.Equals(button8)) { providerPreset = ProviderPresets.presetPhotos; updateGallery = true; } else if (sender.Equals(button9)) { providerPreset = ProviderPresets.presetMusic; updateGallery = true; } else if (sender.Equals(button10)) { providerPreset = ProviderPresets.presetOther; updateGallery = true; } else if (sender.Equals(button11)) SetupGallery(GalleryModes.galleryProviders); else if (sender.Equals(button12)) extendedWebBrowser1.GoBack(); else if (sender.Equals(button13)) extendedWebBrowser1.GoForward(); if (updateGallery) { presetButton.Tag = null; presetButton.ImageIndex = 0; presetButton = (Button)sender; presetButton.Tag = "<disabled>"; presetButton.ImageIndex = 1; SetupGalleryProviders(); } } /* private void InitializeGlass() { bool isGlassSupported = false; if (Environment.OSVersion.Version.Major >= 6) DwmIsCompositionEnabled(ref isGlassSupported); if (isGlassSupported == false) { this.TransparencyKey = Color.FromArgb(254, 255, 254); this.BackColor = Color.FromArgb(254, 255, 254); return; } Margins marg; marg.Left = -1; marg.Top = -1; marg.Right = -1; marg.Bottom = -1; DwmExtendFrameIntoClientArea(this.Handle, ref marg); // this.Paint += new PaintEventHandler(this.Form3_Paint); } private void Form3_Paint(object sender, PaintEventArgs e) { SolidBrush blackBrush = new SolidBrush(Color.Black); e.Graphics.FillRectangle(blackBrush, 0, 0, this.ClientSize.Width, this.ClientSize.Height); blackBrush.Dispose(); } */ } }
using System; using System.Collections.Generic; using System.Threading; using NUnit.Framework; using UnityEngine; using UnityPlatformer; namespace UnityPlatformer.Test { [TestFixture] [Category("Character")] class CharacterHealthTest { bool onHealCalled = false; bool onDamageCalled = false; bool onImmunityCalled = false; bool onMaxHealthCalled = false; bool onInjuredCalled = false; bool onHurtCalled = false; bool onDeathCalled = false; bool onGameOverCalled = false; bool onInvulnerabilityStartCalled = false; bool onInvulnerabilityEndCalled = false; bool onRespawnCalled = false; Configuration config; UpdateManager umgr; CharacterHealth FixtureCreateHealth(string characterName) { Configuration.ClearInstance(); UpdateManager.ClearInstance(); System.GC.Collect(); var obj = new GameObject(); obj.name = characterName; config = obj.AddComponent<Configuration>(); Assert.NotNull(config); umgr = obj.AddComponent<UpdateManager>(); Assert.NotNull(umgr); var objx = new GameObject(); Character character = objx.AddComponent<Character>(); Assert.NotNull(character); CharacterHealth health = objx.GetComponent<CharacterHealth>(); Assert.NotNull(health); PlatformerCollider2D col2d = objx.GetComponent<PlatformerCollider2D>(); Assert.NotNull(col2d); return health; } void AttachEvents(CharacterHealth health) { health.onHeal += () => { onHealCalled = true; }; health.onDamage += () => { onDamageCalled = true; }; health.onImmunity += () => { onImmunityCalled = true; }; health.onMaxHealth += () => { onMaxHealthCalled = true; }; health.onInjured += (Damage dt, CharacterHealth to) => { onInjuredCalled = true; }; health.onHurt += (Damage dt, CharacterHealth to) => { onHurtCalled = true; }; health.onDeath += () => { onDeathCalled = true; }; health.onGameOver += () => { onGameOverCalled = true; }; health.onInvulnerabilityStart += () => { onInvulnerabilityStartCalled = true; }; health.onInvulnerabilityEnd += () => { onInvulnerabilityEndCalled = true; }; health.onRespawn += () => { onRespawnCalled = true; }; ResetCallbacks(); } void ResetCallbacks() { onHealCalled = false; onDamageCalled = false; onImmunityCalled = false; onMaxHealthCalled = false; onInjuredCalled = false; onHurtCalled = false; onDeathCalled = false; onGameOverCalled = false; onInvulnerabilityStartCalled = false; onInvulnerabilityEndCalled = false; onRespawnCalled = false; } [Test] public void DamageTest() { CharacterHealth health = FixtureCreateHealth("testchar"); AttachEvents(health); health.startingHealth = 2; health.maxHealth = 2; health.Start(); Assert.That(health.lives, Is.EqualTo(1)); Assert.That(health.health, Is.EqualTo(2)); Assert.That(health.IsInvulnerable(), Is.EqualTo(false)); Assert.That(onHealCalled, Is.EqualTo(true)); Assert.That(onDamageCalled, Is.EqualTo(false)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(true)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); ResetCallbacks(); health.Damage(1, null); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(true)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(true)); Assert.That(onRespawnCalled, Is.EqualTo(false)); // after recieve damage time to be invulnerable Assert.That(health.IsInvulnerable(), Is.EqualTo(true)); ResetCallbacks(); // TEST add time, wait until invulnerability ends umgr.forceFixedDeltaTime = 0.25f; umgr.FixedUpdate(); Assert.That(health.IsInvulnerable(), Is.EqualTo(true)); umgr.forceFixedDeltaTime = 2.0f; umgr.FixedUpdate(); Assert.That(health.IsInvulnerable(), Is.EqualTo(false)); Assert.That(onInvulnerabilityEndCalled, Is.EqualTo(true)); ResetCallbacks(); health.immunity = DamageType.Water; // TEST invulnerable to recieved damage var obj3 = new GameObject(); var damage = obj3.AddComponent<Damage>(); var character2 = obj3.AddComponent<Character>(); Assert.NotNull(damage); damage.type = DamageType.Water; damage.causer = character2.GetComponent<CharacterHealth>(); damage.causer.alignment = Alignment.Enemy; health.Damage(damage); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(true)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); ResetCallbacks(); /// damage again, kill character health.Damage(1, null); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(true)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(true)); Assert.That(onGameOverCalled, Is.EqualTo(true)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); } [Test] public void DamageUpdateManagerKillTest() { CharacterHealth health = FixtureCreateHealth("testchar"); AttachEvents(health); health.startingLives = 2; health.maxLives = 2; health.startingHealth = 2; health.maxHealth = 2; health.Start(); Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(2)); Assert.That(health.IsInvulnerable(), Is.EqualTo(false)); Assert.That(onHealCalled, Is.EqualTo(true)); Assert.That(onDamageCalled, Is.EqualTo(false)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(true)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); ResetCallbacks(); health.Damage(1, null); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(true)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(true)); Assert.That(onRespawnCalled, Is.EqualTo(false)); // after recieve damage time to be invulnerable Assert.That(health.IsInvulnerable(), Is.EqualTo(true)); ResetCallbacks(); umgr.forceFixedDeltaTime = 0.25f; // TEST add time, wait until invulnerability ends umgr.FixedUpdate(); Assert.That(health.IsInvulnerable(), Is.EqualTo(true)); umgr.forceFixedDeltaTime = 2.0f; umgr.FixedUpdate(); Assert.That(health.IsInvulnerable(), Is.EqualTo(false)); Assert.That(onInvulnerabilityEndCalled, Is.EqualTo(true)); ResetCallbacks(); health.immunity = DamageType.Water; // TEST invulnerable to recieved damage var obj3 = new GameObject(); obj3.name = "Character3"; var damage = obj3.AddComponent<Damage>(); var character2 = obj3.AddComponent<Character>(); Assert.NotNull(damage); damage.type = DamageType.Water; damage.causer = character2.GetComponent<CharacterHealth>(); damage.causer.alignment = Alignment.Enemy; health.Damage(damage); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(true)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); ResetCallbacks(); /// damage again, kill character health.Damage(1, null); Assert.That(onHealCalled, Is.EqualTo(true)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(true)); Assert.That(onInjuredCalled, Is.EqualTo(true)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(true)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(true)); ResetCallbacks(); Assert.That(health.lives, Is.EqualTo(1)); Assert.That(health.health, Is.EqualTo(2)); // kill it! health.Kill(); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(false)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(true)); Assert.That(onGameOverCalled, Is.EqualTo(true)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); } [Test] public void AlignamentTest() { CharacterHealth health = FixtureCreateHealth("testchar"); AttachEvents(health); ResetCallbacks(); health.startingLives = 2; health.maxLives = 2; health.startingHealth = 2; health.maxHealth = 2; health.alignment = Alignment.Enemy; health.Start(); CharacterHealth health2 = FixtureCreateHealth("testchar2"); health2.startingLives = 2; health2.maxLives = 2; health2.startingHealth = 2; health2.maxHealth = 2; health2.alignment = Alignment.Enemy; Damage damage = health2.gameObject.AddComponent<Damage>(); health2.Start(); //------------------------------------------ // DAMAGE NOT DEALT // cannot recieve damage from friends health.friendlyFire = false; ResetCallbacks(); Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(2)); health.Damage(damage); Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(2)); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(false)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); //------------------------------------------ // DAMAGE NOT DEALT // can recieve damage but the damage is not meant for friends damage.friendlyFire = false; health.friendlyFire = true; health.Damage(damage); Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(2)); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(false)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(false)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(false)); Assert.That(onRespawnCalled, Is.EqualTo(false)); //------------------------------------------ // DAMAGE DEALT // we can recieve damage from friends and damage is unfrienly! damage.friendlyFire = true; health.friendlyFire = true; Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(2)); health.Damage(damage); Assert.That(health.lives, Is.EqualTo(2)); Assert.That(health.health, Is.EqualTo(1)); Assert.That(onHealCalled, Is.EqualTo(false)); Assert.That(onDamageCalled, Is.EqualTo(true)); Assert.That(onImmunityCalled, Is.EqualTo(false)); Assert.That(onMaxHealthCalled, Is.EqualTo(false)); Assert.That(onInjuredCalled, Is.EqualTo(true)); Assert.That(onHurtCalled, Is.EqualTo(false)); Assert.That(onDeathCalled, Is.EqualTo(false)); Assert.That(onGameOverCalled, Is.EqualTo(false)); Assert.That(onInvulnerabilityStartCalled, Is.EqualTo(true)); Assert.That(onRespawnCalled, Is.EqualTo(false)); } } }
// 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.Reflection; using System.Reflection.Emit; using System.Threading; using Xunit; namespace System.Reflection.Emit.Tests { public class MethodBuilderGetILGenerator1 { private const string TestDynamicAssemblyName = "TestDynamicAssembly"; private const string TestDynamicModuleName = "TestDynamicModule"; private const string TestDynamicTypeName = "TestDynamicType"; private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run; private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract; private const int MinStringLength = 1; private const int MaxStringLength = 128; private TypeBuilder GetTestTypeBuilder() { AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly( assemblyName, TestAssemblyBuilderAccess); ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName); return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes); } [Fact] public void TestWithPublicAttribute() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithAssemblyAttribute() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Assembly); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithCheckAccessOnOverride() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.CheckAccessOnOverride); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithFamAndAssem() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.FamANDAssem); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithFamily() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Family); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithFamOrAssem() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.FamORAssem); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithFinal() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Final); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithHasSecurity() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.HasSecurity); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithHideBySig() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.HideBySig); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithMemberAccessMask() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.MemberAccessMask); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithNewSlot() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.NewSlot); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithPrivate() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Private); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithPrivateScope() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.PrivateScope); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithRequireSecObject() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.RequireSecObject); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithReuseSlot() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.ReuseSlot); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithRTSpecialName() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.RTSpecialName); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithSpecialName() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.SpecialName); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithStatic() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Static); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithUnManagedExport() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.UnmanagedExport); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithVirtual() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Virtual); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithVTableLayoutMask() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.VtableLayoutMask); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestWithCombinations() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Assembly | MethodAttributes.CheckAccessOnOverride | MethodAttributes.FamORAssem | MethodAttributes.Final | MethodAttributes.HasSecurity | MethodAttributes.HideBySig | MethodAttributes.MemberAccessMask | MethodAttributes.NewSlot | MethodAttributes.Private | MethodAttributes.PrivateScope | MethodAttributes.RequireSecObject | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.Static | MethodAttributes.UnmanagedExport); Assert.NotNull(builder.GetILGenerator()); } [Fact] public void TestThrowsExceptionForPInvoke() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.PinvokeImpl); Assert.Throws<InvalidOperationException>(() => { ILGenerator generator = builder.GetILGenerator(); }); } [Fact] public void TestThrowsExceptionOnInvalidMethodAttributeSet() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, MethodAttributes.Abstract | MethodAttributes.PinvokeImpl); Assert.Throws<InvalidOperationException>(() => { ILGenerator generator = builder.GetILGenerator(); }); } } }
// <copyright file="RealtimeManager.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native.PInvoke { using System; using System.Linq; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Multiplayer; using System.Collections.Generic; using C = GooglePlayGames.Native.Cwrapper.RealTimeMultiplayerManager; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; using MultiplayerStatus = GooglePlayGames.Native.Cwrapper.CommonErrorStatus.MultiplayerStatus; using System.Runtime.InteropServices; internal class RealtimeManager { private readonly GameServices mGameServices; internal RealtimeManager(GameServices gameServices) { this.mGameServices = Misc.CheckNotNull(gameServices); } internal void CreateRoom(RealtimeRoomConfig config, RealTimeEventListenerHelper helper, Action<RealTimeRoomResponse> callback) { C.RealTimeMultiplayerManager_CreateRealTimeRoom(mGameServices.AsHandle(), config.AsPointer(), helper.AsPointer(), InternalRealTimeRoomCallback, ToCallbackPointer(callback)); } internal void ShowPlayerSelectUI(uint minimumPlayers, uint maxiumPlayers, bool allowAutomatching, Action<PlayerSelectUIResponse> callback) { C.RealTimeMultiplayerManager_ShowPlayerSelectUI(mGameServices.AsHandle(), minimumPlayers, maxiumPlayers, allowAutomatching, InternalPlayerSelectUIcallback, Callbacks.ToIntPtr(callback, PlayerSelectUIResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.PlayerSelectUICallback))] internal static void InternalPlayerSelectUIcallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#PlayerSelectUICallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.RealTimeRoomCallback))] internal static void InternalRealTimeRoomCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalRealTimeRoomCallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.RoomInboxUICallback))] internal static void InternalRoomInboxUICallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalRoomInboxUICallback", Callbacks.Type.Temporary, response, data); } internal void ShowRoomInboxUI(Action<RoomInboxUIResponse> callback) { C.RealTimeMultiplayerManager_ShowRoomInboxUI(mGameServices.AsHandle(), InternalRoomInboxUICallback, Callbacks.ToIntPtr(callback, RoomInboxUIResponse.FromPointer)); } internal void ShowWaitingRoomUI(NativeRealTimeRoom room, uint minimumParticipantsBeforeStarting, Action<WaitingRoomUIResponse> callback) { Misc.CheckNotNull(room); C.RealTimeMultiplayerManager_ShowWaitingRoomUI(mGameServices.AsHandle(), room.AsPointer(), minimumParticipantsBeforeStarting, InternalWaitingRoomUICallback, Callbacks.ToIntPtr(callback, WaitingRoomUIResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.WaitingRoomUICallback))] internal static void InternalWaitingRoomUICallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalWaitingRoomUICallback", Callbacks.Type.Temporary, response, data); } [AOT.MonoPInvokeCallback(typeof(C.FetchInvitationsCallback))] internal static void InternalFetchInvitationsCallback(IntPtr response, IntPtr data) { Callbacks.PerformInternalCallback( "RealtimeManager#InternalFetchInvitationsCallback", Callbacks.Type.Temporary, response, data); } internal void FetchInvitations(Action<FetchInvitationsResponse> callback) { C.RealTimeMultiplayerManager_FetchInvitations(mGameServices.AsHandle(), InternalFetchInvitationsCallback, Callbacks.ToIntPtr(callback, FetchInvitationsResponse.FromPointer)); } [AOT.MonoPInvokeCallback(typeof(C.LeaveRoomCallback))] internal static void InternalLeaveRoomCallback(Status.ResponseStatus response, IntPtr data) { Logger.d("Entering internal callback for InternalLeaveRoomCallback"); Action<Status.ResponseStatus> callback = Callbacks.IntPtrToTempCallback<Action<Status.ResponseStatus>>(data); if (callback == null) { return; } try { callback(response); } catch (Exception e) { Logger.e("Error encountered executing InternalLeaveRoomCallback. " + "Smothering to avoid passing exception into Native: " + e); } } internal void LeaveRoom(NativeRealTimeRoom room, Action<Status.ResponseStatus> callback) { C.RealTimeMultiplayerManager_LeaveRoom(mGameServices.AsHandle(), room.AsPointer(), InternalLeaveRoomCallback, Callbacks.ToIntPtr(callback)); } internal void AcceptInvitation(MultiplayerInvitation invitation, RealTimeEventListenerHelper listener, Action<RealTimeRoomResponse> callback) { C.RealTimeMultiplayerManager_AcceptInvitation(mGameServices.AsHandle(), invitation.AsPointer(), listener.AsPointer(), InternalRealTimeRoomCallback, ToCallbackPointer(callback)); } internal void DeclineInvitation(MultiplayerInvitation invitation) { C.RealTimeMultiplayerManager_DeclineInvitation(mGameServices.AsHandle(), invitation.AsPointer()); } internal void SendReliableMessage(NativeRealTimeRoom room, MultiplayerParticipant participant, byte[] data, Action<Status.MultiplayerStatus> callback) { C.RealTimeMultiplayerManager_SendReliableMessage(mGameServices.AsHandle(), room.AsPointer(), participant.AsPointer(), data, PInvokeUtilities.ArrayToSizeT(data), InternalSendReliableMessageCallback, Callbacks.ToIntPtr(callback)); } [AOT.MonoPInvokeCallback(typeof(C.SendReliableMessageCallback))] internal static void InternalSendReliableMessageCallback(Status.MultiplayerStatus response, IntPtr data) { Logger.d("Entering internal callback for InternalSendReliableMessageCallback " + response); Action<Status.MultiplayerStatus> callback = Callbacks.IntPtrToTempCallback<Action<Status.MultiplayerStatus>>(data); if (callback == null) { return; } try { callback(response); } catch (Exception e) { Logger.e("Error encountered executing InternalSendReliableMessageCallback. " + "Smothering to avoid passing exception into Native: " + e); } } internal void SendUnreliableMessageToAll(NativeRealTimeRoom room, byte[] data) { C.RealTimeMultiplayerManager_SendUnreliableMessageToOthers(mGameServices.AsHandle(), room.AsPointer(), data, PInvokeUtilities.ArrayToSizeT(data)); } internal void SendUnreliableMessageToSpecificParticipants(NativeRealTimeRoom room, List<MultiplayerParticipant> recipients, byte[] data) { C.RealTimeMultiplayerManager_SendUnreliableMessage( mGameServices.AsHandle(), room.AsPointer(), recipients.Select(r => r.AsPointer()).ToArray(), new UIntPtr((ulong)recipients.LongCount()), data, PInvokeUtilities.ArrayToSizeT(data)); } private static IntPtr ToCallbackPointer(Action<RealTimeRoomResponse> callback) { return Callbacks.ToIntPtr<RealTimeRoomResponse>( callback, RealTimeRoomResponse.FromPointer ); } internal class RealTimeRoomResponse : BaseReferenceHolder { internal RealTimeRoomResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.MultiplayerStatus ResponseStatus() { return C.RealTimeMultiplayerManager_RealTimeRoomResponse_GetStatus(SelfPtr()); } internal bool RequestSucceeded() { return ResponseStatus() > 0; } internal NativeRealTimeRoom Room() { if (!RequestSucceeded()) { return null; } return new NativeRealTimeRoom( C.RealTimeMultiplayerManager_RealTimeRoomResponse_GetRoom(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_RealTimeRoomResponse_Dispose(selfPointer); } internal static RealTimeRoomResponse FromPointer(IntPtr pointer) { if (pointer.Equals(IntPtr.Zero)) { return null; } return new RealTimeRoomResponse(pointer); } } internal class RoomInboxUIResponse : BaseReferenceHolder { internal RoomInboxUIResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.UIStatus ResponseStatus() { return C.RealTimeMultiplayerManager_RoomInboxUIResponse_GetStatus(SelfPtr()); } internal MultiplayerInvitation Invitation() { if (ResponseStatus() != Status.UIStatus.VALID) { return null; } return new MultiplayerInvitation( C.RealTimeMultiplayerManager_RoomInboxUIResponse_GetInvitation(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_RoomInboxUIResponse_Dispose(selfPointer); } internal static RoomInboxUIResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new RoomInboxUIResponse(pointer); } } internal class WaitingRoomUIResponse : BaseReferenceHolder { internal WaitingRoomUIResponse(IntPtr selfPointer) : base(selfPointer) { } internal Status.UIStatus ResponseStatus() { return C.RealTimeMultiplayerManager_WaitingRoomUIResponse_GetStatus(SelfPtr()); } internal NativeRealTimeRoom Room() { if (ResponseStatus() != Status.UIStatus.VALID) { return null; } return new NativeRealTimeRoom( C.RealTimeMultiplayerManager_WaitingRoomUIResponse_GetRoom(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_WaitingRoomUIResponse_Dispose(selfPointer); } internal static WaitingRoomUIResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new WaitingRoomUIResponse(pointer); } } internal class FetchInvitationsResponse : BaseReferenceHolder { internal FetchInvitationsResponse(IntPtr selfPointer) : base(selfPointer) { } internal bool RequestSucceeded() { return ResponseStatus() > 0; } internal Status.ResponseStatus ResponseStatus() { return C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetStatus(SelfPtr()); } internal IEnumerable<MultiplayerInvitation> Invitations() { return PInvokeUtilities.ToEnumerable( C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetInvitations_Length( SelfPtr()), index => new MultiplayerInvitation( C.RealTimeMultiplayerManager_FetchInvitationsResponse_GetInvitations_GetElement( SelfPtr(), index)) ); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeMultiplayerManager_FetchInvitationsResponse_Dispose(selfPointer); } internal static FetchInvitationsResponse FromPointer(IntPtr pointer) { if (PInvokeUtilities.IsNull(pointer)) { return null; } return new FetchInvitationsResponse(pointer); } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; // TODO: Once we upgrade to C# 6, remove all of these and simply import the libcurl class. using CURLcode = Interop.libcurl.CURLcode; using CURLINFO = Interop.libcurl.CURLINFO; using CURLMcode = Interop.libcurl.CURLMcode; using CURLoption = Interop.libcurl.CURLoption; using SafeCurlMultiHandle = Interop.libcurl.SafeCurlMultiHandle; using size_t = System.UInt64; // TODO: IntPtr namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { /// <summary>Provides a multi handle and the associated processing for all requests on the handle.</summary> private sealed class MultiAgent { private static readonly Interop.libcurl.curl_readwrite_callback s_receiveHeadersCallback = CurlReceiveHeadersCallback; private static readonly Interop.libcurl.curl_readwrite_callback s_sendCallback = CurlSendCallback; private static readonly Interop.libcurl.seek_callback s_seekCallback = CurlSeekCallback; private static readonly Interop.libcurl.curl_readwrite_callback s_receiveBodyCallback = CurlReceiveBodyCallback; /// <summary> /// A collection of not-yet-processed incoming requests for work to be done /// by this multi agent. This can include making new requests, canceling /// active requests, or unpausing active requests. /// Protected by a lock on <see cref="_incomingRequests"/>. /// </summary> private readonly Queue<IncomingRequest> _incomingRequests = new Queue<IncomingRequest>(); /// <summary>Map of activeOperations, indexed by a GCHandle ptr.</summary> private readonly Dictionary<IntPtr, ActiveRequest> _activeOperations = new Dictionary<IntPtr, ActiveRequest>(); /// <summary> /// Lazily-initialized buffer used to transfer data from a request content stream to libcurl. /// This buffer may be shared amongst all of the connections associated with /// this multi agent, as long as those operations are performed synchronously on the thread /// associated with the multi handle. Asynchronous operation must use a separate buffer. /// </summary> private byte[] _transferBuffer; /// <summary> /// Special file descriptor used to wake-up curl_multi_wait calls. This is the read /// end of a pipe, with the write end written to when work is queued or when cancellation /// is requested. This is only valid while the worker is executing. /// </summary> private int _wakeupRequestedPipeFd; /// <summary> /// Write end of the pipe connected to <see cref="_wakeupRequestedPipeFd"/>. /// This is only valid while the worker is executing. /// </summary> private int _requestWakeupPipeFd; /// <summary> /// Task for the currently running worker, or null if there is no current worker. /// Protected by a lock on <see cref="_incomingRequests"/>. /// </summary> private Task _runningWorker; /// <summary>Queues a request for the multi handle to process.</summary> public void Queue(IncomingRequest request) { lock (_incomingRequests) { // Add the request, then initiate processing. _incomingRequests.Enqueue(request); EnsureWorkerIsRunning(); } } /// <summary>Gets the ID of the currently running worker, or null if there isn't one.</summary> internal int? RunningWorkerId { get { return _runningWorker != null ? (int?)_runningWorker.Id : null; } } /// <summary>Schedules the processing worker if one hasn't already been scheduled.</summary> private void EnsureWorkerIsRunning() { Debug.Assert(Monitor.IsEntered(_incomingRequests), "Needs to be called under _incomingRequests lock"); if (_runningWorker == null) { VerboseTrace("MultiAgent worker queued"); // Create pipe used to forcefully wake up curl_multi_wait calls when something important changes. // This is created here rather than in Process so that the pipe is available immediately // for subsequent queue calls to use. Debug.Assert(_wakeupRequestedPipeFd == 0, "Read pipe should have been cleared"); Debug.Assert(_requestWakeupPipeFd == 0, "Write pipe should have been cleared"); unsafe { int* fds = stackalloc int[2]; while (Interop.CheckIo(Interop.Sys.Pipe(fds))) ; _wakeupRequestedPipeFd = fds[Interop.Sys.ReadEndOfPipe]; _requestWakeupPipeFd = fds[Interop.Sys.WriteEndOfPipe]; } // Kick off the processing task. It's "DenyChildAttach" to avoid any surprises if // code happens to create attached tasks, and it's LongRunning because this thread // is likely going to sit around for a while in a wait loop (and the more requests // are concurrently issued to the same agent, the longer the thread will be around). const TaskCreationOptions Options = TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning; _runningWorker = new Task(s => { VerboseTrace("MultiAgent worker starting"); var thisRef = (MultiAgent)s; try { // Do the actual processing thisRef.WorkerLoop(); } catch (Exception exc) { Debug.Fail("Unexpected exception from processing loop: " + exc.ToString()); } finally { VerboseTrace("MultiAgent worker shutting down"); lock (thisRef._incomingRequests) { // Close our wakeup pipe (ignore close errors). // This is done while holding the lock to prevent // subsequent Queue calls to see an improperly configured // set of descriptors. Interop.Sys.Close(thisRef._wakeupRequestedPipeFd); thisRef._wakeupRequestedPipeFd = 0; Interop.Sys.Close(thisRef._requestWakeupPipeFd); thisRef._requestWakeupPipeFd = 0; // In the time between we stopped processing and now, // more requests could have been added. If they were // kick off another processing loop. thisRef._runningWorker = null; if (thisRef._incomingRequests.Count > 0) { thisRef.EnsureWorkerIsRunning(); } } } }, this, CancellationToken.None, Options); _runningWorker.Start(TaskScheduler.Default); // started after _runningWorker field set to avoid race conditions } else // _workerRunning == true { // The worker is already running. If there are already queued requests, we're done. // However, if there aren't any queued requests, Process could be blocked inside of // curl_multi_wait, and we want to make sure it wakes up to see that there additional // requests waiting to be handled. So we write to the wakeup pipe. Debug.Assert(_incomingRequests.Count >= 1, "We just queued a request, so the count should be at least 1"); if (_incomingRequests.Count == 1) { RequestWakeup(); } } } /// <summary>Write a byte to the wakeup pipe.</summary> private void RequestWakeup() { unsafe { VerboseTrace("Writing to wakeup pipe"); byte b = 1; while ((Interop.CheckIo((long)Interop.Sys.Write(_requestWakeupPipeFd, &b, 1)))) ; } } /// <summary>Clears data from the wakeup pipe.</summary> /// <remarks> /// This must only be called when we know there's data to be read. /// The MultiAgent could easily deadlock if it's called when there's no data in the pipe. /// </remarks> private unsafe void ReadFromWakeupPipeWhenKnownToContainData() { // It's possible but unlikely that there will be tons of extra data in the pipe, // more than we end up reading out here (it's unlikely because we only write a byte to the pipe when // transitioning from 0 to 1 incoming request). In that unlikely event, the worst // case will be that the next one or more waits will wake up immediately, with each one // subsequently clearing out more of the pipe. const int ClearBufferSize = 64; // sufficiently large to clear the pipe in any normal case byte* clearBuf = stackalloc byte[ClearBufferSize]; int bytesRead; while (Interop.CheckIo(bytesRead = Interop.Sys.Read(_wakeupRequestedPipeFd, clearBuf, ClearBufferSize))) ; VerboseTraceIf(bytesRead > 1, "Read more than one byte from wakeup pipe: " + bytesRead); } /// <summary>Requests that libcurl unpause the connection associated with this request.</summary> internal void RequestUnpause(EasyRequest easy) { VerboseTrace(easy: easy); Queue(new IncomingRequest { Easy = easy, Type = IncomingRequestType.Unpause }); } private void WorkerLoop() { Debug.Assert(!Monitor.IsEntered(_incomingRequests), "No locks should be held while invoking Process"); Debug.Assert(_runningWorker != null && _runningWorker.Id == Task.CurrentId, "This is the worker, so it must be running"); Debug.Assert(_wakeupRequestedPipeFd != 0, "Should have a valid pipe for wake ups"); // Create the multi handle to use for this round of processing. This one handle will be used // to service all easy requests currently available and all those that come in while // we're processing other requests. Once the work quiesces and there are no more requests // to process, this multi handle will be released as the worker goes away. The next // time a request arrives and a new worker is spun up, a new multi handle will be created. SafeCurlMultiHandle multiHandle = Interop.libcurl.curl_multi_init(); if (multiHandle.IsInvalid) { throw CreateHttpRequestException(); } // Clear our active operations table. This should already be clear, either because // all previous operations completed without unexpected exception, or in the case of an // unexpected exception we should have cleaned up gracefully anyway. But just in case... Debug.Assert(_activeOperations.Count == 0, "We shouldn't have any active operations when starting processing."); _activeOperations.Clear(); bool endingSuccessfully = false; try { // Continue processing as long as there are any active operations while (true) { // First handle any requests in the incoming requests queue. while (true) { IncomingRequest request; lock (_incomingRequests) { if (_incomingRequests.Count == 0) break; request = _incomingRequests.Dequeue(); } HandleIncomingRequest(multiHandle, request); } // If we have no active operations, we're done. if (_activeOperations.Count == 0) { endingSuccessfully = true; return; } // We have one or more active operations. Run any work that needs to be run. int running_handles; ThrowIfCURLMError(Interop.libcurl.curl_multi_perform(multiHandle, out running_handles)); // Complete and remove any requests that have finished being processed. int pendingMessages; IntPtr messagePtr; while ((messagePtr = Interop.libcurl.curl_multi_info_read(multiHandle, out pendingMessages)) != IntPtr.Zero) { Interop.libcurl.CURLMsg message = Marshal.PtrToStructure<Interop.libcurl.CURLMsg>(messagePtr); Debug.Assert(message.msg == Interop.libcurl.CURLMSG.CURLMSG_DONE, "CURLMSG_DONE is supposed to be the only message type"); IntPtr gcHandlePtr; ActiveRequest completedOperation; if (message.msg == Interop.libcurl.CURLMSG.CURLMSG_DONE) { int getInfoResult = Interop.libcurl.curl_easy_getinfo(message.easy_handle, CURLINFO.CURLINFO_PRIVATE, out gcHandlePtr); Debug.Assert(getInfoResult == CURLcode.CURLE_OK, "Failed to get info on a completing easy handle"); if (getInfoResult == CURLcode.CURLE_OK) { bool gotActiveOp = _activeOperations.TryGetValue(gcHandlePtr, out completedOperation); Debug.Assert(gotActiveOp, "Expected to find GCHandle ptr in active operations table"); if (gotActiveOp) { DeactivateActiveRequest(multiHandle, completedOperation.Easy, gcHandlePtr, completedOperation.CancellationRegistration); FinishRequest(completedOperation.Easy, message.result); } } } } // Wait for more things to do. Even with our cancellation mechanism, we specify a timeout so that // just in case something goes wrong we can recover gracefully. This timeout is relatively long. // Note, though, that libcurl has its own internal timeout, which can be requested separately // via curl_multi_timeout, but which is used implicitly by curl_multi_wait if it's shorter // than the value we provide. const int FailsafeTimeoutMilliseconds = 1000; int numFds; unsafe { Interop.libcurl.curl_waitfd extraFds = new Interop.libcurl.curl_waitfd { fd = _wakeupRequestedPipeFd, events = Interop.libcurl.CURL_WAIT_POLLIN, revents = 0 }; ThrowIfCURLMError(Interop.libcurl.curl_multi_wait(multiHandle, &extraFds, 1, FailsafeTimeoutMilliseconds, out numFds)); if ((extraFds.revents & Interop.libcurl.CURL_WAIT_POLLIN) != 0) { // We woke up (at least in part) because a wake-up was requested. // Read the data out of the pipe to clear it. Debug.Assert(numFds >= 1, "numFds should have been at least one, as the extraFd was set"); VerboseTrace("curl_multi_wait wake-up notification"); ReadFromWakeupPipeWhenKnownToContainData(); } VerboseTraceIf(numFds == 0, "curl_multi_wait timeout"); } // PERF NOTE: curl_multi_wait uses poll (assuming it's available), which is O(N) in terms of the number of fds // being waited on. If this ends up being a scalability bottleneck, we can look into using the curl_multi_socket_* // APIs, which would let us switch to using epoll by being notified when sockets file descriptors are added or // removed and configuring the epoll context with EPOLL_CTL_ADD/DEL, which at the expense of a lot of additional // complexity would let us turn the O(N) operation into an O(1) operation. The additional complexity would come // not only in the form of additional callbacks and managing the socket collection, but also in the form of timer // management, which is necessary when using the curl_multi_socket_* APIs and which we avoid by using just // curl_multi_wait/perform. } } finally { // If we got an unexpected exception, something very bad happened. We may have some // operations that we initiated but that weren't completed. Make sure to clean up any // such operations, failing them and releasing their resources. if (_activeOperations.Count > 0) { Debug.Assert(!endingSuccessfully, "We should only have remaining operations if we got an unexpected exception"); foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations) { ActiveRequest failingOperation = pair.Value; IntPtr failingOperationGcHandle = pair.Key; DeactivateActiveRequest(multiHandle, failingOperation.Easy, failingOperationGcHandle, failingOperation.CancellationRegistration); // Complete the operation's task and clean up any of its resources failingOperation.Easy.FailRequest(CreateHttpRequestException()); failingOperation.Easy.Cleanup(); // no active processing remains, so cleanup } // Clear the table. _activeOperations.Clear(); } // Finally, dispose of the multi handle. multiHandle.Dispose(); } } private void HandleIncomingRequest(SafeCurlMultiHandle multiHandle, IncomingRequest request) { Debug.Assert(!Monitor.IsEntered(_incomingRequests), "Incoming requests lock should only be held while accessing the queue"); VerboseTrace("Type: " + request.Type, easy: request.Easy); EasyRequest easy = request.Easy; switch (request.Type) { case IncomingRequestType.New: ActivateNewRequest(multiHandle, easy); break; case IncomingRequestType.Cancel: Debug.Assert(easy._associatedMultiAgent == this, "Should only cancel associated easy requests"); Debug.Assert(easy._cancellationToken.IsCancellationRequested, "Cancellation should have been requested"); FindAndFailActiveRequest(multiHandle, easy, new OperationCanceledException(easy._cancellationToken)); break; case IncomingRequestType.Unpause: Debug.Assert(easy._associatedMultiAgent == this, "Should only unpause associated easy requests"); if (!easy._easyHandle.IsClosed) { IntPtr gcHandlePtr; ActiveRequest ar; Debug.Assert(FindActiveRequest(easy, out gcHandlePtr, out ar), "Couldn't find active request for unpause"); int unpauseResult = Interop.libcurl.curl_easy_pause(easy._easyHandle, Interop.libcurl.CURLPAUSE_CONT); if (unpauseResult != CURLcode.CURLE_OK) { FindAndFailActiveRequest(multiHandle, easy, new CurlException(unpauseResult, isMulti: false)); } } break; default: Debug.Fail("Invalid request type: " + request.Type); break; } } private void ActivateNewRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy) { Debug.Assert(easy != null, "We should never get a null request"); Debug.Assert(easy._associatedMultiAgent == null, "New requests should not be associated with an agent yet"); // If cancellation has been requested, complete the request proactively if (easy._cancellationToken.IsCancellationRequested) { easy.FailRequest(new OperationCanceledException(easy._cancellationToken)); easy.Cleanup(); // no active processing remains, so cleanup return; } // Otherwise, configure it. Most of the configuration was already done when the EasyRequest // was created, but there's additional configuration we need to do specific to this // multi agent, specifically telling the easy request about its own GCHandle and setting // up callbacks for data processing. Once it's configured, add it to the multi handle. GCHandle gcHandle = GCHandle.Alloc(easy); IntPtr gcHandlePtr = GCHandle.ToIntPtr(gcHandle); try { easy._associatedMultiAgent = this; easy.SetCurlOption(CURLoption.CURLOPT_PRIVATE, gcHandlePtr); SetCurlCallbacks(easy, gcHandlePtr); ThrowIfCURLMError(Interop.libcurl.curl_multi_add_handle(multiHandle, easy._easyHandle)); } catch (Exception exc) { gcHandle.Free(); easy.FailRequest(exc); easy.Cleanup(); // no active processing remains, so cleanup return; } // And if cancellation can be requested, hook up a cancellation callback. // This callback will put the easy request back into the queue, which will // ensure that a wake-up request has been issued. When we pull // the easy request out of the request queue, we'll see that it's already // associated with this agent, meaning that it's a cancellation request, // and we'll deal with it appropriately. var cancellationReg = default(CancellationTokenRegistration); if (easy._cancellationToken.CanBeCanceled) { cancellationReg = easy._cancellationToken.Register(s => { var state = (Tuple<MultiAgent, EasyRequest>)s; state.Item1.Queue(new IncomingRequest { Easy = state.Item2, Type = IncomingRequestType.Cancel }); }, Tuple.Create<MultiAgent, EasyRequest>(this, easy)); } // Finally, add it to our map. _activeOperations.Add( gcHandlePtr, new ActiveRequest { Easy = easy, CancellationRegistration = cancellationReg }); } private void DeactivateActiveRequest( SafeCurlMultiHandle multiHandle, EasyRequest easy, IntPtr gcHandlePtr, CancellationTokenRegistration cancellationRegistration) { // Remove the operation from the multi handle so we can shut down the multi handle cleanly int removeResult = Interop.libcurl.curl_multi_remove_handle(multiHandle, easy._easyHandle); Debug.Assert(removeResult == CURLMcode.CURLM_OK, "Failed to remove easy handle"); // ignore cleanup errors in release // Release the associated GCHandle so that it's not kept alive forever if (gcHandlePtr != IntPtr.Zero) { try { GCHandle.FromIntPtr(gcHandlePtr).Free(); _activeOperations.Remove(gcHandlePtr); } catch (InvalidOperationException) { Debug.Fail("Couldn't get/free the GCHandle for an active operation while shutting down due to failure"); } } // Undo cancellation registration cancellationRegistration.Dispose(); } private bool FindActiveRequest(EasyRequest easy, out IntPtr gcHandlePtr, out ActiveRequest activeRequest) { // We maintain an IntPtr=>ActiveRequest mapping, which makes it cheap to look-up by GCHandle ptr but // expensive to look up by EasyRequest. If we find this becoming a bottleneck, we can add a reverse // map that stores the other direction as well. foreach (KeyValuePair<IntPtr, ActiveRequest> pair in _activeOperations) { if (pair.Value.Easy == easy) { gcHandlePtr = pair.Key; activeRequest = pair.Value; return true; } } gcHandlePtr = IntPtr.Zero; activeRequest = default(ActiveRequest); return false; } private void FindAndFailActiveRequest(SafeCurlMultiHandle multiHandle, EasyRequest easy, Exception error) { VerboseTrace("Error: " + error.Message, easy: easy); IntPtr gcHandlePtr; ActiveRequest activeRequest; if (FindActiveRequest(easy, out gcHandlePtr, out activeRequest)) { DeactivateActiveRequest(multiHandle, easy, gcHandlePtr, activeRequest.CancellationRegistration); easy.FailRequest(error); easy.Cleanup(); // no active processing remains, so we can cleanup } else { Debug.Assert(easy.Task.IsCompleted, "We should only not be able to find the request if it failed or we started to send back the response."); } } private void FinishRequest(EasyRequest completedOperation, int messageResult) { VerboseTrace("messageResult: " + messageResult, easy: completedOperation); if (completedOperation._responseMessage.StatusCode != HttpStatusCode.Unauthorized) { if (completedOperation._handler.PreAuthenticate) { ulong availedAuth; if (Interop.libcurl.curl_easy_getinfo(completedOperation._easyHandle, CURLINFO.CURLINFO_HTTPAUTH_AVAIL, out availedAuth) == CURLcode.CURLE_OK) { completedOperation._handler.AddCredentialToCache( completedOperation._requestMessage.RequestUri, availedAuth, completedOperation._networkCredential); } // Ignore errors: no need to fail for the sake of putting the credentials into the cache } completedOperation._handler.AddResponseCookies( completedOperation._requestMessage.RequestUri, completedOperation._responseMessage); } switch (messageResult) { case CURLcode.CURLE_OK: completedOperation.EnsureResponseMessagePublished(); break; case CURLcode.CURLE_UNSUPPORTED_PROTOCOL: if (completedOperation._isRedirect) { completedOperation.EnsureResponseMessagePublished(); } else { completedOperation.FailRequest(CreateHttpRequestException(new CurlException(messageResult, isMulti: false))); } break; default: completedOperation.FailRequest(CreateHttpRequestException(new CurlException(messageResult, isMulti: false))); break; } // At this point, we've completed processing the entire request, either due to error // or due to completing the entire response. completedOperation.Cleanup(); } private static size_t CurlReceiveHeadersCallback(IntPtr buffer, size_t size, size_t nitems, IntPtr context) { CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems); size *= nitems; if (size == 0) { return 0; } EasyRequest easy; if (TryGetEasyRequestFromContext(context, out easy)) { try { // The callback is invoked once per header; multi-line headers get merged into a single line. string responseHeader = Marshal.PtrToStringAnsi(buffer).Trim(); HttpResponseMessage response = easy._responseMessage; if (!TryParseStatusLine(response, responseHeader, easy)) { int colonIndex = responseHeader.IndexOf(':'); // Skip malformed header lines that are missing the colon character. if (colonIndex > 0) { string headerName = responseHeader.Substring(0, colonIndex); string headerValue = responseHeader.Substring(colonIndex + 1); if (!response.Headers.TryAddWithoutValidation(headerName, headerValue)) { response.Content.Headers.TryAddWithoutValidation(headerName, headerValue); } else if (easy._isRedirect && string.Equals(headerName, HttpKnownHeaderNames.Location, StringComparison.OrdinalIgnoreCase)) { HandleRedirectLocationHeader(easy, headerValue); } } } return size; } catch (Exception ex) { easy.FailRequest(ex); // cleanup will be handled by main processing loop } } // Returing a value other than size fails the callback and forces // request completion with an error return size - 1; } private static size_t CurlReceiveBodyCallback( IntPtr buffer, size_t size, size_t nitems, IntPtr context) { CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems); size *= nitems; EasyRequest easy; if (TryGetEasyRequestFromContext(context, out easy)) { try { if (!(easy.Task.IsCanceled || easy.Task.IsFaulted)) { // Complete the task if it hasn't already been. This will make the // stream available to consumers. A previous write callback // may have already completed the task to publish the response. easy.EnsureResponseMessagePublished(); // Try to transfer the data to a reader. This will return either the // amount of data transferred (equal to the amount requested // to be transferred), or it will return a pause request. return easy._responseMessage.ResponseStream.TransferDataToStream(buffer, (long)size); } } catch (Exception ex) { easy.FailRequest(ex); // cleanup will be handled by main processing loop } } // Returing a value other than size fails the callback and forces // request completion with an error. CurlHandler.VerboseTrace("Error: returning a bad size to abort the request"); return (size > 0) ? size - 1 : 1; } private static size_t CurlSendCallback(IntPtr buffer, size_t size, size_t nitems, IntPtr context) { CurlHandler.VerboseTrace("size: " + size + ", nitems: " + nitems); int length = checked((int)(size * nitems)); Debug.Assert(length <= RequestBufferSize, "length " + length + " should not be larger than RequestBufferSize " + RequestBufferSize); if (length == 0) { return 0; } EasyRequest easy; if (TryGetEasyRequestFromContext(context, out easy)) { Debug.Assert(easy._requestContentStream != null, "We should only be in the send callback if we have a request content stream"); Debug.Assert(easy._associatedMultiAgent != null, "The request should be associated with a multi agent."); // Transfer data from the request's content stream to libcurl try { if (easy._requestContentStream is MemoryStream) { // If the request content stream is a memory stream (a very common case, as it's the default // stream type used by the base HttpContent type), then we can simply perform the read synchronously // knowing that it won't block. return (size_t)TransferDataFromRequestMemoryStream(buffer, length, easy); } else { // Otherwise, we need to be concerned about blocking, due to this being called from the only thread able to // service the multi agent (a multi handle can only be accessed by one thread at a time). The whole // operation, across potentially many callbacks, will be performed asynchronously: we issue the request // asynchronously, and if it's not completed immediately, we pause the connection until the data // is ready to be consumed by libcurl. return TransferDataFromRequestStream(buffer, length, easy); } } catch (Exception ex) { easy.FailRequest(ex); // cleanup will be handled by main processing loop } } // Something went wrong. return Interop.libcurl.CURL_READFUNC_ABORT; } /// <summary> /// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s /// request content memory stream to the buffer. /// </summary> /// <returns>The number of bytes transferred.</returns> private static int TransferDataFromRequestMemoryStream(IntPtr buffer, int length, EasyRequest easy) { Debug.Assert(easy._requestContentStream is MemoryStream, "Must only be used when the request stream is a memory stream"); Debug.Assert(easy._sendTransferState == null, "We should never have initialized the transfer state if the request stream is in memory"); MultiAgent multi = easy._associatedMultiAgent; byte[] arr = multi._transferBuffer ?? (multi._transferBuffer = new byte[RequestBufferSize]); int numBytes = easy._requestContentStream.Read(arr, 0, Math.Min(arr.Length, length)); Debug.Assert(numBytes >= 0 && numBytes <= length, "Read more bytes than requested"); if (numBytes > 0) { Marshal.Copy(arr, 0, buffer, numBytes); } multi.VerboseTrace("Transferred " + numBytes + " from memory stream", easy: easy); return numBytes; } /// <summary> /// Transfers up to <paramref name="length"/> data from the <paramref name="easy"/>'s /// request content (non-memory) stream to the buffer. /// </summary> /// <returns>The number of bytes transferred.</returns> private static size_t TransferDataFromRequestStream(IntPtr buffer, int length, EasyRequest easy) { Debug.Assert(!(easy._requestContentStream is MemoryStream), "Memory streams should use TransferFromRequestMemoryStreamToBuffer."); MultiAgent multi = easy._associatedMultiAgent; // First check to see whether there's any data available from a previous asynchronous read request. // If there is, the transfer state's Task field will be non-null, with its Result representing // the number of bytes read. The Buffer will then contain all of that read data. If the Count // is 0, then this is the first time we're checking that Task, and so we populate the Count // from that read result. After that, we can transfer as much data remains between Offset and // Count. Multiple callbacks may pull from that one read. EasyRequest.SendTransferState sts = easy._sendTransferState; if (sts != null) { // Is there a previous read that may still have data to be consumed? if (sts._task != null) { Debug.Assert(sts._task.IsCompleted, "The task must have completed if we're getting called back."); // Determine how many bytes were read on the last asynchronous read. // If nothing was read, then we're done and can simply return 0 to indicate // the end of the stream. int bytesRead = sts._task.GetAwaiter().GetResult(); // will throw if read failed Debug.Assert(bytesRead >= 0 && bytesRead <= sts._buffer.Length, "ReadAsync returned an invalid result length: " + bytesRead); if (bytesRead == 0) { multi.VerboseTrace("End of stream from stored task", easy: easy); sts.SetTaskOffsetCount(null, 0, 0); return 0; } // If Count is still 0, then this is the first time after the task completed // that we're examining the data: transfer the bytesRead to the Count. if (sts._count == 0) { multi.VerboseTrace("ReadAsync completed with bytes: " + bytesRead, easy: easy); sts._count = bytesRead; } // Now Offset and Count are both accurate. Determine how much data we can copy to libcurl... int availableData = sts._count - sts._offset; Debug.Assert(availableData > 0, "There must be some data still available."); // ... and copy as much of that as libcurl will allow. int bytesToCopy = Math.Min(availableData, length); Marshal.Copy(sts._buffer, sts._offset, buffer, bytesToCopy); multi.VerboseTrace("Copied " + bytesToCopy + " bytes from request stream", easy: easy); // Update the offset. If we've gone through all of the data, reset the state // so that the next time we're called back we'll do a new read. sts._offset += bytesToCopy; Debug.Assert(sts._offset <= sts._count, "Offset should never exceed count"); if (sts._offset == sts._count) { sts.SetTaskOffsetCount(null, 0, 0); } // Return the amount of data copied Debug.Assert(bytesToCopy > 0, "We should never return 0 bytes here."); return (size_t)bytesToCopy; } // sts was non-null but sts.Task was null, meaning there was no previous task/data // from which to satisfy any of this request. } else // sts == null { // Allocate a transfer state object to use for the remainder of this request. easy._sendTransferState = sts = new EasyRequest.SendTransferState(); } Debug.Assert(sts != null, "By this point we should have a transfer object"); Debug.Assert(sts._task == null, "There shouldn't be a task now."); Debug.Assert(sts._count == 0, "Count should be zero."); Debug.Assert(sts._offset == 0, "Offset should be zero."); // If we get here, there was no previously read data available to copy. // Initiate a new asynchronous read. Task<int> asyncRead = easy._requestContentStream.ReadAsync( sts._buffer, 0, Math.Min(sts._buffer.Length, length), easy._cancellationToken); Debug.Assert(asyncRead != null, "Badly implemented stream returned a null task from ReadAsync"); // Even though it's "Async", it's possible this read could complete synchronously or extremely quickly. // Check to see if it did, in which case we can also satisfy the libcurl request synchronously in this callback. if (asyncRead.IsCompleted) { multi.VerboseTrace("ReadAsync completed immediately", easy: easy); // Get the amount of data read. int bytesRead = asyncRead.GetAwaiter().GetResult(); // will throw if read failed if (bytesRead == 0) { multi.VerboseTrace("End of stream from quick returning ReadAsync", easy: easy); return 0; } // Copy as much as we can. int bytesToCopy = Math.Min(bytesRead, length); Debug.Assert(bytesToCopy > 0 && bytesToCopy <= sts._buffer.Length, "ReadAsync quickly returned an invalid result length: " + bytesToCopy); Marshal.Copy(sts._buffer, 0, buffer, bytesToCopy); multi.VerboseTrace("Copied " + bytesToCopy + " from quick returning ReadAsync", easy: easy); // If we read more than we were able to copy, stash it away for the next read. if (bytesToCopy < bytesRead) { multi.VerboseTrace("Stashing away " + (bytesRead - bytesToCopy) + " bytes for next read.", easy: easy); sts.SetTaskOffsetCount(asyncRead, bytesToCopy, bytesRead); } // Return the number of bytes read. return (size_t)bytesToCopy; } // Otherwise, the read completed asynchronously. Store the task, and hook up a continuation // such that the connection will be unpaused once the task completes. sts.SetTaskOffsetCount(asyncRead, 0, 0); asyncRead.ContinueWith((t, s) => { EasyRequest easyRef = (EasyRequest)s; easyRef._associatedMultiAgent.RequestUnpause(easyRef); }, easy, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); // Then pause the connection. multi.VerboseTrace("Pausing the connection", easy: easy); return Interop.libcurl.CURL_READFUNC_PAUSE; } private static int CurlSeekCallback(IntPtr context, long offset, int origin) { CurlHandler.VerboseTrace("offset: " + offset + ", origin: " + origin); EasyRequest easy; if (TryGetEasyRequestFromContext(context, out easy)) { try { if (easy._requestContentStream.CanSeek) { easy._requestContentStream.Seek(offset, (SeekOrigin)origin); return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_OK; } else { return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_CANTSEEK; } } catch (Exception ex) { easy.FailRequest(ex); // cleanup will be handled by main processing loop } } // Something went wrong return Interop.libcurl.CURL_SEEKFUNC.CURL_SEEKFUNC_FAIL; } private static bool TryGetEasyRequestFromContext(IntPtr context, out EasyRequest easy) { // Get the EasyRequest from the context try { GCHandle handle = GCHandle.FromIntPtr(context); easy = (EasyRequest)handle.Target; Debug.Assert(easy != null, "Expected non-null EasyRequest in GCHandle"); return easy != null; } catch (InvalidCastException) { Debug.Fail("EasyRequest wasn't the GCHandle's Target"); } catch (InvalidOperationException) { Debug.Fail("Invalid GCHandle"); } easy = null; return false; } private static void SetCurlCallbacks(EasyRequest easy, IntPtr easyGCHandle) { // Add callback for processing headers easy.SetCurlOption(CURLoption.CURLOPT_HEADERFUNCTION, s_receiveHeadersCallback); easy.SetCurlOption(CURLoption.CURLOPT_HEADERDATA, easyGCHandle); // If we're sending data as part of the request, add callbacks for sending request data if (easy._requestMessage.Content != null) { easy.SetCurlOption(CURLoption.CURLOPT_READFUNCTION, s_sendCallback); easy.SetCurlOption(CURLoption.CURLOPT_READDATA, easyGCHandle); easy.SetCurlOption(CURLoption.CURLOPT_SEEKFUNCTION, s_seekCallback); easy.SetCurlOption(CURLoption.CURLOPT_SEEKDATA, easyGCHandle); } // If we're expecting any data in response, add a callback for receiving body data if (easy._requestMessage.Method != HttpMethod.Head) { easy.SetCurlOption(CURLoption.CURLOPT_WRITEFUNCTION, s_receiveBodyCallback); easy.SetCurlOption(CURLoption.CURLOPT_WRITEDATA, easyGCHandle); } } [Conditional(VerboseDebuggingConditional)] private void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null) { CurlHandler.VerboseTrace(text, memberName, easy, agent: this); } [Conditional(VerboseDebuggingConditional)] private void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null) { if (condition) { CurlHandler.VerboseTrace(text, memberName, easy, agent: this); } } /// <summary>Represents an active request currently being processed by the agent.</summary> private struct ActiveRequest { public EasyRequest Easy; public CancellationTokenRegistration CancellationRegistration; } /// <summary>Represents an incoming request to be processed by the agent.</summary> internal struct IncomingRequest { public IncomingRequestType Type; public EasyRequest Easy; } /// <summary>The type of an incoming request to be processed by the agent.</summary> internal enum IncomingRequestType : byte { /// <summary>A new request that's never been submitted to an agent.</summary> New, /// <summary>A request to cancel a request previously submitted to the agent.</summary> Cancel, /// <summary>A request to unpause the connection associated with a request previously submitted to the agent.</summary> Unpause } } } }
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Google.Api.Gax; using Google.Cloud.Spanner.Data; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Internal; namespace Microsoft.EntityFrameworkCore.Storage.Internal { /// <summary> /// </summary> public class SpannerRelationalCommandBuilderFactory : RelationalCommandBuilderFactory { /// <summary> /// </summary> public SpannerRelationalCommandBuilderFactory( IDiagnosticsLogger<DbLoggerCategory.Database.Command> logger, IRelationalTypeMapper typeMapper) : base(logger, typeMapper) { } /// <inheritdoc /> protected override IRelationalCommandBuilder CreateCore( IDiagnosticsLogger<DbLoggerCategory.Database.Command> logger, IRelationalTypeMapper relationalTypeMapper) => new SpannerRelationalCommandBuilder(logger, relationalTypeMapper); private sealed class SpannerRelationalCommandBuilder : RelationalCommandBuilder { public SpannerRelationalCommandBuilder( IDiagnosticsLogger<DbLoggerCategory.Database.Command> logger, IRelationalTypeMapper typeMapper) : base(logger, typeMapper) { } protected override IRelationalCommand BuildCore( IDiagnosticsLogger<DbLoggerCategory.Database.Command> logger, string commandText, IReadOnlyList<IRelationalParameter> parameters) => new SpannerRelationalCommand(logger, commandText, parameters); private sealed class SpannerRelationalCommand : RelationalCommand { public SpannerRelationalCommand( IDiagnosticsLogger<DbLoggerCategory.Database.Command> logger, string commandText, IReadOnlyList<IRelationalParameter> parameters) : base( logger, commandText, parameters) { } protected override object Execute( IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary<string, object> parameterValues) { GaxPreconditions.CheckNotNull(connection, nameof(connection)); var dbCommand = CreateCommand(connection, parameterValues); connection.Open(); var commandId = Guid.NewGuid(); var startTime = DateTimeOffset.UtcNow; var stopwatch = Stopwatch.StartNew(); Logger.CommandExecuting( dbCommand, executeMethod, commandId, connection.ConnectionId, false, startTime); object result; var readerOpen = false; try { //Note that adds/updates/deletes get intercepted at the //modificationcommandbatch level and normally do not get translated //into ADO.NET commands here. However, there are features in EF that //allow raw DML to be sent to the database which end up here and we need //to create the proper command and throw a useful exception. //TODO(benwu): there may be a way we can accept a non-DML text version of updates // but we'll need to send it thru detailed design review. switch (executeMethod) { case DbCommandMethod.ExecuteNonQuery: { result = dbCommand.ExecuteNonQuery(); break; } case DbCommandMethod.ExecuteScalar: { result = dbCommand.ExecuteScalar(); break; } case DbCommandMethod.ExecuteReader: { result = new RelationalDataReader( connection, dbCommand, dbCommand.ExecuteReader(), commandId, Logger); readerOpen = true; break; } default: { throw new NotSupportedException(); } } Logger.CommandExecuted( dbCommand, executeMethod, commandId, connection.ConnectionId, result, false, startTime, stopwatch.Elapsed); } catch (Exception exception) { Logger.CommandError( dbCommand, executeMethod, commandId, connection.ConnectionId, exception, false, startTime, stopwatch.Elapsed); throw; } finally { if (!readerOpen) { dbCommand.Dispose(); connection.Close(); } dbCommand.Parameters.Clear(); } return result; } protected override async Task<object> ExecuteAsync( IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary<string, object> parameterValues, CancellationToken cancellationToken = default) { GaxPreconditions.CheckNotNull(connection, nameof(connection)); var dbCommand = CreateCommand(connection, parameterValues); await connection.OpenAsync(cancellationToken).ConfigureAwait(false); var commandId = Guid.NewGuid(); var startTime = DateTimeOffset.UtcNow; var stopwatch = Stopwatch.StartNew(); Logger.CommandExecuting( dbCommand, executeMethod, commandId, connection.ConnectionId, true, startTime); object result; var readerOpen = false; try { switch (executeMethod) { case DbCommandMethod.ExecuteNonQuery: { result = await dbCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); break; } case DbCommandMethod.ExecuteScalar: { result = await dbCommand.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false); break; } case DbCommandMethod.ExecuteReader: { result = new RelationalDataReader( connection, dbCommand, await dbCommand.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false), commandId, Logger); readerOpen = true; break; } default: { throw new NotSupportedException(); } } Logger.CommandExecuted( dbCommand, executeMethod, commandId, connection.ConnectionId, result, true, startTime, stopwatch.Elapsed); } catch (Exception exception) { Logger.CommandError( dbCommand, executeMethod, commandId, connection.ConnectionId, exception, true, startTime, stopwatch.Elapsed); throw; } finally { if (!readerOpen) { dbCommand.Dispose(); connection.Close(); } dbCommand.Parameters.Clear(); } return result; } private DbCommand CreateCommand( IRelationalConnection connection, IReadOnlyDictionary<string, object> parameterValues) { if (parameterValues != null) { parameterValues = AdjustParameters(parameterValues); } var command = (SpannerCommand) connection.DbConnection.CreateCommand(); command.Logger = new SpannerLogBridge<DbLoggerCategory.Database.Command>(Logger); command.CommandText = CommandText; if (connection.CurrentTransaction != null) { command.Transaction = connection.CurrentTransaction.GetDbTransaction(); } if (connection.CommandTimeout != null) { command.CommandTimeout = (int) connection.CommandTimeout; } if (Parameters.Count > 0) { if (parameterValues == null) { throw new InvalidOperationException( RelationalStrings.MissingParameterValue( Parameters[0].InvariantName)); } foreach (var parameter in Parameters) parameter.AddDbParameter(command, parameterValues); } return command; } private static IReadOnlyDictionary<string, object> AdjustParameters( IReadOnlyDictionary<string, object> parameterValues) { if (parameterValues.Count == 0) { return parameterValues; } return parameterValues.ToDictionary( kv => kv.Key, kv => { var type = kv.Value?.GetType(); if (type != null) { type = Nullable.GetUnderlyingType(type) ?? type; if (type.IsEnum) { var underlyingType = Enum.GetUnderlyingType(type); return Convert.ChangeType(kv.Value, underlyingType); } if (type == typeof(DateTimeOffset)) { throw new NotSupportedException("DateTimeOffset is not supported."); } } return kv.Value; }); } } } } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Mapping; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Core.Data.Raster; using ArcGIS.Desktop.Framework.Dialogs; using ArcGIS.Core.Data; using System.IO; using ArcGIS.Desktop.Core; namespace MaskRaster { /// <summary> /// Viewmodel class that allows functions to mask raster pixels to be UI agnostic. /// </summary> static class MaskRasterVM { /// <summary> /// Mask raster pixels based on the rectangle given and save the output in the /// current project folder. /// </summary> /// <param name="geometry">Rectangle to use to mask raster pixels.</param> public static async void MaskRaster(Geometry geometry) { try { // Check if there is an active map view. if (MapView.Active != null) { // Get the active map view. var mapView = MapView.Active; // Get the list of selected layers. IReadOnlyList<Layer> selectedLayerList = mapView.GetSelectedLayers(); if (selectedLayerList.Count == 0) { // If no layers are selected show a message box with the appropriate message. MessageBox.Show("No Layers selected. Please select one Raster layer."); } else { // Get the most recently selected layer. Layer firstSelectedLayer = mapView.GetSelectedLayers().First(); if (firstSelectedLayer is RasterLayer) { // Working with rasters requires the MCT. await QueuedTask.Run(() => { #region Get the raster dataset from the currently selected layer // Get the raster layer from the selected layer. RasterLayer currentRasterLayer = firstSelectedLayer as RasterLayer; // Get the raster from the current selected raster layer. Raster inputRaster = currentRasterLayer.GetRaster(); // Get the basic raster dataset from the raster. BasicRasterDataset basicRasterDataset = inputRaster.GetRasterDataset(); if (!(basicRasterDataset is RasterDataset)) { // If the dataset is not a raster dataset, show a message box with the appropriate message. MessageBox.Show("No Raster Layers selected. Please select one Raster layer."); return; } // Get the input raster dataset from the basic raster dataset. RasterDataset rasterDataset = basicRasterDataset as RasterDataset; #endregion #region Save a copy of the raster dataset in the project folder and open it // Create a full raster from the input raster dataset. inputRaster = rasterDataset.CreateFullRaster(); // Setup the paths and name of the output file and folder inside the project folder. string ouputFolderName = "MaskedOuput"; string outputFolder = Path.Combine(Project.Current.HomeFolderPath, ouputFolderName); ; string outputName = "MaskedRaster.tif"; // Delete the output directory if it exists and create it. // Note: You will need write access to the project directory for this sample to work. if (Directory.Exists(outputFolder)) Directory.Delete(outputFolder, true); Directory.CreateDirectory(outputFolder); // Create a new file system connection path to open raster datasets using the output folder path. FileSystemConnectionPath outputConnectionPath = new FileSystemConnectionPath( new System.Uri(outputFolder), FileSystemDatastoreType.Raster); // Create a new file system data store for the connection path created above. FileSystemDatastore outputFileSytemDataStore = new FileSystemDatastore(outputConnectionPath); // Create a new raster storage definition. RasterStorageDef rasterStorageDef = new RasterStorageDef(); // Set the pyramid level to 0 meaning no pyramids will be calculated. This is required // because we are going to change the pixels after we save the raster dataset and if the // pyramids are calculated prior to that, the pyramids will be incorrect and will have to // be recalculated. rasterStorageDef.SetPyramidLevel(0); // Save a copy of the raster using the file system data store and the raster storage definition. inputRaster.SaveAs(outputName, outputFileSytemDataStore, "TIFF", rasterStorageDef); // Open the raster dataset you just saved. rasterDataset = OpenRasterDataset(outputFolder, outputName); // Create a full raster from it so we can modify pixels. Raster outputRaster = rasterDataset.CreateFullRaster(); #endregion #region Get the Min/Max Row/Column to mask // If the map spatial reference is different from the spatial reference of the input raster, // set the map spatial reference on the input raster. This will ensure the map points are // correctly reprojected to image points. if (mapView.Map.SpatialReference.Name != inputRaster.GetSpatialReference().Name) inputRaster.SetSpatialReference(mapView.Map.SpatialReference); // Use the MapToPixel method of the input raster to get the row and column values for the // points of the rectangle. Tuple<int, int> tlcTuple = inputRaster.MapToPixel(geometry.Extent.XMin, geometry.Extent.YMin); Tuple<int, int> lrcTuple = inputRaster.MapToPixel(geometry.Extent.XMax, geometry.Extent.YMax); int minCol = (int)tlcTuple.Item1; int minRow = (int)tlcTuple.Item2; int maxCol = (int)lrcTuple.Item1; int maxRow = (int)lrcTuple.Item2; // Ensure the min's are less than the max's. if (maxCol < minCol) { int temp = maxCol; maxCol = minCol; minCol = temp; } if (maxRow < minRow) { int temp = maxRow; maxRow = minRow; minRow = temp; } // Ensure the mins and maxs are within the raster. minCol = (minCol < 0) ? 0 : minCol; minRow = (minRow < 0) ? 0 : minRow; maxCol = (maxCol > outputRaster.GetWidth()) ? outputRaster.GetWidth() : maxCol; maxRow = (maxRow > outputRaster.GetHeight()) ? outputRaster.GetHeight() : maxRow; #endregion #region Mask pixels based on the rectangle drawn by the user // Calculate the width and height of the pixel block to create. int pbWidth = maxCol - minCol; int pbHeight = maxRow - minRow; // Check to see if the output raster can be edited. if (!outputRaster.CanEdit()) { // If not, show a message box with the appropriate message. MessageBox.Show("Cannot edit raster :("); return; } // Create a new pixel block from the output raster of the height and width calculated above. PixelBlock currentPixelBlock = outputRaster.CreatePixelBlock(pbWidth, pbHeight); // Iterate over the bands of the output raster. for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++) { // For each band, clear the pixel block. currentPixelBlock.Clear(plane); //Array noDataMask = currentPixelBlock.GetNoDataMask(plane, true); //for (int i = 0; i < noDataMask.GetLength(0); i++) // noDataMask.SetValue(Convert.ToByte(0), i); //currentPixelBlock.SetNoDataMask(plane, noDataMask); } // Write the cleared pixel block to the output raster dataset. outputRaster.Write(minCol, minRow, currentPixelBlock); // Refresh the properties of the output raster dataset. outputRaster.Refresh(); #endregion // Create a new layer from the masked raster dataset and add it to the map. LayerFactory.Instance.CreateLayer(new Uri(Path.Combine(outputFolder, outputName)), mapView.Map); // Disable the layer representing the original raster dataset. firstSelectedLayer.SetVisibility(false); }); } else { // If the selected layer is not a raster layer show a message box with the appropriate message. MessageBox.Show("No Raster layers selected. Please select one Raster layer."); } } } } catch (Exception exc) { MessageBox.Show("Exception caught in MaskRaster: " + exc.Message); } } /// <summary> /// Open a Raster Dataset given a folder and a dataset name. /// </summary> /// <param name="folder">Full path to the folder containing the raster dataset.</param> /// <param name="name">Name of the raster dataset to open.</param> /// <returns></returns> public static RasterDataset OpenRasterDataset(string folder, string name) { // Create a new raster dataset which is set to null RasterDataset rasterDatasetToOpen = null; try { // Create a new file system connection path to open raster datasets using the folder path. FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(folder), FileSystemDatastoreType.Raster); // Create a new file system data store for the connection path created above. FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath); // Open the raster dataset. rasterDatasetToOpen = dataStore.OpenDataset<RasterDataset>(name); // Check if it is not null. If it is show a message box with the appropriate message. if (rasterDatasetToOpen == null) MessageBox.Show("Failed to open raster dataset: " + name); } catch (Exception exc) { // If an exception occurs, show a message box with the appropriate message. MessageBox.Show("Exception caught in OpenRasterDataset for raster: " + name + exc.Message); } return rasterDatasetToOpen; } } }
// // Copyright 2012-2016, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using Xamarin.Utilities; using System.Linq; //-------------------------------------------------------------------- // Original defines // usings are in Authenticator.<Platform>.cs // //#if PLATFORM_IOS //using AuthenticateUIType = MonoTouch.UIKit.UIViewController; //#elif PLATFORM_ANDROID //using AuthenticateUIType = Android.Content.Intent; //using UIContext = Android.Content.Context; //#elif PLATFORM_WINPHONE //using AuthenticateUIType = System.Uri; //#else //using AuthenticateUIType = System.Object; //#endif //-------------------------------------------------------------------- #if ! AZURE_MOBILE_SERVICES namespace Xamarin.Auth #else namespace Xamarin.Auth._MobileServices #endif { /// <summary> /// A process and user interface to authenticate a user. /// </summary> #if XAMARIN_AUTH_INTERNAL internal abstract partial class Authenticator #else public abstract partial class Authenticator #endif { /// <summary> /// Gets or sets the title of any UI elements that need to be presented for this authenticator. /// </summary> /// <value><c>"Authenticate" by default.</c></value> public string Title { get; set; } /// <summary> /// Gets or sets whether to allow user cancellation. /// </summary> /// <value><c>true</c> by default.</value> public bool AllowCancel { get; set; } /// <summary> /// Gets or sets whether Xamarin.Auth should display login errors. /// </summary> /// <value><c>true</c> by default.</value> public bool ShowErrors { get; set; } /// <summary> /// Occurs when authentication has been successfully or unsuccessfully completed. /// Consult the <see cref="AuthenticatorCompletedEventArgs.IsAuthenticated"/> event argument to determine if /// authentication was successful. /// </summary> public event EventHandler<AuthenticatorCompletedEventArgs> Completed; /// <summary> /// Occurs when there an error is encountered when authenticating. /// </summary> public event EventHandler<AuthenticatorErrorEventArgs> Error; /// <summary> /// Gets whether this authenticator has completed its interaction with the user. /// </summary> /// <value><c>true</c> if authorization has been completed, <c>false</c> otherwise.</value> public bool HasCompleted { get; private set; } #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// IgnoreErrorsWhenCompleted #58 /// https://github.com/xamarin/Xamarin.Auth/pull/58 /// <summary> /// Controls the behavior of the <see cref="OnError"/> method when <see cref="HasCompleted"/> /// is <c>true</c>. /// </summary> /// <value><c>true</c> to raise the <see cref="Error" event/> , <c>false</c> to do nothing.</value> protected bool IgnoreErrorsWhenCompleted { get; set; } //--------------------------------------------------------------------------------------- #endregion /// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.Authenticator"/> class. /// </summary> public Authenticator() { Title = "Authenticate"; HasCompleted = false; AllowCancel = true; ShowErrors = true; #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// IgnoreErrorsWhenCompleted #58 /// https://github.com/xamarin/Xamarin.Auth/pull/58 IgnoreErrorsWhenCompleted = false; //--------------------------------------------------------------------------------------- #endregion #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// Added IsAuthenticated check #88 /// https://github.com/xamarin/Xamarin.Auth/pull/88 /// IsAuthenticated = () => false; //--------------------------------------------------------------------------------------- #endregion return; } #if __ANDROID__ //UIContext context; //public AuthenticateUIType GetUI (UIContext context) //{ // this.context = context; // return GetPlatformUI (context); //} //protected abstract AuthenticateUIType GetPlatformUI (UIContext context); #else /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> //public AuthenticateUIType GetUI () //{ // return GetPlatformUI (); //} /// <summary> /// Gets the UI for this authenticator. /// </summary> /// <returns> /// The UI that needs to be presented. /// </returns> //protected abstract AuthenticateUIType GetPlatformUI (); #endif /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded(Account account) { string msg = null; #if DEBUG string d = string.Join(" ; ", account.Properties.Select(x => x.Key + "=" + x.Value)); msg = String.Format("Authenticator.OnSucceded {0}", d); System.Diagnostics.Debug.WriteLine(msg); #endif if (HasCompleted) { return; } HasCompleted = true; #if !__ANDROID__ Plugin.Threading.UIThreadRunInvoker ri = new Plugin.Threading.UIThreadRunInvoker(); #else Plugin.Threading.UIThreadRunInvoker ri = new Plugin.Threading.UIThreadRunInvoker(this.context); #endif ri.BeginInvokeOnUIThread ( delegate { var ev = Completed; if (ev != null) { System.Diagnostics.Debug.WriteLine("Authenticator.OnSucceded Completed Begin"); ev(this, new AuthenticatorCompletedEventArgs(account)); System.Diagnostics.Debug.WriteLine("Authenticator.OnSucceded Completed End"); } else { msg = "No subscribers to Xamarin.Auth.Authenticator.Completed (OnCompleted) event"; System.Diagnostics.Debug.WriteLine(msg); } } ); return; } /// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='username'> /// User name of the account. /// </param> /// <param name='accountProperties'> /// Additional data, such as access tokens, that need to be stored with the account. This /// information is secured. /// </param> public void OnSucceeded(string username, IDictionary<string, string> accountProperties) { OnSucceeded(new Account(username, accountProperties)); return; } /// <summary> /// Implementations must call this function when they have cancelled the operation. /// </summary> public void OnCancelled() { if (HasCompleted) return; HasCompleted = true; #if !__ANDROID__ new Plugin.Threading.UIThreadRunInvoker().BeginInvokeOnUIThread #else new Plugin.Threading.UIThreadRunInvoker(this.context).BeginInvokeOnUIThread #endif ( delegate { var ev = Completed; if (ev != null) { ev(this, new AuthenticatorCompletedEventArgs(null)); } } ); } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='message'> /// The reason that this authentication has failed. /// </param> public void OnError(string message) { #if !__ANDROID__ new Plugin.Threading.UIThreadRunInvoker().BeginInvokeOnUIThread #else new Plugin.Threading.UIThreadRunInvoker(this.context).BeginInvokeOnUIThread #endif ( delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (message)); } } ); RaiseErrorEvent(new AuthenticatorErrorEventArgs(message)); return; } /// <summary> /// Implementations must call this function when they have failed to authenticate. /// </summary> /// <param name='exception'> /// The reason that this authentication has failed. /// </param> public void OnError(Exception exception) { #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// IgnoreErrorsWhenCompleted #58 /// https://github.com/xamarin/Xamarin.Auth/pull/58 /* BeginInvokeOnUIThread (delegate { var ev = Error; if (ev != null) { ev (this, new AuthenticatorErrorEventArgs (exception)); } }); */ RaiseErrorEvent(new AuthenticatorErrorEventArgs(exception)); //--------------------------------------------------------------------------------------- #endregion return; } #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// IgnoreErrorsWhenCompleted #58 /// https://github.com/xamarin/Xamarin.Auth/pull/58 void RaiseErrorEvent(AuthenticatorErrorEventArgs args) { if (!(HasCompleted && IgnoreErrorsWhenCompleted)) { #if !__ANDROID__ new Plugin.Threading.UIThreadRunInvoker().BeginInvokeOnUIThread #else new Plugin.Threading.UIThreadRunInvoker(this.context).BeginInvokeOnUIThread #endif ( delegate { var ev = Error; if (ev != null) { ev(this, args); } } ); } return; } //--------------------------------------------------------------------------------------- #endregion #region //--------------------------------------------------------------------------------------- /// Pull Request - manually added/fixed /// Added IsAuthenticated check #88 /// https://github.com/xamarin/Xamarin.Auth/pull/88 /// /// <summary> /// Used by the ui to determine if it should stop authenticating /// </summary> public Func<bool> IsAuthenticated { get; set; } /// <summary> /// Used by Android to fill in the result on the activity /// </summary> public Func<Account, AccountResult> GetAccountResult { get; set; } //--------------------------------------------------------------------------------------- #endregion protected int classlevel_depth = 0; public override string ToString() { /* string msg = string.Format ( "[Authenticator: Title={0}, AllowCancel={1}, ShowErrors={2}, HasCompleted={3}," + "IsAuthenticated={4}, GetAccountResult={5}]", Title, AllowCancel, ShowErrors, HasCompleted, IsAuthenticated, GetAccountResult ); */ System.Text.StringBuilder sb = new System.Text.StringBuilder(base.ToString()); sb.AppendLine().AppendLine(this.GetType().ToString()); classlevel_depth++; string prefix = new string('\t', classlevel_depth); sb.Append(prefix).AppendLine($"Title = {Title}"); sb.Append(prefix).AppendLine($"ShowErrors = {ShowErrors}"); sb.Append(prefix).AppendLine($"AllowCancel = {AllowCancel}"); sb.Append(prefix).AppendLine($"HasCompleted = {HasCompleted}"); sb.Append(prefix).AppendLine($"IsAuthenticated = {IsAuthenticated}"); sb.Append(prefix).AppendLine($"GetAccountResult = {GetAccountResult}"); return sb.ToString(); } } }
using System; using System.Threading; namespace Amib.Threading.Internal { #region WorkItemsQueue class /// <summary> /// WorkItemsQueue class. /// </summary> public class WorkItemsQueue : IDisposable { #region Member variables [ThreadStatic] private static WaiterEntry _waiterEntry; /// <summary> /// Waiters queue (implemented as stack). /// </summary> private readonly WaiterEntry _headWaiterEntry = new WaiterEntry(); /// <summary> /// Work items queue /// </summary> private readonly PriorityQueue _workItems = new PriorityQueue(); /// <summary> /// A flag that indicates if the WorkItemsQueue has been disposed. /// </summary> private bool _isDisposed = false; /// <summary> /// Indicate that work items are allowed to be queued /// </summary> private bool _isWorkItemsQueueActive = true; /// <summary> /// Waiters count /// </summary> private int _waitersCount = 0; #if (WINDOWS_PHONE) private static readonly Dictionary<int, WaiterEntry> _waiterEntries = new Dictionary<int, WaiterEntry>(); #elif (_WINDOWS_CE) private static LocalDataStoreSlot _waiterEntrySlot = Thread.AllocateDataSlot(); #else #endif /// <summary> /// Each thread in the thread pool keeps its own waiter entry. /// </summary> private static WaiterEntry CurrentWaiterEntry { #if (WINDOWS_PHONE) get { lock (_waiterEntries) { WaiterEntry waiterEntry; if (_waiterEntries.TryGetValue(Thread.CurrentThread.ManagedThreadId, out waiterEntry)) { return waiterEntry; } } return null; } set { lock (_waiterEntries) { _waiterEntries[Thread.CurrentThread.ManagedThreadId] = value; } } #elif (_WINDOWS_CE) get { return Thread.GetData(_waiterEntrySlot) as WaiterEntry; } set { Thread.SetData(_waiterEntrySlot, value); } #else get { return _waiterEntry; } set { _waiterEntry = value; } #endif } #endregion Member variables #region Public properties /// <summary> /// Returns the current number of work items in the queue /// </summary> public int Count { get { return _workItems.Count; } } /// <summary> /// Returns the current number of waiters /// </summary> public int WaitersCount { get { return _waitersCount; } } #endregion Public properties #region Public methods /// <summary> /// Waits for a work item or exits on timeout or cancel /// </summary> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <param name="cancelEvent">Cancel wait handle</param> /// <returns>Returns true if the resource was granted</returns> public WorkItem DequeueWorkItem( int millisecondsTimeout, WaitHandle cancelEvent) { // This method cause the caller to wait for a work item. // If there is at least one waiting work item then the // method returns immidiately with it. // // If there are no waiting work items then the caller // is queued between other waiters for a work item to arrive. // // If a work item didn't come within millisecondsTimeout or // the user canceled the wait by signaling the cancelEvent // then the method returns null to indicate that the caller // didn't get a work item. WaiterEntry waiterEntry; WorkItem workItem = null; lock (this) { ValidateNotDisposed(); // If there are waiting work items then take one and return. if (_workItems.Count > 0) { workItem = _workItems.Dequeue() as WorkItem; return workItem; } // No waiting work items ... // Get the waiter entry for the waiters queue waiterEntry = GetThreadWaiterEntry(); // Put the waiter with the other waiters PushWaiter(waiterEntry); } // Prepare array of wait handle for the WaitHandle.WaitAny() WaitHandle[] waitHandles = new WaitHandle[] { waiterEntry.WaitHandle, cancelEvent }; // Wait for an available resource, cancel event, or timeout. // During the wait we are supposes to exit the synchronization // domain. (Placing true as the third argument of the WaitAny()) // It just doesn't work, I don't know why, so I have two lock(this) // statments instead of one. int index = STPEventWaitHandle.WaitAny( waitHandles, millisecondsTimeout, true); lock (this) { // success is true if it got a work item. bool success = (0 == index); // The timeout variable is used only for readability. // (We treat cancel as timeout) bool timeout = !success; // On timeout update the waiterEntry that it is timed out if (timeout) { // The Timeout() fails if the waiter has already been signaled timeout = waiterEntry.Timeout(); // On timeout remove the waiter from the queue. // Note that the complexity is O(1). if (timeout) { RemoveWaiter(waiterEntry, false); } // Again readability success = !timeout; } // On success return the work item if (success) { workItem = waiterEntry.WorkItem; if (null == workItem) { workItem = _workItems.Dequeue() as WorkItem; } } } // On failure return null. return workItem; } /// <summary> /// Enqueue a work item to the queue. /// </summary> public bool EnqueueWorkItem(WorkItem workItem) { // A work item cannot be null, since null is used in the // WaitForWorkItem() method to indicate timeout or cancel if (null == workItem) { throw new ArgumentNullException("workItem", "workItem cannot be null"); } bool enqueue = true; // First check if there is a waiter waiting for work item. During // the check, timed out waiters are ignored. If there is no // waiter then the work item is queued. lock (this) { ValidateNotDisposed(); if (!_isWorkItemsQueueActive) { return false; } while (_waitersCount > 0) { // Dequeue a waiter. WaiterEntry waiterEntry = PopWaiter(); // Signal the waiter. On success break the loop if (waiterEntry.Signal(workItem)) { enqueue = false; break; } } if (enqueue) { // Enqueue the work item _workItems.Enqueue(workItem); } } return true; } public object[] GetStates() { lock (this) { object[] states = new object[_workItems.Count]; int i = 0; foreach (WorkItem workItem in _workItems) { states[i] = workItem.GetWorkItemResult().State; ++i; } return states; } } /// <summary> /// Cleanup the work items queue, hence no more work /// items are allowed to be queue /// </summary> private void Cleanup() { lock (this) { // Deactivate only once if (!_isWorkItemsQueueActive) { return; } // Don't queue more work items _isWorkItemsQueueActive = false; foreach (WorkItem workItem in _workItems) { workItem.DisposeOfState(); } // Clear the work items that are already queued _workItems.Clear(); // Note: // I don't iterate over the queue and dispose of work items's states, // since if a work item has a state object that is still in use in the // application then I must not dispose it. // Tell the waiters that they were timed out. // It won't signal them to exit, but to ignore their // next work item. while (_waitersCount > 0) { WaiterEntry waiterEntry = PopWaiter(); waiterEntry.Timeout(); } } } #endregion Public methods #region Private methods /// <summary> /// Returns the WaiterEntry of the current thread /// </summary> /// <returns></returns> /// In order to avoid creation and destuction of WaiterEntry /// objects each thread has its own WaiterEntry object. private static WaiterEntry GetThreadWaiterEntry() { if (null == CurrentWaiterEntry) { CurrentWaiterEntry = new WaiterEntry(); } CurrentWaiterEntry.Reset(); return CurrentWaiterEntry; } #region Waiters stack methods /// <summary> /// Push a new waiter into the waiter's stack /// </summary> /// <param name="newWaiterEntry">A waiter to put in the stack</param> public void PushWaiter(WaiterEntry newWaiterEntry) { // Remove the waiter if it is already in the stack and // update waiter's count as needed RemoveWaiter(newWaiterEntry, false); // If the stack is empty then newWaiterEntry is the new head of the stack if (null == _headWaiterEntry._nextWaiterEntry) { _headWaiterEntry._nextWaiterEntry = newWaiterEntry; newWaiterEntry._prevWaiterEntry = _headWaiterEntry; } // If the stack is not empty then put newWaiterEntry as the new head // of the stack. else { // Save the old first waiter entry WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry; // Update the links _headWaiterEntry._nextWaiterEntry = newWaiterEntry; newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry; newWaiterEntry._prevWaiterEntry = _headWaiterEntry; oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry; } // Increment the number of waiters ++_waitersCount; } /// <summary> /// Pop a waiter from the waiter's stack /// </summary> /// <returns>Returns the first waiter in the stack</returns> private WaiterEntry PopWaiter() { // Store the current stack head WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry; // Store the new stack head WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry; // Update the old stack head list links and decrement the number // waiters. RemoveWaiter(oldFirstWaiterEntry, true); // Update the new stack head _headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry; if (null != newHeadWaiterEntry) { newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry; } // Return the old stack head return oldFirstWaiterEntry; } /// <summary> /// Remove a waiter from the stack /// </summary> /// <param name="waiterEntry">A waiter entry to remove</param> /// <param name="popDecrement">If true the waiter count is always decremented</param> private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement) { // Store the prev entry in the list WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry; // Store the next entry in the list WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry; // A flag to indicate if we need to decrement the waiters count. // If we got here from PopWaiter then we must decrement. // If we got here from PushWaiter then we decrement only if // the waiter was already in the stack. bool decrementCounter = popDecrement; // Null the waiter's entry links waiterEntry._prevWaiterEntry = null; waiterEntry._nextWaiterEntry = null; // If the waiter entry had a prev link then update it. // It also means that the waiter is already in the list and we // need to decrement the waiters count. if (null != prevWaiterEntry) { prevWaiterEntry._nextWaiterEntry = nextWaiterEntry; decrementCounter = true; } // If the waiter entry had a next link then update it. // It also means that the waiter is already in the list and we // need to decrement the waiters count. if (null != nextWaiterEntry) { nextWaiterEntry._prevWaiterEntry = prevWaiterEntry; decrementCounter = true; } // Decrement the waiters count if needed if (decrementCounter) { --_waitersCount; } } #endregion Waiters stack methods #endregion Private methods #region WaiterEntry class // A waiter entry in the _waiters queue. public sealed class WaiterEntry : IDisposable { #region Member variables // Linked list members internal WaiterEntry _nextWaiterEntry = null; internal WaiterEntry _prevWaiterEntry = null; private bool _isDisposed = false; /// <summary> /// Flag to know if the waiter was signaled and got a work item. /// </summary> private bool _isSignaled = false; /// <summary> /// Flag to know if this waiter already quited from the queue /// because of a timeout. /// </summary> private bool _isTimedout = false; /// <summary> /// Event to signal the waiter that it got the work item. /// </summary> //private AutoResetEvent _waitHandle = new AutoResetEvent(false); private AutoResetEvent _waitHandle = EventWaitHandleFactory.CreateAutoResetEvent(); /// <summary> /// A work item that passed directly to the waiter withou going /// through the queue /// </summary> private WorkItem _workItem = null; #endregion Member variables #region Construction public WaiterEntry() { Reset(); } #endregion Construction #region Public methods public WaitHandle WaitHandle { get { return _waitHandle; } } public WorkItem WorkItem { get { return _workItem; } } /// <summary> /// Free resources /// </summary> public void Close() { if (null != _waitHandle) { _waitHandle.Close(); _waitHandle = null; } } /// <summary> /// Reset the wait entry so it can be used again /// </summary> public void Reset() { _workItem = null; _isTimedout = false; _isSignaled = false; _waitHandle.Reset(); } /// <summary> /// Signal the waiter that it got a work item. /// </summary> /// <returns>Return true on success</returns> /// The method fails if Timeout() preceded its call public bool Signal(WorkItem workItem) { lock (this) { if (!_isTimedout) { _workItem = workItem; _isSignaled = true; _waitHandle.Set(); return true; } } return false; } /// <summary> /// Mark the wait entry that it has been timed out /// </summary> /// <returns>Return true on success</returns> /// The method fails if Signal() preceded its call public bool Timeout() { lock (this) { // Time out can happen only if the waiter wasn't marked as // signaled if (!_isSignaled) { // We don't remove the waiter from the queue, the DequeueWorkItem // method skips _waiters that were timed out. _isTimedout = true; return true; } } return false; } #endregion Public methods #region IDisposable Members public void Dispose() { lock (this) { if (!_isDisposed) { Close(); } _isDisposed = true; } } #endregion IDisposable Members } #endregion WaiterEntry class #region IDisposable Members public void Dispose() { if (!_isDisposed) { Cleanup(); } _isDisposed = true; } private void ValidateNotDisposed() { if (_isDisposed) { throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown"); } } #endregion IDisposable Members } #endregion WorkItemsQueue class }
// based on http://wiki.unity3d.com/index.php?title=ExportOBJ (thanks!) using UnityEngine; using System.IO; using System.Text; namespace UTJ.NormalPainter { public class ObjExporter { public class Settings { public bool includeChildren = true; public bool makeSubmeshes = true; public bool applyTransform = true; public bool flipHandedness = true; public bool flipFaces = false; public bool normals = true; public bool uv = true; } public static bool Export(GameObject go, string path, Settings settings) { if (path == null || path.Length == 0 || go == null) return false; var inst = new ObjExporter(); inst.DoExport(go, path, settings); return true; } Settings m_settings; int m_startIndex; void DoExport(GameObject go, string path, Settings settings) { m_settings = settings; StringBuilder meshString = new StringBuilder(); meshString.Append("#" + go.name + ".obj" + "\n#" + System.DateTime.Now.ToLongDateString() + "\n#" + System.DateTime.Now.ToLongTimeString() + "\n#-------" + "\n\n"); Transform t = go.transform; Vector3 originalPosition = t.position; t.position = Vector3.zero; if (!m_settings.makeSubmeshes) meshString.Append("g ").Append(t.name).Append("\n"); meshString.Append(ProcessTransform(t, m_settings.makeSubmeshes)); WriteToFile(meshString.ToString(), path); t.position = originalPosition; Debug.Log("Exported Mesh: " + path); } string ProcessTransform(Transform t, bool makeSubmeshes) { StringBuilder meshString = new StringBuilder(); meshString.Append("#" + t.name + "\n#-------" + "\n"); if (makeSubmeshes) meshString.Append("g ").Append(t.name).Append("\n"); Mesh mesh = null; Material[] materials = null; { var mf = t.GetComponent<MeshFilter>(); if (mf != null) mesh = mf.sharedMesh; else { var smi = t.GetComponent<SkinnedMeshRenderer>(); if (smi != null) mesh = smi.sharedMesh; } var renderer = t.GetComponent<Renderer>(); if (renderer != null) materials = renderer.sharedMaterials; } if (mesh != null) meshString.Append(MeshToString(mesh, materials, t)); if (m_settings.includeChildren) { for (int i = 0; i < t.childCount; i++) meshString.Append(ProcessTransform(t.GetChild(i), makeSubmeshes)); } return meshString.ToString(); } string MeshToString(Mesh mesh, Material[] mats, Transform t) { if (!mesh) return "####Error####"; Vector3[] points = mesh.vertices; Vector3[] normals = m_settings.normals ? mesh.normals : null; Vector2[] uv = m_settings.uv ? mesh.uv : null; if (m_settings.applyTransform && t != null) { if (points != null) { for (int i = 0; i < points.Length; ++i) points[i] = t.TransformPoint(points[i]); } if (normals != null) { for (int i = 0; i < normals.Length; ++i) normals[i] = t.TransformVector(normals[i]); } } if (m_settings.flipHandedness) { if (points != null) { for (int i = 0; i < points.Length; ++i) points[i].x *= -1.0f; } if (normals != null) { for (int i = 0; i < normals.Length; ++i) normals[i].x *= -1.0f; } } StringBuilder sb = new StringBuilder(); if (points != null) { foreach (Vector3 v in points) sb.Append(string.Format("v {0} {1} {2}\n", v.x, v.y, v.z)); sb.Append("\n"); } if (normals != null) { foreach (Vector3 n in normals) sb.Append(string.Format("vn {0} {1} {2}\n", n.x, n.y, n.z)); sb.Append("\n"); } if (uv != null) { foreach (Vector3 u in uv) sb.Append(string.Format("vt {0} {1}\n", u.x, u.y)); } int i1 = m_settings.flipFaces ? 2 : 1; int i2 = m_settings.flipFaces ? 1 : 2; string format = ""; { int numComponents = 0; if (points != null && points.Length > 0) ++numComponents; if (normals != null && normals.Length > 0) ++numComponents; if (uv != null && uv.Length > 0) ++numComponents; switch (numComponents) { case 1: format = "f {0} {1} {2}\n"; break; case 2: format = "f {0}/{0} {1}/{1} {2}/{2}\n"; break; case 3: format = "f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n"; break; } } for (int sm = 0; sm < mesh.subMeshCount; sm++) { sb.Append("\n"); if (mats != null && sm < mats.Length) { sb.Append("usemtl ").Append(mats[sm].name).Append("\n"); sb.Append("usemap ").Append(mats[sm].name).Append("\n"); } int[] triangles = mesh.GetTriangles(sm); for (int i = 0; i < triangles.Length; i += 3) { sb.Append(string.Format(format, triangles[i] + 1 + m_startIndex, triangles[i + i1] + 1 + m_startIndex, triangles[i + i2] + 1 + m_startIndex)); } } m_startIndex += points.Length; return sb.ToString(); } void WriteToFile(string s, string filename) { using (StreamWriter sw = new StreamWriter(filename)) sw.Write(s); } } }
using System; using System.Net.Sockets; using System.Threading; using Orleans.Runtime; namespace Orleans.Messaging { /// <summary> /// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages /// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway. /// /// Note that both sends and receives are synchronous. /// </summary> internal class GatewayConnection : OutgoingMessageSender { internal bool IsLive { get; private set; } internal ProxiedMessageCenter MsgCenter { get; private set; } private Uri addr; internal Uri Address { get { return addr; } private set { addr = value; Silo = addr.ToSiloAddress(); } } internal SiloAddress Silo { get; private set; } private readonly GatewayClientReceiver receiver; internal Socket Socket { get; private set; } // Shared by the receiver private DateTime lastConnect; internal GatewayConnection(Uri address, ProxiedMessageCenter mc) : base("GatewayClientSender_" + address, mc.MessagingConfiguration) { Address = address; MsgCenter = mc; receiver = new GatewayClientReceiver(this); lastConnect = new DateTime(); IsLive = true; } public override void Start() { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address); lock (Lockable) { if (State == ThreadState.Running) { return; } Connect(); if (!IsLive) return; // If the Connect succeeded receiver.Start(); base.Start(); } } public override void Stop() { IsLive = false; receiver.Stop(); base.Stop(); RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(Silo); Socket s; lock (Lockable) { s = Socket; Socket = null; } if (s == null) return; SocketManager.CloseSocket(s); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); } // passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect. public void MarkAsDisconnected(Socket socket2Disconnect) { Socket s = null; lock (Lockable) { if (socket2Disconnect == null || Socket == null) return; if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock. { s = Socket; Socket = null; Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, String.Format("Marking gateway at address {0} as Disconnected", Address)); if ( MsgCenter != null && MsgCenter.GatewayManager != null) // We need a refresh... MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot(); } } if (s != null) { SocketManager.CloseSocket(s); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); } if (socket2Disconnect == s) return; SocketManager.CloseSocket(socket2Disconnect); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); } public void MarkAsDead() { Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, String.Format("Marking gateway at address {0} as Dead in my client local gateway list.", Address)); MsgCenter.GatewayManager.MarkAsDead(Address); Stop(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Connect() { if (!MsgCenter.Running) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address); return; } // Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time. // There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one // will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to... // Hopefully the initial "if" statement will prevent that. lock (Lockable) { if (!IsLive) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address); return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed. } for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++) { try { if (Socket != null) { if (Socket.Connected) return; MarkAsDisconnected(Socket); // clean up the socket before reconnecting. } if (lastConnect != new DateTime()) { var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect; if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY) { var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt; if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i); Thread.Sleep(wait); } } lastConnect = DateTime.UtcNow; Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); Socket.Connect(Silo.Endpoint); NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket(); SocketManager.WriteConnectionPreemble(Socket, MsgCenter.ClientId); // Identifies this client Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i); return; } catch (Exception) { Log.Warn(ErrorCode.ProxyClient_CannotConnect, "Unable to connect to gateway at address {0} on trial {1}.", Address, i); MarkAsDisconnected(Socket); } } // Failed too many times -- give up MarkAsDead(); } } protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; } protected override bool PrepareMessageForSend(Message msg) { // Check to make sure we're not stopped if (Cts.IsCancellationRequested) { // Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead MsgCenter.SendMessage(msg); return false; } if (msg.TargetSilo != null) return true; msg.TargetSilo = Silo; if (msg.TargetGrain.IsSystemTarget) msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo); return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error) { error = null; targetSilo = Silo; socketCapture = null; try { if (Socket == null || !Socket.Connected) { Connect(); } socketCapture = Socket; if (socketCapture == null || !socketCapture.Connected) { // Failed to connect -- Connect will have already declared this connection dead, so recycle the message return false; } } catch (Exception) { //No need to log any errors, as we alraedy do it inside Connect(). return false; } return true; } protected override void OnGetSendingSocketFailure(Message msg, string error) { msg.TargetSilo = null; // clear previous destination! MsgCenter.SendMessage(msg); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override void OnMessageSerializationFailure(Message msg, Exception exc) { // we only get here if we failed to serialise the msg (or any other catastrophic failure). // Request msg fails to serialise on the sending silo, so we just enqueue a rejection msg. Log.Warn(ErrorCode.ProxyClient_SerializationError, String.Format("Unexpected error serializing message to gateway {0}.", Address), exc); FailMessage(msg, String.Format("Unexpected error serializing message to gateway {0}. {1}", Address, exc)); if (msg.Direction == Message.Directions.Request || msg.Direction == Message.Directions.OneWay) { return; } // Response msg fails to serialize on the responding silo, so we try to send an error response back. // if we failed sending an original response, turn the response body into an error and reply with it. msg.Result = Message.ResponseTypes.Error; msg.BodyObject = Response.ExceptionResponse(exc); try { MsgCenter.SendMessage(msg); } catch (Exception ex) { // If we still can't serialize, drop the message on the floor Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Unable to serialize message - DROPPING " + msg, ex); msg.ReleaseBodyAndHeaderBuffers(); } } protected override void OnSendFailure(Socket socket, SiloAddress targetSilo) { MarkAsDisconnected(socket); } protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr) { msg.ReleaseBodyAndHeaderBuffers(); if (sendError) { // We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it FailMessage(msg, sendErrorStr); } } protected override void FailMessage(Message msg, string reason) { msg.ReleaseBodyAndHeaderBuffers(); MessagingStatisticsGroup.OnFailedSentMessage(msg); if (MsgCenter.Running && msg.Direction == Message.Directions.Request) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, reason); MsgCenter.QueueIncomingMessage(error); } else { Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; using Elasticsearch.Net; using Nest.Resolvers; ///This file contains all the typed request parameters that are generated of the client spec. ///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec ///Generated of commit namespace Nest { public static class RequestPameterExtensions { ///<summary>A comma-separated list of fields to return in the output</summary> internal static CatFielddataRequestParameters _Fields<T>( this CatFielddataRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static ExplainRequestParameters _Fields<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static ExplainRequestParameters _SourceExclude<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static ExplainRequestParameters _SourceInclude<T>( this ExplainRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>A comma-separated list of fields for to get field statistics for (min value, max value, and more)</summary> internal static FieldStatsRequestParameters _Fields<T>( this FieldStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static GetRequestParameters _Fields<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static GetRequestParameters _SourceExclude<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static GetRequestParameters _SourceInclude<T>( this GetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static SourceRequestParameters _SourceExclude<T>( this SourceRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static SourceRequestParameters _SourceInclude<T>( this SourceRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>Use the analyzer configured for this field (instead of passing the analyzer name)</summary> internal static AnalyzeRequestParameters _Field<T>( this AnalyzeRequestParameters qs, Expression<Func<T, object>> field) where T : class { var p = (PropertyPathMarker)field; var _field = p; qs.AddQueryString("field", _field); return qs; } ///<summary>A comma-separated list of fields to clear when using the `field_data` parameter (default: all)</summary> internal static ClearCacheRequestParameters _Fields<T>( this ClearCacheRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _CompletionFields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> completion_fields) where T : class { var _completion_fields = completion_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("completion_fields", _completion_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _FielddataFields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fielddata_fields) where T : class { var _fielddata_fields = fielddata_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fielddata_fields", _fielddata_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)</summary> internal static IndicesStatsRequestParameters _Fields<T>( this IndicesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields to return in the response</summary> internal static MultiGetRequestParameters _Fields<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A list of fields to exclude from the returned _source field</summary> internal static MultiGetRequestParameters _SourceExclude<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_exclude) where T : class { var _source_exclude = source_exclude.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_exclude", _source_exclude); return qs; } ///<summary>A list of fields to extract and return from the _source field</summary> internal static MultiGetRequestParameters _SourceInclude<T>( this MultiGetRequestParameters qs, IEnumerable<Expression<Func<T, object>>> source_include) where T : class { var _source_include = source_include.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("_source_include", _source_include); return qs; } ///<summary>Specific fields to perform the query against</summary> internal static MoreLikeThisRequestParameters _MltFields<T>( this MoreLikeThisRequestParameters qs, IEnumerable<Expression<Func<T, object>>> mlt_fields) where T : class { var _mlt_fields = mlt_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("mlt_fields", _mlt_fields); return qs; } ///<summary>A comma-separated list of fields to return. Applies to all returned documents unless otherwise specified in body &quot;params&quot; or &quot;docs&quot;.</summary> internal static MultiTermVectorsRequestParameters _Fields<T>( this MultiTermVectorsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `suggest` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _CompletionFields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> completion_fields) where T : class { var _completion_fields = completion_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("completion_fields", _completion_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _FielddataFields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fielddata_fields) where T : class { var _fielddata_fields = fielddata_fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fielddata_fields", _fielddata_fields); return qs; } ///<summary>A comma-separated list of fields for `fielddata` and `completion` index metric (supports wildcards)</summary> internal static NodesStatsRequestParameters _Fields<T>( this NodesStatsRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } ///<summary>Specify which field to use for suggestions</summary> internal static SearchRequestParameters _SuggestField<T>( this SearchRequestParameters qs, Expression<Func<T, object>> suggest_field) where T : class { var p = (PropertyPathMarker)suggest_field; var _suggest_field = p; qs.AddQueryString("suggest_field", _suggest_field); return qs; } ///<summary>A comma-separated list of fields to return.</summary> internal static TermvectorRequestParameters _Fields<T>( this TermvectorRequestParameters qs, IEnumerable<Expression<Func<T, object>>> fields) where T : class { var _fields = fields.Select(e=>(PropertyPathMarker)e); qs.AddQueryString("fields", _fields); return qs; } } }
// Amplify Motion - Full-scene Motion Blur for Unity Pro // Copyright (c) Amplify Creations, Lda <info@amplify.pt> #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 #define UNITY_4 #endif #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6 || UNITY_5_7 || UNITY_5_8 || UNITY_5_9 #define UNITY_5 #endif using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; using UnityEngine; #if !UNITY_4 using UnityEngine.Rendering; #endif namespace AmplifyMotion { internal class SkinnedState : AmplifyMotion.MotionState { private SkinnedMeshRenderer m_renderer; private int m_boneCount; private Transform[] m_boneTransforms; private Matrix3x4[] m_bones; private int m_weightCount; private int[] m_boneIndices; private float[] m_boneWeights; private int m_vertexCount; private Vector4[] m_baseVertices; private Vector3[] m_prevVertices; private Vector3[] m_currVertices; #if !UNITY_4 private int m_gpuBoneTexWidth; private int m_gpuBoneTexHeight; private int m_gpuVertexTexWidth; private int m_gpuVertexTexHeight; private Material m_gpuSkinDeformMat; private Color[] m_gpuBoneData; private Texture2D m_gpuBones; private Texture2D m_gpuBoneIndices; private Texture2D[] m_gpuBaseVertices; private RenderTexture m_gpuPrevVertices; private RenderTexture m_gpuCurrVertices; #endif private Mesh m_clonedMesh; private Matrix3x4 m_worldToLocalMatrix; private Matrix3x4 m_prevLocalToWorld; private Matrix3x4 m_currLocalToWorld; private MaterialDesc[] m_sharedMaterials; private ManualResetEvent m_asyncUpdateSignal = null; private bool m_asyncUpdateTriggered = false; private bool m_starting; private bool m_wasVisible; private bool m_useFallback; private bool m_useGPU = false; private static HashSet<AmplifyMotionObjectBase> m_uniqueWarnings = new HashSet<AmplifyMotionObjectBase>(); public SkinnedState( AmplifyMotionCamera owner, AmplifyMotionObjectBase obj ) : base( owner, obj ) { m_renderer = m_obj.GetComponent<SkinnedMeshRenderer>(); } void IssueWarning( string message ) { if ( !m_uniqueWarnings.Contains( m_obj ) ) { Debug.LogWarning( message ); m_uniqueWarnings.Add( m_obj ); } } void IssueError( string message ) { IssueWarning( message ); m_error = true; } internal override void Initialize() { if ( !m_renderer.sharedMesh.isReadable ) { IssueError( "[AmplifyMotion] Read/Write Import Setting disabled in object " + m_obj.name + ". Skipping." ); return; } // find out if we're forced to use the fallback path Transform[] bones = m_renderer.bones; m_useFallback = ( bones == null || bones.Length == 0 ); if ( !m_useFallback ) m_useGPU = m_owner.Instance.CanUseGPU; // use GPU, if allowed base.Initialize(); m_vertexCount = m_renderer.sharedMesh.vertexCount; m_prevVertices = new Vector3[ m_vertexCount ]; m_currVertices = new Vector3[ m_vertexCount ]; m_clonedMesh = new Mesh(); if ( !m_useFallback ) { if ( m_renderer.quality == SkinQuality.Auto ) m_weightCount = ( int ) QualitySettings.blendWeights; else m_weightCount = ( int ) m_renderer.quality; m_boneTransforms = m_renderer.bones; m_boneCount = m_renderer.bones.Length; m_bones = new Matrix3x4[ m_boneCount ]; Vector4[] baseVertices = new Vector4[ m_vertexCount * m_weightCount ]; int[] boneIndices = new int[ m_vertexCount * m_weightCount ]; float[] boneWeights = ( m_weightCount > 1 ) ? new float[ m_vertexCount * m_weightCount ] : null; if ( m_weightCount == 1 ) InitializeBone1( baseVertices, boneIndices ); else if ( m_weightCount == 2 ) InitializeBone2( baseVertices, boneIndices, boneWeights ); else InitializeBone4( baseVertices, boneIndices, boneWeights ); m_baseVertices = baseVertices; m_boneIndices = boneIndices; m_boneWeights = boneWeights; Mesh skinnedMesh = m_renderer.sharedMesh; m_clonedMesh.vertices = skinnedMesh.vertices; m_clonedMesh.normals = skinnedMesh.vertices; m_clonedMesh.uv = skinnedMesh.uv; m_clonedMesh.subMeshCount = skinnedMesh.subMeshCount; for ( int i = 0; i < skinnedMesh.subMeshCount; i++ ) m_clonedMesh.SetTriangles( skinnedMesh.GetTriangles( i ), i ); #if !UNITY_4 if ( m_useGPU ) { if ( !InitializeGPUSkinDeform() ) { // fallback Debug.LogWarning( "[AmplifyMotion] Failed initializing GPU skin deform for object " + m_obj.name + ". Falling back to CPU path." ); m_useGPU = false; } else { // release unnecessary data m_boneIndices = null; m_boneWeights = null; m_baseVertices = null; m_prevVertices = null; m_currVertices = null; } } #endif if ( !m_useGPU ) { m_asyncUpdateSignal = new ManualResetEvent( false ); m_asyncUpdateTriggered = false; } } m_sharedMaterials = ProcessSharedMaterials( m_renderer.sharedMaterials ); m_wasVisible = false; } internal override void Shutdown() { if ( !m_useFallback && !m_useGPU ) WaitForAsyncUpdate(); #if !UNITY_4 if ( m_useGPU ) ShutdownGPUSkinDeform(); #endif if ( m_clonedMesh != null ) { Mesh.Destroy( m_clonedMesh ); m_clonedMesh = null; } m_boneTransforms = null; m_bones = null; m_boneIndices = null; m_boneWeights = null; m_baseVertices = null; m_prevVertices = null; m_currVertices = null; m_sharedMaterials = null; } #if !UNITY_4 private bool InitializeGPUSkinDeform() { bool succeeded = true; try { m_gpuBoneTexWidth = m_boneCount; m_gpuBoneTexHeight = 3; m_gpuVertexTexWidth = Mathf.CeilToInt( Mathf.Sqrt( m_vertexCount ) ); m_gpuVertexTexHeight = Mathf.CeilToInt( m_vertexCount / ( float ) m_gpuVertexTexWidth ); // gpu skin deform material m_gpuSkinDeformMat = new Material( Shader.Find( "Hidden/Amplify Motion/GPUSkinDeform" ) ) { hideFlags = HideFlags.DontSave }; // bone matrix texture m_gpuBones = new Texture2D( m_gpuBoneTexWidth, m_gpuBoneTexHeight, TextureFormat.RGBAFloat, false, true ); m_gpuBones.hideFlags = HideFlags.DontSave; m_gpuBones.name = "AM-" + m_obj.name + "-Bones"; m_gpuBones.filterMode = FilterMode.Point; m_gpuBoneData = new Color[ m_gpuBoneTexWidth * m_gpuBoneTexHeight ]; UpdateBonesGPU(); // vertex bone index/weight textures TextureFormat boneIDWFormat = TextureFormat.RHalf; boneIDWFormat = ( m_weightCount == 2 ) ? TextureFormat.RGHalf : boneIDWFormat; boneIDWFormat = ( m_weightCount == 4 ) ? TextureFormat.RGBAHalf : boneIDWFormat; m_gpuBoneIndices = new Texture2D( m_gpuVertexTexWidth, m_gpuVertexTexHeight, boneIDWFormat, false, true ); m_gpuBoneIndices.hideFlags = HideFlags.DontSave; m_gpuBoneIndices.name = "AM-" + m_obj.name + "-Bones"; m_gpuBoneIndices.filterMode = FilterMode.Point; m_gpuBoneIndices.wrapMode = TextureWrapMode.Clamp; BoneWeight[] meshBoneWeights = m_renderer.sharedMesh.boneWeights; Color[] boneIndices = new Color[ m_gpuVertexTexWidth * m_gpuVertexTexHeight ]; for ( int v = 0; v < m_vertexCount; v++ ) { int x = v % m_gpuVertexTexWidth; int y = v / m_gpuVertexTexWidth; int offset = y * m_gpuVertexTexWidth + x; BoneWeight boneWeight = meshBoneWeights[ v ]; boneIndices[ offset ] = new Vector4( boneWeight.boneIndex0, boneWeight.boneIndex1, boneWeight.boneIndex2, boneWeight.boneIndex3 ); } m_gpuBoneIndices.SetPixels( boneIndices ); m_gpuBoneIndices.Apply(); // base vertex textures m_gpuBaseVertices = new Texture2D[ m_weightCount ]; for ( int w = 0; w < m_weightCount; w++ ) { m_gpuBaseVertices[ w ] = new Texture2D( m_gpuVertexTexWidth, m_gpuVertexTexHeight, TextureFormat.RGBAFloat, false, true ); m_gpuBaseVertices[ w ].hideFlags = HideFlags.DontSave; m_gpuBaseVertices[ w ].name = "AM-" + m_obj.name + "-BaseVerts"; m_gpuBaseVertices[ w ].filterMode = FilterMode.Point; } List<Color[]> baseVertices = new List<Color[]>( m_weightCount ); for ( int w = 0; w < m_weightCount; w++ ) baseVertices.Add( new Color[ m_gpuVertexTexWidth * m_gpuVertexTexHeight ] ); for ( int v = 0; v < m_vertexCount; v++ ) { int x = v % m_gpuVertexTexWidth; int y = v / m_gpuVertexTexWidth; int offset = y * m_gpuVertexTexWidth + x; for ( int w = 0; w < m_weightCount; w++ ) baseVertices[ w ][ offset ] = m_baseVertices[ v * m_weightCount + w ]; } for ( int w = 0; w < m_weightCount; w++ ) { m_gpuBaseVertices[ w ].SetPixels( baseVertices[ w ] ); m_gpuBaseVertices[ w ].Apply(); } // create output/target vertex render textures m_gpuPrevVertices = new RenderTexture( m_gpuVertexTexWidth, m_gpuVertexTexHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear ); m_gpuPrevVertices.hideFlags = HideFlags.DontSave; m_gpuPrevVertices.name = "AM-" + m_obj.name + "-PrevVerts"; m_gpuPrevVertices.filterMode = FilterMode.Point; m_gpuPrevVertices.wrapMode = TextureWrapMode.Clamp; m_gpuPrevVertices.Create(); m_gpuCurrVertices = new RenderTexture( m_gpuVertexTexWidth, m_gpuVertexTexHeight, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear ); m_gpuCurrVertices.hideFlags = HideFlags.DontSave; m_gpuCurrVertices.name = "AM-" + m_obj.name + "-CurrVerts"; m_gpuCurrVertices.filterMode = FilterMode.Point; m_gpuCurrVertices.wrapMode = TextureWrapMode.Clamp; m_gpuCurrVertices.Create(); // assign local material constants m_gpuSkinDeformMat.SetTexture( "_AM_BONE_TEX", m_gpuBones ); m_gpuSkinDeformMat.SetTexture( "_AM_BONE_INDEX_TEX", m_gpuBoneIndices ); for ( int w = 0; w < m_weightCount; w++ ) m_gpuSkinDeformMat.SetTexture( "_AM_BASE_VERTEX" + w + "_TEX", m_gpuBaseVertices[ w ] ); // assign global shader constants Vector4 boneTexelSize = new Vector4( 1.0f / m_gpuBoneTexWidth, 1.0f / m_gpuBoneTexHeight, m_gpuBoneTexWidth, m_gpuBoneTexHeight ); Vector4 vertexTexelSize = new Vector4( 1.0f / m_gpuVertexTexWidth, 1.0f / m_gpuVertexTexHeight, m_gpuVertexTexWidth, m_gpuVertexTexHeight ); m_gpuSkinDeformMat.SetVector( "_AM_BONE_TEXEL_SIZE", boneTexelSize ); m_gpuSkinDeformMat.SetVector( "_AM_BONE_TEXEL_HALFSIZE", boneTexelSize * 0.5f ); m_gpuSkinDeformMat.SetVector( "_AM_VERTEX_TEXEL_SIZE", vertexTexelSize ); m_gpuSkinDeformMat.SetVector( "_AM_VERTEX_TEXEL_HALFSIZE", vertexTexelSize * 0.5f ); // assign vertex x/y offsets packed into second uv channel Vector2[] indexCoords = new Vector2[ m_vertexCount ]; for ( int v = 0; v < m_vertexCount; v++ ) { int x = v % m_gpuVertexTexWidth; int y = v / m_gpuVertexTexWidth; float x_norm = ( x / ( float ) m_gpuVertexTexWidth ) + vertexTexelSize.x * 0.5f; float y_norm = ( y / ( float ) m_gpuVertexTexHeight ) + vertexTexelSize.y * 0.5f; indexCoords[ v ] = new Vector2( x_norm, y_norm ); } m_clonedMesh.uv2 = indexCoords; } catch ( Exception ) { succeeded = false; } return succeeded; } private void ShutdownGPUSkinDeform() { if ( m_gpuSkinDeformMat != null ) { Material.DestroyImmediate( m_gpuSkinDeformMat ); m_gpuSkinDeformMat = null; } m_gpuBoneData = null; if ( m_gpuBones != null ) { Texture2D.DestroyImmediate( m_gpuBones ); m_gpuBones = null; } if ( m_gpuBoneIndices != null ) { Texture2D.DestroyImmediate( m_gpuBoneIndices ); m_gpuBoneIndices = null; } if ( m_gpuBaseVertices != null ) { for ( int i = 0; i < m_gpuBaseVertices.Length; i++ ) Texture2D.DestroyImmediate( m_gpuBaseVertices[ i ] ); m_gpuBaseVertices = null; } if ( m_gpuPrevVertices != null ) { RenderTexture.active = null; m_gpuPrevVertices.Release(); RenderTexture.DestroyImmediate( m_gpuPrevVertices ); m_gpuPrevVertices = null; } if ( m_gpuCurrVertices != null ) { RenderTexture.active = null; m_gpuCurrVertices.Release(); RenderTexture.DestroyImmediate( m_gpuCurrVertices ); m_gpuCurrVertices = null; } } private void UpdateBonesGPU() { for ( int b = 0; b < m_boneCount; b++ ) { for ( int r = 0; r < m_gpuBoneTexHeight; r++ ) m_gpuBoneData[ r * m_gpuBoneTexWidth + b ] = m_bones[ b ].GetRow( r ); } m_gpuBones.SetPixels( m_gpuBoneData ); m_gpuBones.Apply(); } private void UpdateVerticesGPU( CommandBuffer updateCB, bool starting ) { if ( !starting && m_wasVisible ) { m_gpuPrevVertices.DiscardContents(); updateCB.Blit( new RenderTargetIdentifier( m_gpuCurrVertices ), m_gpuPrevVertices ); } updateCB.SetGlobalMatrix( "_AM_WORLD_TO_LOCAL_MATRIX", m_worldToLocalMatrix ); m_gpuCurrVertices.DiscardContents(); RenderTexture dummy = null; updateCB.Blit( new RenderTargetIdentifier( dummy ), m_gpuCurrVertices, m_gpuSkinDeformMat, Mathf.Min( m_weightCount - 1, 2 ) ); if ( starting || !m_wasVisible ) { m_gpuPrevVertices.DiscardContents(); updateCB.Blit( new RenderTargetIdentifier( m_gpuCurrVertices ), m_gpuPrevVertices ); } } #endif private void UpdateBones() { for ( int b = 0; b < m_boneCount; b++ ) m_bones[ b ] = ( m_boneTransforms[ b ] != null ) ? m_boneTransforms[ b ].localToWorldMatrix : Matrix4x4.identity; m_worldToLocalMatrix = m_transform.worldToLocalMatrix; #if !UNITY_4 if ( m_useGPU ) { Profiler.BeginSample( "UpdateBonesGPU" ); UpdateBonesGPU(); Profiler.EndSample(); } #endif } private void UpdateVerticesFallback( bool starting ) { if ( !starting && m_wasVisible ) Array.Copy( m_currVertices, m_prevVertices, m_vertexCount ); m_renderer.BakeMesh( m_clonedMesh ); if ( m_clonedMesh.vertexCount == 0 || m_clonedMesh.vertexCount != m_prevVertices.Length ) { IssueError( "[AmplifyMotion] Invalid mesh obtained from SkinnedMeshRenderer.BakeMesh in object " + m_obj.name + ". Skipping." ); return; } Array.Copy( m_clonedMesh.vertices, m_currVertices, m_vertexCount ); if ( starting || !m_wasVisible ) Array.Copy( m_currVertices, m_prevVertices, m_vertexCount ); } private void AsyncUpdateVertices( bool starting ) { if ( !starting && m_wasVisible ) Array.Copy( m_currVertices, m_prevVertices, m_vertexCount ); for ( int i = 0; i < m_boneCount; i++ ) m_bones[ i ] = m_worldToLocalMatrix * m_bones[ i ]; if ( m_weightCount == 1 ) UpdateVerticesBone1(); else if ( m_weightCount == 2 ) UpdateVerticesBone2(); else UpdateVerticesBone4(); if ( starting || !m_wasVisible ) Array.Copy( m_currVertices, m_prevVertices, m_vertexCount ); } private void InitializeBone1( Vector4[] baseVertices, int[] boneIndices ) { Vector3[] meshVertices = m_renderer.sharedMesh.vertices; Matrix4x4[] meshBindPoses = m_renderer.sharedMesh.bindposes; BoneWeight[] meshBoneWeights = m_renderer.sharedMesh.boneWeights; for ( int i = 0; i < m_vertexCount; i++ ) { int offset0 = i * m_weightCount; int bone0 = boneIndices[ offset0 ] = meshBoneWeights[ i ].boneIndex0; Vector3 baseVertex0 = meshBindPoses[ bone0 ].MultiplyPoint3x4( meshVertices[ i ] ); baseVertices[ offset0 ] = new Vector4( baseVertex0.x, baseVertex0.y, baseVertex0.z, 1.0f ); } } private void InitializeBone2( Vector4[] baseVertices, int[] boneIndices, float[] boneWeights ) { Vector3[] meshVertices = m_renderer.sharedMesh.vertices; Matrix4x4[] meshBindPoses = m_renderer.sharedMesh.bindposes; BoneWeight[] meshBoneWeights = m_renderer.sharedMesh.boneWeights; for ( int i = 0; i < m_vertexCount; i++ ) { int offset0 = i * m_weightCount; int offset1 = offset0 + 1; BoneWeight boneWeight = meshBoneWeights[ i ]; int bone0 = boneIndices[ offset0 ] = boneWeight.boneIndex0; int bone1 = boneIndices[ offset1 ] = boneWeight.boneIndex1; float weight0 = boneWeight.weight0; float weight1 = boneWeight.weight1; float rcpSum = 1.0f / ( weight0 + weight1 ); boneWeights[ offset0 ] = weight0 = weight0 * rcpSum; boneWeights[ offset1 ] = weight1 = weight1 * rcpSum; Vector3 baseVertex0 = weight0 * meshBindPoses[ bone0 ].MultiplyPoint3x4( meshVertices[ i ] ); Vector3 baseVertex1 = weight1 * meshBindPoses[ bone1 ].MultiplyPoint3x4( meshVertices[ i ] ); baseVertices[ offset0 ] = new Vector4( baseVertex0.x, baseVertex0.y, baseVertex0.z, weight0 ); baseVertices[ offset1 ] = new Vector4( baseVertex1.x, baseVertex1.y, baseVertex1.z, weight1 ); } } private void InitializeBone4( Vector4[] baseVertices, int[] boneIndices, float[] boneWeights ) { Vector3[] meshVertices = m_renderer.sharedMesh.vertices; Matrix4x4[] meshBindPoses = m_renderer.sharedMesh.bindposes; BoneWeight[] meshBoneWeights = m_renderer.sharedMesh.boneWeights; for ( int i = 0; i < m_vertexCount; i++ ) { int offset0 = i * m_weightCount; int offset1 = offset0 + 1; int offset2 = offset0 + 2; int offset3 = offset0 + 3; BoneWeight boneWeight = meshBoneWeights[ i ]; int bone0 = boneIndices[ offset0 ] = boneWeight.boneIndex0; int bone1 = boneIndices[ offset1 ] = boneWeight.boneIndex1; int bone2 = boneIndices[ offset2 ] = boneWeight.boneIndex2; int bone3 = boneIndices[ offset3 ] = boneWeight.boneIndex3; float weight0 = boneWeights[ offset0 ] = boneWeight.weight0; float weight1 = boneWeights[ offset1 ] = boneWeight.weight1; float weight2 = boneWeights[ offset2 ] = boneWeight.weight2; float weight3 = boneWeights[ offset3 ] = boneWeight.weight3; Vector3 baseVertex0 = weight0 * meshBindPoses[ bone0 ].MultiplyPoint3x4( meshVertices[ i ] ); Vector3 baseVertex1 = weight1 * meshBindPoses[ bone1 ].MultiplyPoint3x4( meshVertices[ i ] ); Vector3 baseVertex2 = weight2 * meshBindPoses[ bone2 ].MultiplyPoint3x4( meshVertices[ i ] ); Vector3 baseVertex3 = weight3 * meshBindPoses[ bone3 ].MultiplyPoint3x4( meshVertices[ i ] ); baseVertices[ offset0 ] = new Vector4( baseVertex0.x, baseVertex0.y, baseVertex0.z, weight0 ); baseVertices[ offset1 ] = new Vector4( baseVertex1.x, baseVertex1.y, baseVertex1.z, weight1 ); baseVertices[ offset2 ] = new Vector4( baseVertex2.x, baseVertex2.y, baseVertex2.z, weight2 ); baseVertices[ offset3 ] = new Vector4( baseVertex3.x, baseVertex3.y, baseVertex3.z, weight3 ); } } private void UpdateVerticesBone1() { for ( int i = 0; i < m_vertexCount; i++ ) MulPoint3x4_XYZ( ref m_currVertices[ i ], ref m_bones[ m_boneIndices[ i ] ], m_baseVertices[ i ] ); } private void UpdateVerticesBone2() { Vector3 deformedVertex = Vector3.zero; for ( int i = 0; i < m_vertexCount; i++ ) { int offset0 = i * 2; int offset1 = offset0 + 1; int b0 = m_boneIndices[ offset0 ]; int b1 = m_boneIndices[ offset1 ]; float weight1 = m_boneWeights[ offset1 ]; MulPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b0 ], m_baseVertices[ offset0 ] ); if ( weight1 != 0 ) MulAddPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b1 ], m_baseVertices[ offset1 ] ); m_currVertices[ i ] = deformedVertex; } } private void UpdateVerticesBone4() { Vector3 deformedVertex = Vector3.zero; for ( int i = 0; i < m_vertexCount; i++ ) { int offset0 = i * 4; int offset1 = offset0 + 1; int offset2 = offset0 + 2; int offset3 = offset0 + 3; int b0 = m_boneIndices[ offset0 ]; int b1 = m_boneIndices[ offset1 ]; int b2 = m_boneIndices[ offset2 ]; int b3 = m_boneIndices[ offset3 ]; float weight1 = m_boneWeights[ offset1 ]; float weight2 = m_boneWeights[ offset2 ]; float weight3 = m_boneWeights[ offset3 ]; MulPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b0 ], m_baseVertices[ offset0 ] ); if ( weight1 != 0 ) MulAddPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b1 ], m_baseVertices[ offset1 ] ); if ( weight2 != 0 ) MulAddPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b2 ], m_baseVertices[ offset2 ] ); if ( weight3 != 0 ) MulAddPoint3x4_XYZW( ref deformedVertex, ref m_bones[ b3 ], m_baseVertices[ offset3 ] ); m_currVertices[ i ] = deformedVertex; } } internal override void AsyncUpdate() { try { AsyncUpdateVertices( m_starting ); } catch ( System.Exception e ) { IssueError( "[AmplifyMotion] Failed on SkinnedMeshRenderer data. Please contact support.\n" + e.Message ); } finally { m_asyncUpdateSignal.Set(); } } #if UNITY_4 internal override void UpdateTransform( bool starting ) #else internal override void UpdateTransform( CommandBuffer updateCB, bool starting ) #endif { if ( !m_initialized ) { Initialize(); return; } Profiler.BeginSample( "Skinned.Update" ); if ( !starting && m_wasVisible ) m_prevLocalToWorld = m_currLocalToWorld; bool isVisible = m_renderer.isVisible; if ( !m_error && ( isVisible || starting ) ) { UpdateBones(); m_starting = !m_wasVisible || starting; if ( !m_useFallback ) { if ( !m_useGPU ) { m_asyncUpdateSignal.Reset(); m_asyncUpdateTriggered = true; m_owner.Instance.WorkerPool.EnqueueAsyncUpdate( this ); } #if !UNITY_4 else UpdateVerticesGPU( updateCB, m_starting ); #endif } else UpdateVerticesFallback( m_starting ); } if ( !m_useFallback ) m_currLocalToWorld = m_transform.localToWorldMatrix; else m_currLocalToWorld = Matrix4x4.TRS( m_transform.position, m_transform.rotation, Vector3.one ); if ( starting || !m_wasVisible ) m_prevLocalToWorld = m_currLocalToWorld; m_wasVisible = isVisible; Profiler.EndSample(); } private void WaitForAsyncUpdate() { if ( m_asyncUpdateTriggered ) { if ( !m_asyncUpdateSignal.WaitOne( MotionState.AsyncUpdateTimeout ) ) { Debug.LogWarning( "[AmplifyMotion] Aborted abnormally long Async Skin deform operation. Not a critical error but might indicate a problem. Please contact support." ); return; } m_asyncUpdateTriggered = false; } } #if UNITY_4 internal override void RenderVectors( Camera camera, float scale, AmplifyMotion.Quality quality ) { if ( m_initialized && !m_error && m_renderer.isVisible ) { Profiler.BeginSample( "Skinned.Update" ); if ( !m_useFallback ) { if ( !m_useGPU ) WaitForAsyncUpdate(); } Profiler.EndSample(); Profiler.BeginSample( "Skinned.Render" ); if ( !m_useGPU ) { if ( !m_useFallback ) m_clonedMesh.vertices = m_currVertices; m_clonedMesh.normals = m_prevVertices; } const float rcp255 = 1 / 255.0f; bool mask = ( m_owner.Instance.CullingMask & ( 1 << m_obj.gameObject.layer ) ) != 0; int objectId = mask ? m_owner.Instance.GenerateObjectId( m_obj.gameObject ) : 255; Matrix4x4 prevModelViewProj; if ( m_obj.FixedStep ) prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_currLocalToWorld; else prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_prevLocalToWorld; Shader.SetGlobalMatrix( "_AM_MATRIX_PREV_MVP", prevModelViewProj ); Shader.SetGlobalFloat( "_AM_OBJECT_ID", objectId * rcp255 ); Shader.SetGlobalFloat( "_AM_MOTION_SCALE", mask ? scale : 0 ); if ( m_useGPU ) { #if !UNITY_4 Vector4 vertexTexelSize = new Vector4( 1.0f / m_gpuVertexTexWidth, 1.0f / m_gpuVertexTexHeight, m_gpuVertexTexWidth, m_gpuVertexTexHeight ); Shader.SetGlobalVector( "_AM_VERTEX_TEXEL_SIZE", vertexTexelSize ); Shader.SetGlobalVector( "_AM_VERTEX_TEXEL_HALFSIZE", vertexTexelSize * 0.5f ); Shader.SetGlobalTexture( "_AM_PREV_VERTEX_TEX", m_gpuPrevVertices ); Shader.SetGlobalTexture( "_AM_CURR_VERTEX_TEX", m_gpuCurrVertices ); #endif } int hardwarePass = m_useGPU ? 4 : 0; int qualityPass = ( quality == AmplifyMotion.Quality.Mobile ) ? 0 : 2; int basePass = hardwarePass + qualityPass; for ( int i = 0; i < m_sharedMaterials.Length; i++ ) { MaterialDesc matDesc = m_sharedMaterials[ i ]; int pass = basePass + ( matDesc.coverage ? 1 : 0 ); if ( matDesc.coverage ) { m_owner.Instance.SkinnedVectorsMaterial.mainTexture = matDesc.material.mainTexture; if ( matDesc.cutoff ) m_owner.Instance.SkinnedVectorsMaterial.SetFloat( "_Cutoff", matDesc.material.GetFloat( "_Cutoff" ) ); } if ( m_owner.Instance.SkinnedVectorsMaterial.SetPass( pass ) ) Graphics.DrawMeshNow( m_clonedMesh, m_currLocalToWorld, i ); } Profiler.EndSample(); } } #else internal override void RenderVectors( Camera camera, CommandBuffer renderCB, float scale, AmplifyMotion.Quality quality ) { if ( m_initialized && !m_error && m_renderer.isVisible ) { Profiler.BeginSample( "Skinned.Update" ); if ( !m_useFallback ) { if ( !m_useGPU ) WaitForAsyncUpdate(); } Profiler.EndSample(); Profiler.BeginSample( "Skinned.Render" ); if ( !m_useGPU ) { if ( !m_useFallback ) m_clonedMesh.vertices = m_currVertices; m_clonedMesh.normals = m_prevVertices; } const float rcp255 = 1 / 255.0f; bool mask = ( m_owner.Instance.CullingMask & ( 1 << m_obj.gameObject.layer ) ) != 0; int objectId = mask ? m_owner.Instance.GenerateObjectId( m_obj.gameObject ) : 255; Matrix4x4 prevModelViewProj; if ( m_obj.FixedStep ) prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_currLocalToWorld; else prevModelViewProj = m_owner.PrevViewProjMatrixRT * ( Matrix4x4 ) m_prevLocalToWorld; renderCB.SetGlobalMatrix( "_AM_MATRIX_PREV_MVP", prevModelViewProj ); renderCB.SetGlobalFloat( "_AM_OBJECT_ID", objectId * rcp255 ); renderCB.SetGlobalFloat( "_AM_MOTION_SCALE", mask ? scale : 0 ); if ( m_useGPU ) { Vector4 vertexTexelSize = new Vector4( 1.0f / m_gpuVertexTexWidth, 1.0f / m_gpuVertexTexHeight, m_gpuVertexTexWidth, m_gpuVertexTexHeight ); renderCB.SetGlobalVector( "_AM_VERTEX_TEXEL_SIZE", vertexTexelSize ); renderCB.SetGlobalVector( "_AM_VERTEX_TEXEL_HALFSIZE", vertexTexelSize * 0.5f ); renderCB.SetGlobalTexture( "_AM_PREV_VERTEX_TEX", m_gpuPrevVertices ); renderCB.SetGlobalTexture( "_AM_CURR_VERTEX_TEX", m_gpuCurrVertices ); } int hardwarePass = m_useGPU ? 4 : 0; int qualityPass = ( quality == AmplifyMotion.Quality.Mobile ) ? 0 : 2; int basePass = hardwarePass + qualityPass; for ( int i = 0; i < m_sharedMaterials.Length; i++ ) { MaterialDesc matDesc = m_sharedMaterials[ i ]; int pass = basePass + ( matDesc.coverage ? 1 : 0 ); if ( matDesc.coverage ) { Texture mainTex = matDesc.material.mainTexture; if ( mainTex != null ) matDesc.propertyBlock.SetTexture( "_MainTex", mainTex ); if ( matDesc.cutoff ) matDesc.propertyBlock.SetFloat( "_Cutoff", matDesc.material.GetFloat( "_Cutoff" ) ); } renderCB.DrawMesh( m_clonedMesh, m_currLocalToWorld, m_owner.Instance.SkinnedVectorsMaterial, i, pass, matDesc.propertyBlock ); } Profiler.EndSample(); } } #endif } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 using System.Diagnostics.CodeAnalysis; using System.Net; using System.Security; using SafeString = System.String; using System.Runtime.Serialization; using System.Security.Cryptography; using Microsoft.PowerShell; #if CORECLR // Use stubs for ISerializable related types using Microsoft.PowerShell.CoreClr.Stubs; using System.Runtime.InteropServices; #endif // FxCop suppressions for resource strings: [module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Credential.resources", MessageId = "Cred")] namespace System.Management.Automation { /// <summary> /// Defines the valid types of MSH credentials. Used by PromptForCredential calls. /// </summary> [Flags] public enum PSCredentialTypes { /// <summary> /// Generic credentials. /// </summary> Generic = 1, /// <summary> /// Credentials valid for a domain. /// </summary> Domain = 2, /// <summary> /// Default credentials. /// </summary> Default = Generic | Domain } /// <summary> /// Defines the options available when prompting for credentials. Used /// by PromptForCredential calls. /// </summary> [Flags] public enum PSCredentialUIOptions { /// <summary> /// Validates the username, but not its existence /// or correctness. /// </summary> Default = ValidateUserNameSyntax, /// <summary> /// Performs no validation. /// </summary> None = 0, /// <summary> /// Validates the username, but not its existence. /// or correctness /// </summary> ValidateUserNameSyntax, /// <summary> /// Always prompt, even if a persisted credential was available. /// </summary> AlwaysPrompt, /// <summary> /// Username is read-only, and the user may not modify it. /// </summary> ReadOnlyUserName } /// <summary> /// Declare a delegate which returns the encryption key and initialization vector for symmetric encryption algorithem. /// </summary> /// <param name="context">The streaming context, which contains the searilization context.</param> /// <param name="key">Symmetric encryption key.</param> /// <param name="iv">symmetric encryption initialization vector.</param> /// <returns></returns> public delegate bool GetSymmetricEncryptionKey(StreamingContext context, out byte[] key, out byte[] iv); /// <summary> /// Offers a centralized way to manage usernames, passwords, and /// credentials. /// </summary> [Serializable()] public sealed class PSCredential : ISerializable { /// <summary> /// Gets or sets a delegate which returns the encryption key and initialization vector for symmetric encryption algorithm. /// </summary> public static GetSymmetricEncryptionKey GetSymmetricEncryptionKeyDelegate { get { return s_delegate; } set { s_delegate = value; } } private static GetSymmetricEncryptionKey s_delegate = null; /// <summary> /// GetObjectData /// </summary> /// <param name="info"></param> /// <param name="context"></param> public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) return; // serialize the secure string string safePassword = string.Empty; if (_password != null && _password.Length > 0) { byte[] key; byte[] iv; if (s_delegate != null && s_delegate(context, out key, out iv)) { safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData; } else { try { safePassword = SecureStringHelper.Protect(_password); } catch (CryptographicException cryptographicException) { throw PSTraceSource.NewInvalidOperationException(cryptographicException, Credential.CredentialDisallowed); } } } info.AddValue("UserName", _userName); info.AddValue("Password", safePassword); } /// <summary> /// PSCredential /// </summary> /// <param name="info"></param> /// <param name="context"></param> private PSCredential(SerializationInfo info, StreamingContext context) { if (info == null) return; _userName = (string)info.GetValue("UserName", typeof(string)); // deserialize to secure string SafeString safePassword = (SafeString)info.GetValue("Password", typeof(SafeString)); if (safePassword == SafeString.Empty) { _password = new SecureString(); } else { byte[] key; byte[] iv; if (s_delegate != null && s_delegate(context, out key, out iv)) { _password = SecureStringHelper.Decrypt(safePassword, key, iv); } else { _password = SecureStringHelper.Unprotect(safePassword); } } } private string _userName; private SecureString _password; /// <summary> /// User's name. /// </summary> public string UserName { get { return _userName; } } /// <summary> /// User's password. /// </summary> public SecureString Password { get { return _password; } } /// <summary> /// Initializes a new instance of the PSCredential class with a /// username and password. /// </summary> /// /// <param name="userName"> User's name. </param> /// <param name="password"> User's password. </param> public PSCredential(string userName, SecureString password) { Utils.CheckArgForNullOrEmpty(userName, "userName"); Utils.CheckArgForNull(password, "password"); _userName = userName; _password = password; } /// <summary> /// Initializes a new instance of the PSCredential class with a /// username and password from PSObject. /// </summary> /// <param name="pso"></param> public PSCredential(PSObject pso) { if (pso == null) throw PSTraceSource.NewArgumentNullException("pso"); if (pso.Properties["UserName"] != null) { _userName = (string)pso.Properties["UserName"].Value; if (pso.Properties["Password"] != null) _password = (SecureString)pso.Properties["Password"].Value; } } /// <summary> /// Initializes a new instance of the PSCredential class. /// </summary> private PSCredential() { } private NetworkCredential _netCred; /// <summary> /// Returns an equivalent NetworkCredential object for this /// PSCredential. /// /// A null is returned if /// -- current object has not been initialized /// -- current creds are not compatible with NetworkCredential /// (such as smart card creds or cert creds) /// </summary> /// /// <returns> /// null if the current object has not been initialized. /// null if the current credentials are incompatible with /// a NetworkCredential -- such as smart card credentials. /// the appropriate network credential for this PSCredential otherwise. /// </returns> public NetworkCredential GetNetworkCredential() { if (_netCred == null) { string user = null; string domain = null; if (IsValidUserName(_userName, out user, out domain)) { #if CORECLR // NetworkCredential constructor only accepts plain string password in CoreCLR // Since user can already access the plain text password via PSCredential.GetNetworkCredential().Password, // this change won't be a security issue for PS on CSS. IntPtr unmanagedPtr = IntPtr.Zero; try { unmanagedPtr = ClrFacade.SecureStringToCoTaskMemUnicode(_password); string pwdInPlainText = System.Runtime.InteropServices.Marshal.PtrToStringUni(unmanagedPtr); _netCred = new NetworkCredential(user, pwdInPlainText, domain); } finally { if (unmanagedPtr != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUnicode(unmanagedPtr); } } #else _netCred = new NetworkCredential(user, _password, domain); #endif } } return _netCred; } /// <summary> /// Provides an explicit cast to get a NetworkCredential /// from this PSCredential. /// </summary> /// /// <param name="credential"> PSCredential to convert. </param> /// /// <returns> /// null if the current object has not been initialized. /// null if the current credentials are incompatible with /// a NetworkCredential -- such as smart card credentials. /// the appropriate network credential for this PSCredential otherwise. /// </returns> public static explicit operator NetworkCredential(PSCredential credential) { #pragma warning disable 56506 if (credential == null) { throw PSTraceSource.NewArgumentNullException("credential"); } return credential.GetNetworkCredential(); #pragma warning restore 56506 } /// <summary> /// Gets an empty PSCredential. This is an PSCredential with both UserName /// and Password initialized to null. /// </summary> public static PSCredential Empty { get { return s_empty; } } private static readonly PSCredential s_empty = new PSCredential(); /// <summary> /// Parse a string that represents a fully qualified username /// to verify that it is syntactically valid. We only support /// two formats: /// -- domain\user /// -- user@domain /// /// for any other format, we simply treat the entire string /// as user name and set domain name to "". /// /// </summary> /// private static bool IsValidUserName(string input, out string user, out string domain) { SplitUserDomain(input, out user, out domain); if ((user == null) || (domain == null) || (user.Length == 0)) { //UserName is the public property of Credential object. Use this as //parameter name in error //See bug NTRAID#Windows OS Bugs-1106386-2005/03/25-hiteshr throw PSTraceSource.NewArgumentException("UserName", Credential.InvalidUserNameFormat); } return true; } /// <summary> /// Split a given string into its user and domain /// components. Supported formats are: /// -- domain\user /// -- user@domain /// /// With any other format, the entire input is treated as user /// name and domain is set to "". /// /// In any case, the function does not check if the split string /// are really valid as user or domain names. /// </summary> /// private static void SplitUserDomain(string input, out string user, out string domain) { int i = 0; user = null; domain = null; if ((i = input.IndexOf('\\')) >= 0) { user = input.Substring(i + 1); domain = input.Substring(0, i); return; } // In V1 and V2, we had a bug where email addresses (i.e. foo@bar.com) // were being split into Username=Foo, Domain=bar.com. // // This was breaking apps (i.e.: Exchange), so we need to make // Username = foo@bar.com if the domain has a dot in it (since // domains can't have dots). // // HOWEVER, there was a workaround for this bug in v1 and v2, where the // cred could be entered as "foo@bar.com@bar.com" - making: // Username = foo@bar.com, Domain = bar.com // // We need to keep the behaviour in this case. i = input.LastIndexOf('@'); if ( (i >= 0) && ( (input.LastIndexOf('.') < i) || (input.IndexOf('@') != i) ) ) { domain = input.Substring(i + 1); user = input.Substring(0, i); } else { user = input; domain = ""; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Runtime.InteropServices.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Marshalling between VARIANT and Object is not supported in AppX")] public class GetObjectsForNativeVariantsTests { [StructLayout(LayoutKind.Sequential)] public struct Record { private IntPtr _record; private IntPtr _recordInfo; } [StructLayout(LayoutKind.Explicit)] public struct UnionTypes { [FieldOffset(0)] internal SByte _i1; [FieldOffset(0)] internal Int16 _i2; [FieldOffset(0)] internal Int32 _i4; [FieldOffset(0)] internal Int64 _i8; [FieldOffset(0)] internal Byte _ui1; [FieldOffset(0)] internal UInt16 _ui2; [FieldOffset(0)] internal UInt32 _ui4; [FieldOffset(0)] internal UInt64 _ui8; [FieldOffset(0)] internal Int32 _int; [FieldOffset(0)] internal UInt32 _uint; [FieldOffset(0)] internal Single _r4; [FieldOffset(0)] internal Double _r8; [FieldOffset(0)] internal Int64 _cy; [FieldOffset(0)] internal double _date; [FieldOffset(0)] internal IntPtr _bstr; [FieldOffset(0)] internal IntPtr _unknown; [FieldOffset(0)] internal IntPtr _dispatch; [FieldOffset(0)] internal IntPtr _pvarVal; [FieldOffset(0)] internal IntPtr _byref; [FieldOffset(0)] internal Record _record; } [StructLayout(LayoutKind.Sequential)] internal struct TypeUnion { public ushort vt; public ushort wReserved1; public ushort wReserved2; public ushort wReserved3; public UnionTypes _unionTypes; } [StructLayout(LayoutKind.Explicit)] internal struct Variant { [FieldOffset(0)] public TypeUnion m_Variant; [FieldOffset(0)] public decimal m_decimal; } #pragma warning disable 618 [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void SByteType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<sbyte>(99, pNative); Marshal.GetNativeVariantForObject<sbyte>(100, pNative + Marshal.SizeOf(v)); sbyte[] actual = Marshal.GetObjectsForNativeVariants<sbyte>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void ByteType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<byte>(99, pNative); Marshal.GetNativeVariantForObject<byte>(100, pNative + Marshal.SizeOf(v)); byte[] actual = Marshal.GetObjectsForNativeVariants<byte>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void DoubleType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<double>(99, pNative); Marshal.GetNativeVariantForObject<double>(100, pNative + Marshal.SizeOf(v)); double[] actual = Marshal.GetObjectsForNativeVariants<double>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void ShortType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<short>(99, pNative); Marshal.GetNativeVariantForObject<short>(100, pNative + Marshal.SizeOf(v)); short[] actual = Marshal.GetObjectsForNativeVariants<short>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void UshortType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<ushort>(99, pNative); Marshal.GetNativeVariantForObject<ushort>(100, pNative + Marshal.SizeOf(v)); ushort[] actual = Marshal.GetObjectsForNativeVariants<ushort>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void IntType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<int>(99, pNative); Marshal.GetNativeVariantForObject<int>(100, pNative + Marshal.SizeOf(v)); int[] actual = Marshal.GetObjectsForNativeVariants<int>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void UIntType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<uint>(99, pNative); Marshal.GetNativeVariantForObject<uint>(100, pNative + Marshal.SizeOf(v)); uint[] actual = Marshal.GetObjectsForNativeVariants<uint>(pNative, 2); Assert.Equal<uint>(99, actual[0]); Assert.Equal<uint>(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void LongType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<long>(99, pNative); Marshal.GetNativeVariantForObject<long>(100, pNative + Marshal.SizeOf(v)); long[] actual = Marshal.GetObjectsForNativeVariants<long>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void ULongType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<ulong>(99, pNative); Marshal.GetNativeVariantForObject<ulong>(100, pNative + Marshal.SizeOf(v)); ulong[] actual = Marshal.GetObjectsForNativeVariants<ulong>(pNative, 2); Assert.Equal<ulong>(99, actual[0]); Assert.Equal<ulong>(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void FloatType() { Variant v = new Variant(); IntPtr pNative = Marshal.AllocHGlobal(2 * Marshal.SizeOf(v)); try { Marshal.GetNativeVariantForObject<float>(99, pNative); Marshal.GetNativeVariantForObject<float>(100, pNative + Marshal.SizeOf(v)); float[] actual = Marshal.GetObjectsForNativeVariants<float>(pNative, 2); Assert.Equal(99, actual[0]); Assert.Equal(100, actual[1]); } finally { Marshal.FreeHGlobal(pNative); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void GetObjectsForNativeVariants_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetObjectsForNativeVariants(IntPtr.Zero, 10)); Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetObjectsForNativeVariants<int>(IntPtr.Zero, 10)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void GetObjectsForNativeVariants_ZeroPointer_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("aSrcNativeVariant", () => Marshal.GetObjectsForNativeVariants(IntPtr.Zero, 10)); AssertExtensions.Throws<ArgumentNullException>("aSrcNativeVariant", () => Marshal.GetObjectsForNativeVariants<int>(IntPtr.Zero, 10)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public static void GetObjectsForNativeVariants_NegativeCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("cVars", () => Marshal.GetObjectsForNativeVariants((IntPtr)1, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("cVars", () => Marshal.GetObjectsForNativeVariants<int>((IntPtr)1, -1)); } #pragma warning restore 618 } }
// // ServiceManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 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.Linq; using System.IO; using System.Collections.Generic; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.MediaProfiles; using Banshee.Sources; using Banshee.Database; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Library; using Banshee.Hardware; using System.Collections.Concurrent; namespace Banshee.ServiceStack { public static class ServiceManager { private static ConcurrentDictionary<string, IService> _services = new ConcurrentDictionary<string, IService> (); private static ConcurrentDictionary<string, IExtensionService> _extensions = new ConcurrentDictionary<string, IExtensionService> (); private static Stack<IService> dispose_services = new Stack<IService> (); private static List<Type> service_types = new List<Type> (); private static ExtensionNodeList extension_nodes; private static bool is_initialized = false; public static event EventHandler StartupBegin; public static event EventHandler StartupFinished; public static event ServiceStartedHandler ServiceStarted; public static void Initialize () { Application.ClientStarted += OnClientStarted; } public static void InitializeAddins () { AddinManager.Initialize (ApplicationContext.CommandLine.Contains ("uninstalled") ? "." : Paths.ApplicationData); IProgressStatus monitor = ApplicationContext.CommandLine.Contains ("debug-addins") ? new ConsoleProgressStatus (true) : null; AddinManager.AddinLoadError += (o, a) => { try { AddinManager.Registry.DisableAddin (a.AddinId); } catch {} Log.Error (a.Message, a.Exception); }; if (ApplicationContext.Debugging) { AddinManager.Registry.Rebuild (monitor); } else { AddinManager.Registry.Update (monitor); } } public static void RegisterAddinServices () { extension_nodes = AddinManager.GetExtensionNodes ("/Banshee/ServiceManager/Service"); } public static void RegisterDefaultServices () { RegisterService<DBusServiceManager> (); RegisterService<DBusCommandService> (); RegisterService<BansheeDbConnection> (); RegisterService<Banshee.Preferences.PreferenceService> (); RegisterService<SourceManager> (); RegisterService<MediaProfileManager> (); RegisterService<PlayerEngineService> (); RegisterService<PlaybackControllerService> (); RegisterService<JobScheduler> (); RegisterService<Banshee.Hardware.HardwareManager> (); RegisterService<Banshee.Collection.Indexer.CollectionIndexerService> (); RegisterService<Banshee.Metadata.SaveTrackMetadataService> (); } public static void DefaultInitialize () { Initialize (); InitializeAddins (); RegisterDefaultServices (); RegisterAddinServices (); } private static void OnClientStarted (Client client) { DelayedInitialize (); } public static void Run() { //lock (self_mutex) { OnStartupBegin (); uint cumulative_timer_id = Log.InformationTimerStart (); System.Net.ServicePointManager.DefaultConnectionLimit = 6; foreach (Type type in service_types) { RegisterService (type); } if (extension_nodes != null) { foreach (TypeExtensionNode node in extension_nodes) { StartExtension (node); } } if (AddinManager.IsInitialized) { AddinManager.AddExtensionNodeHandler ("/Banshee/ServiceManager/Service", OnExtensionChanged); } is_initialized = true; Log.InformationTimerPrint (cumulative_timer_id, "All services are started {0}"); OnStartupFinished (); //} } private static IService RegisterService (Type type) { IService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IService)Activator.CreateInstance (type); RegisterService (service); Log.DebugTimerPrint (timer_id, String.Format ( "Core service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); if (service is IDisposable) { dispose_services.Push (service); } if (service is IInitializeService) { ((IInitializeService)service).Initialize (); } return service; } catch (Exception e) { if (typeof (IRequiredService).IsAssignableFrom (type)) { Log.ErrorFormat ("Error initializing required service {0}", service == null ? type.ToString () : service.ServiceName, false); throw; } Log.Warning (String.Format ("Service `{0}' not started: {1}", type.FullName, e.InnerException != null ? e.InnerException.Message : e.Message)); Log.Error (e.InnerException ?? e); } return null; } private static void StartExtension (TypeExtensionNode node) { if (_extensions.ContainsKey (node.Path)) { return; } IExtensionService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IExtensionService)node.CreateInstance (typeof (IExtensionService)); service.Initialize (); RegisterService (service); DelayedInitialize (service); Log.DebugTimerPrint (timer_id, String.Format ( "Extension service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); _extensions.TryAdd (node.Path, service); dispose_services.Push (service); } catch (Exception e) { Log.Error (e.InnerException ?? e); Log.Warning (String.Format ("Extension `{0}' not started: {1}", service == null ? node.Path : service.GetType ().FullName, e.Message)); } } private static void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { //lock (self_mutex) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add) { StartExtension (node); } else if (args.Change == ExtensionChange.Remove && _extensions.ContainsKey (node.Path)) { IExtensionService service; _extensions.TryRemove (node.Path, out service); Remove (service); ((IDisposable)service).Dispose (); Log.DebugFormat ("Extension service disposed ({0})", service.ServiceName); // Rebuild the dispose stack excluding the extension service IService [] tmp_services = new IService[dispose_services.Count - 1]; int count = tmp_services.Length; foreach (IService tmp_service in dispose_services) { if (tmp_service != service) { tmp_services[--count] = tmp_service; } } dispose_services = new Stack<IService> (tmp_services); } //} } private static bool delayed_initialized, have_client; private static void DelayedInitialize () { //lock (self_mutex) { if (!delayed_initialized) { have_client = true; var initialized = new HashSet <string> (); var to_initialize = _services.Values.ToList (); foreach (IService service in to_initialize) { if (!initialized.Contains (service.ServiceName)) { DelayedInitialize (service); initialized.Add (service.ServiceName); } } delayed_initialized = true; } //} } private static void DelayedInitialize (IService service) { try { if (have_client && service is IDelayedInitializeService) { Log.DebugFormat ("Delayed Initializating {0}", service); ((IDelayedInitializeService)service).DelayedInitialize (); } } catch (Exception e) { Log.Error (e.InnerException ?? e); Log.Warning (String.Format ("Service `{0}' not initialized: {1}", service.GetType ().FullName, e.Message)); } } public static void Shutdown () { //lock (self_mutex) { while (dispose_services.Count > 0) { IService service = dispose_services.Pop (); try { ((IDisposable)service).Dispose (); Log.DebugFormat ("Service disposed ({0})", service.ServiceName); } catch (Exception e) { Log.Error (String.Format ("Service disposal ({0}) threw an exception", service.ServiceName), e); } } _services.Clear (); //} } public static void RegisterService (IService service) { //lock (self_mutex) { Add (service); if(service is IDBusExportable) { DBusServiceManager.RegisterObject ((IDBusExportable)service); } //} } public static void RegisterService<T> () where T : IService { //lock (self_mutex) { if (is_initialized) { RegisterService (Activator.CreateInstance <T> ()); } else { service_types.Add (typeof (T)); } //} } public static bool Contains (string serviceName) { return _services.ContainsKey (serviceName); //lock (self_mutex) { // return services.ContainsKey (serviceName); //} } public static bool Contains<T> () where T : class, IService { return Contains (typeof (T).Name); } public static IService Get (string serviceName) { IService svc; return _services.TryGetValue (serviceName, out svc) ? svc : null; } public static T Get<T> () where T : class, IService { var type = typeof (T); var key = type.Name; if (typeof (IRegisterOnDemandService).IsAssignableFrom (typeof (T))) { return (T) _services.GetOrAdd (key, k => RegisterService (type)); } else { return (T) Get (key); } } private static void Add (IService service) { _services.TryAdd (service.ServiceName, service); _services.TryAdd (service.GetType ().Name, service); } private static void Remove (IService service) { IService svc; _services.TryRemove (service.ServiceName, out svc); _services.TryRemove (service.GetType ().Name, out svc); } private static void OnStartupBegin () { EventHandler handler = StartupBegin; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnStartupFinished () { EventHandler handler = StartupFinished; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnServiceStarted (IService service) { ServiceStartedHandler handler = ServiceStarted; if (handler != null) { handler (new ServiceStartedArgs (service)); } } public static int StartupServiceCount { get { return service_types.Count + (extension_nodes == null ? 0 : extension_nodes.Count) + 1; } } public static bool IsInitialized { get { return is_initialized; } } public static DBusServiceManager DBusServiceManager { get { return Get<DBusServiceManager> (); } } public static BansheeDbConnection DbConnection { get { return (BansheeDbConnection)Get ("DbConnection"); } } public static MediaProfileManager MediaProfileManager { get { return Get<MediaProfileManager> (); } } public static SourceManager SourceManager { get { return (SourceManager)Get ("SourceManager"); } } public static JobScheduler JobScheduler { get { return (JobScheduler)Get ("JobScheduler"); } } public static PlayerEngineService PlayerEngine { get { return (PlayerEngineService)Get ("PlayerEngine"); } } public static PlaybackControllerService PlaybackController { get { return (PlaybackControllerService)Get ("PlaybackController"); } } public static HardwareManager HardwareManager { get { return Get<HardwareManager> (); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of a 32 bit 2's complement ** integer. ** ** ===========================================================*/ using System.Diagnostics.Contracts; 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 Int32 : IComparable, IConvertible, IFormattable, IComparable<Int32>, IEquatable<Int32> { private int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns : // 0 if the values are equal // Negative number if _value is less than value // Positive number if _value is more than value // null is considered to be less than any instance, hence returns positive number // If object is not of type Int32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Int32) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. int i = (int)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt32); } public int CompareTo(int value) { // NOTE: Cannot use return (_value - value) as this causes a wrap // around in cases where _value - value > MaxValue. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int32)) { return false; } return m_value == ((Int32)obj).m_value; } [NonVersionable] public bool Equals(Int32 obj) { return m_value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return m_value; } [Pure] public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo); } [Pure] public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider)); } [Pure] public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider)); } [Pure] public static int Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [Pure] public static int Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [Pure] public static int Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // [Pure] public static int Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider)); } public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // [Pure] public static bool TryParse(String s, out Int32 result) { if (s == null) { result = 0; return false; } return Number.TryParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // [Pure] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, out int result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result); } // // IConvertible implementation // [Pure] public TypeCode GetTypeCode() { return TypeCode.Int32; } 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 Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return 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, "Int32", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Threading.Tasks { // <summary> // Helpers for safely using Task libraries. // </summary> internal static class TaskHelpers { private static readonly Task _defaultCompleted = FromResult<AsyncVoid>(default(AsyncVoid)); private static readonly Task<object> _completedTaskReturningNull = FromResult<object>(null); // <summary> // Returns a canceled Task. The task is completed, IsCanceled = True, IsFaulted = False. // </summary> internal static Task Canceled() { return CancelCache<AsyncVoid>.Canceled; } // <summary> // Returns a canceled Task of the given type. The task is completed, IsCanceled = True, IsFaulted = False. // </summary> internal static Task<TResult> Canceled<TResult>() { return CancelCache<TResult>.Canceled; } // <summary> // Returns a completed task that has no result. // </summary> internal static Task Completed() { return _defaultCompleted; } // <summary> // Returns an error task. The task is Completed, IsCanceled = False, IsFaulted = True // </summary> internal static Task FromError(Exception exception) { return FromError<AsyncVoid>(exception); } // <summary> // Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True // </summary> // <typeparam name="TResult"></typeparam> internal static Task<TResult> FromError<TResult>(Exception exception) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); tcs.SetException(exception); return tcs.Task; } // <summary> // Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True // </summary> internal static Task FromErrors(IEnumerable<Exception> exceptions) { return FromErrors<AsyncVoid>(exceptions); } // <summary> // Returns an error task of the given type. The task is Completed, IsCanceled = False, IsFaulted = True // </summary> internal static Task<TResult> FromErrors<TResult>(IEnumerable<Exception> exceptions) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); tcs.SetException(exceptions); return tcs.Task; } // <summary> // Returns a successful completed task with the given result. // </summary> internal static Task<TResult> FromResult<TResult>(TResult result) { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); tcs.SetResult(result); return tcs.Task; } internal static Task<object> NullResult() { return _completedTaskReturningNull; } // <summary> // Return a task that runs all the tasks inside the iterator sequentially. It stops as soon // as one of the tasks fails or cancels, or after all the tasks have run succesfully. // </summary> // <param name="asyncIterator">collection of tasks to wait on</param> // <param name="cancellationToken">cancellation token</param> // <param name="disposeEnumerator">whether or not to dispose the enumerator we get from <paramref name="asyncIterator"/>. // Only set to <c>false</c> if you can guarantee that <paramref name="asyncIterator"/>'s enumerator does not have any resources it needs to dispose.</param> // <returns>a task that signals completed when all the incoming tasks are finished.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is propagated in a Task.")] internal static Task Iterate(IEnumerable<Task> asyncIterator, CancellationToken cancellationToken = default(CancellationToken), bool disposeEnumerator = true) { Contract.Assert(asyncIterator != null); IEnumerator<Task> enumerator = null; try { enumerator = asyncIterator.GetEnumerator(); Task task = IterateImpl(enumerator, cancellationToken); return (disposeEnumerator && enumerator != null) ? task.Finally(enumerator.Dispose, runSynchronously: true) : task; } catch (Exception ex) { return TaskHelpers.FromError(ex); } } // <summary> // Provides the implementation of the Iterate method. // Contains special logic to help speed up common cases. // </summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is propagated in a Task.")] internal static Task IterateImpl(IEnumerator<Task> enumerator, CancellationToken cancellationToken) { try { while (true) { // short-circuit: iteration canceled if (cancellationToken.IsCancellationRequested) { return TaskHelpers.Canceled(); } // short-circuit: iteration complete if (!enumerator.MoveNext()) { return TaskHelpers.Completed(); } // fast case: Task completed synchronously & successfully Task currentTask = enumerator.Current; if (currentTask.Status == TaskStatus.RanToCompletion) { continue; } // fast case: Task completed synchronously & unsuccessfully if (currentTask.IsCanceled || currentTask.IsFaulted) { return currentTask; } // slow case: Task isn't yet complete return IterateImplIncompleteTask(enumerator, currentTask, cancellationToken); } } catch (Exception ex) { return TaskHelpers.FromError(ex); } } // <summary> // Fallback for IterateImpl when the antecedent Task isn't yet complete. // </summary> internal static Task IterateImplIncompleteTask(IEnumerator<Task> enumerator, Task currentTask, CancellationToken cancellationToken) { // There's a race condition here, the antecedent Task could complete between // the check in Iterate and the call to Then below. If this happens, we could // end up growing the stack indefinitely. But the chances of (a) even having // enough Tasks in the enumerator in the first place and of (b) *every* one // of them hitting this race condition are so extremely remote that it's not // worth worrying about. return currentTask.Then(() => IterateImpl(enumerator, cancellationToken)); } // <summary> // Replacement for Task.Factory.StartNew when the code can run synchronously. // We run the code immediately and avoid the thread switch. // This is used to help synchronous code implement task interfaces. // </summary> // <param name="action">action to run synchronouslyt</param> // <param name="token">cancellation token. This is only checked before we run the task, and if cancelled, we immediately return a cancelled task.</param> // <returns>a task who result is the result from Func()</returns> // <remarks> // Avoid calling Task.Factory.StartNew. // This avoids gotchas with StartNew: // - ensures cancellation token is checked (StartNew doesn't check cancellation tokens). // - Keeps on the same thread. // - Avoids switching synchronization contexts. // Also take in a lambda so that we can wrap in a try catch and honor task failure semantics. // </remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] public static Task RunSynchronously(Action action, CancellationToken token = default(CancellationToken)) { if (token.IsCancellationRequested) { return Canceled(); } try { action(); return Completed(); } catch (Exception e) { return FromError(e); } } // <summary> // Replacement for Task.Factory.StartNew when the code can run synchronously. // We run the code immediately and avoid the thread switch. // This is used to help synchronous code implement task interfaces. // </summary> // <typeparam name="TResult">type of result that task will return.</typeparam> // <param name="func">function to run synchronously and produce result</param> // <param name="cancellationToken">cancellation token. This is only checked before we run the task, and if cancelled, we immediately return a cancelled task.</param> // <returns>a task who result is the result from Func()</returns> // <remarks> // Avoid calling Task.Factory.StartNew. // This avoids gotchas with StartNew: // - ensures cancellation token is checked (StartNew doesn't check cancellation tokens). // - Keeps on the same thread. // - Avoids switching synchronization contexts. // Also take in a lambda so that we can wrap in a try catch and honor task failure semantics. // </remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] internal static Task<TResult> RunSynchronously<TResult>(Func<TResult> func, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return Canceled<TResult>(); } try { return FromResult(func()); } catch (Exception e) { return FromError<TResult>(e); } } // <summary> // Overload of RunSynchronously that avoids a call to Unwrap(). // This overload is useful when func() starts doing some synchronous work and then hits IO and // needs to create a task to finish the work. // </summary> // <typeparam name="TResult">type of result that Task will return</typeparam> // <param name="func">function that returns a task</param> // <param name="cancellationToken">cancellation token. This is only checked before we run the task, and if cancelled, we immediately return a cancelled task.</param> // <returns>a task, created by running func().</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")] internal static Task<TResult> RunSynchronously<TResult>(Func<Task<TResult>> func, CancellationToken cancellationToken = default(CancellationToken)) { if (cancellationToken.IsCancellationRequested) { return Canceled<TResult>(); } try { return func(); } catch (Exception e) { return FromError<TResult>(e); } } // <summary> // Update the completion source if the task failed (cancelled or faulted). No change to completion source if the task succeeded. // </summary> // <typeparam name="TResult">result type of completion source</typeparam> // <param name="tcs">completion source to update</param> // <param name="source">task to update from.</param> // <returns>true on success</returns> internal static bool SetIfTaskFailed<TResult>(this TaskCompletionSource<TResult> tcs, Task source) { switch (source.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: return tcs.TrySetFromTask(source); } return false; } // <summary> // Set a completion source from the given Task. // </summary> // <typeparam name="TResult">result type for completion source.</typeparam> // <param name="tcs">completion source to set</param> // <param name="source">Task to get values from.</param> // <returns>true if this successfully sets the completion source.</returns> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "This is a known safe usage of Task.Result, since it only occurs when we know the task's state to be completed.")] internal static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> tcs, Task source) { if (source.Status == TaskStatus.Canceled) { return tcs.TrySetCanceled(); } if (source.Status == TaskStatus.Faulted) { return tcs.TrySetException(source.Exception.InnerExceptions); } if (source.Status == TaskStatus.RanToCompletion) { Task<TResult> taskOfResult = source as Task<TResult>; return tcs.TrySetResult(taskOfResult == null ? default(TResult) : taskOfResult.Result); } return false; } // <summary> // Set a completion source from the given Task. If the task ran to completion and the result type doesn't match // the type of the completion source, then a default value will be used. This is useful for converting Task into // Task{AsyncVoid}, but it can also accidentally be used to introduce data loss (by passing the wrong // task type), so please execute this method with care. // </summary> // <typeparam name="TResult">result type for completion source.</typeparam> // <param name="tcs">completion source to set</param> // <param name="source">Task to get values from.</param> // <returns>true if this successfully sets the completion source.</returns> [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "This is a known safe usage of Task.Result, since it only occurs when we know the task's state to be completed.")] internal static bool TrySetFromTask<TResult>(this TaskCompletionSource<Task<TResult>> tcs, Task source) { if (source.Status == TaskStatus.Canceled) { return tcs.TrySetCanceled(); } if (source.Status == TaskStatus.Faulted) { return tcs.TrySetException(source.Exception.InnerExceptions); } if (source.Status == TaskStatus.RanToCompletion) { // Sometimes the source task is Task<Task<TResult>>, and sometimes it's Task<TResult>. // The latter usually happens when we're in the middle of a sync-block postback where // the continuation is a function which returns Task<TResult> rather than just TResult, // but the originating task was itself just Task<TResult>. An example of this can be // found in TaskExtensions.CatchImpl(). Task<Task<TResult>> taskOfTaskOfResult = source as Task<Task<TResult>>; if (taskOfTaskOfResult != null) { return tcs.TrySetResult(taskOfTaskOfResult.Result); } Task<TResult> taskOfResult = source as Task<TResult>; if (taskOfResult != null) { return tcs.TrySetResult(taskOfResult); } return tcs.TrySetResult(TaskHelpers.FromResult(default(TResult))); } return false; } // <summary> // Used as the T in a "conversion" of a Task into a Task{T} // </summary> private struct AsyncVoid { } // <summary> // This class is a convenient cache for per-type cancelled tasks // </summary> private static class CancelCache<TResult> { public static readonly Task<TResult> Canceled = GetCancelledTask(); private static Task<TResult> GetCancelledTask() { TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); tcs.SetCanceled(); return tcs.Task; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.ComponentModel; using System.Diagnostics; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Automation.Peers; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Shapes; using Windows.UI.Xaml.Markup; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace XamlCompositorCS { namespace Controls { [Bindable] public sealed class CALayerXamlAutomationPeer : FrameworkElementAutomationPeer { public CALayerXamlAutomationPeer(CALayerXaml owner) : base(owner) { } protected override string GetClassNameCore() { return "FakeClassName"; } protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.ScrollBar; } } [Bindable] public sealed class CALayerXaml : Panel, CacheableObject { internal static double screenScale = 1.0; static bool RoundInitialized = false; static double RoundPixelsPerPoint; static SolidColorBrush TransparentBrush = new SolidColorBrush(Colors.Transparent); FrameworkElement content; Rect contentsCenter = new Rect(0, 0, 1, 1); ContentGravity contentGravity = ContentGravity.Resize; private TranslateTransform InvOriginTransform; private RectangleGeometry ClipGeometry; internal bool originSet = false; internal Color backgroundColor; internal SolidColorBrush backgroundBrush = TransparentBrush; private Point _position; private Point _origin; private Size _size; private bool _createdTransforms = false; private Point _anchorPoint; private bool _masksToBounds; private bool _topMost = false; double _Opacity; bool _hidden = false; static private ObjectCache _LayerContentCache = new ObjectCache(); public void Reset() { Children.Clear(); InvalidateArrange(); content = null; contentsCenter = new Rect(0, 0, 1, 1); contentGravity = ContentGravity.Resize; Clip = null; InvOriginTransform = new TranslateTransform(); ClipGeometry = new RectangleGeometry(); ClipGeometry.Transform = InvOriginTransform; RenderTransform = new TranslateTransform(); _position = new Point(0, 0); _origin = new Point(0, 0); _size = new Size(0, 0); _hidden = false; originSet = false; _createdTransforms = false; LayerOpacity = 1.0; backgroundBrush = TransparentBrush; backgroundColor.R = 0; backgroundColor.G = 0; backgroundColor.B = 0; backgroundColor.A = 0; Set("anchorPoint", new Point(0.5, 0.5)); _masksToBounds = false; this.Background = TransparentBrush; } public double CurrentWidth { get { if (_createdTransforms) { return VisualWidth; } else { return _size.Width; } } } public double CurrentHeight { get { if (_createdTransforms) { return VisualHeight; } else { return _size.Height; } } } static public CALayerXaml CreateLayer() { CacheableObject ret = _LayerContentCache.GetCachableObject(); if (ret != null) { return (CALayerXaml)ret; } return new CALayerXaml(); } static public void DestroyLayer(CALayerXaml layer) { layer.DiscardContent(); _LayerContentCache.PushCacheableObject(layer); } static public void ApplyMagnificationFactor(Canvas windowContainer, float scale, float rotation) { TransformGroup globalTransform = new TransformGroup(); ScaleTransform windowScale = new ScaleTransform(); RotateTransform orientation = new RotateTransform(); windowScale.ScaleX = scale; windowScale.ScaleY = scale; windowScale.CenterX = windowContainer.Width / 2.0; windowScale.CenterY = windowContainer.Height / 2.0; globalTransform.Children.Add(windowScale); if (rotation != 0.0f) { orientation.Angle = rotation; orientation.CenterX = windowContainer.Width / 2.0; orientation.CenterY = windowContainer.Height / 2.0; globalTransform.Children.Add(orientation); } windowContainer.RenderTransform = globalTransform; screenScale = (double)scale; } static public double RoundCoordinate(Object coord) { if (!RoundInitialized) { RoundInitialized = true; RoundPixelsPerPoint = ((int)Windows.Graphics.Display.DisplayInformation.GetForCurrentView().ResolutionScale) / 100.0; } return Math.Floor((double)coord * screenScale * RoundPixelsPerPoint) / (screenScale * RoundPixelsPerPoint); } internal static void AddAnimation(String propertyName, UIElement target, Storyboard storyboard, DoubleAnimation copyProperties, Object fromValue, Object toValue, bool dependent = false) { DoubleAnimation posxAnim = new DoubleAnimation(); if (toValue != null) posxAnim.To = (double)toValue; if (fromValue != null) posxAnim.From = (double)fromValue; posxAnim.Duration = copyProperties.Duration; posxAnim.RepeatBehavior = copyProperties.RepeatBehavior; posxAnim.AutoReverse = copyProperties.AutoReverse; posxAnim.EasingFunction = copyProperties.EasingFunction; posxAnim.EnableDependentAnimation = dependent; posxAnim.FillBehavior = copyProperties.FillBehavior; posxAnim.BeginTime = copyProperties.BeginTime; storyboard.Children.Add(posxAnim); Storyboard.SetTarget(posxAnim, target); Storyboard.SetTargetProperty(posxAnim, propertyName); } static Object GetAnimatedTransformIndex(UIElement element, int idx, DependencyProperty property) { TransformGroup grp = (TransformGroup)element.GetValue(UIElement.RenderTransformProperty); TransformCollection children = (TransformCollection)grp.GetValue(TransformGroup.ChildrenProperty); DependencyObject transform = (DependencyObject)children[idx]; return transform.GetValue(property); } static Object GetGeneralTransformIndex(UIElement element, int idx, DependencyProperty property) { TransformGroup grp = (TransformGroup)element.GetValue(UIElement.RenderTransformProperty); TransformCollection children = (TransformCollection)grp.GetValue(TransformGroup.ChildrenProperty); TransformGroup transform = (TransformGroup)children[2]; TransformCollection generalTransformChildren = (TransformCollection)transform.GetValue(TransformGroup.ChildrenProperty); DependencyObject innerTransform = (DependencyObject)generalTransformChildren[idx]; return innerTransform.GetValue(property); } void AdjustContentOriginX(Storyboard storyboard, DoubleAnimation properties, Object fromValue, Object toValue) { if (content == null) return; if (storyboard != null) { AddAnimation("(UIElement.RenderTransform).(TranslateTransform.X)", content, storyboard, properties, fromValue != null ? (Object)fromValue : null, toValue); } else { ((TranslateTransform)content.RenderTransform).X = (double) toValue; } if (content is LayerContent) { (content as LayerContent).AdjustContentOriginX(storyboard, properties, fromValue, toValue); } } void AdjustContentOriginY(Storyboard storyboard, DoubleAnimation properties, Object fromValue, Object toValue) { if (content == null) return; if (storyboard != null) { AddAnimation("(UIElement.RenderTransform).(TranslateTransform.Y)", content, storyboard, properties, fromValue != null ? (Object)fromValue : null, toValue); } else { ((TranslateTransform)content.RenderTransform).Y = (double)toValue; } if (content is LayerContent) { (content as LayerContent).AdjustContentOriginY(storyboard, properties, fromValue, toValue); } } internal class AnimatableProperty { public delegate void ApplyAnimationFunction(CALayerXaml target, Storyboard storyboard, DoubleAnimation properties, Object fromValue, Object toValue); public delegate void ApplyTransformFunction(CALayerXaml target, Object toValue); public delegate Object GetCurrentValue(CALayerXaml target); public ApplyAnimationFunction Animate; public ApplyTransformFunction Set; public GetCurrentValue GetValue; public AnimatableProperty(ApplyAnimationFunction animFunction, ApplyTransformFunction setFunction, GetCurrentValue getValue) { Animate = animFunction; Set = setFunction; GetValue = getValue; } } internal static Dictionary<String, AnimatableProperty> animatableProperties = new Dictionary<String, AnimatableProperty> { { "position.x", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)", target, storyboard, properties, from, to); }, (target, toValue) => { target._position.X = (double)toValue; if (target._createdTransforms) { ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[3]).X = (double)toValue; } else { target.CalcTransforms(); } }, (target) => { if (!target._createdTransforms) return target._position.X; return CALayerXaml.GetAnimatedTransformIndex(target, 3, TranslateTransform.XProperty); } ) }, { "position.y", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)", target, storyboard, properties, from, to); }, (target, toValue) => { target._position.Y = (double)toValue; if (target._createdTransforms) { ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[3]).Y = (double)toValue; } else { target.CalcTransforms(); } }, (target) => { if (!target._createdTransforms) return target._position.Y; return CALayerXaml.GetAnimatedTransformIndex(target, 3, TranslateTransform.YProperty); } ) }, { "position", new AnimatableProperty( (target, storyboard, properties, from, to) => { animatableProperties["position.x"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).X : null, ((Point)to).X); animatableProperties["position.y"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).Y : null, ((Point)to).Y); }, (target, toValue) => { animatableProperties["position.x"].Set(target, ((Point)toValue).X); animatableProperties["position.y"].Set(target, ((Point)toValue).Y); }, (target) => { return new Point((double)target.Get("position.x"), (double)target.Get("position.y")); } ) }, { "origin.x", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); target.SetupBackground(); double targetFrom = from != null ? (double) from : 0.0f; double targetTo = to != null ? (double)to : 0.0f; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.X)", target, storyboard, properties,from != null ? (Object) (-targetFrom) : null, -targetTo); if (target._masksToBounds) { AddAnimation("(UIElement.Clip).(Transform).(TranslateTransform.X)", target, storyboard, properties, from != null ? (Object) targetFrom : null, targetTo); } target.AdjustContentOriginX(storyboard, properties, targetFrom, targetTo); }, (target, toValue) => { target.SetupBackground(); double targetValue = (double) toValue; targetValue = RoundCoordinate(targetValue); target._origin.X = targetValue; if (target._createdTransforms) { ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[1]).X = -targetValue; } else { target.CalcTransforms(); } if (target.Clip != null) ((TranslateTransform)target.Clip.Transform).X = targetValue; target.AdjustContentOriginX(null, null, null, targetValue); }, (target) => { if (!target._createdTransforms) return target._origin.X; return (Object) (-((double) CALayerXaml.GetAnimatedTransformIndex(target, 1, TranslateTransform.XProperty))); } ) }, { "origin.y", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); target.SetupBackground(); double targetFrom = from != null ? (double) from : 0.0f; double targetTo = to != null ? (double)to : 0.0f; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.Y)", target, storyboard, properties, from != null ? (Object) (-targetFrom) : null, -targetTo); if (target._masksToBounds) { AddAnimation("(UIElement.Clip).(Transform).(TranslateTransform.Y)", target, storyboard, properties, from != null ? (Object)(targetFrom) : null, targetTo); } target.AdjustContentOriginY(storyboard, properties, targetFrom, targetTo); }, (target, toValue) => { target.SetupBackground(); double targetValue = (double) toValue; targetValue = RoundCoordinate(targetValue); target._origin.Y = targetValue; if (target._createdTransforms) { ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[1]).Y = -targetValue; } else { target.CalcTransforms(); } if (target.Clip != null) ((TranslateTransform)target.Clip.Transform).Y = targetValue; target.AdjustContentOriginY(null, null, null, targetValue); }, (target) => { if (!target._createdTransforms) return target._origin.Y; return (Object) (-((double) CALayerXaml.GetAnimatedTransformIndex(target, 1, TranslateTransform.YProperty))); } ) }, { "origin", new AnimatableProperty( (target, storyboard, properties, from, to) => { animatableProperties["origin.x"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).X : null, ((Point)to).X); animatableProperties["origin.y"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).Y : null, ((Point)to).Y); }, (target, toValue) => { animatableProperties["origin.x"].Set(target, ((Point)toValue).X); animatableProperties["origin.y"].Set(target, ((Point)toValue).Y); }, (target) => { return new Point((double) target.Get("origin.x"), (double) target.Get("origin.y")); } ) }, { "anchorPoint.x", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); Object fromVal = from != null ? (Object)(-target._size.Width * (double)from) : null; double destVal = -target._size.Width * (double) to; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)", target, storyboard, properties, fromVal, destVal); }, (target, toValue) => { target._anchorPoint.X = (double)toValue; if (target._createdTransforms) { double destX = -target._size.Width * ((double)toValue); ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[0]).X = destX; } else { target.CalcTransforms(); } }, (target) => { return (Object) target._anchorPoint.X; } ) }, { "anchorPoint.y", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); Object fromVal = from != null ? (Object)(-target._size.Height * (double)from) : null; double destVal = -target._size.Height * (double) to; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.Y)", target, storyboard, properties, fromVal, destVal); }, (target, toValue) => { target._anchorPoint.Y = (double)toValue; if (target._createdTransforms) { double destY = -target._size.Height * ((double)toValue); ((TranslateTransform) ((TransformGroup)target.RenderTransform).Children[0]).Y = destY; } else { target.CalcTransforms(); } }, (target) => { return (Object) target._anchorPoint.Y; } ) }, { "anchorPoint", new AnimatableProperty( (target, storyboard, properties, from, to) => { animatableProperties["anchorPoint.x"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).X : null, ((Point)to).X); animatableProperties["anchorPoint.y"].Animate(target, storyboard, properties, from != null ? (Object)((Point)from).Y : null, ((Point)to).Y); }, (target, toValue) => { animatableProperties["anchorPoint.x"].Set(target, ((Point)toValue).X); animatableProperties["anchorPoint.y"].Set(target, ((Point)toValue).Y); }, (target) => { return new Point((double)target.Get("anchorPoint.x"), (double)target.Get("anchorPoint.y")); } ) }, { "size.width", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); if ( from != null ) if ( (double) from < 0.0 ) from = 0.0; if (to != null) if ((double)to < 0.0) to = 0.0; Object fromVal = from != null ? (Object)((-((double)from)) * target._anchorPoint.X) : null; double dest = -((double) to) * target._anchorPoint.X; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.X)", target, storyboard, properties, fromVal, dest); AddAnimation("(CALayerXaml.VisualWidth)", target, storyboard, properties, from, to, true); }, (target, toValue) => { if (toValue != null) if ((double)toValue < 0) toValue = 0.0; toValue = RoundCoordinate(toValue); if (target._size.Width == (double) toValue) return; target._size.Width = (double)toValue; target.Width = (double)toValue; if (target._createdTransforms) { double destX = -((double) toValue) * target._anchorPoint.X; ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[0]).X = destX; target.VisualWidth = (double)toValue; } else { target.CalcTransforms(); } target.InvalidateArrange(); }, (target) => { if (!target._createdTransforms) return target._size.Width; return target.GetValue(CALayerXaml.VisualWidthProperty); } ) }, { "size.height", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); if ( from != null ) if ( (double) from < 0.0 ) from = 0.0; if (to != null) if ((double)to < 0.0) to = 0.0; Object fromVal = from != null ? (Object)((-((double)from)) * target._anchorPoint.Y) : null; double dest = -((double) to) * target._anchorPoint.Y; AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[0].(TranslateTransform.Y)", target, storyboard, properties, fromVal, dest); AddAnimation("(CALayerXaml.VisualHeight)", target, storyboard, properties, from, to, true); }, (target, toValue) => { if (toValue != null) if ((double)toValue < 0) toValue = 0.0; toValue = RoundCoordinate(toValue); if (target._size.Height == (double)toValue) return; target._size.Height = (double)toValue; target.Height = (double)toValue; if (target._createdTransforms) { double destY = -((double) toValue) * target._anchorPoint.Y; ((TranslateTransform)((TransformGroup)target.RenderTransform).Children[0]).Y = destY; target.VisualHeight = (double)toValue; } else { target.CalcTransforms(); } target.InvalidateArrange(); }, (target) => { if (!target._createdTransforms) return target._size.Height; return target.GetValue(CALayerXaml.VisualHeightProperty); } ) }, { "size", new AnimatableProperty( (target, storyboard, properties, from, to) => { animatableProperties["size.width"].Animate(target, storyboard, properties, from != null ? (Object)((Size)from).Width : null, ((Size)to).Width); animatableProperties["size.height"].Animate(target, storyboard, properties, from != null ? (Object)((Size)from).Height : null, ((Size)to).Height); }, (target, toValue) => { animatableProperties["size.width"].Set(target, ((Size)toValue).Width); animatableProperties["size.height"].Set(target, ((Size)toValue).Height); }, (target) => { return new Size((double) target.Get("size.width"), (double) target.Get("size.height")); } ) }, { "transform.rotation", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[0].(RotateTransform.Angle)", target, storyboard, properties, from, to); }, (target, toValue) => { target.CreateTransforms(); ((RotateTransform) ((TransformGroup) ((TransformGroup)target.RenderTransform).Children[2]).Children[0]).Angle = (double) toValue; }, (target) => { if (!target._createdTransforms) return 0.0; return CALayerXaml.GetGeneralTransformIndex(target, 0, RotateTransform.AngleProperty); } ) }, { "transform.scale.x", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[1].(ScaleTransform.ScaleX)", target, storyboard, properties, from, to); }, (target, toValue) => { target.CreateTransforms(); ((ScaleTransform)((TransformGroup)((TransformGroup)target.RenderTransform).Children[2]).Children[1]).ScaleX = (double)toValue; }, (target) => { if (!target._createdTransforms) return 0.0; return CALayerXaml.GetGeneralTransformIndex(target, 1, ScaleTransform.ScaleXProperty); } ) }, { "transform.scale.y", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[1].(ScaleTransform.ScaleY)", target, storyboard, properties, from, to); }, (target, toValue) => { target.CreateTransforms(); ((ScaleTransform)((TransformGroup)((TransformGroup)target.RenderTransform).Children[2]).Children[1]).ScaleY = (double)toValue; }, (target) => { if (!target._createdTransforms) return 0.0; return CALayerXaml.GetGeneralTransformIndex(target, 1, ScaleTransform.ScaleYProperty); } ) }, { "transform.translation.x", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[2].(TranslateTransform.X)", target, storyboard, properties, from, to); }, (target, toValue) => { target.CreateTransforms(); ((TranslateTransform)((TransformGroup)((TransformGroup)target.RenderTransform).Children[2]).Children[2]).X = (double)toValue; }, (target) => { if (!target._createdTransforms) return 0.0; return CALayerXaml.GetGeneralTransformIndex(target, 2, TranslateTransform.XProperty); } ) }, { "transform.translation.y", new AnimatableProperty( (target, storyboard, properties, from, to) => { target.CreateTransforms(); AddAnimation("(UIElement.RenderTransform).(TransformGroup.Children)[2].(TransformGroup.Children)[2].(TranslateTransform.Y)", target, storyboard, properties, from, to); }, (target, toValue) => { target.CreateTransforms(); ((TranslateTransform)((TransformGroup)((TransformGroup)target.RenderTransform).Children[2]).Children[2]).Y = (double)toValue; }, (target) => { if (!target._createdTransforms) return 0.0; return CALayerXaml.GetGeneralTransformIndex(target, 2, TranslateTransform.YProperty); } ) }, { "opacity", new AnimatableProperty( (target, storyboard, properties, from, to) => { AddAnimation("(UIElement.Opacity)", target, storyboard, properties, from, to); }, (target, toValue) => { target._Opacity = (double)toValue; target.SetOpacity(); }, (target) => { return target._Opacity; } ) }, { "gravity", new AnimatableProperty( null, (target, toValue) => { target.SetContentGravity((ContentGravity)(int)toValue); }, (target) => { return (int) target.contentGravity; } ) }, { "masksToBounds", new AnimatableProperty( null, (target, toValue) => { target._masksToBounds = (bool)toValue; target.Clip = target._masksToBounds ? target.ClipGeometry : null; }, (target) => { return target._masksToBounds; } ) } }; void CalcTransforms() { if (!_createdTransforms) { Point destTranslation; destTranslation.X = -_size.Width * _anchorPoint.X; destTranslation.Y = -_size.Height * _anchorPoint.Y; destTranslation.X -= _origin.X; destTranslation.Y -= _origin.Y; destTranslation.X += _position.X; destTranslation.Y += _position.Y; ((TranslateTransform)RenderTransform).X = destTranslation.X; ((TranslateTransform)RenderTransform).Y = destTranslation.Y; } } void CreateTransforms() { if (!_createdTransforms) { TranslateTransform SizeAnchorTransform = new TranslateTransform(); SizeAnchorTransform.X = -_size.Width * _anchorPoint.X; SizeAnchorTransform.Y = -_size.Height * _anchorPoint.Y; TranslateTransform OriginTransform = new TranslateTransform(); OriginTransform.X = -_origin.X; OriginTransform.Y = -_origin.Y; TransformGroup ContentTransform = new TransformGroup(); ContentTransform.Children.Add(new RotateTransform()); ContentTransform.Children.Add(new ScaleTransform()); ContentTransform.Children.Add(new TranslateTransform()); TranslateTransform PositionTransform = new TranslateTransform(); PositionTransform.X = _position.X; PositionTransform.Y = _position.Y; TransformGroup LayerTransforms = new TransformGroup(); LayerTransforms.Children.Add(SizeAnchorTransform); LayerTransforms.Children.Add(OriginTransform); LayerTransforms.Children.Add(ContentTransform); LayerTransforms.Children.Add(PositionTransform); RenderTransform = LayerTransforms; VisualWidth = _size.Width; VisualHeight = _size.Height; _createdTransforms = true; if (_createdTransforms) CAXamlDebugCounters.IncCounter("CALayerXamlTransforms"); } } public void Set(string propertyName, Object value) { animatableProperties[propertyName].Set(this, value); } public Object Get(string propertyName) { return animatableProperties[propertyName].GetValue(this); } void SetOpacity() { if (_hidden) { this.Opacity = 0.0; } else { this.Opacity = _Opacity; } } public double LayerOpacity { set { _Opacity = value; SetOpacity(); } get { return _Opacity; } } public bool hidden { set { _hidden = value; SetOpacity(); } get { return _hidden; } } /* Disable for now protected override AutomationPeer OnCreateAutomationPeer() { return new CALayerXamlAutomationPeer(this); } */ public static void SizeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((CALayerXaml)d).InvalidateArrange(); } private static readonly DependencyProperty _VisualWidthProperty = DependencyProperty.Register( "VisualWidth", typeof(double), typeof(CALayerXaml), new PropertyMetadata(0.0, SizeChangedCallback) ); private static readonly DependencyProperty _VisualHeightProperty = DependencyProperty.Register( "VisualHeight", typeof(double), typeof(CALayerXaml), new PropertyMetadata(0.0, SizeChangedCallback) ); public static DependencyProperty VisualWidthProperty { get { return _VisualWidthProperty; } } public static DependencyProperty VisualHeightProperty { get { return _VisualHeightProperty; } } public double VisualWidth { get { return (double)GetValue(VisualWidthProperty); } set { SetValue(VisualWidthProperty, value); } } public double VisualHeight { get { return (double)GetValue(VisualHeightProperty); } set { SetValue(VisualHeightProperty, value); } } public CALayerXaml() { CAXamlDebugCounters.IncCounter("CALayerXaml"); InvOriginTransform = new TranslateTransform(); ClipGeometry = new RectangleGeometry(); ClipGeometry.Transform = InvOriginTransform; RenderTransform = new TranslateTransform(); Set("anchorPoint", new Point(0.5, 0.5)); LayerOpacity = 1.0; this.Background = TransparentBrush; this.PointerPressed += CALayerXaml_PointerPressed; this.PointerReleased += CALayerXaml_PointerReleased; this.PointerMoved += CALayerXaml_PointerMoved; this.PointerCanceled += CALayerXaml_PointerCanceled; this.IsHitTestVisible = true; } ~CALayerXaml() { CAXamlDebugCounters.DecCounter("CALayerXaml"); if (_createdTransforms) CAXamlDebugCounters.DecCounter("CALayerXamlTransforms"); } internal void CopyPropertiesFrom(CALayerXaml fromLayer) { Set("opacity", fromLayer.Get("opacity")); Set("position", fromLayer.Get("position")); Set("size", fromLayer.Get("size")); Set("anchorPoint", fromLayer.Get("anchorPoint")); } void CALayerXaml_PointerPressed(object sender, PointerRoutedEventArgs e) { CapturePointer(e.Pointer); CALayerInputHandler.HandleDownInput(this, e); e.Handled = true; } void CALayerXaml_PointerReleased(object sender, PointerRoutedEventArgs e) { CALayerInputHandler.HandleUpInput(this, e); e.Handled = true; } void CALayerXaml_PointerCanceled(object sender, PointerRoutedEventArgs e) { CALayerInputHandler.HandleUpInput(this, e); e.Handled = true; } void CALayerXaml_PointerMoved(object sender, PointerRoutedEventArgs e) { CALayerInputHandler.HandleMoveInput(this, e); e.Handled = true; } public void DiscardContent() { if (content != null) { Children.Remove(content); InvalidateArrange(); if (content is LayerContent) { LayerContent.DestroyLayerContent((LayerContent)content); } content = null; } } void SetContent(FrameworkElement element) { if (content == element) return; DiscardContent(); content = element; if (element != null) { content.RenderTransform = InvOriginTransform; this.Children.Insert(0, content); InvalidateArrange(); } } LayerContent GetImageContent(bool create = false) { if (!(content is LayerContent)) { if (!create) return null; LayerContent imageContent = LayerContent.CreateLayerContent(); imageContent.SetGravity(contentGravity); imageContent.SetContentsCenter(contentsCenter); imageContent.Background = backgroundBrush; imageContent.AdjustContentOriginX(null, null, null, _origin.X); imageContent.AdjustContentOriginY(null, null, null, _origin.Y); this.Background = TransparentBrush; SetContent(imageContent); } return (LayerContent)content; } public void SetContentGravity(ContentGravity gravity) { contentGravity = gravity; if (GetImageContent() != null) { GetImageContent().SetGravity(gravity); } } public void SetContentsCenter(Rect rect) { contentsCenter = rect; if (GetImageContent() != null) { GetImageContent().SetContentsCenter(contentsCenter); } } public void SetupBackground() { if (content == null) { Rectangle rect; rect = new Rectangle(); SetContent(rect); } if (content is Rectangle) { (content as Rectangle).Fill = backgroundBrush; } else { (content as Panel).Background = backgroundBrush; } } public void SetBackgroundColor(float r, float g, float b, float a) { backgroundColor.R = (byte)(r * 255.0); backgroundColor.G = (byte)(g * 255.0); backgroundColor.B = (byte)(b * 255.0); backgroundColor.A = (byte)(a * 255.0); if (backgroundColor.A == 0) { backgroundBrush = TransparentBrush; } else { backgroundBrush = new SolidColorBrush(backgroundColor); } SetupBackground(); } public void SetTopMost() { _topMost = true; SetContent(null); this.Background = null; } public void setContentImage(ImageSource source, float width, float height, float scale) { if (source == null) { if (content is LayerContent) { SetContent(null); SetupBackground(); } } else { LayerContent c = GetImageContent(true); c.SetImageContent(source, (int) width, (int) height); c.SetImageParams(width, height, scale); } } public void setContentElement(FrameworkElement elem, float width, float height, float scale) { if (elem == null) { if (content is LayerContent) { SetContent(null); SetupBackground(); } } else { LayerContent c = GetImageContent(true); c.SetGravity(ContentGravity.Left); c.SetElementContent(elem); c.SetImageParams(width, height, scale); } } protected override Size ArrangeOverride(Size finalSize) { double curWidth = CurrentWidth; double curHeight = CurrentHeight; if (ClipGeometry.Rect.Width != curWidth || ClipGeometry.Rect.Height != curHeight) { ClipGeometry.Rect = new Rect(0, 0, curWidth, curHeight); } if (content != null) { content.Width = curWidth; content.Height = curHeight; content.Arrange(new Rect(0, 0, curWidth, curHeight)); } foreach (UIElement curChild in Children) { if (curChild == content) continue; CALayerXaml subLayer = curChild as CALayerXaml; if (subLayer != null) { subLayer.Arrange(new Rect(0, 0, 1.0, 1.0)); } } Size ret; if (Parent is CALayerXaml) { ret = new Size(1, 1); } else { ret = new Size(curWidth, curHeight); } return ret; } protected override Size MeasureOverride(Size availableSize) { return _size; } } public delegate void AnimationMethod(Object sender); public sealed class EventedStoryboard { Storyboard _container = new Storyboard(); AnimationMethod _Completed; AnimationMethod _Started; bool aborted = false; public EventedStoryboard() { // AppxManifest.xml appears to fail to enumerate runtimeclasses with accessors and no default constructor in the Win8.1 SDK. throw new InvalidOperationException("Do not use the default constructor; this is merely here as a bug fix."); } class Animation { internal string propertyName; internal Object toValue; } List<Animation> Animations = new List<Animation>(); CALayerXaml AnimatedLayer; public AnimationMethod Completed { get { return _Completed; } set { _Completed = value; } } public AnimationMethod Started { get { return _Started; } set { _Started = value; } } public void Start() { _container.Begin(); } public void Abort() { aborted = true; foreach (Animation curAnim in Animations) { Object curValue = CALayerXaml.animatableProperties[curAnim.propertyName].GetValue(AnimatedLayer); CALayerXaml.animatableProperties[curAnim.propertyName].Set(AnimatedLayer, curValue); } } internal void CreateFlip(CALayerXaml layer, bool flipRight, bool invert, bool removeFromParent) { if (layer.Projection == null) { layer.Projection = new PlaneProjection(); } DoubleAnimation rotateAnim = new DoubleAnimation(); rotateAnim.Duration = _container.Duration; if (!invert) { rotateAnim.From = 0.01; if (!flipRight) { rotateAnim.To = 180; } else { rotateAnim.To = -180; } } else { if (!flipRight) { rotateAnim.From = 180; rotateAnim.To = 360; } else { rotateAnim.From = -180; rotateAnim.To = -360; } } ((PlaneProjection)layer.Projection).CenterOfRotationX = layer.CurrentWidth / 2; ((PlaneProjection)layer.Projection).CenterOfRotationY = layer.CurrentHeight / 2; Storyboard.SetTargetProperty(rotateAnim, "(UIElement.Projection).(PlaneProjection.RotationY)"); Storyboard.SetTarget(rotateAnim, layer); _container.Children.Add(rotateAnim); DoubleAnimation moveAnim = new DoubleAnimation(); moveAnim.Duration = _container.Duration; moveAnim.From = 0.01; moveAnim.To = -160; moveAnim.SpeedRatio = 2.0; moveAnim.AutoReverse = true; Storyboard.SetTarget(moveAnim, layer); Storyboard.SetTargetProperty(moveAnim, "(UIElement.Projection).(PlaneProjection.GlobalOffsetZ)"); _container.Children.Add(moveAnim); DoubleAnimation fade1 = new DoubleAnimation(); Storyboard.SetTarget(fade1, layer); Storyboard.SetTargetProperty(fade1, "(UIElement.Opacity)"); if (!invert) { fade1.Duration = TimeSpan.FromSeconds(_container.Duration.TimeSpan.TotalSeconds / 2.0); fade1.From = 1.0; fade1.To = 0.5; fade1.FillBehavior = FillBehavior.HoldEnd; } else { fade1.Duration = TimeSpan.FromSeconds(_container.Duration.TimeSpan.TotalSeconds / 2.0); fade1.BeginTime = TimeSpan.FromSeconds(_container.Duration.TimeSpan.TotalSeconds / 2.0); fade1.From = 0.5; fade1.To = 1.0; fade1.FillBehavior = FillBehavior.HoldEnd; fade1.Completed += (Object sender, Object args) => { layer.Opacity = 1.0; }; } if (removeFromParent) { fade1.Completed += (Object sender, Object args) => { VisualTreeHelper.DisconnectChildrenRecursive(layer); //CALayerXaml.DestroyLayer(layer); }; } _container.Children.Add(fade1); } internal void CreateWoosh(CALayerXaml layer, bool fromRight, bool invert, bool removeFromParent) { if (layer.Projection == null) { layer.Projection = new PlaneProjection(); } DoubleAnimation rotateAnim = new DoubleAnimation(); rotateAnim.Duration = _container.Duration; rotateAnim.EasingFunction = new PowerEase(); rotateAnim.EasingFunction.EasingMode = EasingMode.EaseOut; if (!invert) { if (fromRight) { rotateAnim.From = layer.CurrentWidth; rotateAnim.To = 0.01; } else { rotateAnim.From = 0.01; rotateAnim.To = layer.CurrentWidth; } } else { if (fromRight) { rotateAnim.From = 0.01; rotateAnim.To = -layer.CurrentWidth / 4; } else { rotateAnim.From = -layer.CurrentWidth / 4; rotateAnim.To = 0.01; } } Storyboard.SetTargetProperty(rotateAnim, "(UIElement.Projection).(PlaneProjection.LocalOffsetX)"); Storyboard.SetTarget(rotateAnim, layer); if (removeFromParent) { rotateAnim.Completed += (Object sender, Object args) => { VisualTreeHelper.DisconnectChildrenRecursive(layer); //CALayerXaml.DestroyLayer(layer); }; } _container.Children.Add(rotateAnim); } public IAsyncOperation<int> AddTransition(CALayerXaml layer, String type, String subtype) { return DoAddTransition(layer, type, subtype).AsAsyncOperation<int>(); } async private Task<int> DoAddTransition(CALayerXaml layer, String type, String subtype) { RenderTargetBitmap copiedLayer = new RenderTargetBitmap(); double scale = CALayerXaml.screenScale; await copiedLayer.RenderAsync(layer, (int)(layer.CurrentWidth * scale), 0); CALayerXaml newLayer = CALayerXaml.CreateLayer(); newLayer.CopyPropertiesFrom(layer); int width = copiedLayer.PixelWidth; int height = copiedLayer.PixelHeight; newLayer.setContentImage(copiedLayer, (float)width, (float)height, (float)scale); newLayer.SetContentGravity(ContentGravity.ResizeAspectFill); if (type == "kCATransitionFlip") { _container.Duration = new Duration(TimeSpan.FromSeconds(0.75)); Panel parent = (Panel)VisualTreeHelper.GetParent(layer); int idx = parent.Children.IndexOf(layer); parent.Children.Insert(idx + 1, newLayer); parent.InvalidateArrange(); layer.Opacity = 0; bool flipToLeft = true; if (subtype != "kCATransitionFromLeft") { flipToLeft = false; } CreateFlip(newLayer, flipToLeft, false, true); CreateFlip(layer, flipToLeft, true, false); } else { _container.Duration = new Duration(TimeSpan.FromSeconds(0.5)); Panel parent = (Panel)VisualTreeHelper.GetParent(layer); int idx = parent.Children.IndexOf(layer); bool fromRight = true; if (subtype == "kCATransitionFromLeft") { fromRight = false; } if (fromRight) { parent.Children.Insert(idx, newLayer); parent.InvalidateArrange(); CreateWoosh(newLayer, fromRight, true, true); CreateWoosh(layer, fromRight, false, false); } else { parent.Children.Insert(idx + 1, newLayer); parent.InvalidateArrange(); CreateWoosh(newLayer, fromRight, false, true); CreateWoosh(layer, fromRight, true, false); } } return 0; } enum EasingFunction { EastInEaseIn, Linear } private EasingFunctionBase _AnimationEase; public EasingFunctionBase AnimationEase { set { _AnimationEase = value; } get { return _AnimationEase; } } public void Animate(CALayerXaml layer, String propertyName, Object from, Object to) { DoubleAnimation timeline = new DoubleAnimation(); timeline.Duration = _container.Duration; timeline.EasingFunction = _AnimationEase; CALayerXaml.animatableProperties[propertyName].Animate(layer, _container, timeline, from, to); } public EventedStoryboard(double beginTime, double duration, bool autoReverse, float repeatCount, float repeatDuration, float speed, double timeOffset) { _container.BeginTime = TimeSpan.FromSeconds(beginTime); _container.Duration = TimeSpan.FromSeconds(duration); if (repeatCount != 0) { _container.RepeatBehavior = new RepeatBehavior(repeatCount); } if (repeatDuration != 0) { _container.RepeatBehavior = new RepeatBehavior(TimeSpan.FromSeconds(repeatDuration)); } _container.SpeedRatio = speed; _container.AutoReverse = autoReverse; _container.FillBehavior = FillBehavior.HoldEnd; _container.Completed += (a, b) => { if (Completed != null) Completed(this); _container.Stop(); }; TimeSpan span = _container.BeginTime.Value; Windows.System.Threading.ThreadPoolTimer beginTimer = Windows.System.Threading.ThreadPoolTimer.CreateTimer( (handler) => { _container.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.High, () => { if (Started != null) Started(this); }); }, _container.BeginTime.Value); } public Object GetStoryboard() { return _container; } } public interface CALayerXamlInputEvents { void PointerDown(float x, float y, uint id, ulong timestamp); void PointerUp(float x, float y, uint id, ulong timestamp); void PointerMoved(float x, float y, uint id, ulong timestamp); void KeyDown(uint key); } public sealed class CAXamlDebugCounters : Canvas { class Counter { public string name; public int count; public TextBlock textOutput; public bool _updating = false; public int idx; public void UpdateText() { if (!_updating) { _updating = true; CAXamlDebugCounters._singleton.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { if (textOutput == null) { textOutput = new TextBlock(); textOutput.FontSize = 14; textOutput.Text = name; textOutput.SetValue(Canvas.LeftProperty, 0); textOutput.SetValue(Canvas.TopProperty, 30 + idx * 17.0); CAXamlDebugCounters._singleton.Children.Add(textOutput); CAXamlDebugCounters._singleton.InvalidateArrange(); CAXamlDebugCounters._singleton.InvalidateMeasure(); } _updating = false; textOutput.Text = String.Format("{0}: {1}", name, count); }); } } } static internal CAXamlDebugCounters _singleton; Dictionary<String, Counter> _Counters = new Dictionary<string, Counter>(); Counter GetCounter(string name) { Counter curCounter; if (!_Counters.ContainsKey(name)) { curCounter = new Counter(); curCounter.count = 0; curCounter.name = name; curCounter.idx = _Counters.Count; _Counters[name] = curCounter; } else curCounter = _Counters[name]; return curCounter; } static public void IncCounter(string name) { if (_singleton != null) _singleton.IncrementCounter(name); } static public void DecCounter(string name) { if (_singleton != null) _singleton.DecrementCounter(name); } public void IncrementCounter(string name) { Counter curCounter = GetCounter(name); curCounter.count++; curCounter.UpdateText(); } public void DecrementCounter(string name) { Counter curCounter = GetCounter(name); curCounter.count--; curCounter.UpdateText(); } public CAXamlDebugCounters() { //_singleton = this; } } public sealed class CALayerInputHandler { internal static UIElement rootPane; static CALayerXamlInputEvents InputEventHandler; static Control DummyFocus; static internal void HandleDownInput(CALayerXaml layer, PointerRoutedEventArgs e) { CALayerXaml rootLayer = layer; while (rootLayer.Parent is CALayerXaml) { rootLayer = (rootLayer.Parent as CALayerXaml); } Windows.UI.Input.PointerPoint point = e.GetCurrentPoint(rootLayer); InputEventHandler.PointerDown((float)point.Position.X, (float)point.Position.Y, point.PointerId, point.Timestamp); if (DummyFocus == null) { DummyFocus = new UserControl(); DummyFocus.Width = 0; DummyFocus.Height = 0; DummyFocus.IsTabStop = true; ((Panel)rootLayer.Parent).Children.Add(DummyFocus); } DummyFocus.Focus(FocusState.Keyboard); } static internal void HandleUpInput(CALayerXaml layer, PointerRoutedEventArgs e) { CALayerXaml rootLayer = layer; while (rootLayer.Parent is CALayerXaml) { rootLayer = (rootLayer.Parent as CALayerXaml); } Windows.UI.Input.PointerPoint point = e.GetCurrentPoint(rootLayer); InputEventHandler.PointerUp((float)point.Position.X, (float)point.Position.Y, point.PointerId, point.Timestamp); } static internal void HandleMoveInput(CALayerXaml layer, PointerRoutedEventArgs e) { CALayerXaml rootLayer = layer; while (rootLayer.Parent is CALayerXaml) { rootLayer = (rootLayer.Parent as CALayerXaml); } Windows.UI.Input.PointerPoint point = e.GetCurrentPoint(rootLayer); InputEventHandler.PointerMoved((float)point.Position.X, (float)point.Position.Y, point.PointerId, point.Timestamp); } static public void SetInputHandler(CALayerXamlInputEvents handler) { InputEventHandler = handler; Window.Current.CoreWindow.CharacterReceived += CoreWindow_CharacterReceived; } static void CoreWindow_CharacterReceived(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.CharacterReceivedEventArgs args) { InputEventHandler.KeyDown((uint)args.KeyCode); } } public interface CacheableObject { void Reset(); } internal class ObjectCache { Queue<CacheableObject> _objects = new Queue<CacheableObject>(); int _maxSize; public ObjectCache(int maxSize = 32) { _maxSize = maxSize; } public CacheableObject GetCachableObject() { if (_objects.Count == 0) return null; return _objects.Dequeue(); } public void PushCacheableObject(CacheableObject obj) { obj.Reset(); if (_objects.Count >= _maxSize) return; _objects.Enqueue(obj); } } public sealed class CATextLayerXaml : CacheableObject { public TextBlock TextBlock { get { return _TextBlock; } } TextBlock _TextBlock = new TextBlock(); public void Reset() { TextBlock.Text = ""; TextBlock.Width = Double.NaN; TextBlock.Height = Double.NaN; } static private ObjectCache _TextLayerCache = new ObjectCache(); static public CATextLayerXaml CreateTextLayer() { CacheableObject ret = _TextLayerCache.GetCachableObject(); if (ret != null) { return (CATextLayerXaml)ret; } return new CATextLayerXaml(); } static public void DestroyTextLayer(CATextLayerXaml content) { _TextLayerCache.PushCacheableObject(content); } } public enum ContentGravity { Resize = 0, Center, Top, ResizeAspect, TopLeft, BottomLeft, Left, ResizeAspectFill, Bottom, TopRight, Right, BottomRight } public sealed class LayerContent : Panel, CacheableObject { private Image image; private FrameworkElement content; private Size imageSize; private Size contentSize = new Size(0, 0); private Rect contentsCenter = new Rect(0, 0, 1.0, 1.0); private ContentGravity gravity; private float scaleFactor; private Point origin = new Point(); static private ObjectCache _LayerContentCache = new ObjectCache(); public void Reset() { Children.Clear(); image = null; content = null; imageSize = new Size(0, 0); contentSize = new Size(0, 0); contentsCenter = new Rect(0, 0, 1.0, 1.0); gravity = ContentGravity.Resize; scaleFactor = 1.0f; origin = new Point(); } static public LayerContent CreateLayerContent() { CacheableObject ret = _LayerContentCache.GetCachableObject(); if (ret != null) { return (LayerContent)ret; } return new LayerContent(); } static public void DestroyLayerContent(LayerContent content) { _LayerContentCache.PushCacheableObject(content); } public LayerContent() { gravity = ContentGravity.Resize; scaleFactor = 1.0f; CAXamlDebugCounters.IncCounter("LayerContent"); } ~LayerContent() { CAXamlDebugCounters.DecCounter("LayerContent"); } void ApplyContentsCenter() { if (image == null) { return; } if (image.Source == null) { return; } if (contentsCenter.X == 0.0 && contentsCenter.Y == 0.0 && contentsCenter.Width == 1.0 && contentsCenter.Height == 1.0) { image.NineGrid = new Thickness(0, 0, 0, 0); } else { int left = (int)(contentsCenter.X * imageSize.Width); int top = (int)(contentsCenter.Y * imageSize.Height); int right = ((int)imageSize.Width) - (left + ((int)(contentsCenter.Width * imageSize.Width))); int bottom = ((int)imageSize.Height) - (top + ((int)(contentsCenter.Height * imageSize.Height))); /* left--; top--; right--; bottom--; */ image.NineGrid = new Thickness(left, top, right, bottom); } } Rect GetContentGravityRect(Size size) { double left = 0, top = 0, width = 0, height = 0; // Top/bottom switched due to geometric origin switch (gravity) { case ContentGravity.Center: left = size.Width / 2 - contentSize.Width / 2; top = size.Height / 2 - contentSize.Height / 2; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.Top: left = size.Width / 2 - contentSize.Width / 2; top = size.Height - contentSize.Height; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.Bottom: left = size.Width / 2 - contentSize.Width / 2; top = 0; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.Left: left = 0; top = size.Height / 2 - contentSize.Height / 2; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.Right: left = size.Width - contentSize.Width; top = size.Height / 2 - contentSize.Height / 2; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.TopLeft: left = 0; top = size.Height - contentSize.Height; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.TopRight: left = size.Width - contentSize.Width; top = size.Height - contentSize.Height; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.BottomLeft: left = 0; top = 0; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.BottomRight: left = size.Width - contentSize.Width; top = 0; width = contentSize.Width; height = contentSize.Height; break; case ContentGravity.Resize: left = 0; top = 0; width = size.Width; height = size.Height; break; case ContentGravity.ResizeAspect: left = 0; top = 0; width = size.Width; height = size.Height; if ( image != null ) image.Stretch = Stretch.Uniform; break; case ContentGravity.ResizeAspectFill: left = 0; top = 0; width = size.Width; height = size.Height; if (image != null) image.Stretch = Stretch.UniformToFill; break; } return new Rect(left, top, width, height); } Image GetImage() { if (image == null) { image = new Image(); image.Stretch = Stretch.Fill; scaleFactor = 1.0f; } SetElementContent(image); return image; } public void SetContentsCenter(Rect rect) { contentsCenter = rect; ApplyContentsCenter(); } public void SetGravity(ContentGravity imgGravity) { gravity = imgGravity; InvalidateArrange(); } public void SetImageContent(ImageSource source, int width, int height) { if (source == null) { SetElementContent(null); return; } var imgContents = GetImage(); if (source is BitmapSource) { imageSize = new Size(width, height); } else { imageSize = new Size(0, 0); } imgContents.Source = source; ApplyContentsCenter(); } internal void AdjustContentOriginX(Storyboard storyboard, DoubleAnimation properties, Object fromValue, Object toValue) { if (toValue != null) { toValue = -((double)toValue); origin.X = (double)toValue; } if (image != null || content == null) return; InvalidateArrange(); } internal void AdjustContentOriginY(Storyboard storyboard, DoubleAnimation properties, Object fromValue, Object toValue) { if (toValue != null) { toValue = -((double)toValue); origin.Y = (double)toValue; } if (image != null || content == null) return; InvalidateArrange(); } public void SetElementContent(FrameworkElement source) { if (content == source) return; if (content != null) { Children.Remove(content); content = null; image = null; } if (source != null) { content = source; Children.Add(content); InvalidateArrange(); imageSize = new Size(0, 0); } } public void SetImageParams(float width, float height, float scale) { Size oldSize = contentSize; float oldScale = scale; contentSize = new Size(width / scale, height / scale); if (scaleFactor <= 0.0) scaleFactor = 1.0f; if (scaleFactor != scale) { scaleFactor = scale; if (image != null) { if (scaleFactor != 1.0f) { ScaleTransform trans = new ScaleTransform(); trans.ScaleX = 1.0 / scaleFactor; trans.ScaleY = 1.0 / scaleFactor; image.RenderTransform = trans; } else { image.RenderTransform = null; } } } if (oldScale != scaleFactor || oldSize != contentSize) { InvalidateArrange(); } } protected override Size ArrangeOverride(Size finalSize) { if (content != null) { Rect newSize = GetContentGravityRect(finalSize); if (image != null) { content.Width = newSize.Width * scaleFactor; content.Height = newSize.Height * scaleFactor; } else { double contentWidth = newSize.Width - origin.X; double contentHeight = newSize.Height - origin.Y; if (contentWidth < 0.0) contentWidth = 0.0; if (contentHeight < 0.0) contentHeight = 0.0; content.Width = contentWidth; content.Height = contentHeight; } content.Arrange(new Rect(newSize.Left + origin.X, newSize.Top + origin.Y, content.Width, content.Height)); } return finalSize; } protected override Size MeasureOverride(Size availableSize) { return availableSize; } } } }
using System.Text; /* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace com.google.zxing.client.result { /// <summary> /// @author Sean Owen /// </summary> public sealed class AddressBookParsedResult : ParsedResult { private readonly string[] names; private readonly string pronunciation; private readonly string[] phoneNumbers; private readonly string[] phoneTypes; private readonly string[] emails; private readonly string[] emailTypes; private readonly string instantMessenger; private readonly string note; private readonly string[] addresses; private readonly string[] addressTypes; private readonly string org; private readonly string birthday; private readonly string title; private readonly string url; public AddressBookParsedResult(string[] names, string pronunciation, string[] phoneNumbers, string[] phoneTypes, string[] emails, string[] emailTypes, string instantMessenger, string note, string[] addresses, string[] addressTypes, string org, string birthday, string title, string url) : base(ParsedResultType.ADDRESSBOOK) { this.names = names; this.pronunciation = pronunciation; this.phoneNumbers = phoneNumbers; this.phoneTypes = phoneTypes; this.emails = emails; this.emailTypes = emailTypes; this.instantMessenger = instantMessenger; this.note = note; this.addresses = addresses; this.addressTypes = addressTypes; this.org = org; this.birthday = birthday; this.title = title; this.url = url; } public string[] Names { get { return names; } } /// <summary> /// In Japanese, the name is written in kanji, which can have multiple readings. Therefore a hint /// is often provided, called furigana, which spells the name phonetically. /// </summary> /// <returns> The pronunciation of the getNames() field, often in hiragana or katakana. </returns> public string Pronunciation { get { return pronunciation; } } public string[] PhoneNumbers { get { return phoneNumbers; } } /// <returns> optional descriptions of the type of each phone number. It could be like "HOME", but, /// there is no guaranteed or standard format. </returns> public string[] PhoneTypes { get { return phoneTypes; } } public string[] Emails { get { return emails; } } /// <returns> optional descriptions of the type of each e-mail. It could be like "WORK", but, /// there is no guaranteed or standard format. </returns> public string[] EmailTypes { get { return emailTypes; } } public string InstantMessenger { get { return instantMessenger; } } public string Note { get { return note; } } public string[] Addresses { get { return addresses; } } /// <returns> optional descriptions of the type of each e-mail. It could be like "WORK", but, /// there is no guaranteed or standard format. </returns> public string[] AddressTypes { get { return addressTypes; } } public string Title { get { return title; } } public string Org { get { return org; } } public string URL { get { return url; } } /// <returns> birthday formatted as yyyyMMdd (e.g. 19780917) </returns> public string Birthday { get { return birthday; } } public override string DisplayResult { get { StringBuilder result = new StringBuilder(100); maybeAppend(names, result); maybeAppend(pronunciation, result); maybeAppend(title, result); maybeAppend(org, result); maybeAppend(addresses, result); maybeAppend(phoneNumbers, result); maybeAppend(emails, result); maybeAppend(instantMessenger, result); maybeAppend(url, result); maybeAppend(birthday, result); maybeAppend(note, result); return result.ToString(); } } } }
#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 // .NET Compact Framework 1.0 has no support for System.Web.Mail // SSCLI 1.0 has no support for System.Web.Mail #if !NETCF && !SSCLI using System; using System.IO; using System.Text; #if NET_2_0 || MONO_2_0 using System.Net.Mail; #else using System.Web.Mail; #endif using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Send an e-mail when a specific logging event occurs, typically on errors /// or fatal errors. /// </summary> /// <remarks> /// <para> /// The number of logging events delivered in this e-mail depend on /// the value of <see cref="BufferingAppenderSkeleton.BufferSize"/> option. The /// <see cref="SmtpAppender"/> keeps only the last /// <see cref="BufferingAppenderSkeleton.BufferSize"/> logging events in its /// cyclic buffer. This keeps memory requirements at a reasonable level while /// still delivering useful application context. /// </para> /// <note type="caution"> /// Authentication and setting the server Port are only available on the MS .NET 1.1 runtime. /// For these features to be enabled you need to ensure that you are using a version of /// the log4net assembly that is built against the MS .NET 1.1 framework and that you are /// running the your application on the MS .NET 1.1 runtime. On all other platforms only sending /// unauthenticated messages to a server listening on port 25 (the default) is supported. /// </note> /// <para> /// Authentication is supported by setting the <see cref="Authentication"/> property to /// either <see cref="SmtpAuthentication.Basic"/> or <see cref="SmtpAuthentication.Ntlm"/>. /// If using <see cref="SmtpAuthentication.Basic"/> authentication then the <see cref="Username"/> /// and <see cref="Password"/> properties must also be set. /// </para> /// <para> /// To set the SMTP server port use the <see cref="Port"/> property. The default port is 25. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class SmtpAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public SmtpAppender() { } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses (use semicolon on .NET 1.1 and comma for later versions). /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string To { get { return m_to; } set { m_to = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets a comma- or semicolon-delimited list of recipient e-mail addresses /// that will be carbon copied (use semicolon on .NET 1.1 and comma for later versions). /// </summary> /// <value> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </value> /// <remarks> /// <para> /// For .NET 1.1 (System.Web.Mail): A semicolon-delimited list of e-mail addresses. /// </para> /// <para> /// For .NET 2.0 (System.Net.Mail): A comma-delimited list of e-mail addresses. /// </para> /// </remarks> public string Cc { get { return m_cc; } set { m_cc = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets a semicolon-delimited list of recipient e-mail addresses /// that will be blind carbon copied. /// </summary> /// <value> /// A semicolon-delimited list of e-mail addresses. /// </value> /// <remarks> /// <para> /// A semicolon-delimited list of recipient e-mail addresses. /// </para> /// </remarks> public string Bcc { get { return m_bcc; } set { m_bcc = MaybeTrimSeparators(value); } } /// <summary> /// Gets or sets the e-mail address of the sender. /// </summary> /// <value> /// The e-mail address of the sender. /// </value> /// <remarks> /// <para> /// The e-mail address of the sender. /// </para> /// </remarks> public string From { get { return m_from; } set { m_from = value; } } /// <summary> /// Gets or sets the subject line of the e-mail message. /// </summary> /// <value> /// The subject line of the e-mail message. /// </value> /// <remarks> /// <para> /// The subject line of the e-mail message. /// </para> /// </remarks> public string Subject { get { return m_subject; } set { m_subject = value; } } /// <summary> /// Gets or sets the name of the SMTP relay mail server to use to send /// the e-mail messages. /// </summary> /// <value> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </value> /// <remarks> /// <para> /// The name of the e-mail relay server. If SmtpServer is not set, the /// name of the local SMTP server is used. /// </para> /// </remarks> public string SmtpHost { get { return m_smtpHost; } set { m_smtpHost = value; } } /// <summary> /// Obsolete /// </summary> /// <remarks> /// Use the BufferingAppenderSkeleton Fix methods instead /// </remarks> /// <remarks> /// <para> /// Obsolete property. /// </para> /// </remarks> [Obsolete("Use the BufferingAppenderSkeleton Fix methods. Scheduled removal in v10.0.0.")] public bool LocationInfo { get { return false; } set { ; } } /// <summary> /// The mode to use to authentication with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// Valid Authentication mode values are: <see cref="SmtpAuthentication.None"/>, /// <see cref="SmtpAuthentication.Basic"/>, and <see cref="SmtpAuthentication.Ntlm"/>. /// The default value is <see cref="SmtpAuthentication.None"/>. When using /// <see cref="SmtpAuthentication.Basic"/> you must specify the <see cref="Username"/> /// and <see cref="Password"/> to use to authenticate. /// When using <see cref="SmtpAuthentication.Ntlm"/> the Windows credentials for the current /// thread, if impersonating, or the process will be used to authenticate. /// </para> /// </remarks> public SmtpAuthentication Authentication { get { return m_authentication; } set { m_authentication = value; } } /// <summary> /// The username to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the username will be ignored. /// </para> /// </remarks> public string Username { get { return m_username; } set { m_username = value; } } /// <summary> /// The password to use to authenticate with the SMTP server /// </summary> /// <remarks> /// <note type="caution">Authentication is only available on the MS .NET 1.1 runtime.</note> /// <para> /// A <see cref="Username"/> and <see cref="Password"/> must be specified when /// <see cref="Authentication"/> is set to <see cref="SmtpAuthentication.Basic"/>, /// otherwise the password will be ignored. /// </para> /// </remarks> public string Password { get { return m_password; } set { m_password = value; } } /// <summary> /// The port on which the SMTP server is listening /// </summary> /// <remarks> /// <note type="caution">Server Port is only available on the MS .NET 1.1 runtime.</note> /// <para> /// The port on which the SMTP server is listening. The default /// port is <c>25</c>. The Port can only be changed when running on /// the MS .NET 1.1 runtime. /// </para> /// </remarks> public int Port { get { return m_port; } set { m_port = value; } } /// <summary> /// Gets or sets the priority of the e-mail message /// </summary> /// <value> /// One of the <see cref="MailPriority"/> values. /// </value> /// <remarks> /// <para> /// Sets the priority of the e-mails generated by this /// appender. The default priority is <see cref="MailPriority.Normal"/>. /// </para> /// <para> /// If you are using this appender to report errors then /// you may want to set the priority to <see cref="MailPriority.High"/>. /// </para> /// </remarks> public MailPriority Priority { get { return m_mailPriority; } set { m_mailPriority = value; } } #if NET_2_0 || MONO_2_0 /// <summary> /// Enable or disable use of SSL when sending e-mail message /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public bool EnableSsl { get { return m_enableSsl; } set { m_enableSsl = value; } } /// <summary> /// Gets or sets the reply-to e-mail address. /// </summary> /// <remarks> /// This is available on MS .NET 2.0 runtime and higher /// </remarks> public string ReplyTo { get { return m_replyTo; } set { m_replyTo = value; } } #endif /// <summary> /// Gets or sets the subject encoding to be used. /// </summary> /// <remarks> /// The default encoding is the operating system's current ANSI codepage. /// </remarks> public Encoding SubjectEncoding { get { return m_subjectEncoding; } set { m_subjectEncoding = value; } } /// <summary> /// Gets or sets the body encoding to be used. /// </summary> /// <remarks> /// The default encoding is the operating system's current ANSI codepage. /// </remarks> public Encoding BodyEncoding { get { return m_bodyEncoding; } set { m_bodyEncoding = value; } } #endregion // Public Instance Properties #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Sends the contents of the cyclic buffer as an e-mail message. /// </summary> /// <param name="events">The logging events to send.</param> override protected void SendBuffer(LoggingEvent[] events) { // Note: this code already owns the monitor for this // appender. This frees us from needing to synchronize again. try { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); string t = Layout.Header; if (t != null) { writer.Write(t); } for(int i = 0; i < events.Length; i++) { // Render the event and append the text to the buffer RenderLoggingEvent(writer, events[i]); } t = Layout.Footer; if (t != null) { writer.Write(t); } SendEmail(writer.ToString()); } catch(Exception e) { ErrorHandler.Error("Error occurred while sending e-mail notification.", e); } } #endregion // Override implementation of BufferingAppenderSkeleton #region Override implementation of AppenderSkeleton /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // Override implementation of AppenderSkeleton #region Protected Methods /// <summary> /// Send the email message /// </summary> /// <param name="messageBody">the body text to include in the mail</param> virtual protected void SendEmail(string messageBody) { #if NET_2_0 || MONO_2_0 // .NET 2.0 has a new API for SMTP email System.Net.Mail // This API supports credentials and multiple hosts correctly. // The old API is deprecated. // Create and configure the smtp client SmtpClient smtpClient = new SmtpClient(); if (!String.IsNullOrEmpty(m_smtpHost)) { smtpClient.Host = m_smtpHost; } smtpClient.Port = m_port; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = m_enableSsl; if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication smtpClient.Credentials = new System.Net.NetworkCredential(m_username, m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; } using (MailMessage mailMessage = new MailMessage()) { mailMessage.Body = messageBody; mailMessage.BodyEncoding = m_bodyEncoding; mailMessage.From = new MailAddress(m_from); mailMessage.To.Add(m_to); if (!String.IsNullOrEmpty(m_cc)) { mailMessage.CC.Add(m_cc); } if (!String.IsNullOrEmpty(m_bcc)) { mailMessage.Bcc.Add(m_bcc); } if (!String.IsNullOrEmpty(m_replyTo)) { // .NET 4.0 warning CS0618: 'System.Net.Mail.MailMessage.ReplyTo' is obsolete: // 'ReplyTo is obsoleted for this type. Please use ReplyToList instead which can accept multiple addresses. http://go.microsoft.com/fwlink/?linkid=14202' #if !NET_4_0 && !MONO_4_0 mailMessage.ReplyTo = new MailAddress(m_replyTo); #else mailMessage.ReplyToList.Add(new MailAddress(m_replyTo)); #endif } mailMessage.Subject = m_subject; mailMessage.SubjectEncoding = m_subjectEncoding; mailMessage.Priority = m_mailPriority; // TODO: Consider using SendAsync to send the message without blocking. This would be a change in // behaviour compared to .NET 1.x. We would need a SendCompletedCallback to log errors. smtpClient.Send(mailMessage); } #else // .NET 1.x uses the System.Web.Mail API for sending Mail MailMessage mailMessage = new MailMessage(); mailMessage.Body = messageBody; mailMessage.BodyEncoding = m_bodyEncoding; mailMessage.From = m_from; mailMessage.To = m_to; if (m_cc != null && m_cc.Length > 0) { mailMessage.Cc = m_cc; } if (m_bcc != null && m_bcc.Length > 0) { mailMessage.Bcc = m_bcc; } mailMessage.Subject = m_subject; #if !MONO && !NET_1_0 && !NET_1_1 && !CLI_1_0 mailMessage.SubjectEncoding = m_subjectEncoding; #endif mailMessage.Priority = m_mailPriority; #if NET_1_1 // The Fields property on the MailMessage allows the CDO properties to be set directly. // This property is only available on .NET Framework 1.1 and the implementation must understand // the CDO properties. For details of the fields available in CDO see: // // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_configuration_coclass.asp // try { if (m_authentication == SmtpAuthentication.Basic) { // Perform basic authentication mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", m_username); mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", m_password); } else if (m_authentication == SmtpAuthentication.Ntlm) { // Perform integrated authentication (NTLM) mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 2); } // Set the port if not the default value if (m_port != 25) { mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", m_port); } } catch(MissingMethodException missingMethodException) { // If we were compiled against .NET 1.1 but are running against .NET 1.0 then // we will get a MissingMethodException when accessing the MailMessage.Fields property. ErrorHandler.Error("SmtpAppender: Authentication and server Port are only supported when running on the MS .NET 1.1 framework", missingMethodException); } #else if (m_authentication != SmtpAuthentication.None) { ErrorHandler.Error("SmtpAppender: Authentication is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } if (m_port != 25) { ErrorHandler.Error("SmtpAppender: Server Port is only supported on the MS .NET 1.1 or MS .NET 2.0 builds of log4net"); } #endif // if NET_1_1 if (m_smtpHost != null && m_smtpHost.Length > 0) { SmtpMail.SmtpServer = m_smtpHost; } SmtpMail.Send(mailMessage); #endif // if NET_2_0 } #endregion // Protected Methods #region Private Instance Fields private string m_to; private string m_cc; private string m_bcc; private string m_from; private string m_subject; private string m_smtpHost; private Encoding m_subjectEncoding = Encoding.UTF8; private Encoding m_bodyEncoding = Encoding.UTF8; // authentication fields private SmtpAuthentication m_authentication = SmtpAuthentication.None; private string m_username; private string m_password; // server port, default port 25 private int m_port = 25; private MailPriority m_mailPriority = MailPriority.Normal; #if NET_2_0 || MONO_2_0 private bool m_enableSsl = false; private string m_replyTo; #endif #endregion // Private Instance Fields #region SmtpAuthentication Enum /// <summary> /// Values for the <see cref="SmtpAppender.Authentication"/> property. /// </summary> /// <remarks> /// <para> /// SMTP authentication modes. /// </para> /// </remarks> public enum SmtpAuthentication { /// <summary> /// No authentication /// </summary> None, /// <summary> /// Basic authentication. /// </summary> /// <remarks> /// Requires a username and password to be supplied /// </remarks> Basic, /// <summary> /// Integrated authentication /// </summary> /// <remarks> /// Uses the Windows credentials from the current thread or process to authenticate. /// </remarks> Ntlm } #endregion // SmtpAuthentication Enum private static readonly char[] ADDRESS_DELIMITERS = new char[] { ',', ';' }; /// <summary> /// trims leading and trailing commas or semicolons /// </summary> private static string MaybeTrimSeparators(string s) { #if NET_2_0 || MONO_2_0 return string.IsNullOrEmpty(s) ? s : s.Trim(ADDRESS_DELIMITERS); #else return s != null && s.Length > 0 ? s : s.Trim(ADDRESS_DELIMITERS); #endif } } } #endif // !NETCF && !SSCLI
namespace KojtoCAD.PointCloud { partial class LoadPointCloudForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox3 = new System.Windows.Forms.GroupBox(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.Z1 = new System.Windows.Forms.TextBox(); this.X1 = new System.Windows.Forms.TextBox(); this.Y1 = new System.Windows.Forms.TextBox(); this.groupBox5 = new System.Windows.Forms.GroupBox(); this.Z2 = new System.Windows.Forms.TextBox(); this.X2 = new System.Windows.Forms.TextBox(); this.Y2 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.SS = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.PN = new System.Windows.Forms.TextBox(); this.Filename1 = new System.Windows.Forms.TextBox(); this.button_browse1 = new System.Windows.Forms.Button(); this.Filename2 = new System.Windows.Forms.TextBox(); this.button_browse2 = new System.Windows.Forms.Button(); this.Filename3 = new System.Windows.Forms.TextBox(); this.button_browse3 = new System.Windows.Forms.Button(); this.Filename4 = new System.Windows.Forms.TextBox(); this.button_browse4 = new System.Windows.Forms.Button(); this.Filename5 = new System.Windows.Forms.TextBox(); this.button_browse5 = new System.Windows.Forms.Button(); this.button_OK = new System.Windows.Forms.Button(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.groupBox5.SuspendLayout(); this.SuspendLayout(); // // groupBox3 // this.groupBox3.Controls.Add(this.groupBox4); this.groupBox3.Controls.Add(this.groupBox5); this.groupBox3.Controls.Add(this.label4); this.groupBox3.Controls.Add(this.label5); this.groupBox3.Controls.Add(this.label6); this.groupBox3.Location = new System.Drawing.Point(12, 12); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(260, 178); this.groupBox3.TabIndex = 20; this.groupBox3.TabStop = false; this.groupBox3.Text = "Limits"; // // groupBox4 // this.groupBox4.Controls.Add(this.Z1); this.groupBox4.Controls.Add(this.X1); this.groupBox4.Controls.Add(this.Y1); this.groupBox4.Location = new System.Drawing.Point(33, 27); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(109, 126); this.groupBox4.TabIndex = 18; this.groupBox4.TabStop = false; this.groupBox4.Text = "Limit1"; // // Z1 // this.Z1.Location = new System.Drawing.Point(24, 93); this.Z1.Name = "Z1"; this.Z1.Size = new System.Drawing.Size(71, 20); this.Z1.TabIndex = 16; // // X1 // this.X1.Location = new System.Drawing.Point(24, 23); this.X1.Name = "X1"; this.X1.Size = new System.Drawing.Size(71, 20); this.X1.TabIndex = 12; // // Y1 // this.Y1.Location = new System.Drawing.Point(24, 58); this.Y1.Name = "Y1"; this.Y1.Size = new System.Drawing.Size(71, 20); this.Y1.TabIndex = 14; // // groupBox5 // this.groupBox5.Controls.Add(this.Z2); this.groupBox5.Controls.Add(this.X2); this.groupBox5.Controls.Add(this.Y2); this.groupBox5.Location = new System.Drawing.Point(148, 27); this.groupBox5.Name = "groupBox5"; this.groupBox5.Size = new System.Drawing.Size(101, 126); this.groupBox5.TabIndex = 19; this.groupBox5.TabStop = false; this.groupBox5.Text = "Limit2"; // // Z2 // this.Z2.Location = new System.Drawing.Point(24, 96); this.Z2.Name = "Z2"; this.Z2.Size = new System.Drawing.Size(71, 20); this.Z2.TabIndex = 17; // // X2 // this.X2.Location = new System.Drawing.Point(24, 26); this.X2.Name = "X2"; this.X2.Size = new System.Drawing.Size(71, 20); this.X2.TabIndex = 13; // // Y2 // this.Y2.Location = new System.Drawing.Point(24, 61); this.Y2.Name = "Y2"; this.Y2.Size = new System.Drawing.Size(71, 20); this.Y2.TabIndex = 15; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(10, 54); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(17, 13); this.label4.TabIndex = 9; this.label4.Text = "X:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(10, 88); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(17, 13); this.label5.TabIndex = 10; this.label5.Text = "Y:"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(10, 120); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(17, 13); this.label6.TabIndex = 11; this.label6.Text = "Z:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(302, 17); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(107, 13); this.label1.TabIndex = 21; this.label1.Text = "Separation Character"; // // SS // this.SS.Location = new System.Drawing.Point(416, 12); this.SS.Name = "SS"; this.SS.Size = new System.Drawing.Size(25, 20); this.SS.TabIndex = 22; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(494, 17); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(112, 13); this.label2.TabIndex = 23; this.label2.Text = "Draw a Point for every"; // // PN // this.PN.Location = new System.Drawing.Point(622, 12); this.PN.Name = "PN"; this.PN.Size = new System.Drawing.Size(67, 20); this.PN.TabIndex = 24; // // Filename1 // this.Filename1.Location = new System.Drawing.Point(301, 48); this.Filename1.Name = "Filename1"; this.Filename1.Size = new System.Drawing.Size(516, 20); this.Filename1.TabIndex = 25; // // button_browse1 // this.button_browse1.Location = new System.Drawing.Point(833, 48); this.button_browse1.Name = "button_browse1"; this.button_browse1.Size = new System.Drawing.Size(75, 20); this.button_browse1.TabIndex = 26; this.button_browse1.Text = "BROWSE"; this.button_browse1.UseVisualStyleBackColor = true; this.button_browse1.Click += new System.EventHandler(this.button_browse1_Click); // // Filename2 // this.Filename2.Location = new System.Drawing.Point(301, 75); this.Filename2.Name = "Filename2"; this.Filename2.Size = new System.Drawing.Size(516, 20); this.Filename2.TabIndex = 27; // // button_browse2 // this.button_browse2.Location = new System.Drawing.Point(833, 75); this.button_browse2.Name = "button_browse2"; this.button_browse2.Size = new System.Drawing.Size(75, 20); this.button_browse2.TabIndex = 28; this.button_browse2.Text = "BROWSE"; this.button_browse2.UseVisualStyleBackColor = true; this.button_browse2.Click += new System.EventHandler(this.button_browse2_Click); // // Filename3 // this.Filename3.Location = new System.Drawing.Point(301, 102); this.Filename3.Name = "Filename3"; this.Filename3.Size = new System.Drawing.Size(516, 20); this.Filename3.TabIndex = 29; // // button_browse3 // this.button_browse3.Location = new System.Drawing.Point(833, 102); this.button_browse3.Name = "button_browse3"; this.button_browse3.Size = new System.Drawing.Size(75, 20); this.button_browse3.TabIndex = 30; this.button_browse3.Text = "BROWSE"; this.button_browse3.UseVisualStyleBackColor = true; this.button_browse3.Click += new System.EventHandler(this.button_browse3_Click); // // Filename4 // this.Filename4.Location = new System.Drawing.Point(301, 129); this.Filename4.Name = "Filename4"; this.Filename4.Size = new System.Drawing.Size(516, 20); this.Filename4.TabIndex = 31; // // button_browse4 // this.button_browse4.Location = new System.Drawing.Point(833, 129); this.button_browse4.Name = "button_browse4"; this.button_browse4.Size = new System.Drawing.Size(75, 20); this.button_browse4.TabIndex = 32; this.button_browse4.Text = "BROWSE"; this.button_browse4.UseVisualStyleBackColor = true; this.button_browse4.Click += new System.EventHandler(this.button_browse4_Click); // // Filename5 // this.Filename5.Location = new System.Drawing.Point(301, 156); this.Filename5.Name = "Filename5"; this.Filename5.Size = new System.Drawing.Size(516, 20); this.Filename5.TabIndex = 33; // // button_browse5 // this.button_browse5.Location = new System.Drawing.Point(833, 156); this.button_browse5.Name = "button_browse5"; this.button_browse5.Size = new System.Drawing.Size(75, 20); this.button_browse5.TabIndex = 34; this.button_browse5.Text = "BROWSE"; this.button_browse5.UseVisualStyleBackColor = true; this.button_browse5.Click += new System.EventHandler(this.button_browse5_Click); // // button_OK // this.button_OK.Location = new System.Drawing.Point(12, 199); this.button_OK.Name = "button_OK"; this.button_OK.Size = new System.Drawing.Size(260, 23); this.button_OK.TabIndex = 35; this.button_OK.Text = "OK"; this.button_OK.UseVisualStyleBackColor = true; this.button_OK.Click += new System.EventHandler(this.button_OK_Click); // // LoadPointCloudForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(924, 234); this.Controls.Add(this.button_OK); this.Controls.Add(this.button_browse5); this.Controls.Add(this.Filename5); this.Controls.Add(this.button_browse4); this.Controls.Add(this.Filename4); this.Controls.Add(this.button_browse3); this.Controls.Add(this.Filename3); this.Controls.Add(this.button_browse2); this.Controls.Add(this.Filename2); this.Controls.Add(this.button_browse1); this.Controls.Add(this.Filename1); this.Controls.Add(this.PN); this.Controls.Add(this.label2); this.Controls.Add(this.SS); this.Controls.Add(this.label1); this.Controls.Add(this.groupBox3); this.KeyPreview = true; this.Name = "LoadPointCloudForm"; this.Text = "Load Points from Pointcloud"; this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.LoadPointCloudForm_KeyPress); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.groupBox5.ResumeLayout(false); this.groupBox5.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.TextBox Z1; private System.Windows.Forms.TextBox X1; private System.Windows.Forms.TextBox Y1; private System.Windows.Forms.GroupBox groupBox5; private System.Windows.Forms.TextBox Z2; private System.Windows.Forms.TextBox X2; private System.Windows.Forms.TextBox Y2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox SS; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox PN; private System.Windows.Forms.TextBox Filename1; private System.Windows.Forms.Button button_browse1; private System.Windows.Forms.TextBox Filename2; private System.Windows.Forms.Button button_browse2; private System.Windows.Forms.TextBox Filename3; private System.Windows.Forms.Button button_browse3; private System.Windows.Forms.TextBox Filename4; private System.Windows.Forms.Button button_browse4; private System.Windows.Forms.TextBox Filename5; private System.Windows.Forms.Button button_browse5; private System.Windows.Forms.Button button_OK; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new float[8] { 22, -5, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 1, 1, 50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector128<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector128<float>>(floatTable.inArray2Ptr); var vf3 = Avx.CompareScalar(vf1, vf2, FloatComparisonMode.OrderedEqualNonSignaling); Unsafe.Write(floatTable.outArrayPtr, vf3); var vd1 = Unsafe.Read<Vector128<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector128<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.CompareScalar(vd1, vd2, FloatComparisonMode.OrderedEqualNonSignaling); Unsafe.Write(doubleTable.outArrayPtr, vd3); if (BitConverter.SingleToInt32Bits(floatTable.outArray[0]) != (floatTable.inArray1[0] == floatTable.inArray2[0] ? -1 : 0)) { Console.WriteLine("Avx CompareScalar failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } for (int i = 1; i < 4; i++) { if (floatTable.outArray[i] != floatTable.inArray1[i]) { Console.WriteLine("Avx CompareScalar failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } if (BitConverter.DoubleToInt64Bits(doubleTable.outArray[0]) != (doubleTable.inArray1[0] == doubleTable.inArray2[0] ? -1 : 0)) { Console.WriteLine("Avx CompareScalar failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } for (int i = 1; i < 2; i++) { if (doubleTable.outArray[i] != doubleTable.inArray1[i]) { Console.WriteLine("Avx CompareScalar failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } try { var ve = Avx.CompareScalar(vf1, vf2, (FloatComparisonMode)32); Unsafe.Write(floatTable.outArrayPtr, ve); Console.WriteLine("Avx CompareScalar failed on float with out-of-range argument:"); return Fail; } catch (ArgumentOutOfRangeException e) { testResult = Pass; } try { var ve = Avx.CompareScalar(vd1, vd2, (FloatComparisonMode)32); Unsafe.Write(floatTable.outArrayPtr, ve); Console.WriteLine("Avx CompareScalar failed on double with out-of-range argument:"); return Fail; } catch (ArgumentOutOfRangeException e) { testResult = Pass; } try { var ve = typeof(Avx).GetMethod(nameof(Avx.CompareScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(FloatComparisonMode) }) .Invoke(null, new object[] {vf1, vf2, (FloatComparisonMode)32}); Console.WriteLine("Indirect-calling Avx CompareScalar failed on float with out-of-range argument:"); return Fail; } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is ArgumentOutOfRangeException) { testResult = Pass; } else { Console.WriteLine("Indirect-calling Avx CompareScalar failed on float with out-of-range argument:"); return Fail; } } try { var ve = typeof(Avx).GetMethod(nameof(Avx.CompareScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>), typeof(FloatComparisonMode) }) .Invoke(null, new object[] {vd1, vd2, (FloatComparisonMode)32}); Console.WriteLine("Indirect-calling Avx CompareScalar failed on double with out-of-range argument:"); return Fail; } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is ArgumentOutOfRangeException) { testResult = Pass; } else { Console.WriteLine("Indirect-calling Avx CompareScalar failed on double with out-of-range argument:"); return Fail; } } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, T, bool> check) { for (int i = 0; i < inArray1.Length; i++) { if (!check(inArray1[i], inArray2[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; namespace OpenMetaverse.Imaging { #if !NO_UNSAFE /// <summary> /// Capability to load TGAs to Bitmap /// </summary> public class LoadTGAClass { struct tgaColorMap { public ushort FirstEntryIndex; public ushort Length; public byte EntrySize; public void Read(System.IO.BinaryReader br) { FirstEntryIndex = br.ReadUInt16(); Length = br.ReadUInt16(); EntrySize = br.ReadByte(); } } struct tgaImageSpec { public ushort XOrigin; public ushort YOrigin; public ushort Width; public ushort Height; public byte PixelDepth; public byte Descriptor; public void Read(System.IO.BinaryReader br) { XOrigin = br.ReadUInt16(); YOrigin = br.ReadUInt16(); Width = br.ReadUInt16(); Height = br.ReadUInt16(); PixelDepth = br.ReadByte(); Descriptor = br.ReadByte(); } public byte AlphaBits { get { return (byte)(Descriptor & 0xF); } set { Descriptor = (byte)((Descriptor & ~0xF) | (value & 0xF)); } } public bool BottomUp { get { return (Descriptor & 0x20) == 0x20; } set { Descriptor = (byte)((Descriptor & ~0x20) | (value ? 0x20 : 0)); } } } struct tgaHeader { public byte IdLength; public byte ColorMapType; public byte ImageType; public tgaColorMap ColorMap; public tgaImageSpec ImageSpec; public void Read(System.IO.BinaryReader br) { this.IdLength = br.ReadByte(); this.ColorMapType = br.ReadByte(); this.ImageType = br.ReadByte(); this.ColorMap = new tgaColorMap(); this.ImageSpec = new tgaImageSpec(); this.ColorMap.Read(br); this.ImageSpec.Read(br); } public bool RleEncoded { get { return ImageType >= 9; } } } struct tgaCD { public uint RMask, GMask, BMask, AMask; public byte RShift, GShift, BShift, AShift; public uint FinalOr; public bool NeedNoConvert; } static uint UnpackColor( uint sourceColor, ref tgaCD cd) { if (cd.RMask == 0xFF && cd.GMask == 0xFF && cd.BMask == 0xFF) { // Special case to deal with 8-bit TGA files that we treat as alpha masks return sourceColor << 24; } else { uint rpermute = (sourceColor << cd.RShift) | (sourceColor >> (32 - cd.RShift)); uint gpermute = (sourceColor << cd.GShift) | (sourceColor >> (32 - cd.GShift)); uint bpermute = (sourceColor << cd.BShift) | (sourceColor >> (32 - cd.BShift)); uint apermute = (sourceColor << cd.AShift) | (sourceColor >> (32 - cd.AShift)); uint result = (rpermute & cd.RMask) | (gpermute & cd.GMask) | (bpermute & cd.BMask) | (apermute & cd.AMask) | cd.FinalOr; return result; } } static unsafe void decodeLine( System.Drawing.Imaging.BitmapData b, int line, int byp, byte[] data, ref tgaCD cd) { if (cd.NeedNoConvert) { // fast copy uint* linep = (uint*)((byte*)b.Scan0.ToPointer() + line * b.Stride); fixed (byte* ptr = data) { uint* sptr = (uint*)ptr; for (int i = 0; i < b.Width; ++i) { linep[i] = sptr[i]; } } } else { byte* linep = (byte*)b.Scan0.ToPointer() + line * b.Stride; uint* up = (uint*)linep; int rdi = 0; fixed (byte* ptr = data) { for (int i = 0; i < b.Width; ++i) { uint x = 0; for (int j = 0; j < byp; ++j) { x |= ((uint)ptr[rdi]) << (j << 3); ++rdi; } up[i] = UnpackColor(x, ref cd); } } } } static void decodeRle( System.Drawing.Imaging.BitmapData b, int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp) { try { int w = b.Width; // make buffer larger, so in case of emergency I can decode // over line ends. byte[] linebuffer = new byte[(w + 128) * byp]; int maxindex = w * byp; int index = 0; for (int j = 0; j < b.Height; ++j) { while (index < maxindex) { byte blocktype = br.ReadByte(); int bytestoread; int bytestocopy; if (blocktype >= 0x80) { bytestoread = byp; bytestocopy = byp * (blocktype - 0x80); } else { bytestoread = byp * (blocktype + 1); bytestocopy = 0; } //if (index + bytestoread > maxindex) // throw new System.ArgumentException ("Corrupt TGA"); br.Read(linebuffer, index, bytestoread); index += bytestoread; for (int i = 0; i != bytestocopy; ++i) { linebuffer[index + i] = linebuffer[index + i - bytestoread]; } index += bytestocopy; } if (!bottomUp) decodeLine(b, b.Height - j - 1, byp, linebuffer, ref cd); else decodeLine(b, j, byp, linebuffer, ref cd); if (index > maxindex) { Array.Copy(linebuffer, maxindex, linebuffer, 0, index - maxindex); index -= maxindex; } else index = 0; } } catch (System.IO.EndOfStreamException) { } } static void decodePlain( System.Drawing.Imaging.BitmapData b, int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp) { int w = b.Width; byte[] linebuffer = new byte[w * byp]; for (int j = 0; j < b.Height; ++j) { br.Read(linebuffer, 0, w * byp); if (!bottomUp) decodeLine(b, b.Height - j - 1, byp, linebuffer, ref cd); else decodeLine(b, j, byp, linebuffer, ref cd); } } static void decodeStandard8( System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { tgaCD cd = new tgaCD(); cd.RMask = 0x000000ff; cd.GMask = 0x000000ff; cd.BMask = 0x000000ff; cd.AMask = 0x000000ff; cd.RShift = 0; cd.GShift = 0; cd.BShift = 0; cd.AShift = 0; cd.FinalOr = 0x00000000; if (hdr.RleEncoded) decodeRle(b, 1, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 1, cd, br, hdr.ImageSpec.BottomUp); } static void decodeSpecial16( System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. tgaCD cd = new tgaCD(); cd.RMask = 0x00f00000; cd.GMask = 0x0000f000; cd.BMask = 0x000000f0; cd.AMask = 0xf0000000; cd.RShift = 12; cd.GShift = 8; cd.BShift = 4; cd.AShift = 16; cd.FinalOr = 0; if (hdr.RleEncoded) decodeRle(b, 2, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 2, cd, br, hdr.ImageSpec.BottomUp); } static void decodeStandard16( System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. tgaCD cd = new tgaCD(); cd.RMask = 0x00f80000; // from 0xF800 cd.GMask = 0x0000fc00; // from 0x07E0 cd.BMask = 0x000000f8; // from 0x001F cd.AMask = 0x00000000; cd.RShift = 8; cd.GShift = 5; cd.BShift = 3; cd.AShift = 0; cd.FinalOr = 0xff000000; if (hdr.RleEncoded) decodeRle(b, 2, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 2, cd, br, hdr.ImageSpec.BottomUp); } static void decodeSpecial24(System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. tgaCD cd = new tgaCD(); cd.RMask = 0x00f80000; cd.GMask = 0x0000fc00; cd.BMask = 0x000000f8; cd.AMask = 0xff000000; cd.RShift = 8; cd.GShift = 5; cd.BShift = 3; cd.AShift = 8; cd.FinalOr = 0; if (hdr.RleEncoded) decodeRle(b, 3, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp); } static void decodeStandard24(System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. tgaCD cd = new tgaCD(); cd.RMask = 0x00ff0000; cd.GMask = 0x0000ff00; cd.BMask = 0x000000ff; cd.AMask = 0x00000000; cd.RShift = 0; cd.GShift = 0; cd.BShift = 0; cd.AShift = 0; cd.FinalOr = 0xff000000; if (hdr.RleEncoded) decodeRle(b, 3, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 3, cd, br, hdr.ImageSpec.BottomUp); } static void decodeStandard32(System.Drawing.Imaging.BitmapData b, tgaHeader hdr, System.IO.BinaryReader br) { // i must convert the input stream to a sequence of uint values // which I then unpack. tgaCD cd = new tgaCD(); cd.RMask = 0x00ff0000; cd.GMask = 0x0000ff00; cd.BMask = 0x000000ff; cd.AMask = 0xff000000; cd.RShift = 0; cd.GShift = 0; cd.BShift = 0; cd.AShift = 0; cd.FinalOr = 0x00000000; cd.NeedNoConvert = true; if (hdr.RleEncoded) decodeRle(b, 4, cd, br, hdr.ImageSpec.BottomUp); else decodePlain(b, 4, cd, br, hdr.ImageSpec.BottomUp); } public static System.Drawing.Size GetTGASize(string filename) { System.IO.FileStream f = System.IO.File.OpenRead(filename); System.IO.BinaryReader br = new System.IO.BinaryReader(f); tgaHeader header = new tgaHeader(); header.Read(br); br.Close(); return new System.Drawing.Size(header.ImageSpec.Width, header.ImageSpec.Height); } public static System.Drawing.Bitmap LoadTGA(System.IO.Stream source) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms)) { tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.AlphaBits > 8) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) throw new ArgumentException("Image too large."); System.Drawing.Bitmap b; System.Drawing.Imaging.BitmapData bd; // Create a bitmap for the image. // Only include an alpha layer when the image requires one. if (header.ImageSpec.AlphaBits > 0 || header.ImageSpec.PixelDepth == 8 || // Assume 8 bit images are alpha only header.ImageSpec.PixelDepth == 32) // Assume 32 bit images are ARGB { // Image needs an alpha layer b = new System.Drawing.Bitmap( header.ImageSpec.Width, header.ImageSpec.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); } else { // Image does not need an alpha layer, so do not include one. b = new System.Drawing.Bitmap( header.ImageSpec.Width, header.ImageSpec.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); } switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) decodeSpecial16(bd, header, br); else decodeStandard16(bd, header, br); break; case 24: if (header.ImageSpec.AlphaBits > 0) decodeSpecial24(bd, header, br); else decodeStandard24(bd, header, br); break; case 32: decodeStandard32(bd, header, br); break; default: b.UnlockBits(bd); b.Dispose(); return null; } b.UnlockBits(bd); return b; } } public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source) { return LoadTGAImage(source, false); } public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mask) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); using (System.IO.BinaryReader br = new System.IO.BinaryReader(ms)) { tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.AlphaBits > 8) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) throw new ArgumentException("Image too large."); byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); fixed (byte* pdecoded = &decoded[0]) { bd.Width = header.ImageSpec.Width; bd.Height = header.ImageSpec.Height; bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; bd.Stride = header.ImageSpec.Width * 4; bd.Scan0 = (IntPtr)pdecoded; switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) decodeSpecial16(bd, header, br); else decodeStandard16(bd, header, br); break; case 24: if (header.ImageSpec.AlphaBits > 0) decodeSpecial24(bd, header, br); else decodeStandard24(bd, header, br); break; case 32: decodeStandard32(bd, header, br); break; default: return null; } } int n = header.ImageSpec.Width * header.ImageSpec.Height; ManagedImage image; if (mask && header.ImageSpec.AlphaBits == 0 && header.ImageSpec.PixelDepth == 8) { image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height, ManagedImage.ImageChannels.Alpha); int p = 3; for (int i = 0; i < n; i++) { image.Alpha[i] = decoded[p]; p += 4; } } else { image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); int p = 0; for (int i = 0; i < n; i++) { image.Blue[i] = decoded[p++]; image.Green[i] = decoded[p++]; image.Red[i] = decoded[p++]; image.Alpha[i] = decoded[p++]; } } br.Close(); return image; } } public static System.Drawing.Bitmap LoadTGA(string filename) { try { using (System.IO.FileStream f = System.IO.File.OpenRead(filename)) { return LoadTGA(f); } } catch (System.IO.DirectoryNotFoundException) { return null; // file not found } catch (System.IO.FileNotFoundException) { return null; // file not found } } } #endif }
//------------------------------------------------------------------------------ // <copyright file="RepositoryService.cs"> // Copyright (c) 2014-present Andrea Di Giorgi // // 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> // <author>Andrea Di Giorgi</author> // <website>https://github.com/Ithildir/liferay-sdk-builder-windows</website> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Liferay.SDK.Service.V62.Repository { public class RepositoryService : ServiceBase { public RepositoryService(ISession session) : base(session) { } public async Task<dynamic> AddRepositoryAsync(long groupId, long classNameId, long parentFolderId, string name, string description, string portletId, JsonObjectWrapper typeSettingsProperties, JsonObjectWrapper serviceContext) { var _parameters = new JsonObject(); _parameters.Add("groupId", groupId); _parameters.Add("classNameId", classNameId); _parameters.Add("parentFolderId", parentFolderId); _parameters.Add("name", name); _parameters.Add("description", description); _parameters.Add("portletId", portletId); this.MangleWrapper(_parameters, "typeSettingsProperties", "com.liferay.portal.kernel.util.UnicodeProperties", typeSettingsProperties); this.MangleWrapper(_parameters, "serviceContext", "com.liferay.portal.service.ServiceContext", serviceContext); var _command = new JsonObject() { { "/repository/add-repository", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task CheckRepositoryAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/check-repository", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task DeleteRepositoryAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/delete-repository", _parameters } }; await this.Session.InvokeAsync(_command); } public async Task<dynamic> GetLocalRepositoryImplAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/get-local-repository-impl", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetLocalRepositoryImplAsync(long folderId, long fileEntryId, long fileVersionId) { var _parameters = new JsonObject(); _parameters.Add("folderId", folderId); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("fileVersionId", fileVersionId); var _command = new JsonObject() { { "/repository/get-local-repository-impl", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetRepositoryAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/get-repository", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetRepositoryImplAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/get-repository-impl", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<dynamic> GetRepositoryImplAsync(long folderId, long fileEntryId, long fileVersionId) { var _parameters = new JsonObject(); _parameters.Add("folderId", folderId); _parameters.Add("fileEntryId", fileEntryId); _parameters.Add("fileVersionId", fileVersionId); var _command = new JsonObject() { { "/repository/get-repository-impl", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task<IEnumerable<string>> GetSupportedConfigurationsAsync(long classNameId) { var _parameters = new JsonObject(); _parameters.Add("classNameId", classNameId); var _command = new JsonObject() { { "/repository/get-supported-configurations", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); var _jsonArray = (JsonArray)_obj; return _jsonArray.Cast<string>(); } public async Task<IEnumerable<string>> GetSupportedParametersAsync(long classNameId, string configuration) { var _parameters = new JsonObject(); _parameters.Add("classNameId", classNameId); _parameters.Add("configuration", configuration); var _command = new JsonObject() { { "/repository/get-supported-parameters", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); var _jsonArray = (JsonArray)_obj; return _jsonArray.Cast<string>(); } public async Task<dynamic> GetTypeSettingsPropertiesAsync(long repositoryId) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); var _command = new JsonObject() { { "/repository/get-type-settings-properties", _parameters } }; var _obj = await this.Session.InvokeAsync(_command); return (dynamic)_obj; } public async Task UpdateRepositoryAsync(long repositoryId, string name, string description) { var _parameters = new JsonObject(); _parameters.Add("repositoryId", repositoryId); _parameters.Add("name", name); _parameters.Add("description", description); var _command = new JsonObject() { { "/repository/update-repository", _parameters } }; await this.Session.InvokeAsync(_command); } } }
// 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.Runtime; using System.Runtime.Serialization; using System.Reflection; using System.Xml; namespace System.Runtime.Serialization.Json { internal class JsonDataContract { private JsonDataContractCriticalHelper _helper; protected JsonDataContract(DataContract traditionalDataContract) { _helper = new JsonDataContractCriticalHelper(traditionalDataContract); } protected JsonDataContract(JsonDataContractCriticalHelper helper) { _helper = helper; } internal virtual string TypeName => null; protected JsonDataContractCriticalHelper Helper => _helper; protected DataContract TraditionalDataContract => _helper.TraditionalDataContract; private Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _helper.KnownDataContracts; public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method JsonReadWriteDelegates result; #if uapaot // The c passed in could be a clone which is different from the original key, // We'll need to get the original key data contract from generated assembly. DataContract keyDc = (c?.UnderlyingType != null) ? DataContract.GetDataContractFromGeneratedAssembly(c.UnderlyingType) : null; return (keyDc != null && JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(keyDc, out result)) ? result : null; #else return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; #endif } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString())); } else { return result; } } internal static JsonReadWriteDelegates TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); return result; } public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { PushKnownDataContracts(context); object deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { if (reader.MoveToAttribute(JsonGlobals.typeString) && (reader.Value == JsonGlobals.nullString)) { reader.Skip(); reader.MoveToElement(); return true; } reader.MoveToElement(); return false; } protected void PopKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Pop(); } } protected void PushKnownDataContracts(XmlObjectSerializerContext context) { if (KnownDataContracts != null) { context.scopedKnownTypes.Push(KnownDataContracts); } } internal class JsonDataContractCriticalHelper { private static object s_cacheLock = new object(); private static object s_createDataContractLock = new object(); private static JsonDataContract[] s_dataContractCache = new JsonDataContract[32]; private static int s_dataContractID = 0; private static TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static Dictionary<TypeHandleRef, IntRef> s_typeToIDCache = new Dictionary<TypeHandleRef, IntRef>(new TypeHandleRefEqualityComparer()); private Dictionary<XmlQualifiedName, DataContract> _knownDataContracts; private DataContract _traditionalDataContract; private string _typeName; internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) { _traditionalDataContract = traditionalDataContract; AddCollectionItemContractsToKnownDataContracts(); _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } internal Dictionary<XmlQualifiedName, DataContract> KnownDataContracts => _knownDataContracts; internal DataContract TraditionalDataContract => _traditionalDataContract; internal virtual string TypeName => _typeName; public static JsonDataContract GetJsonDataContract(DataContract traditionalDataContract) { int id = JsonDataContractCriticalHelper.GetId(traditionalDataContract.UnderlyingType.TypeHandle); JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { dataContract = CreateJsonDataContract(id, traditionalDataContract); s_dataContractCache[id] = dataContract; } return dataContract; } internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { IntRef id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { int value = s_dataContractID++; if (value >= s_dataContractCache.Length) { int newSize = (value < Int32.MaxValue / 2) ? value * 2 : Int32.MaxValue; if (newSize <= value) { Fx.Assert("DataContract cache overflow"); throw new SerializationException(SR.DataContractCacheOverflow); } Array.Resize<JsonDataContract>(ref s_dataContractCache, newSize); } id = new IntRef(value); try { s_typeToIDCache.Add(new TypeHandleRef(typeHandle), id); } catch (Exception ex) { if (DiagnosticUtility.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } return id.Value; } } private static JsonDataContract CreateJsonDataContract(int id, DataContract traditionalDataContract) { lock (s_createDataContractLock) { JsonDataContract dataContract = s_dataContractCache[id]; if (dataContract == null) { Type traditionalDataContractType = traditionalDataContract.GetType(); if (traditionalDataContractType == typeof(ObjectDataContract)) { dataContract = new JsonObjectDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(StringDataContract)) { dataContract = new JsonStringDataContract((StringDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(UriDataContract)) { dataContract = new JsonUriDataContract((UriDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(QNameDataContract)) { dataContract = new JsonQNameDataContract((QNameDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(ByteArrayDataContract)) { dataContract = new JsonByteArrayDataContract((ByteArrayDataContract)traditionalDataContract); } else if (traditionalDataContract.IsPrimitive || traditionalDataContract.UnderlyingType == Globals.TypeOfXmlQualifiedName) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(ClassDataContract)) { dataContract = new JsonClassDataContract((ClassDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(EnumDataContract)) { dataContract = new JsonEnumDataContract((EnumDataContract)traditionalDataContract); } else if ((traditionalDataContractType == typeof(GenericParameterDataContract)) || (traditionalDataContractType == typeof(SpecialTypeDataContract))) { dataContract = new JsonDataContract(traditionalDataContract); } else if (traditionalDataContractType == typeof(CollectionDataContract)) { dataContract = new JsonCollectionDataContract((CollectionDataContract)traditionalDataContract); } else if (traditionalDataContractType == typeof(XmlDataContract)) { dataContract = new JsonXmlDataContract((XmlDataContract)traditionalDataContract); } else { throw new ArgumentException(SR.Format(SR.JsonTypeNotSupportedByDataContractJsonSerializer, traditionalDataContract.UnderlyingType), nameof(traditionalDataContract)); } } return dataContract; } } private void AddCollectionItemContractsToKnownDataContracts() { if (_traditionalDataContract.KnownDataContracts != null) { foreach (KeyValuePair<XmlQualifiedName, DataContract> knownDataContract in _traditionalDataContract.KnownDataContracts) { if (!object.ReferenceEquals(knownDataContract, null)) { CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; if (_knownDataContracts == null) { _knownDataContracts = new Dictionary<XmlQualifiedName, DataContract>(); } _knownDataContracts.TryAdd(itemContract.StableName, itemContract); if (collectionDataContract.ItemType.IsGenericType && collectionDataContract.ItemType.GetGenericTypeDefinition() == typeof(KeyValue<,>)) { DataContract itemDataContract = DataContract.GetDataContract(Globals.TypeOfKeyValuePair.MakeGenericType(collectionDataContract.ItemType.GenericTypeArguments)); _knownDataContracts.TryAdd(itemDataContract.StableName, itemDataContract); } if (!(itemContract is CollectionDataContract)) { break; } collectionDataContract = itemContract as CollectionDataContract; } } } } } } } #if uapaot public class JsonReadWriteDelegates #else internal class JsonReadWriteDelegates #endif { // this is the global dictionary for JSON delegates introduced for multi-file private static Dictionary<DataContract, JsonReadWriteDelegates> s_jsonDelegates = new Dictionary<DataContract, JsonReadWriteDelegates>(); public static Dictionary<DataContract, JsonReadWriteDelegates> GetJsonDelegates() { return s_jsonDelegates; } public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; } public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; } public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; } public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; } public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; } } }
using System; using System.IO; namespace NAudio.Midi { /// <summary> /// Represents an individual MIDI event /// </summary> public class MidiEvent { private long absoluteTime; private int channel; /// <summary>The MIDI command code</summary> private MidiCommandCode commandCode; private int deltaTime; /// <summary> /// Default constructor /// </summary> protected MidiEvent() { } /// <summary> /// Creates a MIDI event with specified parameters /// </summary> /// <param name="absoluteTime">Absolute time of this event</param> /// <param name="channel">MIDI channel number</param> /// <param name="commandCode">MIDI command code</param> public MidiEvent(long absoluteTime, int channel, MidiCommandCode commandCode) { this.absoluteTime = absoluteTime; Channel = channel; this.commandCode = commandCode; } /// <summary> /// The MIDI Channel Number for this event (1-16) /// </summary> public virtual int Channel { get { return channel; } set { if ((value < 1) || (value > 16)) { throw new ArgumentOutOfRangeException("value", value, String.Format("Channel must be 1-16 (Got {0})", value)); } channel = value; } } /// <summary> /// The Delta time for this event /// </summary> public int DeltaTime { get { return deltaTime; } } /// <summary> /// The absolute time for this event /// </summary> public long AbsoluteTime { get { return absoluteTime; } set { absoluteTime = value; } } /// <summary> /// The command code for this event /// </summary> public MidiCommandCode CommandCode { get { return commandCode; } } /// <summary> /// Creates a MidiEvent from a raw message received using /// the MME MIDI In APIs /// </summary> /// <param name="rawMessage">The short MIDI message</param> /// <returns>A new MIDI Event</returns> public static MidiEvent FromRawMessage(int rawMessage) { long absoluteTime = 0; int b = rawMessage & 0xFF; int data1 = (rawMessage >> 8) & 0xFF; int data2 = (rawMessage >> 16) & 0xFF; MidiCommandCode commandCode; int channel = 1; if ((b & 0xF0) == 0xF0) { // both bytes are used for command code in this case commandCode = (MidiCommandCode) b; } else { commandCode = (MidiCommandCode) (b & 0xF0); channel = (b & 0x0F) + 1; } MidiEvent me; switch (commandCode) { case MidiCommandCode.NoteOn: case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: if (data2 > 0 && commandCode == MidiCommandCode.NoteOn) { me = new NoteOnEvent(absoluteTime, channel, data1, data2, 0); } else { me = new NoteEvent(absoluteTime, channel, commandCode, data1, data2); } break; case MidiCommandCode.ControlChange: me = new ControlChangeEvent(absoluteTime, channel, (MidiController) data1, data2); break; case MidiCommandCode.PatchChange: me = new PatchChangeEvent(absoluteTime, channel, data1); break; case MidiCommandCode.ChannelAfterTouch: me = new ChannelAfterTouchEvent(absoluteTime, channel, data1); break; case MidiCommandCode.PitchWheelChange: me = new PitchWheelChangeEvent(absoluteTime, channel, data1 + (data2 << 7)); break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: case MidiCommandCode.AutoSensing: me = new MidiEvent(absoluteTime, channel, commandCode); break; case MidiCommandCode.MetaEvent: case MidiCommandCode.Sysex: default: throw new FormatException(String.Format("Unsupported MIDI Command Code for Raw Message {0}", commandCode)); } return me; } /// <summary> /// Constructs a MidiEvent from a BinaryStream /// </summary> /// <param name="br">The binary stream of MIDI data</param> /// <param name="previous">The previous MIDI event (pass null for first event)</param> /// <returns>A new MidiEvent</returns> public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous) { int deltaTime = ReadVarInt(br); MidiCommandCode commandCode; int channel = 1; byte b = br.ReadByte(); if ((b & 0x80) == 0) { // a running command - command & channel are same as previous commandCode = previous.CommandCode; channel = previous.Channel; br.BaseStream.Position--; // need to push this back } else { if ((b & 0xF0) == 0xF0) { // both bytes are used for command code in this case commandCode = (MidiCommandCode) b; } else { commandCode = (MidiCommandCode) (b & 0xF0); channel = (b & 0x0F) + 1; } } MidiEvent me; switch (commandCode) { case MidiCommandCode.NoteOn: me = new NoteOnEvent(br); break; case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: me = new NoteEvent(br); break; case MidiCommandCode.ControlChange: me = new ControlChangeEvent(br); break; case MidiCommandCode.PatchChange: me = new PatchChangeEvent(br); break; case MidiCommandCode.ChannelAfterTouch: me = new ChannelAfterTouchEvent(br); break; case MidiCommandCode.PitchWheelChange: me = new PitchWheelChangeEvent(br); break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: me = new MidiEvent(); break; case MidiCommandCode.Sysex: me = SysexEvent.ReadSysexEvent(br); break; case MidiCommandCode.MetaEvent: me = MetaEvent.ReadMetaEvent(br); break; default: throw new FormatException(String.Format("Unsupported MIDI Command Code {0:X2}", (byte) commandCode)); } me.channel = channel; me.deltaTime = deltaTime; me.commandCode = commandCode; return me; } /// <summary> /// Converts this MIDI event to a short message (32 bit integer) that /// can be sent by the Windows MIDI out short message APIs /// Cannot be implemented for all MIDI messages /// </summary> /// <returns>A short message</returns> public virtual int GetAsShortMessage() { return (channel - 1) + (int) commandCode; } /// <summary> /// Whether this is a note off event /// </summary> public static bool IsNoteOff(MidiEvent midiEvent) { if (midiEvent != null) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { var ne = (NoteEvent) midiEvent; return (ne.Velocity == 0); } return (midiEvent.CommandCode == MidiCommandCode.NoteOff); } return false; } /// <summary> /// Whether this is a note on event /// </summary> public static bool IsNoteOn(MidiEvent midiEvent) { if (midiEvent != null) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { var ne = (NoteEvent) midiEvent; return (ne.Velocity > 0); } } return false; } /// <summary> /// Determines if this is an end track event /// </summary> public static bool IsEndTrack(MidiEvent midiEvent) { if (midiEvent != null) { var me = midiEvent as MetaEvent; if (me != null) { return me.MetaEventType == MetaEventType.EndTrack; } } return false; } /// <summary> /// Displays a summary of the MIDI event /// </summary> /// <returns>A string containing a brief description of this MIDI event</returns> public override string ToString() { if (commandCode >= MidiCommandCode.Sysex) return String.Format("{0} {1}", absoluteTime, commandCode); return String.Format("{0} {1} Ch: {2}", absoluteTime, commandCode, channel); } /// <summary> /// Utility function that can read a variable length integer from a binary stream /// </summary> /// <param name="br">The binary stream</param> /// <returns>The integer read</returns> public static int ReadVarInt(BinaryReader br) { int value = 0; byte b; for (int n = 0; n < 4; n++) { b = br.ReadByte(); value <<= 7; value += (b & 0x7F); if ((b & 0x80) == 0) { return value; } } throw new FormatException("Invalid Var Int"); } /// <summary> /// Writes a variable length integer to a binary stream /// </summary> /// <param name="writer">Binary stream</param> /// <param name="value">The value to write</param> public static void WriteVarInt(BinaryWriter writer, int value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "Cannot write a negative Var Int"); } if (value > 0x0FFFFFFF) { throw new ArgumentOutOfRangeException("value", value, "Maximum allowed Var Int is 0x0FFFFFFF"); } int n = 0; var buffer = new byte[4]; do { buffer[n++] = (byte) (value & 0x7F); value >>= 7; } while (value > 0); while (n > 0) { n--; if (n > 0) writer.Write((byte) (buffer[n] | 0x80)); else writer.Write(buffer[n]); } } /// <summary> /// Exports this MIDI event's data /// Overriden in derived classes, but they should call this version /// </summary> /// <param name="absoluteTime"> /// Absolute time used to calculate delta. /// Is updated ready for the next delta calculation /// </param> /// <param name="writer">Stream to write to</param> public virtual void Export(ref long absoluteTime, BinaryWriter writer) { if (this.absoluteTime < absoluteTime) { throw new FormatException("Can't export unsorted MIDI events"); } WriteVarInt(writer, (int) (this.absoluteTime - absoluteTime)); absoluteTime = this.absoluteTime; var output = (int) commandCode; if (commandCode != MidiCommandCode.MetaEvent) { output += (channel - 1); } writer.Write((byte) output); } } }
using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; using Serilog.Events; namespace Serilog.Sinks.MSSqlServer.Output { internal class XmlPropertyFormatter : IXmlPropertyFormatter { private static readonly Regex _invalidXMLChars = new Regex( @"(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFEFF\uFFFE\uFFFF]", RegexOptions.Compiled); public string Simplify(LogEventPropertyValue value, ColumnOptions.PropertiesColumnOptions options) { if (value is ScalarValue scalar) { return SimplifyScalar(scalar.Value); } if (value is DictionaryValue dict) { return SimplifyDictionary(options, dict); } if (value is SequenceValue seq) { return SimplifySequence(options, seq); } if (value is StructureValue str) { return SimplifyStructure(options, str); } return null; } public string GetValidElementName(string name) { if (string.IsNullOrWhiteSpace(name)) { return "x"; } var validName = name.Trim(); if (!char.IsLetter(validName[0]) || validName.StartsWith("xml", true, CultureInfo.CurrentCulture)) { validName = "x" + validName; } validName = Regex.Replace(validName, @"\s", "_"); return validName; } private static string SimplifyScalar(object value) { if (value == null) return null; return new XText(_invalidXMLChars.Replace(value.ToString(), m => "\\u" + ((ushort)m.Value[0]).ToString("x4", CultureInfo.InvariantCulture))).ToString(); } private string SimplifyDictionary(ColumnOptions.PropertiesColumnOptions options, DictionaryValue dict) { var sb = new StringBuilder(); var isEmpty = true; foreach (var element in dict.Elements) { var itemValue = Simplify(element.Value, options); if (options.OmitElementIfEmpty && string.IsNullOrEmpty(itemValue)) { continue; } if (isEmpty) { isEmpty = false; if (!options.OmitDictionaryContainerElement) { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>", options.DictionaryElementName); } } var key = SimplifyScalar(element.Key.Value); if (options.UsePropertyKeyAsElementName) { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", GetValidElementName(key), itemValue); } else { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0} key='{1}'>{2}</{0}>", options.ItemElementName, key, itemValue); } } if (!isEmpty && !options.OmitDictionaryContainerElement) { sb.AppendFormat(CultureInfo.InvariantCulture, "</{0}>", options.DictionaryElementName); } return sb.ToString(); } private string SimplifySequence(ColumnOptions.PropertiesColumnOptions options, SequenceValue seq) { var sb = new StringBuilder(); var isEmpty = true; foreach (var element in seq.Elements) { var itemValue = Simplify(element, options); if (options.OmitElementIfEmpty && string.IsNullOrEmpty(itemValue)) { continue; } if (isEmpty) { isEmpty = false; if (!options.OmitSequenceContainerElement) { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>", options.SequenceElementName); } } sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", options.ItemElementName, itemValue); } if (!isEmpty && !options.OmitSequenceContainerElement) { sb.AppendFormat(CultureInfo.InvariantCulture, "</{0}>", options.SequenceElementName); } return sb.ToString(); } private string SimplifyStructure(ColumnOptions.PropertiesColumnOptions options, StructureValue str) { var props = str.Properties.ToDictionary(p => p.Name, p => Simplify(p.Value, options)); var sb = new StringBuilder(); var isEmpty = true; foreach (var element in props) { var itemValue = element.Value; if (options.OmitElementIfEmpty && string.IsNullOrEmpty(itemValue)) { continue; } if (isEmpty) { isEmpty = false; if (!options.OmitStructureContainerElement) { if (options.UsePropertyKeyAsElementName) { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>", GetValidElementName(str.TypeTag)); } else { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0} type='{1}'>", options.StructureElementName, str.TypeTag); } } } if (options.UsePropertyKeyAsElementName) { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0}>{1}</{0}>", GetValidElementName(element.Key), itemValue); } else { sb.AppendFormat(CultureInfo.InvariantCulture, "<{0} key='{1}'>{2}</{0}>", options.PropertyElementName, element.Key, itemValue); } } if (!isEmpty && !options.OmitStructureContainerElement) { if (options.UsePropertyKeyAsElementName) { sb.AppendFormat(CultureInfo.InvariantCulture, "</{0}>", GetValidElementName(str.TypeTag)); } else { sb.AppendFormat(CultureInfo.InvariantCulture, "</{0}>", options.StructureElementName); } } return sb.ToString(); } } }
/* * Copyright 2010-2013 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. */ 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.RDS.Model { /// <summary> /// Container for the parameters to the ModifyDBInstance operation. /// <para> Modify settings for a DB Instance. You can change one or more database configuration parameters by specifying these parameters and /// the new values in the request. </para> /// </summary> /// <seealso cref="Amazon.RDS.AmazonRDS.ModifyDBInstance"/> public class ModifyDBInstanceRequest : AmazonWebServiceRequest { private string dBInstanceIdentifier; private int? allocatedStorage; private string dBInstanceClass; private List<string> dBSecurityGroups = new List<string>(); private List<string> vpcSecurityGroupIds = new List<string>(); private bool? applyImmediately; private string masterUserPassword; private string dBParameterGroupName; private int? backupRetentionPeriod; private string preferredBackupWindow; private string preferredMaintenanceWindow; private bool? multiAZ; private string engineVersion; private bool? allowMajorVersionUpgrade; private bool? autoMinorVersionUpgrade; private int? iops; private string optionGroupName; private string newDBInstanceIdentifier; /// <summary> /// The DB Instance identifier. This value is stored as a lowercase string. Constraints: <ul> <li>Must be the identifier for an existing DB /// Instance</li> <li>Must contain from 1 to 63 alphanumeric characters or hyphens</li> <li>First character must be a letter</li> <li>Cannot end /// with a hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public string DBInstanceIdentifier { get { return this.dBInstanceIdentifier; } set { this.dBInstanceIdentifier = value; } } /// <summary> /// Sets the DBInstanceIdentifier property /// </summary> /// <param name="dBInstanceIdentifier">The value to set for the DBInstanceIdentifier property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithDBInstanceIdentifier(string dBInstanceIdentifier) { this.dBInstanceIdentifier = dBInstanceIdentifier; return this; } // Check to see if DBInstanceIdentifier property is set internal bool IsSetDBInstanceIdentifier() { return this.dBInstanceIdentifier != null; } /// <summary> /// The new storage capacity of the RDS instance. Changing this parameter does not result in an outage and the change is applied during the next /// maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> for this request. <b>MySQL</b> Default: Uses existing /// setting Valid Values: 5-1024 Constraints: Value supplied must be at least 10% greater than the current value. Values that are not at least /// 10% greater than the existing value are rounded up so that they are 10% greater than the current value. Type: Integer <b>Oracle</b> Default: /// Uses existing setting Valid Values: 10-1024 Constraints: Value supplied must be at least 10% greater than the current value. Values that are /// not at least 10% greater than the existing value are rounded up so that they are 10% greater than the current value. <b>SQL Server</b> /// Cannot be modified. If you choose to migrate your DB instance from using standard storage to using Provisioned IOPS, or from using /// Provisioned IOPS to using standard storage, the process can take time. The duration of the migration depends on several factors such as /// database load, storage size, storage type (standard or Provisioned IOPS), amount of IOPS provisioned (if any), and the number of prior scale /// storage operations. Typical migration times are under 24 hours, but the process can take up to several days in some cases. During the /// migration, the DB instance will be available for use, but may experience performance degradation. While the migration takes place, nightly /// backups for the instance will be suspended. No other Amazon RDS operations can take place for the instance, including modifying the /// instance, rebooting the instance, deleting the instance, creating a read replica for the instance, and creating a DB snapshot of the /// instance. /// /// </summary> public int AllocatedStorage { get { return this.allocatedStorage ?? default(int); } set { this.allocatedStorage = value; } } /// <summary> /// Sets the AllocatedStorage property /// </summary> /// <param name="allocatedStorage">The value to set for the AllocatedStorage property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithAllocatedStorage(int allocatedStorage) { this.allocatedStorage = allocatedStorage; return this; } // Check to see if AllocatedStorage property is set internal bool IsSetAllocatedStorage() { return this.allocatedStorage.HasValue; } /// <summary> /// The new compute and memory capacity of the DB Instance. To determine the instance classes that are available for a particular DB engine, use /// the <a>DescribeOrderableDBInstanceOptions</a> action. Passing a value for this parameter causes an outage during the change and is applied /// during the next maintenance window, unless the <c>ApplyImmediately</c> parameter is specified as <c>true</c> for this request. Default: Uses /// existing setting Valid Values: <c>db.t1.micro | db.m1.small | db.m1.medium | db.m1.large | db.m1.xlarge | db.m2.xlarge | db.m2.2xlarge | /// db.m2.4xlarge</c> /// /// </summary> public string DBInstanceClass { get { return this.dBInstanceClass; } set { this.dBInstanceClass = value; } } /// <summary> /// Sets the DBInstanceClass property /// </summary> /// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithDBInstanceClass(string dBInstanceClass) { this.dBInstanceClass = dBInstanceClass; return this; } // Check to see if DBInstanceClass property is set internal bool IsSetDBInstanceClass() { return this.dBInstanceClass != null; } /// <summary> /// A list of DB Security Groups to authorize on this DB Instance. Changing this parameter does not result in an outage and the change is /// asynchronously applied as soon as possible. Constraints: <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be /// a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public List<string> DBSecurityGroups { get { return this.dBSecurityGroups; } set { this.dBSecurityGroups = value; } } /// <summary> /// Adds elements to the DBSecurityGroups collection /// </summary> /// <param name="dBSecurityGroups">The values to add to the DBSecurityGroups collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithDBSecurityGroups(params string[] dBSecurityGroups) { foreach (string element in dBSecurityGroups) { this.dBSecurityGroups.Add(element); } return this; } /// <summary> /// Adds elements to the DBSecurityGroups collection /// </summary> /// <param name="dBSecurityGroups">The values to add to the DBSecurityGroups collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithDBSecurityGroups(IEnumerable<string> dBSecurityGroups) { foreach (string element in dBSecurityGroups) { this.dBSecurityGroups.Add(element); } return this; } // Check to see if DBSecurityGroups property is set internal bool IsSetDBSecurityGroups() { return this.dBSecurityGroups.Count > 0; } /// <summary> /// A list of EC2 VPC Security Groups to authorize on this DB Instance. This change is asynchronously applied as soon as possible. Constraints: /// <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be a letter</li> <li>Cannot end with a hyphen or contain two /// consecutive hyphens</li> </ul> /// /// </summary> public List<string> VpcSecurityGroupIds { get { return this.vpcSecurityGroupIds; } set { this.vpcSecurityGroupIds = value; } } /// <summary> /// Adds elements to the VpcSecurityGroupIds collection /// </summary> /// <param name="vpcSecurityGroupIds">The values to add to the VpcSecurityGroupIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithVpcSecurityGroupIds(params string[] vpcSecurityGroupIds) { foreach (string element in vpcSecurityGroupIds) { this.vpcSecurityGroupIds.Add(element); } return this; } /// <summary> /// Adds elements to the VpcSecurityGroupIds collection /// </summary> /// <param name="vpcSecurityGroupIds">The values to add to the VpcSecurityGroupIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithVpcSecurityGroupIds(IEnumerable<string> vpcSecurityGroupIds) { foreach (string element in vpcSecurityGroupIds) { this.vpcSecurityGroupIds.Add(element); } return this; } // Check to see if VpcSecurityGroupIds property is set internal bool IsSetVpcSecurityGroupIds() { return this.vpcSecurityGroupIds.Count > 0; } /// <summary> /// Specifies whether or not the modifications in this request and any pending modifications are asynchronously applied as soon as possible, /// regardless of the <c>PreferredMaintenanceWindow</c> setting for the DB Instance. If this parameter is passed as <c>false</c>, changes to the /// DB Instance are applied on the next call to <a>RebootDBInstance</a>, the next maintenance reboot, or the next failure reboot, whichever /// occurs first. See each parameter to determine when a change is applied. Default: <c>false</c> /// /// </summary> public bool ApplyImmediately { get { return this.applyImmediately ?? default(bool); } set { this.applyImmediately = value; } } /// <summary> /// Sets the ApplyImmediately property /// </summary> /// <param name="applyImmediately">The value to set for the ApplyImmediately property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithApplyImmediately(bool applyImmediately) { this.applyImmediately = applyImmediately; return this; } // Check to see if ApplyImmediately property is set internal bool IsSetApplyImmediately() { return this.applyImmediately.HasValue; } /// <summary> /// The new password for the DB Instance master user. Can be any printable ASCII character except "/", "\", or "@". Changing this parameter does /// not result in an outage and the change is asynchronously applied as soon as possible. Between the time of the request and the completion of /// the request, the <c>MasterUserPassword</c> element exists in the <c>PendingModifiedValues</c> element of the operation response. Default: /// Uses existing setting Constraints: Must be 8 to 41 alphanumeric characters (MySQL), 8 to 30 alphanumeric characters (Oracle), or 8 to 128 /// alphanumeric characters (SQL Server). <note> Amazon RDS API actions never return the password, so this action provides a way to regain /// access to a master instance user if the password is lost. </note> /// /// </summary> public string MasterUserPassword { get { return this.masterUserPassword; } set { this.masterUserPassword = value; } } /// <summary> /// Sets the MasterUserPassword property /// </summary> /// <param name="masterUserPassword">The value to set for the MasterUserPassword property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithMasterUserPassword(string masterUserPassword) { this.masterUserPassword = masterUserPassword; return this; } // Check to see if MasterUserPassword property is set internal bool IsSetMasterUserPassword() { return this.masterUserPassword != null; } /// <summary> /// The name of the DB Parameter Group to apply to this DB Instance. Changing this parameter does not result in an outage and the change is /// applied during the next maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> for this request. Default: /// Uses existing setting Constraints: The DB Parameter Group must be in the same DB Parameter Group family as this DB Instance. /// /// </summary> public string DBParameterGroupName { get { return this.dBParameterGroupName; } set { this.dBParameterGroupName = value; } } /// <summary> /// Sets the DBParameterGroupName property /// </summary> /// <param name="dBParameterGroupName">The value to set for the DBParameterGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithDBParameterGroupName(string dBParameterGroupName) { this.dBParameterGroupName = dBParameterGroupName; return this; } // Check to see if DBParameterGroupName property is set internal bool IsSetDBParameterGroupName() { return this.dBParameterGroupName != null; } /// <summary> /// The number of days to retain automated backups. Setting this parameter to a positive number enables backups. Setting this parameter to 0 /// disables automated backups. Changing this parameter can result in an outage if you change from 0 to a non-zero value or from a non-zero /// value to 0. These changes are applied during the next maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> /// for this request. If you change the parameter from one non-zero value to another non-zero value, the change is asynchronously applied as /// soon as possible. Default: Uses existing setting Constraints: <ul> <li>Must be a value from 0 to 8</li> <li>Cannot be set to 0 if the DB /// Instance is a master instance with read replicas or if the DB Instance is a read replica</li> </ul> /// /// </summary> public int BackupRetentionPeriod { get { return this.backupRetentionPeriod ?? default(int); } set { this.backupRetentionPeriod = value; } } /// <summary> /// Sets the BackupRetentionPeriod property /// </summary> /// <param name="backupRetentionPeriod">The value to set for the BackupRetentionPeriod property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; return this; } // Check to see if BackupRetentionPeriod property is set internal bool IsSetBackupRetentionPeriod() { return this.backupRetentionPeriod.HasValue; } /// <summary> /// The daily time range during which automated backups are created if automated backups are enabled, as determined by the /// <c>BackupRetentionPeriod</c>. Changing this parameter does not result in an outage and the change is asynchronously applied as soon as /// possible. Constraints: <ul> <li>Must be in the format hh24:mi-hh24:mi</li> <li>Times should be Universal Time Coordinated (UTC)</li> /// <li>Must not conflict with the preferred maintenance window</li> <li>Must be at least 30 minutes</li> </ul> /// /// </summary> public string PreferredBackupWindow { get { return this.preferredBackupWindow; } set { this.preferredBackupWindow = value; } } /// <summary> /// Sets the PreferredBackupWindow property /// </summary> /// <param name="preferredBackupWindow">The value to set for the PreferredBackupWindow property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithPreferredBackupWindow(string preferredBackupWindow) { this.preferredBackupWindow = preferredBackupWindow; return this; } // Check to see if PreferredBackupWindow property is set internal bool IsSetPreferredBackupWindow() { return this.preferredBackupWindow != null; } /// <summary> /// The weekly time range (in UTC) during which system maintenance can occur, which may result in an outage. Changing this parameter does not /// result in an outage, except in the following situation, and the change is asynchronously applied as soon as possible. If there are pending /// actions that cause a reboot, and the maintenance window is changed to include the current time, then changing this parameter will cause a /// reboot of the DB Instance. If moving this window to the current time, there must be at least 30 minutes between the current time and end of /// the window to ensure pending changes are applied. Default: Uses existing setting Format: ddd:hh24:mi-ddd:hh24:mi Valid Days: Mon | Tue | Wed /// | Thu | Fri | Sat | Sun Constraints: Must be at least 30 minutes /// /// </summary> public string PreferredMaintenanceWindow { get { return this.preferredMaintenanceWindow; } set { this.preferredMaintenanceWindow = value; } } /// <summary> /// Sets the PreferredMaintenanceWindow property /// </summary> /// <param name="preferredMaintenanceWindow">The value to set for the PreferredMaintenanceWindow property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithPreferredMaintenanceWindow(string preferredMaintenanceWindow) { this.preferredMaintenanceWindow = preferredMaintenanceWindow; return this; } // Check to see if PreferredMaintenanceWindow property is set internal bool IsSetPreferredMaintenanceWindow() { return this.preferredMaintenanceWindow != null; } /// <summary> /// Specifies if the DB Instance is a Multi-AZ deployment. Changing this parameter does not result in an outage and the change is applied during /// the next maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> for this request. Constraints: Cannot be /// specified if the DB Instance is a read replica. /// /// </summary> public bool MultiAZ { get { return this.multiAZ ?? default(bool); } set { this.multiAZ = value; } } /// <summary> /// Sets the MultiAZ property /// </summary> /// <param name="multiAZ">The value to set for the MultiAZ property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithMultiAZ(bool multiAZ) { this.multiAZ = multiAZ; return this; } // Check to see if MultiAZ property is set internal bool IsSetMultiAZ() { return this.multiAZ.HasValue; } /// <summary> /// The version number of the database engine to upgrade to. Changing this parameter results in an outage and the change is applied during the /// next maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> for this request. For major version upgrades, if /// a nondefault DB Parameter Group is currently in use, a new DB Parameter Group in the DB Parameter Group Family for the new engine version /// must be specified. The new DB Parameter Group can be the default for that DB Parameter Group Family. Example: <c>5.1.42</c> /// /// </summary> public string EngineVersion { get { return this.engineVersion; } set { this.engineVersion = value; } } /// <summary> /// Sets the EngineVersion property /// </summary> /// <param name="engineVersion">The value to set for the EngineVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithEngineVersion(string engineVersion) { this.engineVersion = engineVersion; return this; } // Check to see if EngineVersion property is set internal bool IsSetEngineVersion() { return this.engineVersion != null; } /// <summary> /// Indicates that major version upgrades are allowed. Changing this parameter does not result in an outage and the change is asynchronously /// applied as soon as possible. Constraints: This parameter must be set to true when specifying a value for the EngineVersion parameter that is /// a different major version than the DB Instance's current version. /// /// </summary> public bool AllowMajorVersionUpgrade { get { return this.allowMajorVersionUpgrade ?? default(bool); } set { this.allowMajorVersionUpgrade = value; } } /// <summary> /// Sets the AllowMajorVersionUpgrade property /// </summary> /// <param name="allowMajorVersionUpgrade">The value to set for the AllowMajorVersionUpgrade property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithAllowMajorVersionUpgrade(bool allowMajorVersionUpgrade) { this.allowMajorVersionUpgrade = allowMajorVersionUpgrade; return this; } // Check to see if AllowMajorVersionUpgrade property is set internal bool IsSetAllowMajorVersionUpgrade() { return this.allowMajorVersionUpgrade.HasValue; } /// <summary> /// Indicates that minor version upgrades will be applied automatically to the DB Instance during the maintenance window. Changing this /// parameter does not result in an outage except in the following case and the change is asynchronously applied as soon as possible. An outage /// will result if this parameter is set to <c>true</c> during the maintenance window, and a newer minor version is available, and RDS has /// enabled auto patching for that engine version. /// /// </summary> public bool AutoMinorVersionUpgrade { get { return this.autoMinorVersionUpgrade ?? default(bool); } set { this.autoMinorVersionUpgrade = value; } } /// <summary> /// Sets the AutoMinorVersionUpgrade property /// </summary> /// <param name="autoMinorVersionUpgrade">The value to set for the AutoMinorVersionUpgrade property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithAutoMinorVersionUpgrade(bool autoMinorVersionUpgrade) { this.autoMinorVersionUpgrade = autoMinorVersionUpgrade; return this; } // Check to see if AutoMinorVersionUpgrade property is set internal bool IsSetAutoMinorVersionUpgrade() { return this.autoMinorVersionUpgrade.HasValue; } /// <summary> /// The new Provisioned IOPS (I/O operations per second) value for the RDS instance. Changing this parameter does not result in an outage and /// the change is applied during the next maintenance window unless the <c>ApplyImmediately</c> parameter is set to <c>true</c> for this /// request. Default: Uses existing setting Constraints: Value supplied must be at least 10% greater than the current value. Values that are not /// at least 10% greater than the existing value are rounded up so that they are 10% greater than the current value. Type: Integer If you choose /// to migrate your DB instance from using standard storage to using Provisioned IOPS, or from using Provisioned IOPS to using standard storage, /// the process can take time. The duration of the migration depends on several factors such as database load, storage size, storage type /// (standard or Provisioned IOPS), amount of IOPS provisioned (if any), and the number of prior scale storage operations. Typical migration /// times are under 24 hours, but the process can take up to several days in some cases. During the migration, the DB instance will be available /// for use, but may experience performance degradation. While the migration takes place, nightly backups for the instance will be suspended. No /// other Amazon RDS operations can take place for the instance, including modifying the instance, rebooting the instance, deleting the /// instance, creating a read replica for the instance, and creating a DB snapshot of the instance. /// /// </summary> public int Iops { get { return this.iops ?? default(int); } set { this.iops = value; } } /// <summary> /// Sets the Iops property /// </summary> /// <param name="iops">The value to set for the Iops property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithIops(int iops) { this.iops = iops; return this; } // Check to see if Iops property is set internal bool IsSetIops() { return this.iops.HasValue; } /// <summary> /// Indicates that the DB Instance should be associated with the specified option group. Changing this parameter does not result in an outage /// except in the following case and the change is applied during the next maintenance window unless the <c>ApplyImmediately</c> parameter is /// set to <c>true</c> for this request. If the parameter change results in an option group that enables OEM, this change can cause a brief /// (sub-second) period during which new connections are rejected but existing connections are not interrupted. <!-- Note that persistent /// options, such as the TDE_SQLServer option for Microsoft SQL Server, cannot be removed from an option group while DB instances are associated /// with the option group. --> Permanent options, such as the TDE option for Oracle Advanced Security TDE, cannot be removed from an option /// group, and that option group cannot be removed from a DB instance once it is associated with a DB instance /// /// </summary> public string OptionGroupName { get { return this.optionGroupName; } set { this.optionGroupName = value; } } /// <summary> /// Sets the OptionGroupName property /// </summary> /// <param name="optionGroupName">The value to set for the OptionGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithOptionGroupName(string optionGroupName) { this.optionGroupName = optionGroupName; return this; } // Check to see if OptionGroupName property is set internal bool IsSetOptionGroupName() { return this.optionGroupName != null; } /// <summary> /// The new DB Instance identifier for the DB Instance when renaming a DB Instance. This value is stored as a lowercase string. Constraints: /// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens</li> <li>First character must be a letter</li> <li>Cannot end with a /// hyphen or contain two consecutive hyphens</li> </ul> /// /// </summary> public string NewDBInstanceIdentifier { get { return this.newDBInstanceIdentifier; } set { this.newDBInstanceIdentifier = value; } } /// <summary> /// Sets the NewDBInstanceIdentifier property /// </summary> /// <param name="newDBInstanceIdentifier">The value to set for the NewDBInstanceIdentifier property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ModifyDBInstanceRequest WithNewDBInstanceIdentifier(string newDBInstanceIdentifier) { this.newDBInstanceIdentifier = newDBInstanceIdentifier; return this; } // Check to see if NewDBInstanceIdentifier property is set internal bool IsSetNewDBInstanceIdentifier() { return this.newDBInstanceIdentifier != null; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Reflection.Emit { public static class __MethodBuilder { public static IObservable<System.Boolean> Equals( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Object> obj) { return Observable.Zip(MethodBuilderValue, obj, (MethodBuilderValueLambda, objLambda) => MethodBuilderValueLambda.Equals(objLambda)); } public static IObservable<System.Int32> GetHashCode( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetHashCode()); } public static IObservable<System.String> ToString( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ToString()); } public static IObservable<System.Object> Invoke( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Object> obj, IObservable<System.Reflection.BindingFlags> invokeAttr, IObservable<System.Reflection.Binder> binder, IObservable<System.Object[]> parameters, IObservable<System.Globalization.CultureInfo> culture) { return Observable.Zip(MethodBuilderValue, obj, invokeAttr, binder, parameters, culture, (MethodBuilderValueLambda, objLambda, invokeAttrLambda, binderLambda, parametersLambda, cultureLambda) => MethodBuilderValueLambda.Invoke(objLambda, invokeAttrLambda, binderLambda, parametersLambda, cultureLambda)); } public static IObservable<System.Reflection.MethodImplAttributes> GetMethodImplementationFlags( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetMethodImplementationFlags()); } public static IObservable<System.Reflection.MethodInfo> GetBaseDefinition( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetBaseDefinition()); } public static IObservable<System.Reflection.ParameterInfo[]> GetParameters( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetParameters()); } public static IObservable<System.Object[]> GetCustomAttributes( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Boolean> inherit) { return Observable.Zip(MethodBuilderValue, inherit, (MethodBuilderValueLambda, inheritLambda) => MethodBuilderValueLambda.GetCustomAttributes(inheritLambda)); } public static IObservable<System.Object[]> GetCustomAttributes( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit) { return Observable.Zip(MethodBuilderValue, attributeType, inherit, (MethodBuilderValueLambda, attributeTypeLambda, inheritLambda) => MethodBuilderValueLambda.GetCustomAttributes(attributeTypeLambda, inheritLambda)); } public static IObservable<System.Boolean> IsDefined( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type> attributeType, IObservable<System.Boolean> inherit) { return Observable.Zip(MethodBuilderValue, attributeType, inherit, (MethodBuilderValueLambda, attributeTypeLambda, inheritLambda) => MethodBuilderValueLambda.IsDefined(attributeTypeLambda, inheritLambda)); } public static IObservable<System.Reflection.MethodInfo> GetGenericMethodDefinition( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetGenericMethodDefinition()); } public static IObservable<System.Type[]> GetGenericArguments( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetGenericArguments()); } public static IObservable<System.Reflection.MethodInfo> MakeGenericMethod( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type[]> typeArguments) { return Observable.Zip(MethodBuilderValue, typeArguments, (MethodBuilderValueLambda, typeArgumentsLambda) => MethodBuilderValueLambda.MakeGenericMethod(typeArgumentsLambda)); } public static IObservable<System.Reflection.Emit.GenericTypeParameterBuilder[]> DefineGenericParameters( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.String[]> names) { return Observable.Zip(MethodBuilderValue, names, (MethodBuilderValueLambda, namesLambda) => MethodBuilderValueLambda.DefineGenericParameters(namesLambda)); } public static IObservable<System.Reflection.Emit.MethodToken> GetToken( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetToken()); } public static IObservable<System.Reactive.Unit> SetParameters( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type[]> parameterTypes) { return ObservableExt.ZipExecute(MethodBuilderValue, parameterTypes, (MethodBuilderValueLambda, parameterTypesLambda) => MethodBuilderValueLambda.SetParameters(parameterTypesLambda)); } public static IObservable<System.Reactive.Unit> SetReturnType( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type> returnType) { return ObservableExt.ZipExecute(MethodBuilderValue, returnType, (MethodBuilderValueLambda, returnTypeLambda) => MethodBuilderValueLambda.SetReturnType(returnTypeLambda)); } public static IObservable<System.Reactive.Unit> SetSignature( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Type> returnType, IObservable<System.Type[]> returnTypeRequiredCustomModifiers, IObservable<System.Type[]> returnTypeOptionalCustomModifiers, IObservable<System.Type[]> parameterTypes, IObservable<System.Type[][]> parameterTypeRequiredCustomModifiers, IObservable<System.Type[][]> parameterTypeOptionalCustomModifiers) { return ObservableExt.ZipExecute(MethodBuilderValue, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, (MethodBuilderValueLambda, returnTypeLambda, returnTypeRequiredCustomModifiersLambda, returnTypeOptionalCustomModifiersLambda, parameterTypesLambda, parameterTypeRequiredCustomModifiersLambda, parameterTypeOptionalCustomModifiersLambda) => MethodBuilderValueLambda.SetSignature(returnTypeLambda, returnTypeRequiredCustomModifiersLambda, returnTypeOptionalCustomModifiersLambda, parameterTypesLambda, parameterTypeRequiredCustomModifiersLambda, parameterTypeOptionalCustomModifiersLambda)); } public static IObservable<System.Reflection.Emit.ParameterBuilder> DefineParameter( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Int32> position, IObservable<System.Reflection.ParameterAttributes> attributes, IObservable<System.String> strParamName) { return Observable.Zip(MethodBuilderValue, position, attributes, strParamName, (MethodBuilderValueLambda, positionLambda, attributesLambda, strParamNameLambda) => MethodBuilderValueLambda.DefineParameter(positionLambda, attributesLambda, strParamNameLambda)); } public static IObservable<System.Reactive.Unit> SetMarshal( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Reflection.Emit.UnmanagedMarshal> unmanagedMarshal) { return ObservableExt.ZipExecute(MethodBuilderValue, unmanagedMarshal, (MethodBuilderValueLambda, unmanagedMarshalLambda) => MethodBuilderValueLambda.SetMarshal(unmanagedMarshalLambda)); } public static IObservable<System.Reactive.Unit> SetSymCustomAttribute( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.String> name, IObservable<System.Byte[]> data) { return ObservableExt.ZipExecute(MethodBuilderValue, name, data, (MethodBuilderValueLambda, nameLambda, dataLambda) => MethodBuilderValueLambda.SetSymCustomAttribute(nameLambda, dataLambda)); } public static IObservable<System.Reactive.Unit> AddDeclarativeSecurity( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Security.Permissions.SecurityAction> action, IObservable<System.Security.PermissionSet> pset) { return ObservableExt.ZipExecute(MethodBuilderValue, action, pset, (MethodBuilderValueLambda, actionLambda, psetLambda) => MethodBuilderValueLambda.AddDeclarativeSecurity(actionLambda, psetLambda)); } public static IObservable<System.Reactive.Unit> SetMethodBody( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Byte[]> il, IObservable<System.Int32> maxStack, IObservable<System.Byte[]> localSignature, IObservable<System.Collections.Generic.IEnumerable<System.Reflection.Emit.ExceptionHandler>> exceptionHandlers, IObservable<System.Collections.Generic.IEnumerable<System.Int32>> tokenFixups) { return ObservableExt.ZipExecute(MethodBuilderValue, il, maxStack, localSignature, exceptionHandlers, tokenFixups, (MethodBuilderValueLambda, ilLambda, maxStackLambda, localSignatureLambda, exceptionHandlersLambda, tokenFixupsLambda) => MethodBuilderValueLambda.SetMethodBody(ilLambda, maxStackLambda, localSignatureLambda, exceptionHandlersLambda, tokenFixupsLambda)); } public static IObservable<System.Reactive.Unit> CreateMethodBody( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Byte[]> il, IObservable<System.Int32> count) { return ObservableExt.ZipExecute(MethodBuilderValue, il, count, (MethodBuilderValueLambda, ilLambda, countLambda) => MethodBuilderValueLambda.CreateMethodBody(ilLambda, countLambda)); } public static IObservable<System.Reactive.Unit> SetImplementationFlags( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Reflection.MethodImplAttributes> attributes) { return ObservableExt.ZipExecute(MethodBuilderValue, attributes, (MethodBuilderValueLambda, attributesLambda) => MethodBuilderValueLambda.SetImplementationFlags(attributesLambda)); } public static IObservable<System.Reflection.Emit.ILGenerator> GetILGenerator( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetILGenerator()); } public static IObservable<System.Reflection.Emit.ILGenerator> GetILGenerator( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Int32> size) { return Observable.Zip(MethodBuilderValue, size, (MethodBuilderValueLambda, sizeLambda) => MethodBuilderValueLambda.GetILGenerator(sizeLambda)); } public static IObservable<System.Reflection.Module> GetModule( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.GetModule()); } public static IObservable<System.Reactive.Unit> SetCustomAttribute( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Reflection.ConstructorInfo> con, IObservable<System.Byte[]> binaryAttribute) { return ObservableExt.ZipExecute(MethodBuilderValue, con, binaryAttribute, (MethodBuilderValueLambda, conLambda, binaryAttributeLambda) => MethodBuilderValueLambda.SetCustomAttribute(conLambda, binaryAttributeLambda)); } public static IObservable<System.Reactive.Unit> SetCustomAttribute( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Reflection.Emit.CustomAttributeBuilder> customBuilder) { return ObservableExt.ZipExecute(MethodBuilderValue, customBuilder, (MethodBuilderValueLambda, customBuilderLambda) => MethodBuilderValueLambda.SetCustomAttribute(customBuilderLambda)); } public static IObservable<System.String> get_Name( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.Name); } public static IObservable<System.Reflection.Module> get_Module( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.Module); } public static IObservable<System.Type> get_DeclaringType( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.DeclaringType); } public static IObservable<System.Reflection.ICustomAttributeProvider> get_ReturnTypeCustomAttributes( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ReturnTypeCustomAttributes); } public static IObservable<System.Type> get_ReflectedType( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ReflectedType); } public static IObservable<System.Reflection.MethodAttributes> get_Attributes( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.Attributes); } public static IObservable<System.Reflection.CallingConventions> get_CallingConvention( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.CallingConvention); } public static IObservable<System.RuntimeMethodHandle> get_MethodHandle( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.MethodHandle); } public static IObservable<System.Boolean> get_IsSecurityCritical( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.IsSecurityCritical); } public static IObservable<System.Boolean> get_IsSecuritySafeCritical( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.IsSecuritySafeCritical); } public static IObservable<System.Boolean> get_IsSecurityTransparent( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.IsSecurityTransparent); } public static IObservable<System.Type> get_ReturnType( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ReturnType); } public static IObservable<System.Reflection.ParameterInfo> get_ReturnParameter( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ReturnParameter); } public static IObservable<System.Boolean> get_IsGenericMethodDefinition( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.IsGenericMethodDefinition); } public static IObservable<System.Boolean> get_ContainsGenericParameters( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.ContainsGenericParameters); } public static IObservable<System.Boolean> get_IsGenericMethod( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.IsGenericMethod); } public static IObservable<System.Boolean> get_InitLocals( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.InitLocals); } public static IObservable<System.String> get_Signature( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue) { return Observable.Select(MethodBuilderValue, (MethodBuilderValueLambda) => MethodBuilderValueLambda.Signature); } public static IObservable<System.Reactive.Unit> set_InitLocals( this IObservable<System.Reflection.Emit.MethodBuilder> MethodBuilderValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(MethodBuilderValue, value, (MethodBuilderValueLambda, valueLambda) => MethodBuilderValueLambda.InitLocals = valueLambda); } } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using Abp.Auditing; using Abp.Authorization; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.Configuration; using Abp.EntityFramework; using Abp.Localization; using Abp.Notifications; using Abp.Organizations; using Abp.EntityFramework.Extensions; namespace Abp.Zero.EntityFramework { public abstract class AbpZeroCommonDbContext<TRole, TUser, TSelf> : AbpDbContext where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> where TSelf : AbpZeroCommonDbContext<TRole, TUser, TSelf> { /// <summary> /// Roles. /// </summary> public virtual DbSet<TRole> Roles { get; set; } /// <summary> /// Users. /// </summary> public virtual DbSet<TUser> Users { get; set; } /// <summary> /// User logins. /// </summary> public virtual DbSet<UserLogin> UserLogins { get; set; } /// <summary> /// User login attempts. /// </summary> public virtual DbSet<UserLoginAttempt> UserLoginAttempts { get; set; } /// <summary> /// User roles. /// </summary> public virtual DbSet<UserRole> UserRoles { get; set; } /// <summary> /// User claims. /// </summary> public virtual DbSet<UserClaim> UserClaims { get; set; } /// <summary> /// User tokens. /// </summary> public virtual DbSet<UserToken> UserTokens { get; set; } /// <summary> /// Role claims. /// </summary> public virtual DbSet<RoleClaim> RoleClaims { get; set; } /// <summary> /// Permissions. /// </summary> public virtual DbSet<PermissionSetting> Permissions { get; set; } /// <summary> /// Role permissions. /// </summary> public virtual DbSet<RolePermissionSetting> RolePermissions { get; set; } /// <summary> /// User permissions. /// </summary> public virtual DbSet<UserPermissionSetting> UserPermissions { get; set; } /// <summary> /// Settings. /// </summary> public virtual DbSet<Setting> Settings { get; set; } /// <summary> /// Audit logs. /// </summary> public virtual DbSet<AuditLog> AuditLogs { get; set; } /// <summary> /// Languages. /// </summary> public virtual DbSet<ApplicationLanguage> Languages { get; set; } /// <summary> /// LanguageTexts. /// </summary> public virtual DbSet<ApplicationLanguageText> LanguageTexts { get; set; } /// <summary> /// OrganizationUnits. /// </summary> public virtual DbSet<OrganizationUnit> OrganizationUnits { get; set; } /// <summary> /// UserOrganizationUnits. /// </summary> public virtual DbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; } /// <summary> /// OrganizationUnitRoles. /// </summary> public virtual DbSet<OrganizationUnitRole> OrganizationUnitRoles { get; set; } /// <summary> /// Tenant notifications. /// </summary> public virtual DbSet<TenantNotificationInfo> TenantNotifications { get; set; } /// <summary> /// User notifications. /// </summary> public virtual DbSet<UserNotificationInfo> UserNotifications { get; set; } /// <summary> /// Notification subscriptions. /// </summary> public virtual DbSet<NotificationSubscriptionInfo> NotificationSubscriptions { get; set; } /// <summary> /// Default constructor. /// Do not directly instantiate this class. Instead, use dependency injection! /// </summary> protected AbpZeroCommonDbContext() { } /// <summary> /// Constructor with connection string parameter. /// </summary> /// <param name="nameOrConnectionString">Connection string or a name in connection strings in configuration file</param> protected AbpZeroCommonDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected AbpZeroCommonDbContext(DbCompiledModel model) : base(model) { } /// <summary> /// This constructor can be used for unit tests. /// </summary> protected AbpZeroCommonDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected AbpZeroCommonDbContext(string nameOrConnectionString, DbCompiledModel model) : base(nameOrConnectionString, model) { } protected AbpZeroCommonDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { } /// <summary> /// Constructor. /// </summary> protected AbpZeroCommonDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) { } /// <summary> /// /// </summary> /// <param name="modelBuilder"></param> protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); #region TUser.Set_ConcurrencyStamp modelBuilder.Entity<TUser>() .Property(e => e.ConcurrencyStamp) .IsConcurrencyToken(); #endregion #region TUser.Set_ForeignKeys modelBuilder.Entity<TUser>() .HasOptional(p => p.DeleterUser) .WithMany() .HasForeignKey(p => p.DeleterUserId); modelBuilder.Entity<TUser>() .HasOptional(p => p.CreatorUser) .WithMany() .HasForeignKey(p => p.CreatorUserId); modelBuilder.Entity<TUser>() .HasOptional(p => p.LastModifierUser) .WithMany() .HasForeignKey(p => p.LastModifierUserId); #endregion #region TRole.Set_ConcurrencyStamp modelBuilder.Entity<TRole>() .Property(e => e.ConcurrencyStamp) .IsConcurrencyToken(); #endregion #region AuditLog.IX_TenantId_UserId modelBuilder.Entity<AuditLog>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<AuditLog>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); #endregion #region AuditLog.IX_TenantId_ExecutionTime modelBuilder.Entity<AuditLog>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_ExecutionTime", 1); modelBuilder.Entity<AuditLog>() .Property(e => e.ExecutionTime) .CreateIndex("IX_TenantId_ExecutionTime", 2); #endregion #region AuditLog.IX_TenantId_ExecutionDuration modelBuilder.Entity<AuditLog>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_ExecutionDuration", 1); modelBuilder.Entity<AuditLog>() .Property(e => e.ExecutionDuration) .CreateIndex("IX_TenantId_ExecutionDuration", 2); #endregion #region ApplicationLanguage.IX_TenantId_Name modelBuilder.Entity<ApplicationLanguage>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Name", 1); modelBuilder.Entity<ApplicationLanguage>() .Property(e => e.Name) .CreateIndex("IX_TenantId_Name", 2); #endregion #region ApplicationLanguageText.IX_TenantId_Source_LanguageName_Key modelBuilder.Entity<ApplicationLanguageText>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Source_LanguageName_Key", 1); modelBuilder.Entity<ApplicationLanguageText>() .Property(e => e.Source) .CreateIndex("IX_TenantId_Source_LanguageName_Key", 2); modelBuilder.Entity<ApplicationLanguageText>() .Property(e => e.LanguageName) .CreateIndex("IX_TenantId_Source_LanguageName_Key", 3); modelBuilder.Entity<ApplicationLanguageText>() .Property(e => e.Key) .CreateIndex("IX_TenantId_Source_LanguageName_Key", 4); #endregion #region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.NotificationName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.EntityTypeName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.EntityId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.UserId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4); #endregion #region NotificationSubscriptionInfo.IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 1); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.NotificationName) .CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 2); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.EntityTypeName) .CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 3); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.EntityId) .CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 4); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_NotificationName_EntityTypeName_EntityId_UserId", 5); #endregion #region UserNotificationInfo.IX_UserId_State_CreationTime modelBuilder.Entity<UserNotificationInfo>() .Property(e => e.UserId) .CreateIndex("IX_UserId_State_CreationTime", 1); modelBuilder.Entity<UserNotificationInfo>() .Property(e => e.State) .CreateIndex("IX_UserId_State_CreationTime", 2); modelBuilder.Entity<UserNotificationInfo>() .Property(e => e.CreationTime) .CreateIndex("IX_UserId_State_CreationTime", 3); #endregion #region OrganizationUnit.IX_TenantId_Code modelBuilder.Entity<OrganizationUnit>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Code", 1); modelBuilder.Entity<OrganizationUnit>() .Property(e => e.Code) .CreateIndex("IX_TenantId_Code", 2); #endregion #region PermissionSetting.IX_TenantId_Name modelBuilder.Entity<PermissionSetting>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Name", 1); modelBuilder.Entity<PermissionSetting>() .Property(e => e.Name) .CreateIndex("IX_TenantId_Name", 2); #endregion #region RoleClaim.IX_RoleId modelBuilder.Entity<RoleClaim>() .Property(e => e.RoleId) .CreateIndex("IX_RoleId", 1); #endregion #region RoleClaim.IX_TenantId_ClaimType modelBuilder.Entity<RoleClaim>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_ClaimType", 1); modelBuilder.Entity<RoleClaim>() .Property(e => e.ClaimType) .CreateIndex("IX_TenantId_ClaimType", 2); #endregion #region Role.IX_TenantId_NormalizedName modelBuilder.Entity<TRole>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_NormalizedName", 1); modelBuilder.Entity<TRole>() .Property(e => e.NormalizedName) .CreateIndex("IX_TenantId_NormalizedName", 2); #endregion #region Setting.IX_TenantId_Name modelBuilder.Entity<Setting>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Name", 1); modelBuilder.Entity<Setting>() .Property(e => e.Name) .CreateIndex("IX_TenantId_Name", 2); #endregion #region TenantNotificationInfo.IX_TenantId modelBuilder.Entity<TenantNotificationInfo>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_Name", 1); #endregion #region UserClaim.IX_TenantId_ClaimType modelBuilder.Entity<UserClaim>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_ClaimType", 1); modelBuilder.Entity<UserClaim>() .Property(e => e.ClaimType) .CreateIndex("IX_TenantId_ClaimType", 2); #endregion #region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result modelBuilder.Entity<UserLoginAttempt>() .Property(e => e.TenancyName) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(e => e.UserNameOrEmailAddress) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.Result) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3); #endregion #region UserLoginAttempt.IX_UserId_TenantId modelBuilder.Entity<UserLoginAttempt>() .Property(e => e.UserId) .CreateIndex("IX_UserId_TenantId", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(e => e.TenantId) .CreateIndex("IX_UserId_TenantId", 2); #endregion #region UserLogin.IX_TenantId_LoginProvider_ProviderKey modelBuilder.Entity<UserLogin>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 1); modelBuilder.Entity<UserLogin>() .Property(e => e.LoginProvider) .CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 2); modelBuilder.Entity<UserLogin>() .Property(e => e.ProviderKey) .CreateIndex("IX_TenantId_LoginProvider_ProviderKey", 3); #endregion #region UserLogin.IX_TenantId_UserId modelBuilder.Entity<UserLogin>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<UserLogin>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); #endregion #region UserOrganizationUnit.IX_TenantId_UserId modelBuilder.Entity<UserOrganizationUnit>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<UserOrganizationUnit>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); #endregion #region UserOrganizationUnit.IX_TenantId_OrganizationUnitId modelBuilder.Entity<UserOrganizationUnit>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_OrganizationUnitId", 1); modelBuilder.Entity<UserOrganizationUnit>() .Property(e => e.OrganizationUnitId) .CreateIndex("IX_TenantId_OrganizationUnitId", 2); #endregion #region OrganizationUnitRole.IX_TenantId_RoleId modelBuilder.Entity<OrganizationUnitRole>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_RoleId", 1); modelBuilder.Entity<OrganizationUnitRole>() .Property(e => e.RoleId) .CreateIndex("IX_TenantId_RoleId", 2); #endregion #region OrganizationUnitRole.IX_TenantId_OrganizationUnitId modelBuilder.Entity<OrganizationUnitRole>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_OrganizationUnitId", 1); modelBuilder.Entity<OrganizationUnitRole>() .Property(e => e.OrganizationUnitId) .CreateIndex("IX_TenantId_OrganizationUnitId", 2); #endregion #region UserRole.IX_TenantId_UserId modelBuilder.Entity<UserRole>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<UserRole>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); modelBuilder.Entity<Setting>() .HasIndex(e => new { e.TenantId, e.Name, e.UserId }) .IsUnique(); #endregion #region UserRole.IX_TenantId_RoleId modelBuilder.Entity<UserRole>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_RoleId", 1); modelBuilder.Entity<UserRole>() .Property(e => e.RoleId) .CreateIndex("IX_TenantId_RoleId", 2); #endregion #region TUser.IX_TenantId_NormalizedUserName modelBuilder.Entity<TUser>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_NormalizedUserName", 1); modelBuilder.Entity<TUser>() .Property(e => e.NormalizedUserName) .CreateIndex("IX_TenantId_NormalizedUserName", 2); #endregion #region TUser.IX_TenantId_NormalizedEmailAddress modelBuilder.Entity<TUser>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_NormalizedEmailAddress", 1); modelBuilder.Entity<TUser>() .Property(e => e.NormalizedEmailAddress) .CreateIndex("IX_TenantId_NormalizedEmailAddress", 2); #endregion #region UserToken.IX_TenantId_UserId modelBuilder.Entity<UserToken>() .Property(e => e.TenantId) .CreateIndex("IX_TenantId_UserId", 1); modelBuilder.Entity<UserToken>() .Property(e => e.UserId) .CreateIndex("IX_TenantId_UserId", 2); #endregion } } }
// DO NOT MODIFY! This is generated code. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Microsoft.Diagnostics.Runtime; namespace Microsoft.Diagnostics.RuntimeExt { [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("41CBFB96-45E4-4F2C-9002-82FD2ECD585F")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDTarget { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRuntimeCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRuntimeInfo(int num, [Out] [MarshalAs((UnmanagedType)28)] out IMDRuntimeInfo ppInfo); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetPointerSize([Out] out int pPointerSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void CreateRuntimeFromDac([MarshalAs((UnmanagedType)19)] string dacLocation, [Out] [MarshalAs((UnmanagedType)28)] out IMDRuntime ppRuntime); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void CreateRuntimeFromIXCLR([MarshalAs((UnmanagedType)25)] Object ixCLRProcess, [MarshalAs((UnmanagedType)28)] out IMDRuntime ppRuntime); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("4AADFA25-0486-48EB-9338-D4B39E23AF82")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDRuntimeInfo { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRuntimeVersion([Out] [MarshalAs((UnmanagedType)19)] out string pVersion); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDacLocation([Out] [MarshalAs((UnmanagedType)19)] out string pVersion); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDacRequestData([Out] out int pTimestamp, [Out] out int pFilesize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDacRequestFilename([Out] [MarshalAs((UnmanagedType)19)] out string pRequestFileName); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("2900B785-981D-4A6F-82DC-AE7B9DA08EA2")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDRuntime { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsServerGC([Out] out int pServerGC); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHeapCount([Out] out int pHeapCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int ReadVirtual(ulong addr, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] byte[] buffer, int requested, [Out] out int pRead); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int ReadPtr(ulong addr, [Out] out ulong pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Flush(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHeap([Out] [MarshalAs((UnmanagedType)28)] out IMDHeap ppHeap); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateAppDomains([Out] [MarshalAs((UnmanagedType)28)] out IMDAppDomainEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateThreads([Out] [MarshalAs((UnmanagedType)28)] out IMDThreadEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateFinalizerQueue([Out] [MarshalAs((UnmanagedType)28)] out IMDObjectEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateGCHandles([Out] [MarshalAs((UnmanagedType)28)] out IMDHandleEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateMemoryRegions([Out] [MarshalAs((UnmanagedType)28)] out IMDMemoryRegionEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("B53137DF-FC18-4470-A0D9-8EE4F829C970")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDHeap { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetObjectType(ulong addr, [Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetExceptionObject(ulong addr, [Out] [MarshalAs((UnmanagedType)28)] out IMDException ppExcep); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateRoots([Out] [MarshalAs((UnmanagedType)28)] out IMDRootEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateSegments([Out] [MarshalAs((UnmanagedType)28)] out IMDSegmentEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("BCA27E5A-5226-4CB6-AE95-239560E4FD71")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDAppDomainEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDAppDomain ppAppDomain); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("CA6A4D0A-7770-4254-A072-DA72A6CC1A72")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDThreadEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDThread ppThread); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("61119B5D-53DE-443C-911B-EB0607555451")] public interface IMDObjectEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next(int count, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] ulong[] objs, [Out] out int pWrote); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("32742CA6-56E7-438D-8FE8-1D30BE2F1F86")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDHandleEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDHandle ppHandle); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("9B68F32F-0DDD-452B-88F1-972496F44210")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDMemoryRegionEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDMemoryRegion ppRegion); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("FF5B59F4-07A0-4D7C-8B59-69338EECEA16")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDType { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSize(ulong objRef, [Out] out ulong pSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void ContainsPointers([Out] out int pContainsPointers); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCorElementType([Out] out int pCET); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetBaseType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppBaseType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetArrayComponentType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppArrayComponentType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCCW(ulong addr, [Out] [MarshalAs((UnmanagedType)28)] out IMDCCW ppCCW); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRCW(ulong addr, [Out] [MarshalAs((UnmanagedType)28)] out IMDRCW ppRCW); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsArray([Out] out int pIsArray); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsFree([Out] out int pIsFree); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsException([Out] out int pIsException); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsEnum([Out] out int pIsEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetEnumElementType([Out] out int pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetEnumNames([Out] [MarshalAs((UnmanagedType)28)] out IMDStringEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetEnumValueInt32([MarshalAs((UnmanagedType)19)] string name, [Out] out int pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetField(int index, [Out] [MarshalAs((UnmanagedType)28)] out IMDField ppField); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int GetFieldData(ulong obj, int interior, int count, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=2)] MD_FieldData[] fields, [Out] out int pNeeded); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStaticFieldCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStaticField(int index, [Out] [MarshalAs((UnmanagedType)28)] out IMDStaticField ppStaticField); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetThreadStaticFieldCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetThreadStaticField(int index, [Out] [MarshalAs((UnmanagedType)28)] out IMDThreadStaticField ppThreadStaticField); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetArrayLength(ulong objRef, [Out] out int pLength); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetArrayElementAddress(ulong objRef, int index, [Out] out ulong pAddr); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetArrayElementValue(ulong objRef, int index, [Out] [MarshalAs((UnmanagedType)28)] out IMDValue ppValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateReferences(ulong objRef, [Out] [MarshalAs((UnmanagedType)28)] out IMDReferenceEnum ppEnum); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateInterfaces([Out] [MarshalAs((UnmanagedType)28)] out IMDInterfaceEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("E3F30A85-0DBB-44C3-AA3E-460CCF31A2F1")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDException { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetGCHeapType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetMessage([Out] [MarshalAs((UnmanagedType)19)] out string pMessage); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetObjectAddress([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetInnerException([Out] [MarshalAs((UnmanagedType)28)] out IMDException ppException); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHRESULT([Out] [MarshalAs((UnmanagedType)45)] out int pHResult); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateStackFrames([Out] [MarshalAs((UnmanagedType)28)] out IMDStackTraceEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("90783F46-39C8-480A-BD7C-0D89FA97D5AD")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDRootEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDRoot ppRoot); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("18851D2F-A705-492C-9A80-202F39300E80")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDSegmentEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDSegment ppSegment); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("5A73920A-F8C5-4FCB-A725-8564F41BB055")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDCCW { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetIUnknown([Out] out ulong pIUnk); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetObject([Out] out ulong pObject); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHandle([Out] out ulong pHandle); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRefCount([Out] out int pRefCnt); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateInterfaces([Out] [MarshalAs((UnmanagedType)28)] out IMDCOMInterfaceEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("192249CE-6A17-4307-BA70-7AA871682128")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDRCW { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetIUnknown([Out] out ulong pIUnk); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetObject([Out] out ulong pObject); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRefCount([Out] out int pRefCnt); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetVTable([Out] out ulong pHandle); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsDisconnected([Out] out int pDisconnected); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateInterfaces([Out] [MarshalAs((UnmanagedType)28)] out IMDCOMInterfaceEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("B53B96FD-F8E3-4B86-AA5A-ECA1B6352840")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDStringEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)19)] out string pValue); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("823556FD-FFC5-4139-8D84-D9B72E835D2F")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDField { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetElementType([Out] out int pCET); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSize([Out] out int pSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetOffset([Out] out int pOffset); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldValue(ulong objRef, int interior, [Out] [MarshalAs((UnmanagedType)28)] out IMDValue ppValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldAddress(ulong objRef, int interior, [Out] out ulong pAddress); } [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Unicode)] public struct MD_FieldData { [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string name; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string type; public int corElementType; public int offset; public int size; public ulong value; } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("0E65FD09-D7A6-4B45-BEAC-76A002F52525")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDStaticField { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetElementType([Out] out int pCET); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSize([Out] out int pSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldValue([MarshalAs((UnmanagedType)28)] IMDAppDomain appDomain, [Out] [MarshalAs((UnmanagedType)28)] out IMDValue ppValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldAddress([MarshalAs((UnmanagedType)28)] IMDAppDomain appDomain, [Out] out ulong pAddress); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("809B99EF-7E7C-4351-BE76-9DCA2624D53E")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDThreadStaticField { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetElementType([Out] out int pCET); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSize([Out] out int pSize); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldValue([MarshalAs((UnmanagedType)28)] IMDAppDomain appDomain, [MarshalAs((UnmanagedType)28)] IMDThread thread, [Out] [MarshalAs((UnmanagedType)28)] out IMDValue ppValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetFieldAddress([MarshalAs((UnmanagedType)28)] IMDAppDomain appDomain, [MarshalAs((UnmanagedType)28)] IMDThread thread, [Out] out ulong pAddress); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("B72A6495-EE8A-4491-A01D-295B36A730F2")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDValue { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsNull(out int pNull); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetElementType(out int pCET); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetInt32(out int pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetUInt32(out UInt32 pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetInt64(out Int64 pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetUInt64(out ulong pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetString([MarshalAs((UnmanagedType)19)] out string pValue); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetBool(out int pBool); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("35DE7FD4-902C-4CC5-9C87-A7C9632B4B4A")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDReferenceEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next(int count, [In, Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] MD_Reference[] refs, [Out] out int pWrote); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("723BC010-963F-11E1-A8B0-0800200C9A66")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDInterfaceEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] [MarshalAs((UnmanagedType)28)] out IMDInterface ppValue); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("E630B609-502A-43F7-8F88-1598F21F2848")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDCOMInterfaceEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([MarshalAs((UnmanagedType)28)] IMDType pType, out ulong pInterfacePtr); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("6558598B-772F-4686-8F14-72C565072171")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDAppDomain { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetID([Out] out int pID); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAddress([Out] out ulong pAddress); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("A64706CC-C45D-481B-A4B4-4E3D04D27F91")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDThread { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAddress([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsFinalizer([Out] out int IsFinalizer); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsAlive([Out] out int IsAlive); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetOSThreadId([Out] out int pOSThreadId); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAppDomainAddress([Out] out ulong pAppDomain); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetLockCount([Out] out int pLockCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCurrentException([Out] [MarshalAs((UnmanagedType)28)] out IMDException ppException); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetTebAddress([Out] out ulong pTeb); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStackLimits([Out] out ulong pBase, [Out] out ulong pLimit); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateStackTrace([Out] [MarshalAs((UnmanagedType)28)] out IMDStackTraceEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("04DF4D19-7BFB-4535-BE6C-4115AB5F313D")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDStackTraceEnum { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCount([Out] out int pCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void Reset(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] [PreserveSig] int Next([Out] out ulong pIP, [Out] out ulong pSP, [Out] [MarshalAs((UnmanagedType)19)] out string pFunction); } [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Unicode)] public struct MD_Reference { public ulong address; public int offset; } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("31980D20-963F-11E1-A8B0-0800200C9A66")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDInterface { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetBaseInterface([Out] [MarshalAs((UnmanagedType)28)] out IMDInterface ppBase); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("CF7DD882-7CF9-4F13-91C3-3E102CEDA943")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDRoot { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRootInfo([Out] out ulong pAddress, [Out] out ulong pObjRef, [Out] out MDRootType pType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetType([Out] [MarshalAs((UnmanagedType)28)] out IMDType ppType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetName([Out] [MarshalAs((UnmanagedType)19)] out string ppName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAppDomain([Out] [MarshalAs((UnmanagedType)28)] out IMDAppDomain ppDomain); } public enum MDRootType { MDRoot_StaticVar, MDRoot_ThreadStaticVar, MDRoot_LocalVar, MDRoot_Strong, MDRoot_Weak, MDRoot_Pinning, MDRoot_Finalizer, MDRoot_AsyncPinning, } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("62CE62BA-066A-4FBD-B150-B4E5EAA080EE")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDSegment { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetStart([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetEnd([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetReserveLimit([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetCommitLimit([Out] out ulong pAddress); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetLength([Out] out ulong pLength); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetProcessorAffinity([Out] out int pProcessor); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsLarge([Out] out int pLarge); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsEphemeral([Out] out int pEphemeral); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetGen0Info([Out] out ulong pStart, [Out] out ulong pLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetGen1Info([Out] out ulong pStart, [Out] out ulong pLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetGen2Info([Out] out ulong pStart, [Out] out ulong pLen); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void EnumerateObjects([Out] [MarshalAs((UnmanagedType)28)] out IMDObjectEnum ppEnum); } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("FDB00A49-0584-4C24-95A4-B5CB08917596")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDHandle { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHandleData([Out] out ulong pAddr, [Out] out ulong pObjRef, [Out] out MDHandleTypes pType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void IsStrong([Out] out int pStrong); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRefCount([Out] out int pRefCount); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDependentTarget([Out] out ulong pTarget); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAppDomain([Out] [MarshalAs((UnmanagedType)28)] out IMDAppDomain ppDomain); } public enum MDHandleTypes { MDHandle_WeakShort, MDHandle_WeakLong, MDHandle_Strong, MDHandle_Pinned, MDHandle_Variable, MDHandle_RefCount, MDHandle_Dependent, MDHandle_AsyncPinned, MDHandle_SizedRef, } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.GuidAttribute("8E5310DF-0F3A-4456-ACC4-52DEE8754767")] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDMemoryRegion { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetRegionInfo([Out] out ulong pAddress, [Out] out ulong pSize, [Out] out MDMemoryRegionType pType); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetAppDomain([Out] [MarshalAs((UnmanagedType)28)] out IMDAppDomain ppDomain); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetModule([Out] [MarshalAs((UnmanagedType)19)] out string pModule); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetHeapNumber([Out] out int pHeap); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetDisplayString([Out] [MarshalAs((UnmanagedType)19)] out string pName); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void GetSegmentType([Out] out MDSegmentType pType); } public enum MDMemoryRegionType { MDRegion_LowFrequencyLoaderHeap, MDRegion_HighFrequencyLoaderHeap, MDRegion_StubHeap, MDRegion_IndcellHeap, MDRegion_LookupHeap, MDRegion_ResolveHeap, MDRegion_DispatchHeap, MDRegion_CacheEntryHeap, MDRegion_JITHostCodeHeap, MDRegion_JITLoaderCodeHeap, MDRegion_ModuleThunkHeap, MDRegion_ModuleLookupTableHeap, MDRegion_GCSegment, MDRegion_ReservedGCSegment, MDRegion_HandleTableChunk, } public enum MDSegmentType { MDSegment_Ephemeral, MDSegment_Regular, MDSegment_LargeObject, } [System.Runtime.InteropServices.ComImportAttribute()] [System.Runtime.InteropServices.GuidAttribute("5DC19835-504C-47AF-B96B-06AF1A737AE9")] [System.Runtime.InteropServices.TypeLibTypeAttribute((System.Runtime.InteropServices.TypeLibTypeFlags)128)] [System.Runtime.InteropServices.InterfaceTypeAttribute((System.Runtime.InteropServices.ComInterfaceType)1)] public interface IMDActivator { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void CreateFromCrashDump([MarshalAs((UnmanagedType)19)] string crashdump, [Out] [MarshalAs((UnmanagedType)28)] out IMDTarget ppTarget); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)] void CreateFromIDebugClient([MarshalAs((UnmanagedType)25)] Object iDebugClient, [Out] [MarshalAs((UnmanagedType)28)] out IMDTarget ppTarget); } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using Moq; using NuGet.Test.Mocks; using Xunit; using Xunit.Extensions; namespace NuGet.Test { public class PackageSourceProviderTest { [Fact] public void LoadPackageSourcesWhereAMigratedSourceIsAlsoADefaultSource() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("AOld", "urlA", false), new SettingValue("userDefinedSource", "userDefinedSourceUrl", false) }); settings.Setup(s => s.GetSettingValues("disabledPackageSources", false)).Returns( new SettingValue[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var defaultPackageSourceA = new PackageSource("urlA", "ANew"); var defaultPackageSourceB = new PackageSource("urlB", "B"); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new[] { defaultPackageSourceA, defaultPackageSourceB }, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("urlA", "AOld"), defaultPackageSourceA }, }); // Act var values = provider.LoadPackageSources().ToList(); // Assert // Package Source AOld will be migrated to ANew. B will simply get added // Since default source B got added when there are other package sources it will be disabled // However, package source ANew must stay enabled // PackageSource userDefinedSource is a user package source and is untouched Assert.Equal(3, values.Count); Assert.Equal("urlA", values[0].Source); Assert.Equal("ANew", values[0].Name); Assert.True(values[0].IsEnabled); Assert.Equal("userDefinedSourceUrl", values[1].Source); Assert.Equal("userDefinedSource", values[1].Name); Assert.True(values[1].IsEnabled); Assert.Equal("urlB", values[2].Source); Assert.Equal("B", values[2].Name); Assert.False(values[2].IsEnabled); // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetSettingValues("disabledPackageSources", false)).Returns(new SettingValue[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); } [Fact] public void TestNoPackageSourcesAreReturnedIfUserSettingsIsEmpty() { // Arrange var provider = CreatePackageSourceProvider(); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(0, values.Count); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsNull() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new PackageSource[] { }); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsDefaultSourcesIfSpecified() { // Arrange var settings = new Mock<ISettings>().Object; var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("A"), new PackageSource("B") }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("A", values.First().Source); Assert.Equal("B", values.Last().Source); } [Fact] public void LoadPackageSourcesPerformMigrationIfSpecified() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)).Returns( new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false), } ); // disable package "three" settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("three", "true" ) }); IList<KeyValuePair<string, string>> savedSettingValues = null; settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback<string, IList<KeyValuePair<string, string>>>((_, savedVals) => { savedSettingValues = savedVals; }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, null, new Dictionary<PackageSource, PackageSource> { { new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") }, { new PackageSource("foo", "bar"), new PackageSource("foo", "bar") }, { new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") } } ); // Act var values = provider.LoadPackageSources().ToList(); savedSettingValues = savedSettingValues.ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "good", "goodsource", true); AssertPackageSource(values[1], "two", "twosource", true); AssertPackageSource(values[2], "awesome", "awesomesource", false); Assert.Equal(3, savedSettingValues.Count); Assert.Equal("good", savedSettingValues[0].Key); Assert.Equal("goodsource", savedSettingValues[0].Value); Assert.Equal("two", savedSettingValues[1].Key); Assert.Equal("twosource", savedSettingValues[1].Value); Assert.Equal("awesome", savedSettingValues[2].Key); Assert.Equal("awesomesource", savedSettingValues[2].Value); } [Fact] public void CallSaveMethodAndLoadMethodShouldReturnTheSamePackageSet() { // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); provider.SavePackageSources(sources); // Assert settings.Verify(); Assert.Equal(3, sources.Count); for (int i = 0; i < sources.Count; i++) { AssertPackageSource(expectedSources[i], sources[i].Name, sources[i].Source, true); } } [Fact] public void WithMachineWideSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", true), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that only sources "two" and "three" are passed. // the machine wide source "one" is not. Assert.Equal(2, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("two", values[0].Value); Assert.Equal("three", values[1].Key); Assert.Equal("three", values[1].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that the machine wide source "one" is passed here // since it is disabled. Assert.Equal(1, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("true", values[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); // disable the machine wide source "one", and save the result in provider. Assert.Equal("one", sources[2].Name); sources[2].IsEnabled = false; provider.SavePackageSources(sources); // Assert // all assertions are done inside Callback()'s } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", true), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "three", "threesource", true); AssertPackageSource(values[2], "one", "onesource", true, true); } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettingsWhenSomePackageSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("two", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "one", "onesource", true); AssertPackageSource(values[1], "two", "twosource", false); AssertPackageSource(values[2], "three", "threesource", true); } /// <summary> /// The following test tests case 1 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 1. Default Package Source is already present matching both feed source and the feed name /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameAndSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false)}); // Disable package source one settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("one", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='one' value='onesource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'one' represents case 1. No real change takes place. IsOfficial will become true though. IsEnabled remains false as it is ISettings AssertPackageSource(values.First(), "one", "onesource", false, false, true); } /// <summary> /// The following test tests case 2 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 2. Default Package Source is already present matching feed source but with a different feed name. DO NOTHING /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInSourceButNotInName() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("two", "twosource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='twodefault' value='twosource' /> </packageSources> <disabledPackageSources> <add key='twodefault' value='true' /> </disabledPackageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'two' represents case 2. No Change effected. The existing feed will not be official AssertPackageSource(values.First(), "two", "twosource", true, false, false); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 3. Default Package Source is not present, but there is another feed source with the same feed name. Override that feed entirely /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameButNotInSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='three' value='threedefaultsource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'three' represents case 3. Completely overwritten. Noticeably, Feed Source will match Configuration Default settings AssertPackageSource(values.First(), "three", "threedefaultsource", true, false, true); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 4. Default Package Source is not present, simply, add it /// </summary> [Fact] public void LoadPackageSourcesWhereNoLoadedSourceMatchesADefaultSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>()); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='four' value='foursource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'four' represents case 4. Simply Added to the list increasing the count by 1. ISettings only has 3 package sources. But, LoadPackageSources returns 4 AssertPackageSource(values.First(), "four", "foursource", true, false, true); } [Fact] public void LoadPackageSourcesDoesNotReturnProviderDefaultsWhenConfigurationDefaultPackageSourcesIsNotEmpty() { // Arrange var settings = new Mock<ISettings>().Object; string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='configurationDefaultOne' value='configurationDefaultOneSource' /> <add key='configurationDefaultTwo' value='configurationDefaultTwoSource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("providerDefaultA"), new PackageSource("providerDefaultB") }, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(2, values.Count()); Assert.Equal("configurationDefaultOneSource", values.First().Source); Assert.Equal("configurationDefaultTwoSource", values.Last().Source); } [Fact] public void LoadPackageSourcesAddsAConfigurationDefaultBackEvenAfterMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='NuGet official package source' value='https://nuget.org/api/v2' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); Assert.Equal("NuGet official package source", values[1].Name); Assert.Equal("https://nuget.org/api/v2", values[1].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigrationAndSavesIt() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> valuePairs) => { Assert.Equal(1, valuePairs.Count); Assert.Equal("nuget.org", valuePairs[0].Key); Assert.Equal("https://www.nuget.org/api/v2", valuePairs[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); settings.Verify(); } [Fact] public void DisablePackageSourceAddEntryToSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.SetValue("disabledPackageSources", "A", "true")).Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.DisablePackageSource(new PackageSource("source", "A")); // Assert settings.Verify(); } [Fact] public void IsPackageSourceEnabledReturnsFalseIfTheSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns("sdfds"); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.False(isEnabled); } [Theory] [InlineData((string)null)] [InlineData("")] public void IsPackageSourceEnabledReturnsTrueIfTheSourceIsNotDisabled(string returnValue) { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns(returnValue); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.True(isEnabled); } [Theory] [InlineData(new object[] { null, "abcd" })] [InlineData(new object[] { "", "abcd" })] [InlineData(new object[] { "abcd", null })] [InlineData(new object[] { "abcd", "" })] public void LoadPackageSourcesIgnoresInvalidCredentialPairsFromSettings(string userName, string password) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new [] { new KeyValuePair<string, string>("Username", userName), new KeyValuePair<string, string>("Password", password) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesReadsCredentialPairsFromSettings() { // Arrange string encryptedPassword = EncryptionUtility.EncryptString("topsecret"); var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("Password", encryptedPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.Equal("topsecret", values[1].Password); Assert.False(values[1].IsPasswordClearText); } [Fact] public void LoadPackageSourcesReadsClearTextCredentialPairsFromSettings() { // Arrange const string clearTextPassword = "topsecret"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("ClearTextPassword", clearTextPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.True(values[1].IsPasswordClearText); Assert.Equal("topsecret", values[1].Password); } [Theory] [InlineData("Username=john;Password=johnspassword")] [InlineData("uSerName=john;PASSWOrD=johnspassword")] [InlineData(" Username=john; Password=johnspassword ")] public void LoadPackageSourcesLoadsCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange const string userName = "john"; const string password = "johnspassword"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment:environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal(userName, values[1].UserName); Assert.Equal(password, values[1].Password); } [Theory] [InlineData("uername=john;Password=johnspassword")] [InlineData(".Username=john;Password=johnspasswordf")] [InlineData("What is this I don't even")] public void LoadPackageSourcesIgnoresMalformedCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesEnvironmentCredentialsTakePrecedenceOverSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("Username=envirouser;Password=enviropassword"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("envirouser", values[1].UserName); Assert.Equal("enviropassword", values[1].Password); } [Fact] public void LoadPackageSourcesWhenEnvironmentCredentialsAreMalformedFallsbackToSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("I for one don't understand environment variables"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("settinguser", values[1].UserName); Assert.Equal("settingpassword", values[1].Password); } // Test that when there are duplicate sources, i.e. sources with the same name, // then the source specified in one Settings with the highest priority is used. [Fact] public void DuplicatePackageSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("one", "threesource", false) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "one", "threesource", true); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettings() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two"), new PackageSource("three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettingsWhenSomePackageSourceIsDisabled() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two", "two", isEnabled: false), new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(1, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("true", values[0].Value, StringComparer.OrdinalIgnoreCase); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesCredentials() { // Arrange var entropyBytes = Encoding.UTF8.GetBytes("NuGet"); var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password" }, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); Assert.Equal("Password", values[1].Key); string decryptedPassword = Encoding.UTF8.GetString( ProtectedData.Unprotect(Convert.FromBase64String(values[1].Value), entropyBytes, DataProtectionScope.CurrentUser)); Assert.Equal("Password", values[1].Key); Assert.Equal("password", decryptedPassword); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesClearTextCredentials() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password", IsPasswordClearText = true}, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); AssertKVP(new KeyValuePair<string, string>("ClearTextPassword", "password"), values[1]); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void GetAggregateReturnsAggregateRepositoryForAllSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryB.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsInvalidSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: true); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryC.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsDisabledSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Throws(new Exception()); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B", "B", isEnabled: false), new PackageSource("C", "C", isEnabled: false) }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(1, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); } [Fact] public void GetAggregateHandlesInvalidUriSources() { // Arrange var factory = PackageRepositoryFactory.Default; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("Bad 1"), new PackageSource(@"x:sjdkfjhsdjhfgjdsgjglhjk"), new PackageSource(@"http:\\//") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory, ignoreFailingRepositories: true); // Assert Assert.False(repo.Repositories.Any()); } [Fact] public void GetAggregateSetsIgnoreInvalidRepositoryProperty() { // Arrange var factory = new Mock<IPackageRepositoryFactory>(); bool ignoreRepository = true; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(Enumerable.Empty<PackageSource>()); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: ignoreRepository); // Assert Assert.True(repo.IgnoreFailingRepositories); } [Fact] public void GetAggregateWithInvalidSourcesThrows() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>(() => sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false)); } [Fact] public void ResolveSourceLooksUpNameAndSource() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal(source2.Source, result1); Assert.Equal(source2.Source, result2); Assert.Equal(source1.Source, result3); } [Fact] public void ResolveSourceIgnoreDisabledSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"); PackageSource source2 = new PackageSource("http://www.test.com", "Baz", isEnabled: false); PackageSource source3 = new PackageSource("http://www.bing.com", "Foo", isEnabled: false); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2, source3 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("Foo"); var result4 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal("http://www.test.com", result1); Assert.Equal("Baz", result2); Assert.Equal("Foo", result3); Assert.Equal("Source", result4); } [Fact] public void ResolveSourceReturnsOriginalValueIfNotFoundInSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); var source = "http://www.does-not-exist.com"; // Act var result = sources.Object.ResolveSource(source); // Assert Assert.Equal(source, result); } private void AssertPackageSource(PackageSource ps, string name, string source, bool isEnabled, bool isMachineWide = false, bool isOfficial = false) { Assert.Equal(name, ps.Name); Assert.Equal(source, ps.Source); Assert.True(ps.IsEnabled == isEnabled); Assert.True(ps.IsMachineWide == isMachineWide); Assert.True(ps.IsOfficial == isOfficial); } private IPackageSourceProvider CreatePackageSourceProvider( ISettings settings = null, IEnumerable<PackageSource> providerDefaultSources = null, IDictionary<PackageSource, PackageSource> migratePackageSources = null, IEnumerable<PackageSource> configurationDefaultSources = null, IEnvironmentVariableReader environment = null) { settings = settings ?? new Mock<ISettings>().Object; environment = environment ?? new Mock<IEnvironmentVariableReader>().Object; return new PackageSourceProvider(settings, providerDefaultSources, migratePackageSources, configurationDefaultSources, environment); } private static void AssertKVP(KeyValuePair<string, string> expected, KeyValuePair<string, string> actual) { Assert.Equal(expected.Key, actual.Key); Assert.Equal(expected.Value, actual.Value); } } }
// <copyright file="CombinatoricsCountingTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.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> namespace MathNet.Numerics.UnitTests.CombinatoricsTests { using NUnit.Framework; /// <summary> /// Combinatorics counting tests. /// </summary> [TestFixture] public class CombinatoricsCountingTest { /// <summary> /// Can count variations. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> /// <param name="expected">Expected value.</param> [TestCase(0, 0, 1)] [TestCase(1, 0, 1)] [TestCase(10, 0, 1)] [TestCase(10, 2, 90)] [TestCase(10, 4, 5040)] [TestCase(10, 6, 151200)] [TestCase(10, 9, 3628800)] [TestCase(10, 10, 3628800)] public void CanCountVariations(int n, int k, long expected) { Assert.AreEqual( expected, Combinatorics.Variations(n, k), "Count the number of variations without repetition"); } /// <summary> /// Out of range variations count to zero. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> [TestCase(0, 1)] [TestCase(10, 11)] [TestCase(0, -1)] [TestCase(1, -1)] [TestCase(-1, 0)] [TestCase(-1, 1)] public void OutOfRangeVariationsCountToZero(int n, int k) { Assert.AreEqual( 0, Combinatorics.Variations(n, k), "The number of variations without repetition but out of the range must be 0."); } /// <summary> /// Can count variations with repetition. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> /// <param name="expected">Expected value.</param> [TestCase(0, 0, 1)] [TestCase(1, 0, 1)] [TestCase(10, 0, 1)] [TestCase(10, 2, 100)] [TestCase(10, 4, 10000)] [TestCase(10, 6, 1000000)] [TestCase(10, 9, 1000000000)] [TestCase(10, 10, 10000000000)] [TestCase(10, 11, 100000000000)] public void CanCountVariationsWithRepetition(int n, int k, long expected) { Assert.AreEqual( expected, Combinatorics.VariationsWithRepetition(n, k), "Count the number of variations with repetition"); } /// <summary> /// Out of range variations withR repetition count to zero. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> [TestCase(0, 1)] [TestCase(0, -1)] [TestCase(1, -1)] [TestCase(-1, 0)] [TestCase(-1, 1)] public void OutOfRangeVariationsWithRepetitionCountToZero(int n, int k) { Assert.AreEqual( 0, Combinatorics.VariationsWithRepetition(n, k), "The number of variations with repetition but out of the range must be 0."); } /// <summary> /// Can count combinations. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> /// <param name="expected">Expected value.</param> [TestCase(0, 0, 1)] [TestCase(1, 0, 1)] [TestCase(10, 0, 1)] [TestCase(10, 2, 45)] [TestCase(10, 4, 210)] [TestCase(10, 6, 210)] [TestCase(10, 9, 10)] [TestCase(10, 10, 1)] public void CanCountCombinations(int n, int k, long expected) { Assert.AreEqual( expected, Combinatorics.Combinations(n, k), "Count the number of combinations without repetition"); } /// <summary> /// Out of range combinations count to zero. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> [TestCase(0, 1)] [TestCase(10, 11)] [TestCase(0, -1)] [TestCase(1, -1)] [TestCase(-1, 0)] [TestCase(-1, 1)] public void OutOfRangeCombinationsCountToZero(int n, int k) { Assert.AreEqual( 0, Combinatorics.Combinations(n, k), "The number of combinations without repetition but out of the range must be 0."); } /// <summary> /// Can count combinations with repetition. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> /// <param name="expected">Expected value.</param> [TestCase(0, 0, 1)] [TestCase(1, 0, 1)] [TestCase(10, 0, 1)] [TestCase(10, 2, 55)] [TestCase(10, 4, 715)] [TestCase(10, 6, 5005)] [TestCase(10, 9, 48620)] [TestCase(10, 10, 92378)] [TestCase(10, 11, 167960)] public void CanCountCombinationsWithRepetition(int n, int k, long expected) { Assert.AreEqual( expected, Combinatorics.CombinationsWithRepetition(n, k), "Count the number of combinations with repetition"); } /// <summary> /// Out of range combinations with repetition count to zero. /// </summary> /// <param name="n">N parameter.</param> /// <param name="k">K parameter.</param> [TestCase(0, 1)] [TestCase(0, -1)] [TestCase(1, -1)] [TestCase(-1, 0)] [TestCase(-1, 1)] public void OutOfRangeCombinationsWithRepetitionCountToZero(int n, int k) { Assert.AreEqual( 0, Combinatorics.CombinationsWithRepetition(n, k), "The number of combinations with repetition but out of the range must be 0."); } /// <summary> /// Can count permutations. /// </summary> /// <param name="n">N parameter.</param> /// <param name="expected">Expected value.</param> [TestCase(0, 1)] [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(8, 40320)] [TestCase(15, 1307674368000)] public void CanCountPermutations(int n, long expected) { Assert.AreEqual( expected, Combinatorics.Permutations(n), "Count the number of permutations"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { public partial class CodeGenerationTests { internal static async Task TestAddNamespaceAsync( string initial, string expected, string name = "N", IList<ISymbol> imports = null, IList<INamespaceOrTypeSymbol> members = null, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var @namespace = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name, imports, members); context.Result = await context.Service.AddNamespaceAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), @namespace, codeGenerationOptions); } } internal static async Task TestAddFieldAsync( string initial, string expected, Func<SemanticModel, ITypeSymbol> type = null, string name = "F", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true, bool hasConstantValue = false, object constantValue = null, bool addToCompilationUnit = false) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var typeSymbol = type != null ? type(context.SemanticModel) : null; var field = CodeGenerationSymbolFactory.CreateFieldSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, typeSymbol, name, hasConstantValue, constantValue); if (!addToCompilationUnit) { context.Result = await context.Service.AddFieldAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), field, codeGenerationOptions); } else { var newRoot = context.Service.AddField(await context.Document.GetSyntaxRootAsync(), field, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot(newRoot); } } } internal static async Task TestAddConstructorAsync( string initial, string expected, string name = "C", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), ImmutableArray<SyntaxNode> statements = default(ImmutableArray<SyntaxNode>), ImmutableArray<SyntaxNode> baseArguments = default(ImmutableArray<SyntaxNode>), ImmutableArray<SyntaxNode> thisArguments = default(ImmutableArray<SyntaxNode>), CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parameterSymbols = GetParameterSymbols(parameters, context); var ctor = CodeGenerationSymbolFactory.CreateConstructorSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, name, parameterSymbols, statements, baseConstructorArguments: baseArguments, thisConstructorArguments: thisArguments); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), ctor, codeGenerationOptions); } } internal static async Task TestAddMethodAsync( string initial, string expected, string name = "M", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), Type returnType = null, Func<SemanticModel, ImmutableArray<IMethodSymbol>> getExplicitInterfaces = null, ImmutableArray<ITypeParameterSymbol> typeParameters = default(ImmutableArray<ITypeParameterSymbol>), ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), string statements = null, ImmutableArray<SyntaxNode> handlesExpressions = default(ImmutableArray<SyntaxNode>), CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { if (statements != null) { expected = expected.Replace("$$", statements); } using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var explicitInterfaceImplementations = GetMethodSymbols(getExplicitInterfaces, context); var method = CodeGenerationSymbolFactory.CreateMethodSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), false, explicitInterfaceImplementations, name, typeParameters, parameterSymbols, parsedStatements, handlesExpressions: handlesExpressions); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } } internal static async Task TestAddOperatorsAsync( string initial, string expected, CodeGenerationOperatorKind[] operatorKinds, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), Type returnType = null, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), string statements = null, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { if (statements != null) { while (expected.IndexOf("$$", StringComparison.Ordinal) != -1) { expected = expected.Replace("$$", statements); } } using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var methods = operatorKinds.Select(kind => CodeGenerationSymbolFactory.CreateOperatorSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), kind, parameterSymbols, parsedStatements)); context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), methods.ToArray(), codeGenerationOptions); } } internal static async Task TestAddUnsupportedOperatorAsync( string initial, CodeGenerationOperatorKind operatorKind, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), Type returnType = null, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), string statements = null, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, initial, ignoreResult: true)) { var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var method = CodeGenerationSymbolFactory.CreateOperatorSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), operatorKind, parameterSymbols, parsedStatements); ArgumentException exception = null; try { await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } catch (ArgumentException e) { exception = e; } var expectedMessage = string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name); Assert.True(exception != null && exception.Message.StartsWith(expectedMessage, StringComparison.Ordinal), string.Format("\r\nExpected exception: {0}\r\nActual exception: {1}\r\n", expectedMessage, exception == null ? "no exception" : exception.Message)); } } internal static async Task TestAddConversionAsync( string initial, string expected, Type toType, Func<SemanticModel, IParameterSymbol> fromType, bool isImplicit = false, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), string statements = null, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { if (statements != null) { expected = expected.Replace("$$", statements); } using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parsedStatements = context.ParseStatements(statements); var method = CodeGenerationSymbolFactory.CreateConversionSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(toType)(context.SemanticModel), fromType(context.SemanticModel), isImplicit, parsedStatements); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } } internal static async Task TestAddStatementsAsync( string initial, string expected, string statements, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { if (statements != null) { expected = expected.Replace("$$", statements); } using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parsedStatements = context.ParseStatements(statements); var oldSyntax = context.GetSelectedSyntax<SyntaxNode>(true); var newSyntax = context.Service.AddStatements(oldSyntax, parsedStatements, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldSyntax, newSyntax)); } } internal static async Task TestAddParametersAsync( string initial, string expected, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parameterSymbols = GetParameterSymbols(parameters, context); var oldMemberSyntax = context.GetSelectedSyntax<SyntaxNode>(true); var newMemberSyntax = context.Service.AddParameters(oldMemberSyntax, parameterSymbols, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldMemberSyntax, newMemberSyntax)); } } internal static async Task TestAddDelegateTypeAsync( string initial, string expected, string name = "D", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), Type returnType = null, ImmutableArray<ITypeParameterSymbol> typeParameters = default(ImmutableArray<ITypeParameterSymbol>), ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var parameterSymbols = GetParameterSymbols(parameters, context); var type = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), false, name, typeParameters, parameterSymbols); context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), type, codeGenerationOptions); } } internal static async Task TestAddEventAsync( string initial, string expected, string name = "E", ImmutableArray<AttributeData> attributes = default(ImmutableArray<AttributeData>), Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), Type type = null, Func<SemanticModel, ImmutableArray<IEventSymbol>> getExplicitInterfaceImplementations = null, IMethodSymbol addMethod = null, IMethodSymbol removeMethod = null, IMethodSymbol raiseMethod = null, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { type = type ?? typeof(Action); var parameterSymbols = GetParameterSymbols(parameters, context); var typeSymbol = GetTypeSymbol(type)(context.SemanticModel); var @event = CodeGenerationSymbolFactory.CreateEventSymbol( attributes, accessibility, modifiers, typeSymbol, getExplicitInterfaceImplementations?.Invoke(context.SemanticModel) ?? default, name, addMethod, removeMethod, raiseMethod); context.Result = await context.Service.AddEventAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), @event, codeGenerationOptions); } } internal static async Task TestAddPropertyAsync( string initial, string expected, string name = "P", Accessibility defaultAccessibility = Accessibility.Public, Accessibility setterAccessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), string getStatements = null, string setStatements = null, Type type = null, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default(ImmutableArray<Func<SemanticModel, IParameterSymbol>>), bool isIndexer = false, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true, IDictionary<OptionKey, object> options = null) { // This assumes that tests will not use place holders for get/set statements at the same time if (getStatements != null) { expected = expected.Replace("$$", getStatements); } if (setStatements != null) { expected = expected.Replace("$$", setStatements); } using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { if (options != null) { foreach (var kvp in options) { context.Workspace.Options = context.Workspace.Options.WithChangedOption(kvp.Key, kvp.Value); } } var typeSymbol = GetTypeSymbol(type)(context.SemanticModel); var getParameterSymbols = GetParameterSymbols(parameters, context); var setParameterSymbols = getParameterSymbols == null ? default(ImmutableArray<IParameterSymbol>) : getParameterSymbols.Add(Parameter(type, "value")(context.SemanticModel)); IMethodSymbol getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( default(ImmutableArray<AttributeData>), defaultAccessibility, new Editing.DeclarationModifiers(isAbstract: getStatements == null), typeSymbol, false, default, "get_" + name, default(ImmutableArray<ITypeParameterSymbol>), getParameterSymbols, statements: context.ParseStatements(getStatements)); IMethodSymbol setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( default(ImmutableArray<AttributeData>), setterAccessibility, new Editing.DeclarationModifiers(isAbstract: setStatements == null), GetTypeSymbol(typeof(void))(context.SemanticModel), false, default, "set_" + name, default(ImmutableArray<ITypeParameterSymbol>), setParameterSymbols, statements: context.ParseStatements(setStatements)); // If get is provided but set isn't, we don't want an accessor for set if (getStatements != null && setStatements == null) { setAccessor = null; } // If set is provided but get isn't, we don't want an accessor for get if (getStatements == null && setStatements != null) { getAccessor = null; } var property = CodeGenerationSymbolFactory.CreatePropertySymbol( default(ImmutableArray<AttributeData>), defaultAccessibility, modifiers, typeSymbol, false, explicitInterfaceImplementations, name, getParameterSymbols, getAccessor, setAccessor, isIndexer); context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions); } } internal static async Task TestAddNamedTypeAsync( string initial, string expected, string name = "C", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default(Editing.DeclarationModifiers), TypeKind typeKind = TypeKind.Class, ImmutableArray<ITypeParameterSymbol> typeParameters = default(ImmutableArray<ITypeParameterSymbol>), INamedTypeSymbol baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default(ImmutableArray<INamedTypeSymbol>), SpecialType specialType = SpecialType.None, ImmutableArray<Func<SemanticModel, ISymbol>> members = default(ImmutableArray<Func<SemanticModel, ISymbol>>), CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var memberSymbols = GetSymbols(members, context); var type = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, typeKind, name, typeParameters, baseType, interfaces, specialType, memberSymbols); context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), type, codeGenerationOptions); } } internal static async Task TestAddAttributeAsync( string initial, string expected, Type attributeClass, SyntaxToken? target = null, bool ignoreTrivia = true) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var attr = CodeGenerationSymbolFactory.CreateAttributeData((INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel)); var oldNode = context.GetDestinationNode(); var newNode = CodeGenerator.AddAttributes(oldNode, context.Document.Project.Solution.Workspace, new[] { attr }, target) .WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(oldNode, newNode)); } } internal static async Task TestRemoveAttributeAsync<T>( string initial, string expected, Type attributeClass, SyntaxToken? target = null, bool ignoreTrivia = false) where T : SyntaxNode { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var attributeType = (INamedTypeSymbol)GetTypeSymbol(attributeClass)(context.SemanticModel); var taggedNode = context.GetDestinationNode(); ISymbol attributeTarget = context.SemanticModel.GetDeclaredSymbol(taggedNode); var attribute = attributeTarget.GetAttributes().Single(attr => attr.AttributeClass == attributeType); var declarationNode = taggedNode.FirstAncestorOrSelf<T>(); var newNode = CodeGenerator.RemoveAttribute(declarationNode, context.Document.Project.Solution.Workspace, attribute) .WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, newNode)); } } internal static async Task TestUpdateDeclarationAsync<T>( string initial, string expected, Accessibility? accessibility = null, IEnumerable<SyntaxToken> modifiers = null, Func<SemanticModel, ITypeSymbol> getType = null, ImmutableArray<Func<SemanticModel, ISymbol>> getNewMembers = default(ImmutableArray<Func<SemanticModel, ISymbol>>), bool? declareNewMembersAtTop = null, string retainedMembersKey = "RetainedMember", bool ignoreTrivia = false) where T : SyntaxNode { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia)) { var declarationNode = context.GetDestinationNode().FirstAncestorOrSelf<T>(); var updatedDeclarationNode = declarationNode; var workspace = context.Document.Project.Solution.Workspace; if (accessibility.HasValue) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationAccessibility(declarationNode, workspace, accessibility.Value); } else if (modifiers != null) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationModifiers(declarationNode, workspace, modifiers); } else if (getType != null) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationType(declarationNode, workspace, getType(context.SemanticModel)); } else if (getNewMembers != null) { var retainedMembers = context.GetAnnotatedDeclaredSymbols(retainedMembersKey, context.SemanticModel); var newMembersToAdd = GetSymbols(getNewMembers, context); List<ISymbol> allMembers = new List<ISymbol>(); if (declareNewMembersAtTop.HasValue && declareNewMembersAtTop.Value) { allMembers.AddRange(newMembersToAdd); allMembers.AddRange(retainedMembers); } else { allMembers.AddRange(retainedMembers); allMembers.AddRange(newMembersToAdd); } updatedDeclarationNode = CodeGenerator.UpdateDeclarationMembers(declarationNode, workspace, allMembers); } updatedDeclarationNode = updatedDeclarationNode.WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, updatedDeclarationNode)); } } internal static async Task TestGenerateFromSourceSymbolAsync( string symbolSource, string initial, string expected, bool onlyGenerateMembers = false, CodeGenerationOptions codeGenerationOptions = default(CodeGenerationOptions), bool ignoreTrivia = true, string forceLanguage = null) { using (var context = await TestContext.CreateAsync(initial, expected, ignoreTrivia, forceLanguage)) { TextSpan destSpan = new TextSpan(); MarkupTestFile.GetSpan(symbolSource.NormalizeLineEndings(), out symbolSource, out destSpan); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var semanticModel = await context.Solution .AddProject(projectId, "GenerationSource", "GenerationSource", TestContext.GetLanguage(symbolSource)) .AddDocument(documentId, "Source.cs", symbolSource) .GetDocument(documentId) .GetSemanticModelAsync(); var symbol = context.GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, semanticModel); var destination = context.GetDestination(); if (destination.IsType) { var members = onlyGenerateMembers ? symbol.GetMembers().ToArray() : new[] { symbol }; context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)destination, members, codeGenerationOptions); } else { context.Result = await context.Service.AddNamespaceOrTypeAsync(context.Solution, (INamespaceSymbol)destination, symbol, codeGenerationOptions); } } } internal static Func<SemanticModel, IParameterSymbol> Parameter(Type type, string name, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false) { return s => CodeGenerationSymbolFactory.CreateParameterSymbol( default(ImmutableArray<AttributeData>), RefKind.None, isParams, GetTypeSymbol(s.Compilation, type), name, isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue); } internal static Func<SemanticModel, IParameterSymbol> Parameter(string typeFullName, string parameterName, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false, int typeArrayRank = 0) { return s => CodeGenerationSymbolFactory.CreateParameterSymbol( default(ImmutableArray<AttributeData>), RefKind.None, isParams, GetTypeSymbol(s.Compilation, typeFullName, typeArrayRank), parameterName, isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue); } private static ITypeSymbol GetTypeSymbol(Compilation compilation, Type type) { return !type.IsArray ? GetTypeSymbol(compilation, type.FullName) : GetTypeSymbol(compilation, type.GetElementType().FullName, type.GetArrayRank()); } private static ITypeSymbol GetTypeSymbol(Compilation compilation, string typeFullName, int arrayRank = 0) { return arrayRank == 0 ? (ITypeSymbol)compilation.GetTypeByMetadataName(typeFullName) : compilation.CreateArrayTypeSymbol(compilation.GetTypeByMetadataName(typeFullName), arrayRank); } internal static ImmutableArray<Func<SemanticModel, IParameterSymbol>> Parameters(params Func<SemanticModel, IParameterSymbol>[] p) => p.ToImmutableArray(); internal static ImmutableArray<Func<SemanticModel, ISymbol>> Members(params Func<SemanticModel, ISymbol>[] m) => m.ToImmutableArray(); internal static Func<SemanticModel, ITypeSymbol> CreateArrayType(Type type, int rank = 1) { return s => CodeGenerationSymbolFactory.CreateArrayTypeSymbol(GetTypeSymbol(type)(s), rank); } private static ImmutableArray<IParameterSymbol> GetParameterSymbols(ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, TestContext context) => parameters.IsDefault ? default(ImmutableArray<IParameterSymbol>) : parameters.SelectAsArray(p => p(context.SemanticModel)); private static ImmutableArray<IMethodSymbol> GetMethodSymbols( Func<SemanticModel, ImmutableArray<IMethodSymbol>> explicitInterface, TestContext context) { return explicitInterface == null ? default : explicitInterface(context.SemanticModel); } private static ImmutableArray<ISymbol> GetSymbols(ImmutableArray<Func<SemanticModel, ISymbol>> members, TestContext context) { return members == null ? default(ImmutableArray<ISymbol>) : members.SelectAsArray(m => m(context.SemanticModel)); } private static Func<SemanticModel, ISymbol> CreateEnumField(string name, object value) { return s => CodeGenerationSymbolFactory.CreateFieldSymbol( default(ImmutableArray<AttributeData>), Accessibility.Public, new Editing.DeclarationModifiers(), GetTypeSymbol(typeof(int))(s), name, value != null, value); } internal static Func<SemanticModel, ISymbol> CreateField(Accessibility accessibility, Editing.DeclarationModifiers modifiers, Type type, string name) { return s => CodeGenerationSymbolFactory.CreateFieldSymbol( default(ImmutableArray<AttributeData>), accessibility, modifiers, GetTypeSymbol(type)(s), name); } private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(Type type) { return GetTypeSymbol(type.FullName); } private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(string typeMetadataName) { return s => s == null ? null : s.Compilation.GetTypeByMetadataName(typeMetadataName); } internal static IEnumerable<SyntaxToken> CreateModifierTokens(Editing.DeclarationModifiers modifiers, string language) { if (language == LanguageNames.CSharp) { if (modifiers.IsAbstract) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AbstractKeyword); } if (modifiers.IsAsync) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AsyncKeyword); } if (modifiers.IsConst) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ConstKeyword); } if (modifiers.IsNew) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.NewKeyword); } if (modifiers.IsOverride) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.OverrideKeyword); } if (modifiers.IsPartial) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.PartialKeyword); } if (modifiers.IsReadOnly) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ReadOnlyKeyword); } if (modifiers.IsSealed) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.SealedKeyword); } if (modifiers.IsStatic) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.StaticKeyword); } if (modifiers.IsUnsafe) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.UnsafeKeyword); } if (modifiers.IsVirtual) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.VirtualKeyword); } } else { if (modifiers.IsAbstract) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.MustOverrideKeyword); } if (modifiers.IsAsync) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.AsyncKeyword); } if (modifiers.IsConst) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ConstKeyword); } if (modifiers.IsNew) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NewKeyword); } if (modifiers.IsOverride) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridesKeyword); } if (modifiers.IsPartial) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.PartialKeyword); } if (modifiers.IsReadOnly) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ReadOnlyKeyword); } if (modifiers.IsSealed) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NotInheritableKeyword); } if (modifiers.IsStatic) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.StaticKeyword); } if (modifiers.IsVirtual) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridableKeyword); } } } internal class TestContext : IDisposable { private readonly string _expected; public readonly bool IsVisualBasic; public Document Document; public SemanticModel SemanticModel; public SyntaxTree SyntaxTree; public ICodeGenerationService Service; public Document Result; public readonly TestWorkspace Workspace; private readonly string _language; private readonly bool _compareTokens; private readonly bool _ignoreResult; public TestContext( string initial, string expected, bool ignoreTrivia, bool ignoreResult, string language, TestWorkspace workspace, SemanticModel semanticModel) { _expected = expected.NormalizeLineEndings(); _language = language; this.IsVisualBasic = _language == LanguageNames.VisualBasic; _compareTokens = ignoreTrivia; _ignoreResult = ignoreResult; Workspace = workspace; this.Document = Workspace.CurrentSolution.Projects.Single().Documents.Single(); this.SemanticModel = semanticModel; this.SyntaxTree = SemanticModel.SyntaxTree; this.Service = Document.Project.LanguageServices.GetService<ICodeGenerationService>(); } public static async Task<TestContext> CreateAsync(string initial, string expected, bool ignoreTrivia = true, string forceLanguage = null, bool ignoreResult = false) { var language = forceLanguage != null ? forceLanguage : GetLanguage(initial); var isVisualBasic = language == LanguageNames.VisualBasic; var workspace = CreateWorkspaceFromFile(initial.NormalizeLineEndings(), isVisualBasic, null, null); var semanticModel = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetSemanticModelAsync(); return new TestContext(initial, expected, ignoreTrivia, ignoreResult, language, workspace, semanticModel); } public Solution Solution { get { return Workspace.CurrentSolution; } } public SyntaxNode GetDestinationNode() { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); return SemanticModel.SyntaxTree.GetRoot().FindNode(destSpan, getInnermostNodeForTie: true); } public INamespaceOrTypeSymbol GetDestination() { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); return GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, this.SemanticModel); } public IEnumerable<ISymbol> GetAnnotatedDeclaredSymbols(string key, SemanticModel semanticModel) { var annotatedSpans = Workspace.Documents.Single().AnnotatedSpans[key]; foreach (var span in annotatedSpans) { yield return GetSelectedSymbol<ISymbol>(span, semanticModel); } } public T GetSelectedSymbol<T>(TextSpan selection, SemanticModel semanticModel) where T : class, ISymbol { var token = semanticModel.SyntaxTree.GetRoot().FindToken(selection.Start); var symbol = token.Parent.AncestorsAndSelf() .Select(a => semanticModel.GetDeclaredSymbol(a)) .Where(s => s != null).FirstOrDefault() as T; return symbol; } public T GetSelectedSyntax<T>(bool fullSpanCoverage = false) where T : SyntaxNode { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); var token = SemanticModel.SyntaxTree.GetRoot().FindToken(destSpan.Start); return token.Parent.AncestorsAndSelf().OfType<T>().FirstOrDefault(t => !fullSpanCoverage || t.Span.End >= destSpan.End); } public ImmutableArray<SyntaxNode> ParseStatements(string statements) { if (statements == null) { return default(ImmutableArray<SyntaxNode>); } var list = ArrayBuilder<SyntaxNode>.GetInstance(); var delimiter = IsVisualBasic ? "\r\n" : ";"; var parts = statements.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries); foreach (var p in parts) { if (IsVisualBasic) { list.Add(VB.SyntaxFactory.ParseExecutableStatement(p)); } else { list.Add(CS.SyntaxFactory.ParseStatement(p + delimiter)); } } return list.ToImmutableAndFree(); } public void Dispose() { try { if (!_ignoreResult) { this.Document = this.Result; if (_compareTokens) { var reduced = Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result; var formatted = Formatter.FormatAsync(reduced).Result.GetSyntaxRootAsync().Result; var root = reduced.GetSyntaxRootAsync().Result; var actual = string.Join(" ", root.DescendantTokens()); TokenUtilities.AssertTokensEqual(_expected, actual, _language); } else { var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result .GetSyntaxRootAsync().Result.ToFullString(); Assert.Equal(_expected, actual); } } } finally { Workspace.Dispose(); } } public static string GetLanguage(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Module") || input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim") || input.Contains("Enum"); } private static TestWorkspace CreateWorkspaceFromFile(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions) { return isVisualBasic ? TestWorkspace.CreateVisualBasic(file, (VB.VisualBasicParseOptions)parseOptions, (VB.VisualBasicCompilationOptions)compilationOptions) : TestWorkspace.CreateCSharp(file, (CS.CSharpParseOptions)parseOptions, (CS.CSharpCompilationOptions)compilationOptions); } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ReadOnlyKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCompilationUnit() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"extern alias Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"extern alias Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"using Foo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeDeclaration() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateDeclaration() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"delegate void Foo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Foo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Foo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAssemblyAttribute() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"[assembly: foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"[assembly: foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(@"[foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideInterface() { await VerifyAbsenceAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideEnum() { await VerifyAbsenceAsync(@"enum E { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() { await VerifyAbsenceAsync(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() { await VerifyAbsenceAsync(@"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterProtected() { await VerifyAbsenceAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() { await VerifyAbsenceAsync(@"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealed() { await VerifyAbsenceAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() { await VerifyAbsenceAsync(@"delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterConst() { await VerifyAbsenceAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterReadOnly() { await VerifyAbsenceAsync( @"class C { readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVolatile() { await VerifyAbsenceAsync( @"class C { volatile $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInMethod() { await VerifyAbsenceAsync( @"class C { void Foo() { $$"); } } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Encodings; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /// <summary> test vectors from ISO 9796-1 and ISO 9796-2 edition 1.</summary> [TestFixture] public class ISO9796Test : SimpleTest { static BigInteger mod1 = new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16); static BigInteger pub1 = new BigInteger("03", 16); static BigInteger pri1 = new BigInteger("2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac9f0783a49dd5f6c5af651f4c9d0dc9281c96a3f16a85f9572d7cc3f2d0f25a9dbf1149e4cdc32273faadd3fda5dcda7", 16); static BigInteger mod2 = new BigInteger("ffffff7fa27087c35ebead78412d2bdffe0301edd494df13458974ea89b364708f7d0f5a00a50779ddf9f7d4cb80b8891324da251a860c4ec9ef288104b3858d", 16); static BigInteger pub2 = new BigInteger("03", 16); static BigInteger pri2 = new BigInteger("2aaaaa9545bd6bf5e51fc7940adcdca5550080524e18cfd88b96e8d1c19de6121b13fac0eb0495d47928e047724d91d1740f6968457ce53ec8e24c9362ce84b5", 16); static byte[] msg1 = Hex.Decode("0cbbaa99887766554433221100"); // // you'll need to see the ISO 9796 to make sense of this // static byte[] sig1 = mod1.Subtract(new BigInteger("309f873d8ded8379490f6097eaafdabc137d3ebfd8f25ab5f138d56a719cdc526bdd022ea65dabab920a81013a85d092e04d3e421caab717c90d89ea45a8d23a", 16)).ToByteArray(); static byte[] msg2 = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); static byte[] sig2 = new BigInteger("319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c", 16).ToByteArray(); static byte[] msg3 = Hex.Decode("0112233445566778899aabbccd"); static byte[] sig3 = mod2.Subtract(new BigInteger("58e59ffb4b1fb1bcdbf8d1fe9afa3730c78a318a1134f5791b7313d480ff07ac319b068edf8f212945cb09cf33df30ace54f4a063fcca0b732f4b662dc4e2454", 16)).ToByteArray(); // // ISO 9796-2 // static BigInteger mod3 = new BigInteger("ffffffff78f6c55506c59785e871211ee120b0b5dd644aa796d82413a47b24573f1be5745b5cd9950f6b389b52350d4e01e90009669a8720bf265a2865994190a661dea3c7828e2e7ca1b19651adc2d5", 16); static BigInteger pub3 = new BigInteger("03", 16); static BigInteger pri3 = new BigInteger("2aaaaaaa942920e38120ee965168302fd0301d73a4e60c7143ceb0adf0bf30b9352f50e8b9e4ceedd65343b2179005b2f099915e4b0c37e41314bb0821ad8330d23cba7f589e0f129b04c46b67dfce9d", 16); static BigInteger mod4 = new BigInteger("FFFFFFFF45f1903ebb83d4d363f70dc647b839f2a84e119b8830b2dec424a1ce0c9fd667966b81407e89278283f27ca8857d40979407fc6da4cc8a20ecb4b8913b5813332409bc1f391a94c9c328dfe46695daf922259174544e2bfbe45cc5cd", 16); static BigInteger pub4 = new BigInteger("02", 16); static BigInteger pri4 = new BigInteger("1fffffffe8be3207d7707a9a6c7ee1b8c8f7073e5509c2337106165bd8849439c193faccf2cd70280fd124f0507e4f94cb66447680c6b87b6599d1b61c8f3600854a618262e9c1cb1438e485e47437be036d94b906087a61ee74ab0d9a1accd8", 16); static byte[] msg4 = Hex.Decode("6162636462636465636465666465666765666768666768696768696a68696a6b696a6b6c6a6b6c6d6b6c6d6e6c6d6e6f6d6e6f706e6f7071"); static byte[] sig4 = Hex.Decode("374695b7ee8b273925b4656cc2e008d41463996534aa5aa5afe72a52ffd84e118085f8558f36631471d043ad342de268b94b080bee18a068c10965f581e7f32899ad378835477064abed8ef3bd530fce"); static byte[] msg5 = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"); static byte[] sig5 = Hex.Decode("5cf9a01854dbacaec83aae8efc563d74538192e95466babacd361d7c86000fe42dcb4581e48e4feb862d04698da9203b1803b262105104d510b365ee9c660857ba1c001aa57abfd1c8de92e47c275cae"); // // scheme 2 data // static BigInteger mod6 = new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16); static BigInteger pub6 = new BigInteger("11", 16); static BigInteger pri6 = new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16); // static byte[] sig6 = new BigInteger("0073FEAF13EB12914A43FE635022BB4AB8188A8F3ABD8D8A9E4AD6C355EE920359C7F237AE36B1212FE947F676C68FE362247D27D1F298CA9302EB21F4A64C26CE44471EF8C0DFE1A54606F0BA8E63E87CDACA993BFA62973B567473B4D38FAE73AB228600934A9CC1D3263E632E21FD52D2B95C5F7023DA63DE9509C01F6C7BBC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] sig6 = new BigInteger("0073FEAF13EB12914A43FE635022BB4AB8188A8F3ABD8D8A9E4AD6C355EE920359C7F237AE36B1212FE947F676C68FE362247D27D1F298CA9302EB21F4A64C26CE44471EF8C0DFE1A54606F0BA8E63E87CDACA993BFA62973B567473B4D38FAE73AB228600934A9CC1D3263E632E21FD52D2B95C5F7023DA63DE9509C01F6C7BBC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg7 = Hex.Decode("6162636462636465636465666465666765666768666768696768696A68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F70716F70717270717273"); static byte[] sig7 = new BigInteger("296B06224010E1EC230D4560A5F88F03550AAFCE31C805CE81E811E5E53E5F71AE64FC2A2A486B193E87972D90C54B807A862F21A21919A43ECF067240A8C8C641DE8DCDF1942CF790D136728FFC0D98FB906E7939C1EC0E64C0E067F0A7443D6170E411DF91F797D1FFD74009C4638462E69D5923E7433AEC028B9A90E633CC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg8 = Hex.Decode("FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA98"); static byte[] sig8 = new BigInteger("01402B29ABA104079677CE7FC3D5A84DB24494D6F9508B4596484F5B3CC7E8AFCC4DDE7081F21CAE9D4F94D6D2CCCB43FCEDA0988FFD4EF2EAE72CFDEB4A2638F0A34A0C49664CD9DB723315759D758836C8BA26AC4348B66958AC94AE0B5A75195B57ABFB9971E21337A4B517F2E820B81F26BCE7C66F48A2DB12A8F3D731CC", 16).ModPow(pri6, mod6).ToByteArray(); static byte[] msg9 = Hex.Decode("6162636462636465636465666465666765666768666768696768696A68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F70716F707172707172737172737472737475737475767475767775767778767778797778797A78797A61797A61627A6162636162636462636465"); static byte[] sig9 = new BigInteger("6F2BB97571FE2EF205B66000E9DD06656655C1977F374E8666D636556A5FEEEEAF645555B25F45567C4EE5341F96FED86508C90A9E3F11B26E8D496139ED3E55ECE42860A6FB3A0817DAFBF13019D93E1D382DA07264FE99D9797D2F0B7779357CA7E74EE440D8855B7DDF15F000AC58EE3FFF144845E771907C0C83324A6FBC", 16).ModPow(pri6, mod6).ToByteArray(); public override string Name { get { return "ISO9796"; } } private bool IsSameAs( byte[] a, int off, byte[] b) { if ((a.Length - off) != b.Length) { return false; } for (int i = 0; i != b.Length; i++) { if (a[i + off] != b[i]) { return false; } } return true; } private bool StartsWith( byte[] a, byte[] b) { if (a.Length < b.Length) return false; for (int i = 0; i != b.Length; i++) { if (a[i] != b[i]) return false; } return true; } [Test] public virtual void DoTest1() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod1, pub1); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod1, pri1); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); eng.SetPadBits(4); data = eng.ProcessBlock(msg1, 0, msg1.Length); eng.Init(false, pubParameters); if (!AreEqual(sig1, data)) { Fail("failed ISO9796-1 generation Test 1"); } data = eng.ProcessBlock(data, 0, data.Length); if (!AreEqual(msg1, data)) { Fail("failed ISO9796-1 retrieve Test 1"); } } [Test] public virtual void DoTest2() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod1, pub1); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod1, pri1); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); data = eng.ProcessBlock(msg2, 0, msg2.Length); eng.Init(false, pubParameters); if (!IsSameAs(data, 1, sig2)) { Fail("failed ISO9796-1 generation Test 2"); } data = eng.ProcessBlock(data, 0, data.Length); if (!AreEqual(msg2, data)) { Fail("failed ISO9796-1 retrieve Test 2"); } } [Test] public virtual void DoTest3() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod2, pub2); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod2, pri2); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-1 - public encrypt, private decrypt // ISO9796d1Encoding eng = new ISO9796d1Encoding(rsa); eng.Init(true, privParameters); eng.SetPadBits(4); data = eng.ProcessBlock(msg3, 0, msg3.Length); eng.Init(false, pubParameters); if (!IsSameAs(sig3, 1, data)) { Fail("failed ISO9796-1 generation Test 3"); } data = eng.ProcessBlock(data, 0, data.Length); if (!IsSameAs(msg3, 0, data)) { Fail("failed ISO9796-1 retrieve Test 3"); } } [Test] public virtual void DoTest4() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - Signing // Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD128Digest()); eng.Init(true, privParameters); eng.Update(msg4[0]); eng.BlockUpdate(msg4, 1, msg4.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig4, 0, data)) { Fail("failed ISO9796-2 generation Test 4"); } eng.Update(msg4[0]); eng.BlockUpdate(msg4, 1, msg4.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 4"); } if (eng.HasFullMessage()) { eng = new Iso9796d2Signer(rsa, new RipeMD128Digest()); eng.Init(false, pubParameters); if (!eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 verify and recover Test 4"); } if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 recovered message Test 4"); } // try update with recovered eng.UpdateWithRecoveredMessage(sig4); if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 updateWithRecovered recovered message Test 4"); } if (!eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4"); } if(!IsSameAs(eng.GetRecoveredMessage(), 0, msg4)) { Fail("failed ISO9796-2 updateWithRecovered recovered verify message Test 4"); } // should fail eng.UpdateWithRecoveredMessage(sig4); eng.BlockUpdate(msg4, 0, msg4.Length); if (eng.VerifySignature(sig4)) { Fail("failed ISO9796-2 updateWithRecovered verify and recover Test 4"); } } else { Fail("full message flag false - Test 4"); } } [Test] public virtual void DoTest5() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod3, pub3); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod3, pri3); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - Signing // Iso9796d2Signer eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true); eng.Init(true, privParameters); eng.Update(msg5[0]); eng.BlockUpdate(msg5, 1, msg5.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig5, 0, data)) { Fail("failed ISO9796-2 generation Test 5"); } eng.Update(msg5[0]); eng.BlockUpdate(msg5, 1, msg5.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage true - Test 5"); } if (!StartsWith(msg5, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 partial recovered message Test 5"); } int length = eng.GetRecoveredMessage().Length; if (length >= msg5.Length) { Fail("Test 5 recovered message too long"); } eng = new Iso9796d2Signer(rsa, new RipeMD160Digest(), true); eng.Init(false, pubParameters); eng.UpdateWithRecoveredMessage(sig5); if (!StartsWith(msg5, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 updateWithRecovered partial recovered message Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage updateWithRecovered true - Test 5"); } for (int i = length ; i != msg5.Length; i++) { eng.Update(msg5[i]); } if (!eng.VerifySignature(sig5)) { Fail("failed ISO9796-2 verify Test 5"); } if (eng.HasFullMessage()) { Fail("fullMessage updateWithRecovered true - Test 5"); } // should fail eng.UpdateWithRecoveredMessage(sig5); eng.BlockUpdate(msg5, 0, msg5.Length); if (eng.VerifySignature(sig5)) { Fail("failed ISO9796-2 updateWithRecovered verify fail Test 5"); } } // // against a zero length string // [Test] public virtual void DoTest6() { byte[] salt = Hex.Decode("61DF870C4890FE85D6E3DD87C3DCE3723F91DB49"); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, true); eng.Init(true, sigParameters); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig6, 1, data)) { Fail("failed ISO9796-2 generation Test 6"); } if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 6"); } } [Test] public virtual void DoTest7() { byte[] salt = new byte[0]; RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new Sha1Digest(), 0, false); eng.Init(true, sigParameters); eng.Update(msg7[0]); eng.BlockUpdate(msg7, 1, msg7.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig7, 0, data)) { Fail("failed ISO9796-2 generation Test 7"); } eng.Update(msg7[0]); eng.BlockUpdate(msg7, 1, msg7.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 7"); } if (!IsSameAs(msg7, 0, eng.GetRecoveredMessage())) { Fail("failed ISO9796-2 recovery Test 7"); } } [Test] public virtual void DoTest8() { byte[] salt = Hex.Decode("78E293203CBA1B7F92F05F4D171FF8CA3E738FF8"); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); ParametersWithSalt sigParameters = new ParametersWithSalt(privParameters, salt); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 20, false); eng.Init(true, sigParameters); eng.Update(msg8[0]); eng.BlockUpdate(msg8, 1, msg8.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig8, 0, data)) { Fail("failed ISO9796-2 generation Test 8"); } eng.Update(msg8[0]); eng.BlockUpdate(msg8, 1, msg8.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 8"); } } [Test] public virtual void DoTest9() { RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod6, pub6); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod6, pri6); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, new RipeMD160Digest(), 0, true); eng.Init(true, privParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); if (!IsSameAs(sig9, 0, data)) { Fail("failed ISO9796-2 generation Test 9"); } eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 9"); } } [Test] public virtual void DoTest10() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; // // ISO 9796-2 - PSS Signing // IDigest dig = new Sha1Digest(); Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize()); // // as the padding is random this test needs to repeat a few times to // make sure // for (int i = 0; i != 500; i++) { eng.Init(true, privParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.Update(msg9[0]); eng.BlockUpdate(msg9, 1, msg9.Length - 1); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 10"); } } } [Test] public virtual void DoTest11() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; byte[] m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; byte[] m3 = { 1, 2, 3, 4, 5, 6, 7, 8 }; // // ISO 9796-2 - PSS Signing // IDigest dig = new Sha1Digest(); Iso9796d2PssSigner eng = new Iso9796d2PssSigner(rsa, dig, dig.GetDigestSize()); // // check message bounds // eng.Init(true, privParameters); eng.BlockUpdate(m1, 0, m1.Length); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.BlockUpdate(m2, 0, m2.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m2 verify Test 11"); } eng.Init(false, pubParameters); eng.BlockUpdate(m3, 0, m3.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m3 verify Test 11"); } eng.Init(false, pubParameters); eng.BlockUpdate(m1, 0, m1.Length); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 11"); } } [Test] public virtual void DoTest12() { BigInteger mod = new BigInteger("B3ABE6D91A4020920F8B3847764ECB34C4EB64151A96FDE7B614DC986C810FF2FD73575BDF8532C06004C8B4C8B64F700A50AEC68C0701ED10E8D211A4EA554D", 16); BigInteger pubExp = new BigInteger("65537", 10); BigInteger priExp = new BigInteger("AEE76AE4716F77C5782838F328327012C097BD67E5E892E75C1356E372CCF8EE1AA2D2CBDFB4DA19F703743F7C0BA42B2D69202BA7338C294D1F8B6A5771FF41", 16); RsaKeyParameters pubParameters = new RsaKeyParameters(false, mod, pubExp); RsaKeyParameters privParameters = new RsaKeyParameters(true, mod, priExp); RsaEngine rsa = new RsaEngine(); byte[] data; byte[] m1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] m2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; byte[] m3 = { 1, 2, 3, 4, 5, 6, 7, 8 }; // // ISO 9796-2 - Regular Signing // IDigest dig = new Sha1Digest(); Iso9796d2Signer eng = new Iso9796d2Signer(rsa, dig); // // check message bounds // eng.Init(true, privParameters); eng.BlockUpdate(m1, 0, m1.Length); data = eng.GenerateSignature(); eng.Init(false, pubParameters); eng.BlockUpdate(m2, 0, m2.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m2 verify Test 12"); } eng.Init(false, pubParameters); eng.BlockUpdate(m3, 0, m3.Length); if (eng.VerifySignature(data)) { Fail("failed ISO9796-2 m3 verify Test 12"); } eng.Init(false, pubParameters); eng.BlockUpdate(m1, 0, m1.Length); if (!eng.VerifySignature(data)) { Fail("failed ISO9796-2 verify Test 12"); } } public override void PerformTest() { DoTest1(); DoTest2(); DoTest3(); DoTest4(); DoTest5(); DoTest6(); DoTest7(); DoTest8(); DoTest9(); DoTest10(); DoTest11(); DoTest12(); } public static void Main( string[] args) { RunTest(new ISO9796Test()); } } }
using System; using System.ComponentModel; using System.Windows.Forms; using Csla.Rules; using ProjectTracker.Library; namespace PTWin { public partial class ResourceEdit : WinPart { #region Properties public ProjectTracker.Library.ResourceEdit Resource { get; private set; } protected internal override object GetIdValue() { return Resource; } public override string ToString() { return Resource.FullName; } #endregion #region Change event handlers private void ResourceEdit_CurrentPrincipalChanged(object sender, EventArgs e) { ApplyAuthorizationRules(); } private void Resource_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsDirty") { this.ResourceBindingSource.ResetBindings(true); this.AssignmentsBindingSource.ResetBindings(true); } } #endregion #region Constructors private ResourceEdit() { // force to use parametrized constructor } public ResourceEdit(ProjectTracker.Library.ResourceEdit resource) { InitializeComponent(); // store object reference Resource = resource; } #endregion #region Plumbing... private void ResourceEdit_Load(object sender, EventArgs e) { this.CurrentPrincipalChanged += new EventHandler(ResourceEdit_CurrentPrincipalChanged); Resource.PropertyChanged += new PropertyChangedEventHandler(Resource_PropertyChanged); Setup(); } private void Setup() { // set up binding this.RoleListBindingSource.DataSource = ProjectTracker.Library.RoleList.GetCachedList(); BindUI(); // check authorization ApplyAuthorizationRules(); } private void ApplyAuthorizationRules() { bool canEdit = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(ProjectTracker.Library.ResourceEdit)); if (!canEdit) RebindUI(false, true); // have the controls enable/disable/etc this.ReadWriteAuthorization1.ResetControlAuthorization(); // enable/disable appropriate buttons this.OKButton.Enabled = canEdit; this.ApplyButton.Enabled = canEdit; this.Cancel_Button.Enabled = canEdit; this.AssignButton.Enabled = canEdit; this.UnassignButton.Enabled = canEdit; // enable/disable role column in grid this.AssignmentsDataGridView.Columns[3].ReadOnly = !canEdit; } private void BindUI() { Resource.BeginEdit(); this.ResourceBindingSource.DataSource = Resource; } private bool RebindUI(bool saveObject, bool rebind) { // disable events this.ResourceBindingSource.RaiseListChangedEvents = false; this.AssignmentsBindingSource.RaiseListChangedEvents = false; try { // unbind the UI UnbindBindingSource(this.AssignmentsBindingSource, saveObject, false); UnbindBindingSource(this.ResourceBindingSource, saveObject, true); this.AssignmentsBindingSource.DataSource = this.ResourceBindingSource; // save or cancel changes if (saveObject) { Resource.ApplyEdit(); try { Resource = Resource.Save(); } catch (Csla.DataPortalException ex) { MessageBox.Show(ex.BusinessException.ToString(), "Error saving", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error Saving", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } } else Resource.CancelEdit(); return true; } finally { // rebind UI if requested if (rebind) BindUI(); // restore events this.ResourceBindingSource.RaiseListChangedEvents = true; this.AssignmentsBindingSource.RaiseListChangedEvents = true; if (rebind) { // refresh the UI if rebinding this.ResourceBindingSource.ResetBindings(false); this.AssignmentsBindingSource.ResetBindings(false); } } } #endregion #region Button event handlers private void OKButton_Click(object sender, EventArgs e) { if (IsSavable()) { using (StatusBusy busy = new StatusBusy("Saving...")) { if (RebindUI(true, false)) { this.Close(); } } } } private void ApplyButton_Click(object sender, EventArgs e) { if (IsSavable()) { using (StatusBusy busy = new StatusBusy("Saving...")) { RebindUI(true, true); } } } private bool IsSavable() { if (Resource.IsSavable) return true; if (!Resource.IsValid) { MessageBox.Show(GetErrorMessage(), "Saving Resource", MessageBoxButtons.OK, MessageBoxIcon.Error); } return false; } private string GetErrorMessage() { var message = "Resource is invalid and cannot be saved." + Environment.NewLine + Environment.NewLine; foreach (var rule in Resource.BrokenRulesCollection) { if (rule.Severity == RuleSeverity.Error) message += "- " + rule.Description + Environment.NewLine; } return message; } private void Cancel_Button_Click(object sender, EventArgs e) { RebindUI(false, true); } private void CloseButton_Click(object sender, EventArgs e) { RebindUI(false, false); this.Close(); } private void RefreshButton_Click(object sender, EventArgs e) { if (CanRefresh()) { using (StatusBusy busy = new StatusBusy("Refreshing...")) { if (RebindUI(false, false)) { Resource = ProjectTracker.Library.ResourceEdit.GetResourceEdit(Resource.Id); RoleList.InvalidateCache(); RoleList.CacheList(); Setup(); } } } } private bool CanRefresh() { if (!Resource.IsDirty) return true; var dlg = MessageBox.Show("Resource is not saved and all changes will be lost.\r\n\r\nDo you want to refresh?.", "Refreshing Resource", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); return dlg == DialogResult.OK; } private void AssignButton_Click(object sender, EventArgs e) { using (ProjectSelect dlg = new ProjectSelect()) { if (dlg.ShowDialog() == DialogResult.OK) { try { Resource.Assignments.AssignTo(dlg.ProjectId); } catch (InvalidOperationException ex) { MessageBox.Show(ex.Message, "Error Assigning", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error Assigning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } } private void UnassignButton_Click(object sender, EventArgs e) { if (this.AssignmentsDataGridView.SelectedRows.Count > 0) { var projectId = (int) this.AssignmentsDataGridView.SelectedRows[0].Cells[0].Value; Resource.Assignments.Remove(projectId); } } private void AssignmentsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 1 && e.RowIndex > -1) { var projectId = (int) this.AssignmentsDataGridView.Rows[e.RowIndex].Cells[0].Value; MainForm.Instance.ShowEditProject(projectId); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Dynamic; using System.Linq; using IronPython.Runtime.Binding; using IronPython.Runtime.Types; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Runtime.Operations { internal static class PythonTypeOps { private static readonly Dictionary<FieldInfo, PythonTypeSlot> _fieldCache = new Dictionary<FieldInfo, PythonTypeSlot>(); private static readonly Dictionary<BuiltinFunction, BuiltinMethodDescriptor> _methodCache = new Dictionary<BuiltinFunction, BuiltinMethodDescriptor>(); private static readonly Dictionary<BuiltinFunction, ClassMethodDescriptor> _classMethodCache = new Dictionary<BuiltinFunction, ClassMethodDescriptor>(); internal static readonly Dictionary<BuiltinFunctionKey, BuiltinFunction> _functions = new Dictionary<BuiltinFunctionKey, BuiltinFunction>(); private static readonly Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction> _ctors = new Dictionary<ReflectionCache.MethodBaseCache, ConstructorFunction>(); private static readonly Dictionary<EventTracker, ReflectedEvent> _eventCache = new Dictionary<EventTracker, ReflectedEvent>(); internal static readonly Dictionary<PropertyTracker, ReflectedGetterSetter> _propertyCache = new Dictionary<PropertyTracker, ReflectedGetterSetter>(); internal static PythonTuple MroToPython(IList<PythonType> types) { List<object> res = new List<object>(types.Count); foreach (PythonType dt in types) { if (dt.UnderlyingSystemType == typeof(ValueType)) continue; // hide value type res.Add(dt); } return PythonTuple.Make(res); } internal static string GetModuleName(CodeContext/*!*/ context, Type type) { Type curType = type; while (curType != null) { string moduleName; if (context.LanguageContext.BuiltinModuleNames.TryGetValue(curType, out moduleName)) { return moduleName; } curType = curType.DeclaringType; } FieldInfo modField = type.GetField("__module__"); if (modField != null && modField.IsLiteral && modField.FieldType == typeof(string)) { return (string)modField.GetRawConstantValue(); } return "builtins"; } internal static object CallParams(CodeContext/*!*/ context, PythonType cls, params object[] args\u03c4) { if (args\u03c4 == null) args\u03c4 = ArrayUtils.EmptyObjects; return CallWorker(context, cls, args\u03c4); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, object[] args) { object newObject = PythonOps.CallWithContext(context, GetTypeNew(context, dt), ArrayUtils.Insert<object>(dt, args)); if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Length)) { PythonOps.CallWithContext(context, GetInitMethod(context, dt, newObject), args); AddFinalizer(context, dt, newObject); } return newObject; } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, IDictionary<string, object> kwArgs, object[] args) { object[] allArgs = ArrayOps.CopyArray(args, kwArgs.Count + args.Length); string[] argNames = new string[kwArgs.Count]; int i = args.Length; foreach (KeyValuePair<string, object> kvp in kwArgs) { allArgs[i] = kvp.Value; argNames[i++ - args.Length] = kvp.Key; } return CallWorker(context, dt, new KwCallInfo(allArgs, argNames)); } internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, KwCallInfo args) { object[] clsArgs = ArrayUtils.Insert<object>(dt, args.Arguments); object newObject = PythonCalls.CallWithKeywordArgs(context, GetTypeNew(context, dt), clsArgs, args.Names); if (newObject == null) return null; if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Arguments.Length)) { PythonCalls.CallWithKeywordArgs(context, GetInitMethod(context, dt, newObject), args.Arguments, args.Names); AddFinalizer(context, dt, newObject); } return newObject; } /// <summary> /// Looks up __init__ avoiding calls to __getattribute__ and handling both /// new-style and old-style classes in the MRO. /// </summary> private static object GetInitMethod(CodeContext/*!*/ context, PythonType dt, object newObject) { // __init__ is never searched for w/ __getattribute__ for (int i = 0; i < dt.ResolutionOrder.Count; i++) { PythonType cdt = dt.ResolutionOrder[i]; PythonTypeSlot dts; object value; if (cdt.TryLookupSlot(context, "__init__", out dts) && dts.TryGetValue(context, newObject, dt, out value)) { return value; } } return null; } private static void AddFinalizer(CodeContext/*!*/ context, PythonType dt, object newObject) { // check if object has finalizer... if (dt.TryResolveSlot(context, "__del__", out _)) { IWeakReferenceable iwr = context.LanguageContext.ConvertToWeakReferenceable(newObject); Debug.Assert(iwr != null); InstanceFinalizer nif = new InstanceFinalizer(context, newObject); iwr.SetFinalizer(new WeakRefTracker(iwr, nif, nif)); } } private static object GetTypeNew(CodeContext/*!*/ context, PythonType dt) { PythonTypeSlot dts; if (!dt.TryResolveSlot(context, "__new__", out dts)) { throw PythonOps.TypeError("cannot create instances of {0}", dt.Name); } object newInst; bool res = dts.TryGetValue(context, dt, dt, out newInst); Debug.Assert(res); return newInst; } internal static bool IsRuntimeAssembly(Assembly assembly) { if (assembly == typeof(PythonOps).Assembly || // IronPython.dll assembly == typeof(Microsoft.Scripting.Interpreter.LightCompiler).Assembly || // Microsoft.Scripting.dll assembly == typeof(DynamicMetaObject).Assembly) { // Microsoft.Scripting.Core.dll return true; } AssemblyName assemblyName = new AssemblyName(assembly.FullName); if (assemblyName.Name.Equals("IronPython.Modules", StringComparison.Ordinal)) { // IronPython.Modules.dll return true; } return false; } private static bool ShouldInvokeInit(PythonType cls, PythonType newObjectType, int argCnt) { // don't run __init__ if it's not a subclass of ourselves, // or if this is the user doing type(x), or if it's a standard // .NET type which doesn't have an __init__ method (this is a perf optimization) return (!cls.IsSystemType || cls.IsPythonType) && newObjectType.IsSubclassOf(cls) && (cls != TypeCache.PythonType || argCnt > 1); } internal static string GetName(object o) { // Resolve Namespace-Tracker name, which would end in `namespace#` if // it is not handled individually if (o is NamespaceTracker nt) return nt.Name; return DynamicHelpers.GetPythonType(o).Name; } internal static PythonType[] ObjectTypes(object[] args) { PythonType[] types = new PythonType[args.Length]; for (int i = 0; i < args.Length; i++) { types[i] = DynamicHelpers.GetPythonType(args[i]); } return types; } internal static Type[] ConvertToTypes(PythonType[] pythonTypes) { Type[] types = new Type[pythonTypes.Length]; for (int i = 0; i < pythonTypes.Length; i++) { types[i] = ConvertToType(pythonTypes[i]); } return types; } private static Type ConvertToType(PythonType pythonType) { if (pythonType.IsNull) { return typeof(DynamicNull); } else { return pythonType.UnderlyingSystemType; } } internal static TrackerTypes GetMemberType(MemberGroup members) { TrackerTypes memberType = TrackerTypes.All; for (int i = 0; i < members.Count; i++) { MemberTracker mi = members[i]; if (mi.MemberType != memberType) { if (memberType != TrackerTypes.All) { return TrackerTypes.All; } memberType = mi.MemberType; } } return memberType; } internal static PythonTypeSlot/*!*/ GetSlot(MemberGroup group, string name, bool privateBinding) { if (group.Count == 0) { return null; } group = FilterNewSlots(group); TrackerTypes tt = GetMemberType(group); switch(tt) { case TrackerTypes.Method: bool checkStatic = false; List<MemberInfo> mems = new List<MemberInfo>(); foreach (MemberTracker mt in group) { MethodTracker metht = (MethodTracker)mt; mems.Add(metht.Method); checkStatic |= metht.IsStatic; } Type declType = group[0].DeclaringType; MemberInfo[] memArray = mems.ToArray(); FunctionType ft = GetMethodFunctionType(declType, memArray, checkStatic); return GetFinalSlotForFunction(GetBuiltinFunction(declType, group[0].Name, name, ft, memArray)); case TrackerTypes.Field: return GetReflectedField(((FieldTracker)group[0]).Field); case TrackerTypes.Property: return GetReflectedProperty((PropertyTracker)group[0], group, privateBinding); case TrackerTypes.Event: return GetReflectedEvent(((EventTracker)group[0])); case TrackerTypes.Type: TypeTracker type = (TypeTracker)group[0]; for (int i = 1; i < group.Count; i++) { type = TypeGroup.UpdateTypeEntity(type, (TypeTracker)group[i]); } if (type is TypeGroup) { return new PythonTypeUserDescriptorSlot(type, true); } return new PythonTypeUserDescriptorSlot(DynamicHelpers.GetPythonTypeFromType(type.Type), true); case TrackerTypes.Constructor: return GetConstructorFunction(group[0].DeclaringType, privateBinding); case TrackerTypes.Custom: return ((PythonCustomTracker)group[0]).GetSlot(); default: // if we have a new slot in the derived class filter out the // members from the base class. throw new InvalidOperationException(String.Format("Bad member type {0} on {1}.{2}", tt.ToString(), group[0].DeclaringType, name)); } } internal static MemberGroup FilterNewSlots(MemberGroup group) { if (GetMemberType(group) == TrackerTypes.All) { Type declType = group[0].DeclaringType; for (int i = 1; i < group.Count; i++) { if (group[i].DeclaringType != declType) { if (group[i].DeclaringType.IsSubclassOf(declType)) { declType = group[i].DeclaringType; } } } List<MemberTracker> trackers = new List<MemberTracker>(); for (int i = 0; i < group.Count; i++) { if (group[i].DeclaringType == declType) { trackers.Add(group[i]); } } if (trackers.Count != group.Count) { return new MemberGroup(trackers.ToArray()); } } return group; } private static BuiltinFunction GetConstructorFunction(Type t, bool privateBinding) { BuiltinFunction ctorFunc = InstanceOps.NonDefaultNewInst; MethodBase[] ctors = GetConstructors(t, privateBinding, true); return GetConstructor(t, ctorFunc, ctors); } internal static MethodBase[] GetConstructors(Type t, bool privateBinding, bool includeProtected = false) { MethodBase[] ctors = CompilerHelpers.GetConstructors(t, privateBinding, includeProtected); if (t.IsEnum) { var enumCtor = typeof(PythonTypeOps).GetDeclaredMethods(nameof(CreateEnum)).Single().MakeGenericMethod(t); ctors = ctors.Concat(new[] { enumCtor }).ToArray(); } return ctors; } // support for EnumType(number) private static T CreateEnum<T>(object value) { if (value == null) { throw PythonOps.ValueError( $"None is not a valid {PythonOps.ToString(typeof(T))}" ); } try { return (T)Enum.ToObject(typeof(T), value); } catch (ArgumentException) { throw PythonOps.ValueError( $"{PythonOps.ToString(value)} is not a valid {PythonOps.ToString(typeof(T))}" ); } } internal static bool IsDefaultNew(MethodBase[] targets) { if (targets.Length == 1) { ParameterInfo[] pis = targets[0].GetParameters(); if (pis.Length == 0) { return true; } if (pis.Length == 1 && pis[0].ParameterType == typeof(CodeContext)) { return true; } } return false; } internal static BuiltinFunction GetConstructorFunction(Type type, string name) { List<MethodBase> methods = new List<MethodBase>(); bool hasDefaultConstructor = false; foreach (ConstructorInfo ci in type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)) { if (ci.IsPublic) { if (ci.GetParameters().Length == 0) { hasDefaultConstructor = true; } methods.Add(ci); } } if (type.IsValueType && !hasDefaultConstructor && type != typeof(void)) { try { methods.Add(typeof(ScriptingRuntimeHelpers).GetMethod(nameof(ScriptingRuntimeHelpers.CreateInstance), ReflectionUtils.EmptyTypes).MakeGenericMethod(type)); } catch (BadImageFormatException) { // certain types (e.g. ArgIterator) won't survive the above call. // we won't let you create instances of these types. } } if (methods.Count > 0) { return BuiltinFunction.MakeFunction(name, methods.ToArray(), type); } return null; } internal static ReflectedEvent GetReflectedEvent(EventTracker tracker) { ReflectedEvent res; lock (_eventCache) { if (!_eventCache.TryGetValue(tracker, out res)) { if (PythonBinder.IsExtendedType(tracker.DeclaringType)) { _eventCache[tracker] = res = new ReflectedEvent(tracker, true); } else { _eventCache[tracker] = res = new ReflectedEvent(tracker, false); } } } return res; } internal static PythonTypeSlot/*!*/ GetFinalSlotForFunction(BuiltinFunction/*!*/ func) { if ((func.FunctionType & FunctionType.Method) != 0) { BuiltinMethodDescriptor desc; lock (_methodCache) { if (!_methodCache.TryGetValue(func, out desc)) { _methodCache[func] = desc = new BuiltinMethodDescriptor(func); } return desc; } } if (func.Targets[0].IsDefined(typeof(ClassMethodAttribute), true)) { lock (_classMethodCache) { ClassMethodDescriptor desc; if (!_classMethodCache.TryGetValue(func, out desc)) { _classMethodCache[func] = desc = new ClassMethodDescriptor(func); } return desc; } } return func; } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, null, mems); } #pragma warning disable IDE0052 // Remove unread private members - they're used by GetHashCode() internal readonly struct BuiltinFunctionKey { private readonly Type DeclaringType; private readonly ReflectionCache.MethodBaseCache Cache; private readonly FunctionType FunctionType; public BuiltinFunctionKey(Type declaringType, ReflectionCache.MethodBaseCache cache, FunctionType funcType) { Cache = cache; FunctionType = funcType; DeclaringType = declaringType; } } #pragma warning restore IDE0052 // Remove unread private members public static MethodBase[] GetNonBaseHelperMethodInfos(MemberInfo[] members) { List<MethodBase> res = new List<MethodBase>(); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb != null && !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix, StringComparison.Ordinal)) { res.Add(mb); } } return res.ToArray(); } public static MemberInfo[] GetNonBaseHelperMemberInfos(MemberInfo[] members) { List<MemberInfo> res = new List<MemberInfo>(members.Length); foreach (MemberInfo mi in members) { MethodBase mb = mi as MethodBase; if (mb == null || !mb.Name.StartsWith(NewTypeMaker.BaseMethodPrefix, StringComparison.Ordinal)) { res.Add(mi); } } return res.ToArray(); } internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ name, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { return GetBuiltinFunction(type, name, name, funcType, mems); } /// <summary> /// Gets a builtin function for the given declaring type and member infos. /// /// Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction /// for each .NET method. /// /// This method takes both a cacheName and a pythonName. The cache name is the real method name. The pythonName /// is the name of the method as exposed to Python. /// </summary> internal static BuiltinFunction/*!*/ GetBuiltinFunction(Type/*!*/ type, string/*!*/ cacheName, string/*!*/ pythonName, FunctionType? funcType, params MemberInfo/*!*/[]/*!*/ mems) { BuiltinFunction res = null; if (mems.Length != 0) { FunctionType ft = funcType ?? GetMethodFunctionType(type, mems); type = GetBaseDeclaringType(type, mems); BuiltinFunctionKey cache = new BuiltinFunctionKey(type, new ReflectionCache.MethodBaseCache(cacheName, GetNonBaseHelperMethodInfos(mems)), ft); lock (_functions) { if (!_functions.TryGetValue(cache, out res)) { if (PythonTypeOps.GetFinalSystemType(type) == type) { IList<MethodInfo> overriddenMethods = NewTypeMaker.GetOverriddenMethods(type, cacheName); if (overriddenMethods.Count > 0) { List<MemberInfo> newMems = new List<MemberInfo>(mems); foreach (MethodInfo mi in overriddenMethods) { newMems.Add(mi); } mems = newMems.ToArray(); } } _functions[cache] = res = BuiltinFunction.MakeMethod(pythonName, ReflectionUtils.GetMethodInfos(mems), type, ft); } } } return res; } private static Type GetCommonBaseType(Type xType, Type yType) { if (xType.IsSubclassOf(yType)) { return yType; } else if (yType.IsSubclassOf(xType)) { return xType; } else if (xType == yType) { return xType; } Type xBase = xType.BaseType; Type yBase = yType.BaseType; if (xBase != null) { Type res = GetCommonBaseType(xBase, yType); if (res != null) { return res; } } if (yBase != null) { Type res = GetCommonBaseType(xType, yBase); if (res != null) { return res; } } return null; } private static Type GetBaseDeclaringType(Type type, MemberInfo/*!*/[] mems) { // get the base most declaring type, first sort the list so that // the most derived class is at the beginning. Array.Sort<MemberInfo>(mems, delegate(MemberInfo x, MemberInfo y) { if (x.DeclaringType.IsSubclassOf(y.DeclaringType)) { return -1; } else if (y.DeclaringType.IsSubclassOf(x.DeclaringType)) { return 1; } else if (x.DeclaringType == y.DeclaringType) { return 0; } // no relationship between these types, they should be base helper // methods for two different types - for example object.MemberwiseClone for // ExtensibleInt & object. We need to reset our type to the common base type. type = GetCommonBaseType(x.DeclaringType, y.DeclaringType) ?? typeof(object); // generic type definitions will have a null name. if (x.DeclaringType.FullName == null) { return -1; } else if (y.DeclaringType.FullName == null) { return 1; } return string.Compare(x.DeclaringType.FullName, y.DeclaringType.FullName, StringComparison.Ordinal); }); // then if the provided type is a subclass of the most derived type // then our declaring type is the methods declaring type. foreach (MemberInfo mb in mems) { // skip extension methods if (mb.DeclaringType.IsAssignableFrom(type)) { if (type == mb.DeclaringType || type.IsSubclassOf(mb.DeclaringType)) { type = mb.DeclaringType; break; } } } return type; } internal static ConstructorFunction GetConstructor(Type type, BuiltinFunction realTarget, params MethodBase[] mems) { ConstructorFunction res = null; if (mems.Length != 0) { ReflectionCache.MethodBaseCache cache = new ReflectionCache.MethodBaseCache("__new__", mems); lock (_ctors) { if (!_ctors.TryGetValue(cache, out res)) { _ctors[cache] = res = new ConstructorFunction(realTarget, mems); } } } return res; } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { return GetMethodFunctionType(type, methods, true); } internal static FunctionType GetMethodFunctionType(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods, bool checkStatic) { FunctionType ft = FunctionType.None; foreach (MethodInfo mi in methods) { if (mi.IsStatic && mi.IsSpecialName) { ParameterInfo[] pis = mi.GetParameters(); if ((pis.Length == 2 && pis[0].ParameterType != typeof(CodeContext)) || (pis.Length == 3 && pis[0].ParameterType == typeof(CodeContext))) { ft |= FunctionType.BinaryOperator; if (pis[pis.Length - 2].ParameterType != type && pis[pis.Length - 1].ParameterType == type) { ft |= FunctionType.ReversedOperator; } } } if (checkStatic && IsStaticFunction(type, mi)) { ft |= FunctionType.Function; } else { ft |= FunctionType.Method; } } if (IsMethodAlwaysVisible(type, methods)) { ft |= FunctionType.AlwaysVisible; } return ft; } /// <summary> /// Checks to see if the provided members are always visible for the given type. /// /// This filters out methods such as GetHashCode and Equals on standard .NET /// types that we expose directly as Python types (e.g. object, string, etc...). /// /// It also filters out the base helper overrides that are added for supporting /// super calls on user defined types. /// </summary> private static bool IsMethodAlwaysVisible(Type/*!*/ type, MemberInfo/*!*/[]/*!*/ methods) { bool alwaysVisible = true; if (PythonBinder.IsPythonType(type)) { // only show methods defined outside of the system types (object, string) foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType) || PythonBinder.IsExtendedType(mi.GetBaseDefinition().DeclaringType) || PythonHiddenAttribute.IsHidden(mi)) { alwaysVisible = false; break; } } } else if (typeof(IPythonObject).IsAssignableFrom(type)) { // check if this is a virtual override helper, if so we // may need to filter it out. foreach (MethodInfo mi in methods) { if (PythonBinder.IsExtendedType(mi.DeclaringType)) { alwaysVisible = false; break; } } } return alwaysVisible; } /// <summary> /// a function is static if it's a static .NET method and it's defined on the type or is an extension method /// with StaticExtensionMethod decoration. /// </summary> private static bool IsStaticFunction(Type type, MethodInfo mi) { return mi.IsStatic && // method must be truly static !mi.IsDefined(typeof(WrapperDescriptorAttribute), false) && // wrapper descriptors are instance methods (mi.DeclaringType.IsAssignableFrom(type) || mi.IsDefined(typeof(StaticExtensionMethodAttribute), false)); // or it's not an extension method or it's a static extension method } internal static PythonTypeSlot GetReflectedField(FieldInfo info) { PythonTypeSlot res; NameType nt = NameType.Field; if (!PythonBinder.IsExtendedType(info.DeclaringType) && !PythonHiddenAttribute.IsHidden(info)) { nt |= NameType.PythonField; } lock (_fieldCache) { if (!_fieldCache.TryGetValue(info, out res)) { if (nt == NameType.PythonField && info.IsLiteral) { if (info.FieldType == typeof(int)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.Int32ToObject((int)info.GetRawConstantValue()), true ); } else if (info.FieldType == typeof(bool)) { res = new PythonTypeUserDescriptorSlot( ScriptingRuntimeHelpers.BooleanToObject((bool)info.GetRawConstantValue()), true ); } else { res = new PythonTypeUserDescriptorSlot( info.GetValue(null), true ); } } else { res = new ReflectedField(info, nt); } _fieldCache[info] = res; } } return res; } internal static string GetDocumentation(Type type) { // Python documentation object[] docAttr = type.GetCustomAttributes(typeof(DocumentationAttribute), false); if (docAttr != null && docAttr.Length > 0) { return ((DocumentationAttribute)docAttr[0]).Documentation; } if (type == typeof(DynamicNull)) return null; // Auto Doc (XML or otherwise) string autoDoc = DocBuilder.CreateAutoDoc(type); if (autoDoc == null) { autoDoc = String.Empty; } else { autoDoc += Environment.NewLine + Environment.NewLine; } // Simple generated helpbased on ctor, if available. ConstructorInfo[] cis = type.GetConstructors(); foreach (ConstructorInfo ci in cis) { autoDoc += FixCtorDoc(type, DocBuilder.CreateAutoDoc(ci, DynamicHelpers.GetPythonTypeFromType(type).Name, 0)) + Environment.NewLine; } return autoDoc; } private static string FixCtorDoc(Type type, string autoDoc) { return autoDoc.Replace("__new__(cls)", DynamicHelpers.GetPythonTypeFromType(type).Name + "()"). Replace("__new__(cls, ", DynamicHelpers.GetPythonTypeFromType(type).Name + "("); } internal static ReflectedGetterSetter GetReflectedProperty(PropertyTracker pt, MemberGroup allProperties, bool privateBinding) { ReflectedGetterSetter rp; lock (_propertyCache) { if (_propertyCache.TryGetValue(pt, out rp)) { return rp; } NameType nt = NameType.PythonProperty; MethodInfo getter = FilterProtectedGetterOrSetter(pt.GetGetMethod(true), privateBinding); MethodInfo setter = FilterProtectedGetterOrSetter(pt.GetSetMethod(true), privateBinding); if ((getter != null && PythonHiddenAttribute.IsHidden(getter, true)) || (setter != null && PythonHiddenAttribute.IsHidden(setter, true))) { nt = NameType.Property; } if (pt is ReflectedPropertyTracker rpt) { if (PythonBinder.IsExtendedType(pt.DeclaringType) || PythonHiddenAttribute.IsHidden(rpt.Property, true)) { nt = NameType.Property; } if (pt.GetIndexParameters().Length == 0) { List<MethodInfo> getters = new List<MethodInfo>(); List<MethodInfo> setters = new List<MethodInfo>(); IList<ExtensionPropertyTracker> overriddenProperties = NewTypeMaker.GetOverriddenProperties((getter ?? setter).DeclaringType, pt.Name); foreach (ExtensionPropertyTracker tracker in overriddenProperties) { MethodInfo method = tracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = tracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } foreach (PropertyTracker propTracker in allProperties) { MethodInfo method = propTracker.GetGetMethod(privateBinding); if (method != null) { getters.Add(method); } method = propTracker.GetSetMethod(privateBinding); if (method != null) { setters.Add(method); } } rp = new ReflectedProperty(rpt.Property, getters.ToArray(), setters.ToArray(), nt); } else { rp = new ReflectedIndexer(rpt.Property, NameType.Property, privateBinding); } } else { Debug.Assert(pt is ExtensionPropertyTracker); rp = new ReflectedExtensionProperty(new ExtensionPropertyInfo(pt.DeclaringType, getter ?? setter), nt); } _propertyCache[pt] = rp; return rp; } } private static MethodInfo FilterProtectedGetterOrSetter(MethodInfo info, bool privateBinding) { if (info != null) { if (privateBinding || info.IsPublic) { return info; } if (info.IsProtected()) { return info; } } return null; } internal static bool TryGetOperator(CodeContext context, object o, string name, out object callable) { PythonType pt = DynamicHelpers.GetPythonType(o); if (pt.TryResolveSlot(context, name, out PythonTypeSlot pts) && pts.TryGetValue(context, o, pt, out callable)) { return true; } callable = default; return false; } internal static bool TryInvokeUnaryOperator(CodeContext context, object o, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "UnaryOp " + CompilerHelpers.GetType(o).Name + " " + name); if (TryGetOperator(context, o, name, out object callable)) { value = PythonCalls.Call(context, callable); return true; } value = null; return false; } internal static bool TryInvokeBinaryOperator(CodeContext context, object o, object arg1, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "BinaryOp " + CompilerHelpers.GetType(o).Name + " " + name); if (TryGetOperator(context, o, name, out object callable)) { value = PythonCalls.Call(context, callable, arg1); return true; } value = null; return false; } internal static bool TryInvokeTernaryOperator(CodeContext context, object o, object arg1, object arg2, string name, out object value) { PerfTrack.NoteEvent(PerfTrack.Categories.Temporary, "TernaryOp " + CompilerHelpers.GetType(o).Name + " " + name); if (TryGetOperator(context, o, name, out object callable)) { value = PythonCalls.Call(context, callable, arg1, arg2); return true; } value = null; return false; } /// <summary> /// If we have only interfaces, we'll need to insert object's base /// </summary> internal static PythonTuple EnsureBaseType(PythonTuple bases) { bool hasInterface = false; foreach (object baseClass in bases) { PythonType dt = baseClass as PythonType; if (!dt.UnderlyingSystemType.IsInterface) { return bases; } else { hasInterface = true; } } if (hasInterface || bases.Count == 0) { // We found only interfaces. We need do add System.Object to the bases return new PythonTuple(bases, TypeCache.Object); } throw PythonOps.TypeError("a new-style class can't have only classic bases"); } internal static Type GetFinalSystemType(Type type) { while (typeof(IPythonObject).IsAssignableFrom(type) && !type.IsDefined(typeof(DynamicBaseTypeAttribute), false)) { type = type.BaseType; } return type; } } }
namespace AngleSharp.Core.Tests { using AngleSharp.Dom; using NUnit.Framework; using System; /// <summary> /// Tests from https://github.com/html5lib/html5lib-tests: /// tree-construction/tests21.dat /// </summary> [TestFixture] public class CDataTests { [Test] public void CDataInSvgElement() { var doc = (@"<svg><![CDATA[foo]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("foo", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataInMathElement() { var doc = (@"<math><![CDATA[foo]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1math0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1math0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1math0).Attributes.Length); Assert.AreEqual("math", dochtml0body1math0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1math0.NodeType); var dochtml0body1math0Text0 = dochtml0body1math0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1math0Text0.NodeType); Assert.AreEqual("foo", dochtml0body1math0Text0.TextContent); } [Test] public void CDataInDivElement() { var doc = (@"<div><![CDATA[foo]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1div0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1div0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1div0).Attributes.Length); Assert.AreEqual("div", dochtml0body1div0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1div0.NodeType); var dochtml0body1div0Comment0 = dochtml0body1div0.ChildNodes[0]; Assert.AreEqual(NodeType.Comment, dochtml0body1div0Comment0.NodeType); Assert.AreEqual(@"[CDATA[foo]]", dochtml0body1div0Comment0.TextContent); } [Test] public void CDataUnclosedInSvgElement() { var doc = (@"<svg><![CDATA[foo").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("foo", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataUnclosedWithoutTextInSvgElement() { var doc = (@"<svg><![CDATA[").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(0, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); } [Test] public void CDataWithoutTextInSvgElement() { var doc = (@"<svg><![CDATA[]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(0, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); } [Test] public void CDataClosedWrongInSvgElement() { var doc = (@"<svg><![CDATA[]] >]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("]] >", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataMissingClosingBracketInSvgElement() { var doc = (@"<svg><![CDATA[]]").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("]]", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataMissingClosingBracketsInSvgElement() { var doc = (@"<svg><![CDATA[]").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("]", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataMissingClosingSquareBracketInSvgElement() { var doc = (@"<svg><![CDATA[]>a").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("]>a", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithAdditionalClosingSquareBracketInSvgElementWithStandardDoctype() { var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]>").ToHtmlDocument(); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual(@"html", docType0.Name); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1svg0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml1body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType); var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType); Assert.AreEqual("foo]", dochtml1body1svg0Text0.TextContent); } [Test] public void CDataWithManyClosingSquareBracketsInSvgElementWithStandardDoctype() { var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]]>").ToHtmlDocument(); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual(@"html", docType0.Name); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1svg0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml1body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType); var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType); Assert.AreEqual("foo]]", dochtml1body1svg0Text0.TextContent); } [Test] public void CDataWithManyMoreClosingSquareBracketsInSvgElementWithStandardDoctype() { var doc = (@"<!DOCTYPE html><svg><![CDATA[foo]]]]]>").ToHtmlDocument(); var docType0 = doc.ChildNodes[0] as DocumentType; Assert.IsNotNull(docType0); Assert.AreEqual(NodeType.DocumentType, docType0.NodeType); Assert.AreEqual(@"html", docType0.Name); var dochtml1 = doc.ChildNodes[1]; Assert.AreEqual(2, dochtml1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1).Attributes.Length); Assert.AreEqual("html", dochtml1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1.NodeType); var dochtml1head0 = dochtml1.ChildNodes[0]; Assert.AreEqual(0, dochtml1head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1head0).Attributes.Length); Assert.AreEqual("head", dochtml1head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1head0.NodeType); var dochtml1body1 = dochtml1.ChildNodes[1]; Assert.AreEqual(1, dochtml1body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1).Attributes.Length); Assert.AreEqual("body", dochtml1body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1.NodeType); var dochtml1body1svg0 = dochtml1body1.ChildNodes[0]; Assert.AreEqual(1, dochtml1body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml1body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml1body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml1body1svg0.NodeType); var dochtml1body1svg0Text0 = dochtml1body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml1body1svg0Text0.NodeType); Assert.AreEqual("foo]]]", dochtml1body1svg0Text0.TextContent); } [Test] public void CDataInDivLocatedInForeignObjectWhichIsPlacedInSvgElement() { var doc = (@"<svg><foreignObject><div><![CDATA[foo]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0foreignObject0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0foreignObject0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0foreignObject0).Attributes.Length); Assert.AreEqual("foreignObject", dochtml0body1svg0foreignObject0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0foreignObject0.NodeType); var dochtml0body1svg0foreignObject0div0 = dochtml0body1svg0foreignObject0.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0foreignObject0div0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0foreignObject0div0).Attributes.Length); Assert.AreEqual("div", dochtml0body1svg0foreignObject0div0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0foreignObject0div0.NodeType); var dochtml0body1svg0foreignObject0div0Comment0 = dochtml0body1svg0foreignObject0div0.ChildNodes[0]; Assert.AreEqual(NodeType.Comment, dochtml0body1svg0foreignObject0div0Comment0.NodeType); Assert.AreEqual(@"[CDATA[foo]]", dochtml0body1svg0foreignObject0div0Comment0.TextContent); } [Test] public void CDataWithSvgTagInSvgElement() { var doc = (@"<svg><![CDATA[<svg>]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithClosingSvgTagInSvgElement() { var doc = (@"<svg><![CDATA[</svg>a]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("</svg>a", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithSvgTagUnclosedInSvgElement() { var doc = (@"<svg><![CDATA[<svg>a").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>a", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithClosingSvgTagUnclosedInSvgElement() { var doc = (@"<svg><![CDATA[</svg>a").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("</svg>a", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithSvgTagInSvgElementFollowedByPath() { var doc = (@"<svg><![CDATA[<svg>]]><path>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(2, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent); var dochtml0body1svg0path1 = dochtml0body1svg0.ChildNodes[1]; Assert.AreEqual(0, dochtml0body1svg0path1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0path1).Attributes.Length); Assert.AreEqual("path", dochtml0body1svg0path1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0path1.NodeType); } [Test] public void CDataWithSvgTagInSvgElementFollowedByClosingPath() { var doc = (@"<svg><![CDATA[<svg>]]></path>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithSvgTagInSvgElementFollowedByComment() { var doc = (@"<svg><![CDATA[<svg>]]><!--path-->").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(2, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>", dochtml0body1svg0Text0.TextContent); var dochtml0body1svg0Comment1 = dochtml0body1svg0.ChildNodes[1]; Assert.AreEqual(NodeType.Comment, dochtml0body1svg0Comment1.NodeType); Assert.AreEqual(@"path", dochtml0body1svg0Comment1.TextContent); } [Test] public void CDataWithSvgTagInSvgElementFollowedByText() { var doc = (@"<svg><![CDATA[<svg>]]>path").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<svg>path", dochtml0body1svg0Text0.TextContent); } [Test] public void CDataWithCommentInSvgElement() { var doc = (@"<svg><![CDATA[<!--svg-->]]>").ToHtmlDocument(); var dochtml0 = doc.ChildNodes[0]; Assert.AreEqual(2, dochtml0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0).Attributes.Length); Assert.AreEqual("html", dochtml0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0.NodeType); var dochtml0head0 = dochtml0.ChildNodes[0]; Assert.AreEqual(0, dochtml0head0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0head0).Attributes.Length); Assert.AreEqual("head", dochtml0head0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0head0.NodeType); var dochtml0body1 = dochtml0.ChildNodes[1]; Assert.AreEqual(1, dochtml0body1.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1).Attributes.Length); Assert.AreEqual("body", dochtml0body1.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1.NodeType); var dochtml0body1svg0 = dochtml0body1.ChildNodes[0]; Assert.AreEqual(1, dochtml0body1svg0.ChildNodes.Length); Assert.AreEqual(0, ((Element)dochtml0body1svg0).Attributes.Length); Assert.AreEqual("svg", dochtml0body1svg0.GetTagName()); Assert.AreEqual(NodeType.Element, dochtml0body1svg0.NodeType); var dochtml0body1svg0Text0 = dochtml0body1svg0.ChildNodes[0]; Assert.AreEqual(NodeType.Text, dochtml0body1svg0Text0.NodeType); Assert.AreEqual("<!--svg-->", dochtml0body1svg0Text0.TextContent); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GetTypedObjectForIUnknownTests { public static IEnumerable<object> GetTypedObjectForIUnknown_RoundtrippableType_TestData() { yield return new object(); yield return 10; yield return "string"; yield return new NonGenericClass(); yield return new NonGenericStruct(); yield return Int32Enum.Value1; MethodInfo method = typeof(GetTypedObjectForIUnknownTests).GetMethod(nameof(NonGenericMethod), BindingFlags.NonPublic | BindingFlags.Static); Delegate d = method.CreateDelegate(typeof(NonGenericDelegate)); yield return d; } public static IEnumerable<object[]> GetTypedObjectForIUnknown_TestData() { foreach (object o in GetTypedObjectForIUnknown_RoundtrippableType_TestData()) { yield return new object[] { o, o.GetType() }; yield return new object[] { o, typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] }; yield return new object[] { o, typeof(int).MakeByRefType() }; Type baseType = o.GetType().BaseType; while (baseType != null) { yield return new object[] { o, baseType }; baseType = baseType.BaseType; } } yield return new object[] { new ClassWithInterface(), typeof(NonGenericInterface) }; yield return new object[] { new StructWithInterface(), typeof(NonGenericInterface) }; yield return new object[] { new GenericClass<string>(), typeof(object) }; yield return new object[] { new Dictionary<string, int>(), typeof(object) }; yield return new object[] { new GenericStruct<string>(), typeof(object) }; yield return new object[] { new GenericStruct<string>(), typeof(ValueType) }; yield return new object[] { new int[] { 10 }, typeof(object) }; yield return new object[] { new int[] { 10 }, typeof(Array) }; yield return new object[] { new int[][] { new int[] { 10 } }, typeof(object) }; yield return new object[] { new int[][] { new int[] { 10 } }, typeof(Array) }; yield return new object[] { new int[,] { { 10 } }, typeof(object) }; yield return new object[] { new int[,] { { 10 } }, typeof(Array) }; yield return new object[] { new KeyValuePair<string, int>("key", 10), typeof(object) }; yield return new object[] { new KeyValuePair<string, int>("key", 10), typeof(ValueType) }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ValidPointer_ReturnsExpected(object o, Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Equal(o, Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void GetTypedObjectForIUnknown_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int))); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ZeroUnknown_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pUnk", () => Marshal.GetTypedObjectForIUnknown(IntPtr.Zero, typeof(int))); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_NullType_ThrowsArgumentNullException() { IntPtr iUnknown = Marshal.GetIUnknownForObject(new object()); try { AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetTypedObjectForIUnknown(iUnknown, null)); } finally { Marshal.Release(iUnknown); } } public static IEnumerable<object[]> GetTypedObjectForIUnknown_Invalid_TestData() { yield return new object[] { typeof(GenericClass<string>) }; yield return new object[] { typeof(GenericStruct<string>) }; yield return new object[] { typeof(GenericInterface<string>) }; yield return new object[] { typeof(GenericClass<>) }; AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); yield return new object[] { typeBuilder }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_Invalid_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_InvalidType_ThrowsArgumentException(Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(new object()); try { AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } public static IEnumerable<object[]> GetTypedObjectForIUnknownType_UncastableObject_TestData() { yield return new object[] { new object(), typeof(AbstractClass) }; yield return new object[] { new object(), typeof(NonGenericClass) }; yield return new object[] { new object(), typeof(NonGenericStruct) }; yield return new object[] { new object(), typeof(NonGenericStruct) }; yield return new object[] { new object(), typeof(NonGenericInterface) }; yield return new object[] { new NonGenericClass(), typeof(IFormattable) }; yield return new object[] { new ClassWithInterface(), typeof(IFormattable) }; yield return new object[] { new object(), typeof(int).MakePointerType() }; AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); Type collectibleType = typeBuilder.CreateType(); yield return new object[] { new object(), collectibleType }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknownType_UncastableObject_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_UncastableObject_ThrowsInvalidCastException(object o, Type type) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Throws<InvalidCastException>(() => Marshal.GetTypedObjectForIUnknown(ptr, type)); } finally { Marshal.Release(ptr); } } public static IEnumerable<object[]> GetTypedObjectForIUnknown_ArrayObjects_TestData() { yield return new object[] { new int[] { 10 } }; yield return new object[] { new int[][] { new int[] { 10 } } }; yield return new object[] { new int[,] { { 10 } } }; } [Theory] [MemberData(nameof(GetTypedObjectForIUnknown_ArrayObjects_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_ArrayType_ThrowsBadImageFormatException(object o) { IntPtr ptr = Marshal.GetIUnknownForObject(o); try { Assert.Throws<BadImageFormatException>(() => Marshal.GetTypedObjectForIUnknown(ptr, o.GetType())); } finally { Marshal.Release(ptr); } } public class ClassWithInterface : NonGenericInterface { } public struct StructWithInterface : NonGenericInterface { } private static void NonGenericMethod(int i) { } public delegate void NonGenericDelegate(int i); public enum Int32Enum : int { Value1, Value2 } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using ServiceStack.Model; namespace ServiceStack.Examples.ServiceModel.Types { [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class CustomerOrders { public CustomerOrders() { this.Orders = new List<Order>(); } public Customer Customer { get; set; } public List<Order> Orders { get; set; } public override bool Equals(object obj) { var other = obj as CustomerOrders; if (other == null) return false; var i = 0; return this.Customer.Equals(other.Customer) && this.Orders.All(x => x.Equals(other.Orders[i++])); } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class Customer : IHasStringId { public Customer() { } public Customer(string customerId, string companyName, string contactName, string contactTitle, string address, string city, string region, string postalCode, string country, string phoneNo, string faxNo, byte[] picture) { Id = customerId; CompanyName = companyName; ContactName = contactName; ContactTitle = contactTitle; Address = address; City = city; Region = region; PostalCode = postalCode; Country = country; Phone = phoneNo; Fax = faxNo; Picture = picture; } public string Id { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public byte[] Picture { get; set; } public override bool Equals(object obj) { var other = obj as Customer; if (other == null) return false; return this.Address == other.Address && this.City == other.City && this.CompanyName == other.CompanyName && this.ContactName == other.ContactName && this.ContactTitle == other.ContactTitle && this.Country == other.Country && this.Fax == other.Fax && this.Id == other.Id && this.Phone == other.Phone && this.Picture == other.Picture && this.PostalCode == other.PostalCode && this.Region == other.Region; } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class Order { public Order() { this.OrderDetails = new List<OrderDetail>(); } public OrderHeader OrderHeader { get; set; } public List<OrderDetail> OrderDetails { get; set; } public override bool Equals(object obj) { var other = obj as Order; if (other == null) return false; var i = 0; return this.OrderHeader.Equals(other.OrderHeader) && this.OrderDetails.All(x => x.Equals(other.OrderDetails[i++])); } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class OrderHeader : IHasIntId { public OrderHeader() { } public OrderHeader( int orderId, string customerId, int employeeId, DateTime? orderDate, DateTime? requiredDate, DateTime? shippedDate, int shipVia, decimal freight, string shipName, string address, string city, string region, string postalCode, string country) { Id = orderId; CustomerId = customerId; EmployeeId = employeeId; OrderDate = orderDate; RequiredDate = requiredDate; ShippedDate = shippedDate; ShipVia = shipVia; Freight = freight; ShipName = shipName; ShipAddress = address; ShipCity = city; ShipRegion = region; ShipPostalCode = postalCode; ShipCountry = country; } public int Id { get; set; } public string CustomerId { get; set; } public int EmployeeId { get; set; } public DateTime? OrderDate { get; set; } public DateTime? RequiredDate { get; set; } public DateTime? ShippedDate { get; set; } public int? ShipVia { get; set; } public decimal Freight { get; set; } public string ShipName { get; set; } public string ShipAddress { get; set; } public string ShipCity { get; set; } public string ShipRegion { get; set; } public string ShipPostalCode { get; set; } public string ShipCountry { get; set; } public override bool Equals(object obj) { var other = obj as OrderHeader; if (other == null) return false; return this.Id == other.Id && this.CustomerId == other.CustomerId && this.EmployeeId == other.EmployeeId && this.OrderDate == other.OrderDate && this.RequiredDate == other.RequiredDate && this.ShippedDate == other.ShippedDate && this.ShipVia == other.ShipVia && this.Freight == other.Freight && this.ShipName == other.ShipName && this.ShipAddress == other.ShipAddress && this.ShipCity == other.ShipCity && this.ShipRegion == other.ShipRegion && this.ShipPostalCode == other.ShipPostalCode && this.ShipCountry == other.ShipCountry; } public override int GetHashCode() { return base.GetHashCode(); } } [DataContract(Namespace = ExampleConfig.DefaultNamespace)] public class OrderDetail : IHasStringId { public OrderDetail() { } public OrderDetail( int orderId, int productId, decimal unitPrice, short quantity, double discount) { OrderId = orderId; ProductId = productId; UnitPrice = unitPrice; Quantity = quantity; Discount = discount; } public string Id { get { return this.OrderId + "/" + this.ProductId; } } public int OrderId { get; set; } public int ProductId { get; set; } public decimal UnitPrice { get; set; } public short Quantity { get; set; } public double Discount { get; set; } public override bool Equals(object obj) { var other = obj as OrderDetail; if (other == null) return false; return this.Id == other.Id && this.OrderId == other.OrderId && this.ProductId == other.ProductId && this.UnitPrice == other.UnitPrice && this.Quantity == other.Quantity && this.Discount == other.Discount; } public override int GetHashCode() { return base.GetHashCode(); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using XMLSIGNLib; namespace CSharpWinApp { /// <summary> /// Summary description for Form1. /// </summary> /// public class VerifyPFX : System.Windows.Forms.Form { private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.OpenFileDialog openFileDialog2; private System.ComponentModel.IContainer components; public XMLSIGNLib.Signature SigObj; private System.Windows.Forms.Button selectFileButton; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button selectPFX; private System.Windows.Forms.TextBox tbPFXName; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button delCRL; private System.Windows.Forms.Button btVerify; private System.Windows.Forms.Button btSave; private System.Windows.Forms.PictureBox pbResult; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.RichTextBox tbResult; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.Button btReset; private System.Windows.Forms.CheckBox cbExplicit; private System.Windows.Forms.CheckBox cbP1; private System.Windows.Forms.CheckBox cbP2; private System.Windows.Forms.CheckBox cbP3; private System.Windows.Forms.CheckBox cbP4; private System.Windows.Forms.CheckBox cbP5; private System.Windows.Forms.CheckBox cbPA; private System.Windows.Forms.GroupBox groupBox3; string [] pOID_Jitc; string [] pOID_Pkits; string [] pOID; private System.Data.OleDb.OleDbCommand oleDbSelectCommand1; private System.Data.OleDb.OleDbCommand oleDbInsertCommand1; private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1; private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1; private System.Data.OleDb.OleDbConnection oleDbConnection1; private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.ListBox listBox2; private System.Windows.Forms.Button RemoveTrustedRootButton; private System.Windows.Forms.Button selectTrustedRootButton; private System.Windows.Forms.Button addCrlUrl; private System.Windows.Forms.TextBox pfxPasswordBox; private System.Windows.Forms.Label pfxPasswordLabel; private System.Windows.Forms.Button selectCertFromStore; string usedPolicies; string certId, certSubject, certIssuer, certExpiry, certShortSubject; private System.Windows.Forms.Button viewCertificate; private System.Windows.Forms.RadioButton Jitc; private System.Windows.Forms.RadioButton Pkits; private System.Windows.Forms.TextBox certDetails; public VerifyPFX() { // // Required for Windows Form Designer support // InitializeComponent(); pOID_Jitc = new string[6]; pOID_Jitc[0] = "2.16.840.1.101.3.1.48.1"; pOID_Jitc[1] = "2.16.840.1.101.3.1.48.2"; pOID_Jitc[2] = "2.16.840.1.101.3.1.48.3"; pOID_Jitc[3] = "2.16.840.1.101.3.1.48.4"; pOID_Jitc[4] = "2.16.840.1.101.3.1.48.5"; pOID_Jitc[5] = "2.5.29.32.0"; pOID_Pkits = new string[6]; pOID_Pkits[0] = "2.16.840.1.101.3.2.1.48.1"; pOID_Pkits[1] = "2.16.840.1.101.3.2.1.48.2"; pOID_Pkits[2] = "2.16.840.1.101.3.2.1.48.3"; pOID_Pkits[3] = "2.16.840.1.101.3.2.1.48.4"; pOID_Pkits[4] = "2.16.840.1.101.3.2.1.48.5"; pOID_Pkits[5] = "2.5.29.32.0"; // // TODO: Add any constructor code after InitializeComponent call // SigObj = new XMLSIGNLib.SignatureClass(); SigObj.DoDCompliance = 1; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(VerifyPFX)); this.selectFileButton = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.selectPFX = new System.Windows.Forms.Button(); this.tbPFXName = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tbResult = new System.Windows.Forms.RichTextBox(); this.pbResult = new System.Windows.Forms.PictureBox(); this.btSave = new System.Windows.Forms.Button(); this.delCRL = new System.Windows.Forms.Button(); this.btVerify = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.Pkits = new System.Windows.Forms.RadioButton(); this.Jitc = new System.Windows.Forms.RadioButton(); this.cbPA = new System.Windows.Forms.CheckBox(); this.cbP5 = new System.Windows.Forms.CheckBox(); this.cbP4 = new System.Windows.Forms.CheckBox(); this.cbP3 = new System.Windows.Forms.CheckBox(); this.cbP2 = new System.Windows.Forms.CheckBox(); this.cbP1 = new System.Windows.Forms.CheckBox(); this.cbExplicit = new System.Windows.Forms.CheckBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.addCrlUrl = new System.Windows.Forms.Button(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.btReset = new System.Windows.Forms.Button(); this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection(); this.oleDbInsertCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbUpdateCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbDeleteCommand1 = new System.Data.OleDb.OleDbCommand(); this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.RemoveTrustedRootButton = new System.Windows.Forms.Button(); this.listBox2 = new System.Windows.Forms.ListBox(); this.selectTrustedRootButton = new System.Windows.Forms.Button(); this.pfxPasswordBox = new System.Windows.Forms.TextBox(); this.pfxPasswordLabel = new System.Windows.Forms.Label(); this.selectCertFromStore = new System.Windows.Forms.Button(); this.certDetails = new System.Windows.Forms.TextBox(); this.viewCertificate = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // selectFileButton // this.selectFileButton.BackColor = System.Drawing.SystemColors.Info; this.selectFileButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.selectFileButton.Location = new System.Drawing.Point(24, 376); this.selectFileButton.Name = "selectFileButton"; this.selectFileButton.Size = new System.Drawing.Size(96, 24); this.selectFileButton.TabIndex = 4; this.selectFileButton.Text = "Add CRL file"; this.selectFileButton.Click += new System.EventHandler(this.selectFileButton_Click); // // listBox1 // this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.listBox1.HorizontalScrollbar = true; this.listBox1.Location = new System.Drawing.Point(8, 48); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(336, 121); this.listBox1.TabIndex = 7; // // selectPFX // this.selectPFX.BackColor = System.Drawing.SystemColors.Info; this.selectPFX.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204))); this.selectPFX.Location = new System.Drawing.Point(24, 8); this.selectPFX.Name = "selectPFX"; this.selectPFX.Size = new System.Drawing.Size(176, 24); this.selectPFX.TabIndex = 8; this.selectPFX.Text = "Select Certificate File"; this.selectPFX.Click += new System.EventHandler(this.selectPFX_Click); // // tbPFXName // this.tbPFXName.Location = new System.Drawing.Point(216, 8); this.tbPFXName.Name = "tbPFXName"; this.tbPFXName.Size = new System.Drawing.Size(536, 20); this.tbPFXName.TabIndex = 9; this.tbPFXName.Text = ""; // // groupBox1 // this.groupBox1.Controls.Add(this.tbResult); this.groupBox1.Controls.Add(this.pbResult); this.groupBox1.Controls.Add(this.btSave); this.groupBox1.Location = new System.Drawing.Point(424, 144); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(304, 496); this.groupBox1.TabIndex = 10; this.groupBox1.TabStop = false; this.groupBox1.Text = "Verification Results"; // // tbResult // this.tbResult.Location = new System.Drawing.Point(16, 104); this.tbResult.Name = "tbResult"; this.tbResult.Size = new System.Drawing.Size(272, 352); this.tbResult.TabIndex = 18; this.tbResult.Text = ""; // // pbResult // this.pbResult.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.pbResult.Location = new System.Drawing.Point(56, 24); this.pbResult.Name = "pbResult"; this.pbResult.Size = new System.Drawing.Size(152, 72); this.pbResult.TabIndex = 17; this.pbResult.TabStop = false; // // btSave // this.btSave.BackColor = System.Drawing.SystemColors.Info; this.btSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.btSave.Location = new System.Drawing.Point(16, 464); this.btSave.Name = "btSave"; this.btSave.Size = new System.Drawing.Size(96, 24); this.btSave.TabIndex = 16; this.btSave.Text = "Save as file"; this.btSave.Click += new System.EventHandler(this.btSave_Click); // // delCRL // this.delCRL.BackColor = System.Drawing.SystemColors.Info; this.delCRL.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.delCRL.Location = new System.Drawing.Point(248, 16); this.delCRL.Name = "delCRL"; this.delCRL.Size = new System.Drawing.Size(96, 24); this.delCRL.TabIndex = 14; this.delCRL.Text = "Del CRL Entry"; this.delCRL.Click += new System.EventHandler(this.delCRL_Click); // // btVerify // this.btVerify.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btVerify.BackColor = System.Drawing.SystemColors.Info; this.btVerify.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.btVerify.Location = new System.Drawing.Point(632, 656); this.btVerify.Name = "btVerify"; this.btVerify.Size = new System.Drawing.Size(96, 24); this.btVerify.TabIndex = 15; this.btVerify.Text = "Verify!"; this.btVerify.Click += new System.EventHandler(this.verifyButton_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.Pkits); this.groupBox2.Controls.Add(this.Jitc); this.groupBox2.Controls.Add(this.cbPA); this.groupBox2.Controls.Add(this.cbP5); this.groupBox2.Controls.Add(this.cbP4); this.groupBox2.Controls.Add(this.cbP3); this.groupBox2.Controls.Add(this.cbP2); this.groupBox2.Controls.Add(this.cbP1); this.groupBox2.Controls.Add(this.cbExplicit); this.groupBox2.Location = new System.Drawing.Point(16, 144); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(360, 200); this.groupBox2.TabIndex = 17; this.groupBox2.TabStop = false; this.groupBox2.Text = "User Policies"; // // Pkits // this.Pkits.Location = new System.Drawing.Point(272, 32); this.Pkits.Name = "Pkits"; this.Pkits.Size = new System.Drawing.Size(56, 24); this.Pkits.TabIndex = 8; this.Pkits.Text = "PKITS"; this.Pkits.CheckedChanged += new System.EventHandler(this.Pkits_CheckedChanged); // // Jitc // this.Jitc.Checked = true; this.Jitc.Location = new System.Drawing.Point(272, 8); this.Jitc.Name = "Jitc"; this.Jitc.Size = new System.Drawing.Size(56, 24); this.Jitc.TabIndex = 7; this.Jitc.TabStop = true; this.Jitc.Text = "JITC"; this.Jitc.CheckedChanged += new System.EventHandler(this.Jitc_CheckedChanged); // // cbPA // this.cbPA.Location = new System.Drawing.Point(8, 144); this.cbPA.Name = "cbPA"; this.cbPA.Size = new System.Drawing.Size(248, 24); this.cbPA.TabIndex = 6; this.cbPA.Text = "any-policy (2.5.29.32.0)"; // // cbP5 // this.cbP5.Location = new System.Drawing.Point(8, 120); this.cbP5.Name = "cbP5"; this.cbP5.Size = new System.Drawing.Size(248, 24); this.cbP5.TabIndex = 5; this.cbP5.Text = "test-policy-5 (2.16.840.1.101.3.1.48.5)"; // // cbP4 // this.cbP4.Location = new System.Drawing.Point(8, 96); this.cbP4.Name = "cbP4"; this.cbP4.Size = new System.Drawing.Size(248, 24); this.cbP4.TabIndex = 4; this.cbP4.Text = "test-policy-4 (2.16.840.1.101.3.1.48.4)"; // // cbP3 // this.cbP3.Location = new System.Drawing.Point(8, 72); this.cbP3.Name = "cbP3"; this.cbP3.Size = new System.Drawing.Size(248, 24); this.cbP3.TabIndex = 3; this.cbP3.Text = "test-policy-3 (2.16.840.1.101.3.1.48.3)"; // // cbP2 // this.cbP2.Location = new System.Drawing.Point(8, 48); this.cbP2.Name = "cbP2"; this.cbP2.Size = new System.Drawing.Size(248, 24); this.cbP2.TabIndex = 2; this.cbP2.Text = "test-policy-2 (2.16.840.1.101.3.1.48.2)"; // // cbP1 // this.cbP1.Location = new System.Drawing.Point(8, 24); this.cbP1.Name = "cbP1"; this.cbP1.Size = new System.Drawing.Size(248, 24); this.cbP1.TabIndex = 1; this.cbP1.Text = "test-policy-1 (2.16.840.1.101.3.1.48.1)"; // // cbExplicit // this.cbExplicit.Location = new System.Drawing.Point(8, 168); this.cbExplicit.Name = "cbExplicit"; this.cbExplicit.TabIndex = 0; this.cbExplicit.Text = "Policy Explicit"; // // groupBox3 // this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.groupBox3.Controls.Add(this.addCrlUrl); this.groupBox3.Controls.Add(this.delCRL); this.groupBox3.Controls.Add(this.listBox1); this.groupBox3.Location = new System.Drawing.Point(16, 360); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(360, 176); this.groupBox3.TabIndex = 18; this.groupBox3.TabStop = false; this.groupBox3.Text = "CRL files"; // // addCrlUrl // this.addCrlUrl.BackColor = System.Drawing.SystemColors.Info; this.addCrlUrl.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.addCrlUrl.Location = new System.Drawing.Point(120, 16); this.addCrlUrl.Name = "addCrlUrl"; this.addCrlUrl.Size = new System.Drawing.Size(96, 24); this.addCrlUrl.TabIndex = 21; this.addCrlUrl.Text = "Add CRL URL"; this.addCrlUrl.Click += new System.EventHandler(this.addCrlUrl_Click); // // imageList1 // this.imageList1.ImageSize = new System.Drawing.Size(147, 71); this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // btReset // this.btReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btReset.BackColor = System.Drawing.SystemColors.Info; this.btReset.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.btReset.Location = new System.Drawing.Point(424, 656); this.btReset.Name = "btReset"; this.btReset.Size = new System.Drawing.Size(96, 24); this.btReset.TabIndex = 19; this.btReset.Text = "Reset"; this.btReset.Click += new System.EventHandler(this.btReset_Click); // // oleDbSelectCommand1 // this.oleDbSelectCommand1.CommandText = "SELECT ErrorDetail, ErrorNumber, ErrorShortName FROM ErrorTable"; this.oleDbSelectCommand1.Connection = this.oleDbConnection1; // // oleDbConnection1 // this.oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=C:\Temp\CSharpWinApp\bin\Release\ErrorCodes.mdb;Mode=Share Deny None;Extended Properties="""";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"; // // oleDbInsertCommand1 // this.oleDbInsertCommand1.CommandText = "INSERT INTO ErrorTable(ErrorDetail, ErrorNumber, ErrorShortName) VALUES (?, ?, ?)" + ""; this.oleDbInsertCommand1.Connection = this.oleDbConnection1; this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorDetail", System.Data.OleDb.OleDbType.VarWChar, 255, "ErrorDetail")); this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorNumber", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "ErrorNumber", System.Data.DataRowVersion.Current, null)); this.oleDbInsertCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorShortName", System.Data.OleDb.OleDbType.VarWChar, 50, "ErrorShortName")); // // oleDbUpdateCommand1 // this.oleDbUpdateCommand1.CommandText = "UPDATE ErrorTable SET ErrorDetail = ?, ErrorNumber = ?, ErrorShortName = ? WHERE " + "(ErrorNumber = ?) AND (ErrorDetail = ? OR ? IS NULL AND ErrorDetail IS NULL) AND" + " (ErrorShortName = ? OR ? IS NULL AND ErrorShortName IS NULL)"; this.oleDbUpdateCommand1.Connection = this.oleDbConnection1; this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorDetail", System.Data.OleDb.OleDbType.VarWChar, 255, "ErrorDetail")); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorNumber", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "ErrorNumber", System.Data.DataRowVersion.Current, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("ErrorShortName", System.Data.OleDb.OleDbType.VarWChar, 50, "ErrorShortName")); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorNumber", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "ErrorNumber", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorDetail", System.Data.OleDb.OleDbType.VarWChar, 255, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorDetail", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorDetail1", System.Data.OleDb.OleDbType.VarWChar, 255, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorDetail", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorShortName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorShortName", System.Data.DataRowVersion.Original, null)); this.oleDbUpdateCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorShortName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorShortName", System.Data.DataRowVersion.Original, null)); // // oleDbDeleteCommand1 // this.oleDbDeleteCommand1.CommandText = "DELETE FROM ErrorTable WHERE (ErrorNumber = ?) AND (ErrorDetail = ? OR ? IS NULL " + "AND ErrorDetail IS NULL) AND (ErrorShortName = ? OR ? IS NULL AND ErrorShortName" + " IS NULL)"; this.oleDbDeleteCommand1.Connection = this.oleDbConnection1; this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorNumber", System.Data.OleDb.OleDbType.Integer, 0, System.Data.ParameterDirection.Input, false, ((System.Byte)(10)), ((System.Byte)(0)), "ErrorNumber", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorDetail", System.Data.OleDb.OleDbType.VarWChar, 255, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorDetail", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorDetail1", System.Data.OleDb.OleDbType.VarWChar, 255, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorDetail", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorShortName", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorShortName", System.Data.DataRowVersion.Original, null)); this.oleDbDeleteCommand1.Parameters.Add(new System.Data.OleDb.OleDbParameter("Original_ErrorShortName1", System.Data.OleDb.OleDbType.VarWChar, 50, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "ErrorShortName", System.Data.DataRowVersion.Original, null)); // // oleDbDataAdapter1 // this.oleDbDataAdapter1.DeleteCommand = this.oleDbDeleteCommand1; this.oleDbDataAdapter1.InsertCommand = this.oleDbInsertCommand1; this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1; this.oleDbDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] { new System.Data.Common.DataTableMapping("Table", "ErrorTable", new System.Data.Common.DataColumnMapping[] { new System.Data.Common.DataColumnMapping("ErrorNumber", "ErrorNumber"), new System.Data.Common.DataColumnMapping("ErrorDetail", "ErrorDetail"), new System.Data.Common.DataColumnMapping("ErrorShortName", "ErrorShortName")})}); this.oleDbDataAdapter1.UpdateCommand = this.oleDbUpdateCommand1; // // groupBox4 // this.groupBox4.Controls.Add(this.RemoveTrustedRootButton); this.groupBox4.Controls.Add(this.listBox2); this.groupBox4.Controls.Add(this.selectTrustedRootButton); this.groupBox4.Location = new System.Drawing.Point(16, 544); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(360, 136); this.groupBox4.TabIndex = 20; this.groupBox4.TabStop = false; this.groupBox4.Text = "Trusted Root"; // // RemoveTrustedRootButton // this.RemoveTrustedRootButton.BackColor = System.Drawing.SystemColors.Info; this.RemoveTrustedRootButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.RemoveTrustedRootButton.Location = new System.Drawing.Point(208, 24); this.RemoveTrustedRootButton.Name = "RemoveTrustedRootButton"; this.RemoveTrustedRootButton.Size = new System.Drawing.Size(136, 24); this.RemoveTrustedRootButton.TabIndex = 17; this.RemoveTrustedRootButton.Text = "Remove Trusted Root"; this.RemoveTrustedRootButton.Click += new System.EventHandler(this.RemoveTrustedRootButton_Click); // // listBox2 // this.listBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.listBox2.HorizontalScrollbar = true; this.listBox2.Location = new System.Drawing.Point(8, 56); this.listBox2.Name = "listBox2"; this.listBox2.Size = new System.Drawing.Size(336, 69); this.listBox2.TabIndex = 16; // // selectTrustedRootButton // this.selectTrustedRootButton.BackColor = System.Drawing.SystemColors.Info; this.selectTrustedRootButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.selectTrustedRootButton.Location = new System.Drawing.Point(8, 24); this.selectTrustedRootButton.Name = "selectTrustedRootButton"; this.selectTrustedRootButton.Size = new System.Drawing.Size(120, 24); this.selectTrustedRootButton.TabIndex = 15; this.selectTrustedRootButton.Text = "Add Trusted Root"; this.selectTrustedRootButton.Click += new System.EventHandler(this.selectTrustedRootButton_Click); // // pfxPasswordBox // this.pfxPasswordBox.Location = new System.Drawing.Point(216, 40); this.pfxPasswordBox.Name = "pfxPasswordBox"; this.pfxPasswordBox.Size = new System.Drawing.Size(536, 20); this.pfxPasswordBox.TabIndex = 22; this.pfxPasswordBox.Text = "password"; // // pfxPasswordLabel // this.pfxPasswordLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.pfxPasswordLabel.Location = new System.Drawing.Point(24, 40); this.pfxPasswordLabel.Name = "pfxPasswordLabel"; this.pfxPasswordLabel.Size = new System.Drawing.Size(184, 23); this.pfxPasswordLabel.TabIndex = 23; this.pfxPasswordLabel.Text = "Enter PFX/P12 File Password"; // // selectCertFromStore // this.selectCertFromStore.BackColor = System.Drawing.SystemColors.Info; this.selectCertFromStore.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204))); this.selectCertFromStore.Location = new System.Drawing.Point(24, 80); this.selectCertFromStore.Name = "selectCertFromStore"; this.selectCertFromStore.Size = new System.Drawing.Size(176, 24); this.selectCertFromStore.TabIndex = 24; this.selectCertFromStore.Text = "Select Certificate From Store"; this.selectCertFromStore.Click += new System.EventHandler(this.selectCertFromStore_Click); // // certDetails // this.certDetails.Location = new System.Drawing.Point(216, 72); this.certDetails.Multiline = true; this.certDetails.Name = "certDetails"; this.certDetails.Size = new System.Drawing.Size(536, 48); this.certDetails.TabIndex = 25; this.certDetails.Text = "No Certificate Selected"; // // viewCertificate // this.viewCertificate.BackColor = System.Drawing.SystemColors.Info; this.viewCertificate.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204))); this.viewCertificate.Location = new System.Drawing.Point(24, 112); this.viewCertificate.Name = "viewCertificate"; this.viewCertificate.Size = new System.Drawing.Size(176, 24); this.viewCertificate.TabIndex = 26; this.viewCertificate.Text = "View Certificate"; this.viewCertificate.Click += new System.EventHandler(this.viewCertificate_Click); // // VerifyPFX // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(760, 694); this.Controls.Add(this.viewCertificate); this.Controls.Add(this.certDetails); this.Controls.Add(this.pfxPasswordBox); this.Controls.Add(this.tbPFXName); this.Controls.Add(this.selectCertFromStore); this.Controls.Add(this.pfxPasswordLabel); this.Controls.Add(this.groupBox4); this.Controls.Add(this.btReset); this.Controls.Add(this.btVerify); this.Controls.Add(this.groupBox1); this.Controls.Add(this.selectPFX); this.Controls.Add(this.selectFileButton); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox3); this.MinimumSize = new System.Drawing.Size(640, 512); this.Name = "VerifyPFX"; this.Text = "Infomosaic SecureXML JITC/PKITS Test Suite"; this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.groupBox4.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new VerifyPFX()); } private void selectFileButton_Click(object sender, System.EventArgs e) { openFileDialog1 = new OpenFileDialog(); openFileDialog1.Multiselect = true; openFileDialog1.Filter = "CRL files (*.crl)|*.crl|All files (*.*)|*.*" ; openFileDialog1.FilterIndex = 1 ; openFileDialog1.RestoreDirectory = true ; if(openFileDialog1.ShowDialog() == DialogResult.OK) { string [] fileNameListStr = openFileDialog1.FileNames; string [] f1 = new String[fileNameListStr.Length + 1]; for (int i=0; i < fileNameListStr.Length; i++) { f1[i] = fileNameListStr[i]; listBox1.Items.Add(fileNameListStr[i]); } } openFileDialog1.Dispose(); } private void verifyButton_Click(object sender, System.EventArgs e) { if ((tbPFXName.Text=="") && (certId == null)) { System.Windows.Forms.MessageBox.Show("Select PFX file or a certificate from store first"); return; } // Prepare Trusted root list int trustedRootCount = listBox2.Items.Count; if (trustedRootCount != 0) { object [] crtList = new object[trustedRootCount]; SigObj.CertificateTrustExplicit = 1; for (int count=0; count < trustedRootCount; count++) crtList[count] = listBox2.Items[count].ToString(); SigObj.TrustedRoots = crtList; } else SigObj.CertificateTrustExplicit = 0; // prepare CRL List int cnt = listBox1.Items.Count; object [] crl1 = new object[1]; object [] crl2 = new object[2]; object [] crl3 = new object[3]; object [] crl4 = new object[4]; object [] crl5 = new object[5]; switch (cnt) { case 0: break; case 1: crl1[0] = listBox1.Items[0].ToString(); SigObj.CRLLocation = crl1; break; case 2: crl2[0] = listBox1.Items[0].ToString(); crl2[1] = listBox1.Items[1].ToString(); SigObj.CRLLocation = crl2; break; case 3: crl3[0] = listBox1.Items[0].ToString(); crl3[1] = listBox1.Items[1].ToString(); crl3[2] = listBox1.Items[2].ToString(); SigObj.CRLLocation = crl3; break; case 4: crl4[0] = listBox1.Items[0].ToString(); crl4[1] = listBox1.Items[1].ToString(); crl4[2] = listBox1.Items[2].ToString(); crl4[3] = listBox1.Items[3].ToString(); SigObj.CRLLocation = crl4; break; case 5: crl5[0] = listBox1.Items[0].ToString(); crl5[1] = listBox1.Items[1].ToString(); crl5[2] = listBox1.Items[2].ToString(); crl5[3] = listBox1.Items[3].ToString(); crl5[4] = listBox1.Items[4].ToString(); SigObj.CRLLocation = crl5; break; default: MessageBox.Show("Unsupported number of CRLs, max 5 is allowed"); break; } // certificate policy object [] pl1 = new Object[1]; object [] pl2 = new Object[2]; object [] pl3 = new Object[3]; object [] pl4 = new Object[4]; object [] pl5 = new Object[5]; object [] pl6 = new Object[6]; string [] policies = new string[6]; if (Jitc.Checked) pOID = pOID_Jitc; else pOID = pOID_Pkits; int iCur=0; if (cbP1.Checked) { policies[iCur] = pOID[0]; iCur++; } if (cbP2.Checked) { policies[iCur] = pOID[1]; iCur++; } if (cbP3.Checked) { policies[iCur] = pOID[2]; iCur++; } if (cbP4.Checked) { policies[iCur] = pOID[3]; iCur++; } if (cbP5.Checked) { policies[iCur] = pOID[4]; iCur++; } if (cbPA.Checked) { policies[iCur] = pOID[5]; iCur++; } usedPolicies = ""; switch(iCur) { case 0: break; case 1: pl1[0] = policies[0]; usedPolicies += policies[0] + "\n"; SigObj.CertificatePolicy = pl1; break; case 2: pl2[0] = policies[0]; pl2[1] = policies[1]; usedPolicies += policies[0] + "\n"; usedPolicies += policies[1] + "\n"; SigObj.CertificatePolicy = pl2; break; case 3: pl3[0] = policies[0]; pl3[1] = policies[1]; pl3[2] = policies[2]; usedPolicies += policies[0] + "\n"; usedPolicies += policies[1] + "\n"; usedPolicies += policies[2] + "\n"; SigObj.CertificatePolicy = pl3; break; case 4: pl4[0] = policies[0]; pl4[1] = policies[1]; pl4[2] = policies[2]; pl4[3] = policies[3]; usedPolicies += policies[0] + "\n"; usedPolicies += policies[1] + "\n"; usedPolicies += policies[2] + "\n"; usedPolicies += policies[3] + "\n"; SigObj.CertificatePolicy = pl4; break; case 5: pl5[0] = policies[0]; pl5[1] = policies[1]; pl5[2] = policies[2]; pl5[3] = policies[3]; pl5[4] = policies[4]; usedPolicies += policies[0] + "\n"; usedPolicies += policies[1] + "\n"; usedPolicies += policies[2] + "\n"; usedPolicies += policies[3] + "\n"; usedPolicies += policies[4] + "\n"; SigObj.CertificatePolicy = pl5; break; case 6: pl6[0] = policies[0]; pl6[1] = policies[1]; pl6[2] = policies[2]; pl6[3] = policies[3]; pl6[4] = policies[4]; pl6[5] = policies[5]; usedPolicies += policies[0] + "\n"; usedPolicies += policies[1] + "\n"; usedPolicies += policies[2] + "\n"; usedPolicies += policies[3] + "\n"; usedPolicies += policies[4] + "\n"; usedPolicies += policies[5] + "\n"; SigObj.CertificatePolicy = pl6; break; default: MessageBox.Show("Maximum 6 user policies are allowed"); break; } usedPolicies += (cbExplicit.Checked)?"Policy Explicit\n":""; SigObj.CertificatePolicyExplicit = (cbExplicit.Checked)?1:0; int res = 0; int err = 0; if (certId == null) { string password = (pfxPasswordBox.Text.Length == 0)? "password":pfxPasswordBox.Text; string extension = Path.GetExtension(tbPFXName.Text); if ((extension == ".P12") || (extension == ".PFX") || (extension == ".p12") || (extension == ".pfx")) { res = SigObj.VerifyPFXCertCRL(tbPFXName.Text,password,"",1); } else { res = SigObj.VerifyX509CertCRL(SigObj.ReadAllBase64(tbPFXName.Text), "", 1); } err = SigObj.GetLastError(); if (res!=1) { tbResult.Text = "Certificate File = " + tbPFXName.Text + "\n\nCertificate path failed to validate\nLast Error: " + err + ": " + SigObj.GetErrorDetail(err) + "\n\n" + "Error Stack: \n" + SigObj.GetError() + "\n\n" + logInputValues(); pbResult.Image = imageList1.Images[1]; } else { tbResult.Text = "Certificate File = " + tbPFXName.Text + "\n\nCertificate path validated\n\n" + logInputValues(); pbResult.Image = imageList1.Images[0]; } } else { string x509Cert = SigObj.GetX509Certificate(certId); res = SigObj.VerifyX509CertCRL(x509Cert, "", 1); err = SigObj.GetLastError(); if (res!=1) { tbResult.Text = "Certificate Subject = " + certSubject + "Certificate Issuer = " + certIssuer + "\n\nCertificate path failed to validate\nLast Error: " + err + ": " + SigObj.GetErrorDetail(err) + "\n\n" + "Error Stack: \n" + SigObj.GetError() + "\n\n" + logInputValues(); pbResult.Image = imageList1.Images[1]; } else { tbResult.Text = "Certificate Subject = " + certSubject + "Certificate Issuer = " + certIssuer + "\n\nCertificate path validated\n\n" + logInputValues(); pbResult.Image = imageList1.Images[0]; } } } private void delCRL_Click(object sender, System.EventArgs e) { if (listBox1.SelectedIndex>=0) { listBox1.Items.RemoveAt(listBox1.SelectedIndex); } } private void selectPFX_Click(object sender, System.EventArgs e) { certId = null; certDetails.Text = "Using Certificate File"; System.Windows.Forms.OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = false; ofd.Filter = "Certificate files (*.p12, *.pfx, *.cer, *.crt)|*.p12; *.pfx; *.cer; *.crt|All files (*.*)|*.*" ; ofd.FilterIndex = 1 ; ofd.RestoreDirectory = true ; if(ofd.ShowDialog() == DialogResult.OK) { tbPFXName.Text = ofd.FileName; } } private void btSave_Click(object sender, System.EventArgs e) { try { System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog(); sfd.RestoreDirectory = true; if (sfd.ShowDialog() == DialogResult.OK) { System.IO.StreamWriter sw = System.IO.File.CreateText(sfd.FileName); sw.Write(tbResult.Text); sw.Close(); } } catch(Exception) { MessageBox.Show("Cannot save file"); } } private void btReset_Click(object sender, System.EventArgs e) { tbPFXName.Text = ""; certId = null; certDetails.Clear(); listBox1.Items.Clear(); cbP1.Checked = false; cbP2.Checked = false; cbP3.Checked = false; cbP4.Checked = false; cbP5.Checked = false; cbPA.Checked = false; pbResult.Image = null; tbResult.Text = ""; cbExplicit.Checked = false; listBox2.Items.Clear(); SigObj = new XMLSIGNLib.SignatureClass(); SigObj.DoDCompliance = 1; } private string logInputValues() { string res = ""; res += "Used CRL files:\n"; foreach (object iCrl in listBox1.Items) { res += iCrl.ToString() + "\n"; } res += "\nUsed User Policies:\n"; if (usedPolicies.Length == 0) res += pOID[5]; else res += usedPolicies; res += "\nAuthority Constrained Policy Set:"; string [] authPolSet = (string [])SigObj.AuthorityConstrainedPolicy; if (authPolSet != null) { for (int i=0; i < authPolSet.Length; i++) res += "\n" + authPolSet[i]; } else res += "Empty"; res += "\nUser Constrained Policy Set:"; string [] userPolSet = (string [])SigObj.UserConstrainedPolicy; if (userPolSet != null) { for (int i=0; i < userPolSet.Length; i++) res += "\n" + userPolSet[i]; } else res += "Empty"; if (SigObj.CertificatePolicyExplicit == 1) res += "\nExplicit Policy State Variable= TRUE"; else res += "\nExplicit Policy State Variable= FALSE"; return res; } private void selectTrustedRootButton_Click(object sender, System.EventArgs e) { openFileDialog2 = new OpenFileDialog(); openFileDialog2.Multiselect = true; openFileDialog2.Filter = "CRT/CER files (*.crt, *.cer)|*.crt; *.cer|All files (*.*)|*.*" ; openFileDialog2.FilterIndex = 1 ; openFileDialog2.RestoreDirectory = true ; if(openFileDialog2.ShowDialog() == DialogResult.OK) { string [] fileNameListStr = openFileDialog2.FileNames; string [] f1 = new String[fileNameListStr.Length + 1]; for (int i=0; i < fileNameListStr.Length; i++) { f1[i] = fileNameListStr[i]; listBox2.Items.Add(fileNameListStr[i]); } } openFileDialog2.Dispose(); } private void RemoveTrustedRootButton_Click(object sender, System.EventArgs e) { if (listBox2.SelectedIndex>=0) { listBox2.Items.RemoveAt(listBox2.SelectedIndex); } } private void addCrlUrl_Click(object sender, System.EventArgs e) { System.Windows.Forms.Form f1 = new Form(); string [] initialUrlList = new string [listBox1.Items.Count]; UrlList urlList = new UrlList(); for (int i=0; i<listBox1.Items.Count; i++) { initialUrlList[i] = listBox1.Items[i].ToString(); } urlList.crlUrlTextBox.Lines = initialUrlList; f1.Height = 550; f1.Width = 530; f1.Controls.Add(urlList); if (f1.ShowDialog() == DialogResult.OK) { // Create a string array and store the contents of the Lines property. string[] tempArray = new string [urlList.crlUrlTextBox.Lines.Length]; tempArray = urlList.crlUrlTextBox.Lines; listBox1.Items.Clear(); // Loop through the array and send the contents of the array to main window. for(int counter=0; counter < tempArray.Length;counter++) { listBox1.Items.Add(tempArray[counter]); } } urlList.Dispose(); } private void selectCertFromStore_Click(object sender, System.EventArgs e) { certId = SigObj.SelectActiveCertificate(); if (certId != null) { tbPFXName.Text = "Using Certificate From Store"; certIssuer = SigObj.GetCertificateInfo(-3, 2); certSubject = SigObj.GetCertificateInfo(-3, 3); certExpiry = SigObj.GetCertificateInfo(-3, 4); certShortSubject = SigObj.GetCertificateInfo(-3, 5); certDetails.Text = "Certificate Subject = " + certSubject + "\n" + "Certificate Issuer = " + certIssuer + "\n" + "Certificate Expiration Date = " + certExpiry; } } private void viewCertificate_Click(object sender, System.EventArgs e) { if (certId == null) { if (tbPFXName.Text.Length != 0) { string password = (pfxPasswordBox.Text.Length == 0)? "password":pfxPasswordBox.Text; string extension = Path.GetExtension(tbPFXName.Text); string x509Cert; if ((extension == ".P12") || (extension == ".PFX") || (extension == ".p12") || (extension == ".pfx")) { x509Cert = SigObj.SetActivePFXFileCert(tbPFXName.Text,password); } else { x509Cert = SigObj.ReadAllBase64(tbPFXName.Text); } SigObj.ViewAnyCertificate(x509Cert); } } else SigObj.ViewCertificate(certId); } private void Jitc_CheckedChanged(object sender, System.EventArgs e) { if (Jitc.Checked) { // // cbPA // this.cbPA.Text = "any-policy (2.5.29.32.0)"; // // cbP5 // this.cbP5.Text = "test-policy-5 (2.16.840.1.101.3.1.48.5)"; // // cbP4 // this.cbP4.Text = "test-policy-4 (2.16.840.1.101.3.1.48.4)"; // // cbP3 // this.cbP3.Text = "test-policy-3 (2.16.840.1.101.3.1.48.3)"; // // cbP2 // this.cbP2.Text = "test-policy-2 (2.16.840.1.101.3.1.48.2)"; // // cbP1 // this.cbP1.Text = "test-policy-1 (2.16.840.1.101.3.1.48.1)"; // // cbExplicit // this.cbExplicit.Text = "Policy Explicit"; } } private void Pkits_CheckedChanged(object sender, System.EventArgs e) { if (Pkits.Checked) { // // cbPA // this.cbPA.Text = "any-policy (2.5.29.32.0)"; // // cbP5 // this.cbP5.Text = "test-policy-5 (2.16.840.1.101.3.2.1.48.5)"; // // cbP4 // this.cbP4.Text = "test-policy-4 (2.16.840.1.101.3.2.1.48.4)"; // // cbP3 // this.cbP3.Text = "test-policy-3 (2.16.840.1.101.3.2.1.48.3)"; // // cbP2 // this.cbP2.Text = "test-policy-2 (2.16.840.1.101.3.2.1.48.2)"; // // cbP1 // this.cbP1.Text = "test-policy-1 (2.16.840.1.101.3.2.1.48.1)"; // // cbExplicit // this.cbExplicit.Text = "Policy Explicit"; } } } }
/* * ResourceSet.cs - Implementation of the * "System.Resources.ResourceSet" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Resources { #if CONFIG_RUNTIME_INFRA using System; using System.IO; using System.Collections; using System.Globalization; using System.Runtime.InteropServices; #if ECMA_COMPAT internal #else public #endif class ResourceSet : IDisposable, IEnumerable { // Internal state. protected IResourceReader Reader; protected Hashtable Table; private Hashtable ignoreCaseTable; // Constructors. protected ResourceSet() { Reader = null; Table = new Hashtable(); ignoreCaseTable = null; } public ResourceSet(IResourceReader reader) { if(reader == null) { throw new ArgumentNullException("reader"); } Reader = reader; Table = new Hashtable(); ignoreCaseTable = null; ReadResources(); } public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); Table = new Hashtable(); ignoreCaseTable = null; ReadResources(); } public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); Table = new Hashtable(); ignoreCaseTable = null; ReadResources(); } // Close this resource set. public virtual void Close() { Dispose(true); } // Dispose this resource set. protected virtual void Dispose(bool disposing) { if(Reader != null) { Reader.Close(); Reader = null; } Table = null; ignoreCaseTable = null; } // Implement IDisposable. public void Dispose() { Dispose(true); } // Implement IEnumerable. IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // Get the dictionary enumerator for this instance. #if !ECMA_COMPAT [ComVisible(false)] #endif public virtual IDictionaryEnumerator GetEnumerator() { return Table.GetEnumerator(); } // Get the default reader type for this resource set. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Get the default write type for this resource set. public virtual Type GetDefaultWriter() { return typeof(ResourceWriter); } // Create the "ignore case" table from the primary hash table. private void CreateIgnoreCaseTable() { TextInfo info = CultureInfo.InvariantCulture.TextInfo; ignoreCaseTable = new Hashtable(); IDictionaryEnumerator e = Table.GetEnumerator(); while(e.MoveNext()) { ignoreCaseTable[info.ToLower((String)(e.Key))] = e.Value; } } // Get an object from this resource set. public virtual Object GetObject(String name) { if(name == null) { throw new ArgumentNullException("name"); } else if(Reader == null) { throw new InvalidOperationException (_("Invalid_ResourceReaderClosed")); } else { return Table[name]; } } public virtual Object GetObject(String name, bool ignoreCase) { // Validate the parameters. if(name == null) { throw new ArgumentNullException("name"); } else if(Reader == null) { throw new InvalidOperationException (_("Invalid_ResourceReaderClosed")); } // Try looking for the resource by exact name. Object value = Table[name]; if(value != null || !ignoreCase) { return value; } // Create the "ignore case" table if necessary. if(ignoreCaseTable == null) { CreateIgnoreCaseTable(); } // Look for the resource in the "ignore case" table. TextInfo info = CultureInfo.InvariantCulture.TextInfo; return ignoreCaseTable[info.ToLower(name)]; } // Get a string from this resource set. public virtual String GetString(String name) { if(name == null) { throw new ArgumentNullException("name"); } else if(Reader == null) { throw new InvalidOperationException (_("Invalid_ResourceReaderClosed")); } try { return (String)(Table[name]); } catch(InvalidCastException) { throw new InvalidOperationException (_("Invalid_ResourceNotString")); } } public virtual String GetString(String name, bool ignoreCase) { // Validate the parameters. if(name == null) { throw new ArgumentNullException("name"); } else if(Reader == null) { throw new InvalidOperationException (_("Invalid_ResourceReaderClosed")); } // Try looking for the resource by exact name. Object value = Table[name]; if(value != null || !ignoreCase) { try { return (String)value; } catch(InvalidCastException) { throw new InvalidOperationException (_("Invalid_ResourceNotString")); } } // Create the "ignore case" table if necessary. if(ignoreCaseTable == null) { CreateIgnoreCaseTable(); } // Look for the resource in the "ignore case" table. try { TextInfo info = CultureInfo.InvariantCulture.TextInfo; return (String)(ignoreCaseTable[info.ToLower(name)]); } catch(InvalidCastException) { throw new InvalidOperationException (_("Invalid_ResourceNotString")); } } // Read all resources into the hash table. protected virtual void ReadResources() { IDictionaryEnumerator e = Reader.GetEnumerator(); while(e.MoveNext()) { Table.Add(e.Key, e.Value); } } }; // class ResourceSet #endif // CONFIG_RUNTIME_INFRA }; // namespace System.Resources
// // SmfLite.cs - A minimal toolkit for handling standard MIDI files (SMF) on Unity // // Copyright (C) 2013 Keijiro Takahashi // // 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.Collections.Generic; namespace SmfLite { // An alias for internal use. using DeltaEventPairList = System.Collections.Generic.List<SmfLite.MidiTrack.DeltaEventPair>; // // MIDI event // public struct MidiEvent { #region Public members public byte status; public byte data1; public byte data2; public MidiEvent (byte status, byte data1, byte data2) { this.status = status; this.data1 = data1; this.data2 = data2; } public override string ToString () { return "[" + status.ToString ("X") + "," + data1 + "," + data2 + "]"; } #endregion } // // MIDI track // // Stores only one track (usually a MIDI file contains one or more tracks). // public class MidiTrack { #region Internal data structure // Data pair storing a delta-time value and an event. public struct DeltaEventPair { public int delta; public MidiEvent midiEvent; public DeltaEventPair (int delta, MidiEvent midiEvent) { this.delta = delta; this.midiEvent = midiEvent; } public override string ToString () { return "(" + delta + ":" + midiEvent + ")"; } } #endregion #region Public members public MidiTrack () { sequence = new List<DeltaEventPair> (); } // Returns an enumerator which enumerates the all delta-event pairs. public List<DeltaEventPair>.Enumerator GetEnumerator () { return sequence.GetEnumerator (); } public DeltaEventPair GetAtIndex (int index) { return sequence [index]; } public override string ToString () { var s = ""; foreach (var pair in sequence) s += pair; return s; } #endregion #region Private and internal members List<DeltaEventPair> sequence; public void AddEvent (int delta, MidiEvent midiEvent) { sequence.Add (new DeltaEventPair (delta, midiEvent)); } #endregion } // // MIDI file container // public struct MidiFileContainer { #region Public members // Division number == PPQN for this song. public int division; // Track list contained in this file. public List<MidiTrack> tracks; public MidiFileContainer (int division, List<MidiTrack> tracks) { this.division = division; this.tracks = tracks; } public override string ToString () { var temp = division.ToString () + ","; foreach (var track in tracks) { temp += track; } return temp; } #endregion } // // Sequencer for MIDI tracks // // Works like an enumerator for MIDI events. // Note that not only Advance() but also Start() can return MIDI events. // public class MidiTrackSequencer { #region Public members public bool loop = false; public bool Playing { get { return playing; } } // Constructor // "ppqn" stands for Pulse Per Quater Note, // which is usually provided with a MIDI header. public MidiTrackSequencer (MidiTrack track, int ppqn, float bpm) { pulsePerSecond = bpm / 60.0f * ppqn; enumerator = track.GetEnumerator (); } // Start the sequence. // Returns a list of events at the beginning of the track. public List<MidiEvent> Start (float startTime = 0.0f) { if (enumerator.MoveNext ()) { pulseToNext = enumerator.Current.delta; playing = true; return Advance (startTime); } else { playing = false; return null; } } // Advance the song position. // Returns a list of events between the current position and the next one. public List<MidiEvent> Advance (float deltaTime) { if (!playing) { return null; } pulseCounter += pulsePerSecond * deltaTime; if (pulseCounter < pulseToNext) { return null; } var messages = new List<MidiEvent> (); while (pulseCounter >= pulseToNext) { var pair = enumerator.Current; messages.Add (pair.midiEvent); if (!enumerator.MoveNext ()) { playing = false; break; } pulseCounter -= pulseToNext; pulseToNext = enumerator.Current.delta; } return messages; } #endregion #region Private members DeltaEventPairList.Enumerator enumerator; bool playing; float pulsePerSecond; float pulseToNext; float pulseCounter; #endregion } // // MIDI file loader // // Loads an SMF and returns a file container object. // public static class MidiFileLoader { #region Public members public static MidiFileContainer Load (byte[] data) { var tracks = new List<MidiTrack> (); var reader = new MidiDataStreamReader (data); // Chunk type. if (new string (reader.ReadChars (4)) != "MThd") { throw new System.FormatException ("Can't find header chunk."); } // Chunk length. if (reader.ReadBEInt32 () != 6) { throw new System.FormatException ("Length of header chunk must be 6."); } // Format (unused). reader.Advance (2); // Number of tracks. var trackCount = reader.ReadBEInt16 (); // Delta-time divisions. var division = reader.ReadBEInt16 (); if ((division & 0x8000) != 0) { throw new System.FormatException ("SMPTE time code is not supported."); } // Read the tracks. for (var trackIndex = 0; trackIndex < trackCount; trackIndex++) { tracks.Add (ReadTrack (reader)); } return new MidiFileContainer (division, tracks); } #endregion #region Private members static MidiTrack ReadTrack (MidiDataStreamReader reader) { var track = new MidiTrack (); // Chunk type. if (new string (reader.ReadChars (4)) != "MTrk") { throw new System.FormatException ("Can't find track chunk."); } // Chunk length. var chunkEnd = reader.ReadBEInt32 (); chunkEnd += reader.Offset; // Read delta-time and event pairs. byte ev = 0; while (reader.Offset < chunkEnd) { // Delta time. var delta = reader.ReadMultiByteValue (); // Event type. if ((reader.PeekByte () & 0x80) != 0) { ev = reader.ReadByte (); } if (ev == 0xff) { // 0xff: Meta event (unused). reader.Advance (1); reader.Advance (reader.ReadMultiByteValue ()); } else if (ev == 0xf0) { // 0xf0: SysEx (unused). while (reader.ReadByte() != 0xf7) { } } else { // MIDI event byte data1 = reader.ReadByte (); byte data2 = ((ev & 0xe0) == 0xc0) ? (byte)0 : reader.ReadByte (); track.AddEvent (delta, new MidiEvent (ev, data1, data2)); } } return track; } #endregion } // // Binary data stream reader (for internal use) // class MidiDataStreamReader { byte[] data; int offset; public int Offset { get { return offset; } } public MidiDataStreamReader (byte[] data) { this.data = data; } public void Advance (int length) { offset += length; } public byte PeekByte () { return data [offset]; } public byte ReadByte () { return data [offset++]; } public char[] ReadChars (int length) { var temp = new char[length]; for (var i = 0; i < length; i++) { temp [i] = (char)ReadByte (); } return temp; } public int ReadBEInt32 () { int b1 = ReadByte (); int b2 = ReadByte (); int b3 = ReadByte (); int b4 = ReadByte (); return b4 + (b3 << 8) + (b2 << 16) + (b1 << 24); } public int ReadBEInt16 () { int b1 = ReadByte (); int b2 = ReadByte (); return b2 + (b1 << 8); } public int ReadMultiByteValue () { int value = 0; while (true) { int b = ReadByte (); value += b & 0x7f; if (b < 0x80) break; value <<= 7; } return value; } } }
//--------------------------------------------------------------------------- // // <copyright file="GroupItem.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: GroupItem object - root of the UI subtree generated for a CollectionViewGroup // // Specs: http://avalon/connecteddata/M5%20General%20Docs/Data%20Styling.mht // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Specialized; using System.Windows.Media; using System.Windows.Controls.Primitives; using System.Windows.Threading; using System.Collections.Generic; using MS.Internal.Utility; using MS.Internal.Hashing.PresentationFramework; using System.Diagnostics; using MS.Internal; using System.Windows.Automation; namespace System.Windows.Controls { /// <summary> /// A GroupItem appears as the root of the visual subtree generated for a CollectionViewGroup. /// </summary> public class GroupItem : ContentControl, IHierarchicalVirtualizationAndScrollInfo, IContainItemStorage { static GroupItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(GroupItem), new FrameworkPropertyMetadata(typeof(GroupItem))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(GroupItem)); // GroupItems should not be focusable by default FocusableProperty.OverrideMetadata(typeof(GroupItem), new FrameworkPropertyMetadata(false)); AutomationProperties.IsOffscreenBehaviorProperty.OverrideMetadata(typeof(GroupItem), new FrameworkPropertyMetadata(IsOffscreenBehavior.FromClip)); } /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return new System.Windows.Automation.Peers.GroupItemAutomationPeer(this); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _header = this.GetTemplateChild("PART_Header") as FrameworkElement; // GroupItem is generally re-templated to have an Expander. // Look for an Expander and store its Header size.g _expander = Helper.FindTemplatedDescendant<Expander>(this, this); // // ItemValueStorage: restore saved values for this item onto the new container // if (_expander != null) { ItemsControl itemsControl = ParentItemsControl; if (itemsControl != null && VirtualizingPanel.GetIsVirtualizingWhenGrouping(itemsControl)) { Helper.SetItemValuesOnContainer(itemsControl, _expander, itemsControl.ItemContainerGenerator.ItemFromContainer(this)); } _expander.Expanded += new RoutedEventHandler(OnExpanded); } } private static void OnExpanded(object sender, RoutedEventArgs e) { GroupItem groupItem = sender as GroupItem; if (groupItem != null && groupItem._expander != null && groupItem._expander.IsExpanded) { ItemsControl itemsControl = groupItem.ParentItemsControl; if (itemsControl != null && VirtualizingPanel.GetIsVirtualizing(itemsControl) && VirtualizingPanel.GetVirtualizationMode(itemsControl) == VirtualizationMode.Recycling) { ItemsPresenter itemsHostPresenter = groupItem.ItemsHostPresenter; if (itemsHostPresenter != null) { // In case a GroupItem that wasn't previously expanded is now // recycled to represent an entity that is expanded, we face a situation // where the ItemsHost isn't connected yet but we do need to synchronously // remeasure the sub tree through the ItemsPresenter leading up to the // ItemsHost panel. If we didnt do this the offsets could get skewed. groupItem.InvalidateMeasure(); Helper.InvalidateMeasureOnPath(itemsHostPresenter, groupItem, false /*duringMeasure*/); } } } } internal override void OnTemplateChangedInternal(FrameworkTemplate oldTemplate,FrameworkTemplate newTemplate) { base.OnTemplateChangedInternal(oldTemplate, newTemplate); if (_expander != null) { _expander.Expanded -= new RoutedEventHandler(OnExpanded); _expander = null; } _itemsHost = null; } protected override Size ArrangeOverride(Size arrangeSize) { arrangeSize = base.ArrangeOverride(arrangeSize); Helper.ComputeCorrectionFactor(ParentItemsControl, this, ItemsHost, HeaderElement); return arrangeSize; } /// <summary> /// Gives a string representation of this object. /// </summary> /// <returns></returns> internal override string GetPlainText() { System.Windows.Data.CollectionViewGroup cvg = Content as System.Windows.Data.CollectionViewGroup; if (cvg != null && cvg.Name != null) { return cvg.Name.ToString(); } return base.GetPlainText(); } //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ internal ItemContainerGenerator Generator { get { return _generator; } set { _generator = value; } } //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ internal void PrepareItemContainer(object item, ItemsControl parentItemsControl) { if (Generator == null) return; // user-declared GroupItem - ignore (bug 108423) // If a GroupItem is being recycled set back IsItemsHost if (_itemsHost != null) { _itemsHost.IsItemsHost = true; } bool isVirtualizingWhenGrouping = (parentItemsControl != null && VirtualizingPanel.GetIsVirtualizingWhenGrouping(parentItemsControl)); // Release any previous containers. Also ensures Items and GroupStyle are hooked up correctly if (Generator != null) { if (!isVirtualizingWhenGrouping) { Generator.Release(); } else { Generator.RemoveAllInternal(true /*saveRecycleQueue*/); } } ItemContainerGenerator generator = Generator.Parent; GroupStyle groupStyle = generator.GroupStyle; // apply the container style Style style = groupStyle.ContainerStyle; // no ContainerStyle set, try ContainerStyleSelector if (style == null) { if (groupStyle.ContainerStyleSelector != null) { style = groupStyle.ContainerStyleSelector.SelectStyle(item, this); } } // apply the style, if found if (style != null) { // verify style is appropriate before applying it if (!style.TargetType.IsInstanceOfType(this)) throw new InvalidOperationException(SR.Get(SRID.StyleForWrongType, style.TargetType.Name, this.GetType().Name)); this.Style = style; this.WriteInternalFlag2(InternalFlags2.IsStyleSetFromGenerator, true); } // forward the header template information if (ContentIsItem || !HasNonDefaultValue(ContentProperty)) { this.Content = item; ContentIsItem = true; } if (!HasNonDefaultValue(ContentTemplateProperty)) this.ContentTemplate = groupStyle.HeaderTemplate; if (!HasNonDefaultValue(ContentTemplateSelectorProperty)) this.ContentTemplateSelector = groupStyle.HeaderTemplateSelector; if (!HasNonDefaultValue(ContentStringFormatProperty)) this.ContentStringFormat = groupStyle.HeaderStringFormat; // // Clear previously cached items sizes // Helper.ClearVirtualizingElement(this); // // ItemValueStorage: restore saved values for this item onto the new container // if (isVirtualizingWhenGrouping) { Helper.SetItemValuesOnContainer(parentItemsControl, this, item); if (_expander != null) { Helper.SetItemValuesOnContainer(parentItemsControl, _expander, item); } } } internal void ClearItemContainer(object item, ItemsControl parentItemsControl) { if (Generator == null) return; // user-declared GroupItem - ignore (bug 108423) // // ItemValueStorage: save off values for this container if we're a virtualizing Group. // if (parentItemsControl != null && VirtualizingPanel.GetIsVirtualizingWhenGrouping(parentItemsControl)) { Helper.StoreItemValues((IContainItemStorage)parentItemsControl, this, item); if (_expander != null) { Helper.StoreItemValues((IContainItemStorage)parentItemsControl, _expander, item); } // Tell the panel to clear off all its containers. This will cause this method to be called // recursively down the tree, allowing all descendent data to be stored before we save off // the ItemValueStorage DP for this container. VirtualizingPanel vp = _itemsHost as VirtualizingPanel; if (vp != null) { vp.OnClearChildrenInternal(); } Generator.RemoveAllInternal(true /*saveRecycleQueue*/); } else { Generator.Release(); } ClearContentControl(item); } #region IHierarchicalVirtualizationAndScrollInfo HierarchicalVirtualizationConstraints IHierarchicalVirtualizationAndScrollInfo.Constraints { get { return HierarchicalVirtualizationConstraintsField.GetValue(this); } set { if (value.CacheLengthUnit == VirtualizationCacheLengthUnit.Page) { throw new InvalidOperationException(SR.Get(SRID.PageCacheSizeNotAllowed)); } HierarchicalVirtualizationConstraintsField.SetValue(this, value); } } HierarchicalVirtualizationHeaderDesiredSizes IHierarchicalVirtualizationAndScrollInfo.HeaderDesiredSizes { get { FrameworkElement headerElement = HeaderElement; Size pixelHeaderSize = new Size(); if (this.IsVisible && headerElement != null) { pixelHeaderSize = headerElement.DesiredSize; Helper.ApplyCorrectionFactorToPixelHeaderSize(ParentItemsControl, this, _itemsHost, ref pixelHeaderSize); } Size logicalHeaderSize = new Size(DoubleUtil.GreaterThan(pixelHeaderSize.Width, 0) ? 1 : 0, DoubleUtil.GreaterThan(pixelHeaderSize.Height, 0) ? 1 : 0); return new HierarchicalVirtualizationHeaderDesiredSizes(logicalHeaderSize, pixelHeaderSize); } } HierarchicalVirtualizationItemDesiredSizes IHierarchicalVirtualizationAndScrollInfo.ItemDesiredSizes { get { return Helper.ApplyCorrectionFactorToItemDesiredSizes(this, _itemsHost); } set { HierarchicalVirtualizationItemDesiredSizesField.SetValue(this, value); } } Panel IHierarchicalVirtualizationAndScrollInfo.ItemsHost { get { return _itemsHost; } } bool IHierarchicalVirtualizationAndScrollInfo.MustDisableVirtualization { get { return MustDisableVirtualizationField.GetValue(this); } set { MustDisableVirtualizationField.SetValue(this, value); } } bool IHierarchicalVirtualizationAndScrollInfo.InBackgroundLayout { get { return InBackgroundLayoutField.GetValue(this); } set { InBackgroundLayoutField.SetValue(this, value); } } #endregion #region ItemValueStorage object IContainItemStorage.ReadItemValue(object item, DependencyProperty dp) { return Helper.ReadItemValue(this, item, dp.GlobalIndex); } void IContainItemStorage.StoreItemValue(object item, DependencyProperty dp, object value) { Helper.StoreItemValue(this, item, dp.GlobalIndex, value); } void IContainItemStorage.ClearItemValue(object item, DependencyProperty dp) { Helper.ClearItemValue(this, item, dp.GlobalIndex); } void IContainItemStorage.ClearValue(DependencyProperty dp) { Helper.ClearItemValueStorage(this, new int[] {dp.GlobalIndex}); } void IContainItemStorage.Clear() { Helper.ClearItemValueStorage(this); } #endregion private ItemsControl ParentItemsControl { get { DependencyObject parent = this; do { parent = VisualTreeHelper.GetParent(parent); ItemsControl parentItemsControl = parent as ItemsControl; if (parentItemsControl != null) { return parentItemsControl; } } while (parent != null); return null; } } internal IContainItemStorage ParentItemStorageProvider { get { DependencyObject parentPanel = VisualTreeHelper.GetParent(this); if (parentPanel != null) { DependencyObject owner = ItemsControl.GetItemsOwnerInternal(parentPanel); return owner as IContainItemStorage; } return null; } } internal Panel ItemsHost { get { return _itemsHost; } set { _itemsHost = value; } } private ItemsPresenter ItemsHostPresenter { get { if (_expander != null) { return Helper.FindTemplatedDescendant<ItemsPresenter>(_expander, _expander); } else { return Helper.FindTemplatedDescendant<ItemsPresenter>(this, this); } } } internal Expander Expander { get { return _expander; } } private FrameworkElement ExpanderHeader { get { if (_expander != null) { return _expander.GetTemplateChild(ExpanderHeaderPartName) as FrameworkElement; } return null; } } private FrameworkElement HeaderElement { get { FrameworkElement headerElement = null; if (_header != null) { headerElement = _header; } else if (_expander != null) { // Look for Expander. We special case for Expander since its a very common usage of grouping. headerElement = ExpanderHeader; } return headerElement; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ ItemContainerGenerator _generator; private Panel _itemsHost; FrameworkElement _header; Expander _expander; internal static readonly UncommonField<bool> MustDisableVirtualizationField = new UncommonField<bool>(); internal static readonly UncommonField<bool> InBackgroundLayoutField = new UncommonField<bool>(); internal static readonly UncommonField<Thickness> DesiredPixelItemsSizeCorrectionFactorField = new UncommonField<Thickness>(); internal static readonly UncommonField<HierarchicalVirtualizationConstraints> HierarchicalVirtualizationConstraintsField = new UncommonField<HierarchicalVirtualizationConstraints>(); internal static readonly UncommonField<HierarchicalVirtualizationHeaderDesiredSizes> HierarchicalVirtualizationHeaderDesiredSizesField = new UncommonField<HierarchicalVirtualizationHeaderDesiredSizes>(); internal static readonly UncommonField<HierarchicalVirtualizationItemDesiredSizes> HierarchicalVirtualizationItemDesiredSizesField = new UncommonField<HierarchicalVirtualizationItemDesiredSizes>(); #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; private const string ExpanderHeaderPartName = "HeaderSite"; #endregion DTypeThemeStyleKey } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.WebSites.Models; namespace Microsoft.WindowsAzure.Management.WebSites.Models { /// <summary> /// The response body contains the status of the specified long-running /// operation, indicating whether it has succeeded, is inprogress, has /// timed out, or has failed. Note that this status is distinct from the /// HTTP status code returned for the Get Operation Status operation /// itself. If the long-running operation failed, the response body /// includes error information regarding the failure. /// </summary> public partial class WebSiteOperationStatusResponse : OperationResponse { private DateTime _createdTime; /// <summary> /// Optional. The time when the operation was created. /// </summary> public DateTime CreatedTime { get { return this._createdTime; } set { this._createdTime = value; } } private IList<WebSiteOperationStatusResponse.Error> _errors; /// <summary> /// Optional. The list of errors that occurred during the operation. /// </summary> public IList<WebSiteOperationStatusResponse.Error> Errors { get { return this._errors; } set { this._errors = value; } } private DateTime _expirationTime; /// <summary> /// Optional. The time when the operation will time out. /// </summary> public DateTime ExpirationTime { get { return this._expirationTime; } set { this._expirationTime = value; } } private string _geoMasterOperationId; /// <summary> /// Optional. The GeoMaster Operation ID for this operation, if any. /// </summary> public string GeoMasterOperationId { get { return this._geoMasterOperationId; } set { this._geoMasterOperationId = value; } } private DateTime _modifiedTime; /// <summary> /// Optional. The time when the operation was last modified. /// </summary> public DateTime ModifiedTime { get { return this._modifiedTime; } set { this._modifiedTime = value; } } private string _name; /// <summary> /// Optional. The name of the operation. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operationId; /// <summary> /// Optional. The Operation ID for this operation. Used to poll for /// operation status. /// </summary> public string OperationId { get { return this._operationId; } set { this._operationId = value; } } private WebSiteOperationStatus _status; /// <summary> /// Optional. The status of the asynchronous operation. /// </summary> public WebSiteOperationStatus Status { get { return this._status; } set { this._status = value; } } /// <summary> /// Initializes a new instance of the WebSiteOperationStatusResponse /// class. /// </summary> public WebSiteOperationStatusResponse() { this.Errors = new LazyList<WebSiteOperationStatusResponse.Error>(); } /// <summary> /// Information about an error that occurred during the operation. /// </summary> public partial class Error { private string _code; /// <summary> /// Optional. The error code. /// </summary> public string Code { get { return this._code; } set { this._code = value; } } private string _extendedCode; /// <summary> /// Optional. The extended error code. /// </summary> public string ExtendedCode { get { return this._extendedCode; } set { this._extendedCode = value; } } private string _innerErrors; /// <summary> /// Optional. The inner errors for this operation. /// </summary> public string InnerErrors { get { return this._innerErrors; } set { this._innerErrors = value; } } private string _message; /// <summary> /// Optional. The error message. /// </summary> public string Message { get { return this._message; } set { this._message = value; } } private string _messageTemplate; /// <summary> /// Optional. The message template. /// </summary> public string MessageTemplate { get { return this._messageTemplate; } set { this._messageTemplate = value; } } private IList<string> _parameters; /// <summary> /// Optional. The parameters for the message template. /// </summary> public IList<string> Parameters { get { return this._parameters; } set { this._parameters = value; } } /// <summary> /// Initializes a new instance of the Error class. /// </summary> public Error() { this.Parameters = new LazyList<string>(); } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.Async; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="IGrainMethodInvoker"/> for grains. /// </summary> public static class GrainMethodInvokerGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "MethodInvoker"; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType"> /// The grain interface type. /// </param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType) { var baseTypes = new List<BaseTypeSyntax> { SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax()) }; var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainType.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special method invoker marker attribute. var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainType); var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)); var grainTypeArgument = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)); var attributes = new List<AttributeSyntax> { CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument(grainTypeArgument), SF.AttributeArgument(interfaceIdArgument)), #if !NETSTANDARD SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()) #endif }; var members = new List<MemberDeclarationSyntax>(GenerateGenericInvokerFields(grainType)) { GenerateInvokeMethod(grainType), GenerateInterfaceIdProperty(grainType) }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (typeof(IGrainExtension).GetTypeInfo().IsAssignableFrom(grainTypeInfo)) { baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax())); members.Add(GenerateExtensionInvokeMethod(grainType)); } var classDeclaration = SF.ClassDeclaration( CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Returns method declaration syntax for the InterfaceId property. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>Method declaration syntax for the InterfaceId property.</returns> private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword)); } /// <summary> /// Generates syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainMethodInvoker x) => x.Invoke(default(IAddressable), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <returns> /// Syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method. /// </returns> private static MethodDeclarationSyntax GenerateExtensionInvokeMethod(Type grainType) { // Get the method with the correct type. var invokeMethod = TypeUtils.Method( (IGrainExtensionMethodInvoker x) => x.Invoke(default(IGrainExtension), default(InvokeMethodRequest))); return GenerateInvokeMethod(grainType, invokeMethod); } /// <summary> /// Generates syntax for an invoke method. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="invokeMethod"> /// The invoke method to generate. /// </param> /// <returns> /// Syntax for an invoke method. /// </returns> private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod) { var parameters = invokeMethod.GetParameters(); var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("interfaceId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.InterfaceId))))); var interfaceIdVariable = SF.IdentifierName("interfaceId"); var methodIdDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(int).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("methodId") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.MethodId))))); var methodIdVariable = SF.IdentifierName("methodId"); var argumentsDeclaration = SF.LocalDeclarationStatement( SF.VariableDeclaration(typeof(object[]).GetTypeSyntax()) .AddVariables( SF.VariableDeclarator("arguments") .WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.Arguments))))); var argumentsVariable = SF.IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdVariable, methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsVariable)); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdVariable); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); // If the provided grain is null, throw an argument exception. var argumentNullException = SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression())); var grainArgumentCheck = SF.IfStatement( SF.BinaryExpression( SyntaxKind.EqualsExpression, grainArgument, SF.LiteralExpression(SyntaxKind.NullLiteralExpression)), SF.ThrowStatement(argumentNullException)); return methodDeclaration.AddBodyStatements(grainArgumentCheck, interfaceIdSwitch); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> /// <param name="grainType"> /// The grain type. /// </param> /// <param name="grain"> /// The grain instance expression. /// </param> /// <param name="method"> /// The method. /// </param> /// <param name="arguments"> /// The arguments expression. /// </param> /// <returns> /// Syntax to invoke a method on a grain. /// </returns> private static StatementSyntax[] GenerateInvokeForMethod( Type grainType, IdentifierNameSyntax grain, MethodInfo method, ExpressionSyntax arguments) { var castGrain = SF.ParenthesizedExpression(SF.CastExpression(grainType.GetTypeSyntax(), grain)); // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.GetParameters().ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.ParameterType.GetTypeSyntax(); var indexArg = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(i))); var arg = SF.CastExpression( parameterType, SF.ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethodDefinition) { var invokerFieldName = GetGenericMethodInvokerFieldName(method); var invokerCall = SF.InvocationExpression( SF.IdentifierName(invokerFieldName) .Member((GenericMethodInvoker invoker) => invoker.Invoke(null, null))) .AddArgumentListArguments(SF.Argument(grain), SF.Argument(arguments)); return new StatementSyntax[] { SF.ReturnStatement(invokerCall) }; } // Invoke the method. var grainMethodCall = SF.InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(SF.Argument).ToArray()); // For void methods, invoke the method and return a completed task. if (method.ReturnType == typeof(void)) { var completed = (Expression<Func<Task<object>>>)(() => TaskUtility.Completed()); return new StatementSyntax[] { SF.ExpressionStatement(grainMethodCall), SF.ReturnStatement(completed.Invoke()) }; } // For methods which return the expected type, Task<object>, simply return that. if (method.ReturnType == typeof(Task<object>)) { return new StatementSyntax[] { SF.ReturnStatement(grainMethodCall) }; } // The invoke method expects a Task<object>, so we need to upcast the returned value. // For methods which do not return a value, the Box extension method returns a meaningless value. return new StatementSyntax[] { SF.ReturnStatement(SF.InvocationExpression(grainMethodCall.Member((Task _) => _.Box()))) }; } /// <summary> /// Generates <see cref="GenericMethodInvoker"/> fields for the generic methods in <paramref name="grainType"/>. /// </summary> /// <param name="grainType">The grain type.</param> /// <returns>The generated fields.</returns> private static MemberDeclarationSyntax[] GenerateGenericInvokerFields(Type grainType) { var methods = GrainInterfaceUtils.GetMethods(grainType); var result = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { if (!method.IsGenericMethodDefinition) continue; result.Add(GenerateGenericInvokerField(method)); } return result.ToArray(); } /// <summary> /// Generates a <see cref="GenericMethodInvoker"/> field for the provided generic method. /// </summary> /// <param name="method">The method.</param> /// <returns>The generated field.</returns> private static MemberDeclarationSyntax GenerateGenericInvokerField(MethodInfo method) { var fieldInfoVariable = SF.VariableDeclarator(GetGenericMethodInvokerFieldName(method)) .WithInitializer( SF.EqualsValueClause( SF.ObjectCreationExpression(typeof(GenericMethodInvoker).GetTypeSyntax()) .AddArgumentListArguments( SF.Argument(SF.TypeOfExpression(method.DeclaringType.GetTypeSyntax())), SF.Argument(method.Name.GetLiteralExpression()), SF.Argument( SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(method.GetGenericArguments().Length)))))); return SF.FieldDeclaration( SF.VariableDeclaration(typeof(GenericMethodInvoker).GetTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( SF.Token(SyntaxKind.PrivateKeyword), SF.Token(SyntaxKind.StaticKeyword), SF.Token(SyntaxKind.ReadOnlyKeyword)); } /// <summary> /// Returns the name of the <see cref="GenericMethodInvoker"/> field corresponding to <paramref name="method"/>. /// </summary> /// <param name="method">The method.</param> /// <returns>The name of the invoker field corresponding to the provided method.</returns> private static string GetGenericMethodInvokerFieldName(MethodInfo method) { return method.Name + string.Join("_", method.GetGenericArguments().Select(arg => arg.Name)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using Orleans.Internal; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using Xunit.Abstractions; namespace DefaultCluster.Tests { /// <summary> /// Summary description for ErrorHandlingGrainTest /// </summary> public class ErrorGrainTest : HostedTestClusterEnsureDefaultStarted { private static readonly TimeSpan timeout = TimeSpan.FromSeconds(10); private readonly ITestOutputHelper output; public ErrorGrainTest(ITestOutputHelper output, DefaultClusterFixture fixture) : base(fixture) { this.output = output; } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling")] public async Task ErrorGrain_GetGrain() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); int ignored = await grain.GetA(); } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling")] public async Task ErrorHandlingLocalError() { LocalErrorGrain localGrain = new LocalErrorGrain(); Task<int> intPromise = localGrain.GetAxBError(); try { await intPromise; Assert.True(false, "Should not have executed"); } catch (Exception exc2) { Assert.Equal(exc2.GetBaseException().Message, (new Exception("GetAxBError-Exception")).Message); } Assert.True(intPromise.Status == TaskStatus.Faulted); } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling")] // check that grain that throws an error breaks its promise and later Wait and GetValue on it will throw public void ErrorHandlingGrainError1() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); Task<int> intPromise = grain.GetAxBError(); try { intPromise.Wait(); Assert.True(false, "Should have thrown"); } catch (Exception) { Assert.True(intPromise.Status == TaskStatus.Faulted); } try { intPromise.Wait(); Assert.True(false, "Should have thrown"); } catch (Exception exc2) { Assert.True(intPromise.Status == TaskStatus.Faulted); Assert.Equal((new Exception("GetAxBError-Exception")).Message, exc2.GetBaseException().Message); } Assert.True(intPromise.Status == TaskStatus.Faulted); } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling")] // check that premature wait finishes on time with false. public void ErrorHandlingTimedMethod() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); Task promise = grain.LongMethod(2000); // there is a race in the test here. If run in debugger, the invocation can actually finish OK Stopwatch stopwatch = Stopwatch.StartNew(); Assert.False(promise.Wait(1000), "The task shouldn't have completed yet."); // these asserts depend on timing issues and will be wrong for the sync version of OrleansTask Assert.True(stopwatch.ElapsedMilliseconds >= 900, $"Waited less than 900ms: ({stopwatch.ElapsedMilliseconds}ms)"); // check that we waited at least 0.9 second Assert.True(stopwatch.ElapsedMilliseconds <= 1300, $"Waited longer than 1300ms: ({stopwatch.ElapsedMilliseconds}ms)"); promise.Wait(); // just wait for the server side grain invocation to finish Assert.True(promise.Status == TaskStatus.RanToCompletion); } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling")] // check that premature wait finishes on time but does not throw with false and later wait throws. public void ErrorHandlingTimedMethodWithError() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); Task promise = grain.LongMethodWithError(2000); // there is a race in the test here. If run in debugger, the invocation can actually finish OK Stopwatch stopwatch = Stopwatch.StartNew(); Assert.False(promise.Wait(1000), "The task shouldn't have completed yet."); stopwatch.Stop(); Assert.True(stopwatch.ElapsedMilliseconds >= 900, $"Waited less than 900ms: ({stopwatch.ElapsedMilliseconds}ms)"); // check that we waited at least 0.9 second Assert.True(stopwatch.ElapsedMilliseconds <= 1300, $"Waited longer than 1300ms: ({stopwatch.ElapsedMilliseconds}ms)"); Assert.ThrowsAsync<Exception>(() => promise).Wait(); Assert.True(promise.Status == TaskStatus.Faulted); } [Fact, TestCategory("Functional"), TestCategory("ErrorHandling"), TestCategory("Stress")] public async Task StressHandlingMultipleDelayedRequests() { IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId()); bool once = true; List<Task> tasks = new List<Task>(); for (int i = 0; i < 500; i++) { Task promise = grain.DelayMethod(1); tasks.Add(promise); if (once) { once = false; promise.Wait(); } } await Task.WhenAll(tasks).WithTimeout(TimeSpan.FromSeconds(20)); } [Fact, TestCategory("BVT"), TestCategory("ErrorHandling"), TestCategory("GrainReference")] public void ArgumentTypes_ListOfGrainReferences() { var grainFullName = typeof(ErrorGrain).FullName; List<IErrorGrain> list = new List<IErrorGrain>(); IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); list.Add(this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName)); list.Add(this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName)); bool ok = grain.AddChildren(list).Wait(timeout); if (!ok) throw new TimeoutException(); } [Fact, TestCategory("BVT"), TestCategory("AsynchronyPrimitives"), TestCategory("ErrorHandling")] public async Task AC_DelayedExecutor_2() { var grainFullName = typeof(ErrorGrain).FullName; IErrorGrain grain = this.GrainFactory.GetGrain<IErrorGrain>(GetRandomGrainId(), grainFullName); Task<bool> promise = grain.ExecuteDelayed(TimeSpan.FromMilliseconds(2000)); bool result = await promise; Assert.True(result); } [Fact, TestCategory("BVT"), TestCategory("SimpleGrain")] public void SimpleGrain_AsyncMethods() { ISimpleGrainWithAsyncMethods grain = this.GrainFactory.GetGrain<ISimpleGrainWithAsyncMethods>(GetRandomGrainId()); Task setPromise = grain.SetA_Async(10); setPromise.Wait(); setPromise = grain.SetB_Async(30); setPromise.Wait(); Task<int> intPromise = grain.GetAxB_Async(); Assert.Equal(300, intPromise.Result); } [Fact, TestCategory("BVT"), TestCategory("SimpleGrain")] public void SimpleGrain_PromiseForward() { ISimpleGrain forwardGrain = this.GrainFactory.GetGrain<IPromiseForwardGrain>(GetRandomGrainId()); Task<int> promise = forwardGrain.GetAxB(5, 6); int result = promise.Result; Assert.Equal(30, result); } [Fact, TestCategory("BVT"), TestCategory("SimpleGrain")] public void SimpleGrain_GuidDistribution() { int n = 0x1111; CreateGR(n, 1); CreateGR(n + 1, 1); CreateGR(n + 2, 1); CreateGR(n + 3, 1); CreateGR(n + 4, 1); Logger.Info("================"); CreateGR(n, 2); CreateGR(n + 1, 2); CreateGR(n + 2, 2); CreateGR(n + 3, 2); CreateGR(n + 4, 2); Logger.Info("DONE."); } private void CreateGR(int n, int type) { Guid guid; if (type == 1) { guid = Guid.Parse(string.Format("00000000-0000-0000-0000-{0:X12}", n)); } else { guid = Guid.Parse(string.Format("{0:X8}-0000-0000-0000-000000000000", n)); } IEchoGrain grain = this.GrainFactory.GetGrain<IEchoGrain>(guid); GrainId grainId = ((GrainReference)grain.AsReference<IEchoGrain>()).GrainId; output.WriteLine("Guid = {0}, Guid.HashCode = x{1:X8}, GrainId.HashCode = x{2:X8}, GrainId.UniformHashCode = x{3:X8}", guid, guid.GetHashCode(), grainId.GetHashCode(), grainId.GetUniformHashCode()); } [Fact, TestCategory("Revisit"), TestCategory("Observers")] public void ObserverTest_Disconnect() { ObserverTest_DisconnectRunner(false); } [Fact, TestCategory("Revisit"), TestCategory("Observers")] public void ObserverTest_Disconnect2() { ObserverTest_DisconnectRunner(true); } private void ObserverTest_DisconnectRunner(bool observeTwice) { // this is for manual repro & validation in the debugger // wait to send event because it takes 60s to drop client grain //var simple1 = SimpleGrainTests.GetSimpleGrain(); //var simple2 = SimpleGrainFactory.Cast(Domain.Current.Create(typeof(ISimpleGrain).FullName, // new Dictionary<string, object> { { "EventDelay", 70000 } })); //var result = new ResultHandle(); //var callback = new SimpleGrainObserver((a, b, r) => //{ // r.Done = (a == 10); // output.WriteLine("Received observer callback: A={0} B={1} Done={2}", a, b, r.Done); //}, result); //var observer = SimpleGrainObserverFactory.CreateObjectReference(callback); //if (observeTwice) //{ // simple1.Subscribe(observer).Wait(); // simple1.SetB(1).Wait(); // send a message to the observer to get it in the cache //} //simple2.Subscribe(observer).Wait(); //simple2.SetA(10).Wait(); //Thread.Sleep(2000); //Client.Uninitialize(); //var timeout80sec = TimeSpan.FromSeconds(80); //Assert.False(result.WaitForFinished(timeout80sec), "WaitforFinished Timeout=" + timeout80sec); //// prevent silo from shutting down right away //Thread.Sleep(Debugger.IsAttached ? TimeSpan.FromMinutes(2) : TimeSpan.FromSeconds(5)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Physics; using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Assertions; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// This script allows for an object to be movable, scalable, and rotatable with one or two hands. /// You may also configure the script on only enable certain manipulations. The script works with /// both HoloLens' gesture input and immersive headset's motion controller input. /// </summary> public class ManipulationHandler : MonoBehaviour, IMixedRealityPointerHandler, IMixedRealityFocusHandler { #region Public Enums public enum HandMovementType { OneHandedOnly = 0, TwoHandedOnly, OneAndTwoHanded } public enum TwoHandedManipulation { Scale, Rotate, MoveScale, MoveRotate, RotateScale, MoveRotateScale }; public enum RotateInOneHandType { MaintainRotationToUser, GravityAlignedMaintainRotationToUser, FaceUser, FaceAwayFromUser, MaintainOriginalRotation, RotateAboutObjectCenter, RotateAboutGrabPoint }; [System.Flags] public enum ReleaseBehaviorType { KeepVelocity = 1 << 0, KeepAngularVelocity = 1 << 1 } #endregion Public Enums #region Serialized Fields [SerializeField] [Tooltip("Transform that will be dragged. Defaults to the object of the component.")] private Transform hostTransform = null; public Transform HostTransform => hostTransform; [Header("Manipulation")] [SerializeField] [Tooltip("Can manipulation be done only with one hand, only with two hands, or with both?")] private HandMovementType manipulationType = HandMovementType.OneAndTwoHanded; public HandMovementType ManipulationType => manipulationType; [SerializeField] [Tooltip("What manipulation will two hands perform?")] private TwoHandedManipulation twoHandedManipulationType = TwoHandedManipulation.MoveRotateScale; public TwoHandedManipulation TwoHandedManipulationType => twoHandedManipulationType; [SerializeField] [Tooltip("Specifies whether manipulation can be done using far interaction with pointers.")] private bool allowFarManipulation = true; public bool AllowFarManipulation => allowFarManipulation; [SerializeField] [Tooltip("Rotation behavior of object when using one hand near")] private RotateInOneHandType oneHandRotationModeNear = RotateInOneHandType.RotateAboutGrabPoint; [SerializeField] [Tooltip("Rotation behavior of object when using one hand at distance")] private RotateInOneHandType oneHandRotationModeFar = RotateInOneHandType.RotateAboutGrabPoint; [SerializeField] [EnumFlags] [Tooltip("Rigid body behavior of the dragged object when releasing it.")] private ReleaseBehaviorType releaseBehavior = ReleaseBehaviorType.KeepVelocity | ReleaseBehaviorType.KeepAngularVelocity; public ReleaseBehaviorType ReleaseBehavior => releaseBehavior; [Header("Constraints")] [SerializeField] [Tooltip("Constrain rotation along an axis")] private RotationConstraintType constraintOnRotation = RotationConstraintType.None; public RotationConstraintType ConstraintOnRotation => constraintOnRotation; [SerializeField] [Tooltip("Constrain movement")] private MovementConstraintType constraintOnMovement = MovementConstraintType.None; public MovementConstraintType ConstraintOnMovement => constraintOnMovement; [Header("Smoothing")] [SerializeField] [Tooltip("Check to enable frame-rate independent smoothing. ")] private bool smoothingActive = true; public bool SmoothingActive => smoothingActive; [SerializeField] [Range(0, 1)] [Tooltip("Enter amount representing amount of smoothing to apply to the movement, scale, rotation. Smoothing of 0 means no smoothing. Max value means no change to value.")] private float smoothingAmountOneHandManip = 0.001f; public float SmoothingAmoutOneHandManip => smoothingAmountOneHandManip; #endregion Serialized Fields #region Event handlers [Header("Manipulation Events")] public ManipulationEvent OnManipulationStarted; public ManipulationEvent OnManipulationEnded; public ManipulationEvent OnHoverEntered; public ManipulationEvent OnHoverExited; #endregion #region Private Properties [System.Flags] private enum State { Start = 0x000, Moving = 0x001, Scaling = 0x010, Rotating = 0x100, MovingRotating = Moving | Rotating, MovingScaling = Moving | Scaling, RotatingScaling = Rotating | Scaling, MovingRotatingScaling = Moving | Rotating | Scaling }; private State currentState = State.Start; private TwoHandMoveLogic m_moveLogic; private TwoHandScaleLogic m_scaleLogic; private TwoHandRotateLogic m_rotateLogic; private Dictionary<uint, IMixedRealityPointer> pointerIdToPointerMap = new Dictionary<uint, IMixedRealityPointer>(); private Quaternion objectToHandRotation; private Vector3 objectToHandTranslation; private bool isNearManipulation; // This can probably be consolidated so that we use same for one hand and two hands private Quaternion targetRotationTwoHands; private Rigidbody rigidBody; private bool wasKinematic = false; private Quaternion startObjectRotationCameraSpace; private Quaternion startObjectRotationFlatCameraSpace; #endregion #region MonoBehaviour Functions private void Awake() { m_moveLogic = new TwoHandMoveLogic(constraintOnMovement); m_rotateLogic = new TwoHandRotateLogic(); m_scaleLogic = new TwoHandScaleLogic(); } private void Start() { if (hostTransform == null) { hostTransform = transform; } } private void Update() { if (currentState != State.Start) { UpdateStateMachine(); } } #endregion MonoBehaviour Functions #region Private Methods private Vector3 GetPointersCentroid() { Vector3 sum = Vector3.zero; int count = 0; foreach (var p in pointerIdToPointerMap.Values) { sum += p.Position; count++; } return sum / Math.Max(1, count); } private Vector3 GetPointersVelocity() { Vector3 sum = Vector3.zero; foreach (var p in pointerIdToPointerMap.Values) { sum += p.Controller.Velocity; } return sum / Math.Max(1, pointerIdToPointerMap.Count); } private Vector3 GetPointersAngularVelocity() { Vector3 sum = Vector3.zero; foreach (var p in pointerIdToPointerMap.Values) { sum += p.Controller.AngularVelocity; } return sum / Math.Max(1, pointerIdToPointerMap.Count); } private bool IsNearManipulation() { foreach (var item in pointerIdToPointerMap) { if (item.Value is IMixedRealityNearPointer) { return true; } } return false; } private void UpdateStateMachine() { var handsPressedCount = pointerIdToPointerMap.Count; State newState = currentState; switch (currentState) { case State.Start: case State.Moving: if (handsPressedCount == 0) { newState = State.Start; } else if (handsPressedCount == 1 && manipulationType != HandMovementType.TwoHandedOnly) { newState = State.Moving; } else if (handsPressedCount > 1 && manipulationType != HandMovementType.OneHandedOnly) { switch (twoHandedManipulationType) { case TwoHandedManipulation.Scale: newState = State.Scaling; break; case TwoHandedManipulation.Rotate: newState = State.Rotating; break; case TwoHandedManipulation.MoveRotate: newState = State.MovingRotating; break; case TwoHandedManipulation.MoveScale: newState = State.MovingScaling; break; case TwoHandedManipulation.RotateScale: newState = State.RotatingScaling; break; case TwoHandedManipulation.MoveRotateScale: newState = State.MovingRotatingScaling; break; default: throw new ArgumentOutOfRangeException(); } } break; case State.Scaling: case State.Rotating: case State.MovingScaling: case State.MovingRotating: case State.RotatingScaling: case State.MovingRotatingScaling: // TODO: if < 2, make this go to start state ('drop it') if (handsPressedCount == 0) { newState = State.Start; } else if (handsPressedCount == 1) { newState = State.Moving; } break; default: throw new ArgumentOutOfRangeException(); } InvokeStateUpdateFunctions(currentState, newState); currentState = newState; } private void InvokeStateUpdateFunctions(State oldState, State newState) { if (newState != oldState) { switch (newState) { case State.Moving: HandleOneHandMoveStarted(); break; case State.Start: HandleManipulationEnded(); break; case State.RotatingScaling: case State.MovingRotating: case State.MovingRotatingScaling: case State.Scaling: case State.Rotating: case State.MovingScaling: HandleTwoHandManipulationStarted(newState); break; } switch (oldState) { case State.Start: HandleManipulationStarted(); break; case State.Scaling: case State.Rotating: case State.RotatingScaling: case State.MovingRotating: case State.MovingRotatingScaling: case State.MovingScaling: HandleTwoHandManipulationEnded(); break; } } else { switch (newState) { case State.Moving: HandleOneHandMoveUpdated(); break; case State.Scaling: case State.Rotating: case State.RotatingScaling: case State.MovingRotating: case State.MovingRotatingScaling: case State.MovingScaling: HandleTwoHandManipulationUpdated(); break; default: break; } } } #endregion Private Methods #region Hand Event Handlers private MixedRealityInteractionMapping GetSpatialGripInfoForController(IMixedRealityController controller) { if (controller == null) { return null; } return controller.Interactions?.First(x => x.InputType == DeviceInputType.SpatialGrip); } /// <inheritdoc /> public void OnPointerDown(MixedRealityPointerEventData eventData) { if (!allowFarManipulation && eventData.Pointer as IMixedRealityNearPointer == null) { return; } // If we only allow one handed manipulations, check there is no hand interacting yet. if (manipulationType != HandMovementType.OneHandedOnly || pointerIdToPointerMap.Count == 0) { uint id = eventData.Pointer.PointerId; // Ignore poke pointer events if (!eventData.used && !pointerIdToPointerMap.ContainsKey(eventData.Pointer.PointerId)) { if (pointerIdToPointerMap.Count == 0) { rigidBody = GetComponent<Rigidbody>(); if (rigidBody != null) { wasKinematic = rigidBody.isKinematic; rigidBody.isKinematic = true; } } pointerIdToPointerMap.Add(id, eventData.Pointer); UpdateStateMachine(); } } if (pointerIdToPointerMap.Count > 0) { // Always mark the pointer data as used to prevent any other behavior to handle pointer events // as long as the ManipulationHandler is active. // This is due to us reacting to both "Select" and "Grip" events. eventData.Use(); } } /// <inheritdoc /> public void OnPointerUp(MixedRealityPointerEventData eventData) { uint id = eventData.Pointer.PointerId; if (pointerIdToPointerMap.ContainsKey(id)) { if (pointerIdToPointerMap.Count == 1 && rigidBody != null) { rigidBody.isKinematic = wasKinematic; if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepVelocity)) { rigidBody.velocity = GetPointersVelocity(); } if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepAngularVelocity)) { rigidBody.angularVelocity = GetPointersAngularVelocity(); } rigidBody = null; } pointerIdToPointerMap.Remove(id); } UpdateStateMachine(); eventData.Use(); } #endregion Hand Event Handlers #region Private Event Handlers private void HandleTwoHandManipulationUpdated() { var targetPosition = hostTransform.position; var targetScale = hostTransform.localScale; if ((currentState & State.Moving) > 0) { targetPosition = m_moveLogic.Update(GetPointersCentroid(), IsNearManipulation()); } var handPositionMap = GetHandPositionMap(); if ((currentState & State.Rotating) > 0) { targetRotationTwoHands = m_rotateLogic.Update(handPositionMap, targetRotationTwoHands, constraintOnRotation); } if ((currentState & State.Scaling) > 0) { targetScale = m_scaleLogic.UpdateMap(handPositionMap); } float lerpAmount = GetLerpAmount(); hostTransform.position = Vector3.Lerp(hostTransform.position, targetPosition, lerpAmount); // Currently the two hand rotation algorithm doesn't allow for lerping, but it should. Fix this. hostTransform.rotation = Quaternion.Lerp(hostTransform.rotation, targetRotationTwoHands, lerpAmount); hostTransform.localScale = Vector3.Lerp(hostTransform.localScale, targetScale, lerpAmount); } private void HandleOneHandMoveUpdated() { Debug.Assert(pointerIdToPointerMap.Count == 1); IMixedRealityPointer pointer = pointerIdToPointerMap.Values.First(); var interactionMapping = GetSpatialGripInfoForController(pointer.Controller); if (interactionMapping != null) { Quaternion targetRotation = Quaternion.identity; RotateInOneHandType rotateInOneHandType = isNearManipulation ? oneHandRotationModeNear : oneHandRotationModeFar; if (rotateInOneHandType == RotateInOneHandType.MaintainOriginalRotation) { targetRotation = hostTransform.rotation; } else if (rotateInOneHandType == RotateInOneHandType.MaintainRotationToUser) { targetRotation = CameraCache.Main.transform.rotation * startObjectRotationCameraSpace; } else if (rotateInOneHandType == RotateInOneHandType.GravityAlignedMaintainRotationToUser) { var cameraForwardFlat = CameraCache.Main.transform.forward; cameraForwardFlat.y = 0; targetRotation = Quaternion.LookRotation(cameraForwardFlat, Vector3.up) * startObjectRotationFlatCameraSpace; } else if (rotateInOneHandType == RotateInOneHandType.FaceUser) { Vector3 directionToTarget = hostTransform.position - CameraCache.Main.transform.position; targetRotation = Quaternion.LookRotation(-directionToTarget); } else if (rotateInOneHandType == RotateInOneHandType.FaceAwayFromUser) { Vector3 directionToTarget = hostTransform.position - CameraCache.Main.transform.position; targetRotation = Quaternion.LookRotation(directionToTarget); } else { targetRotation = interactionMapping.PoseData.Rotation * objectToHandRotation; switch (constraintOnRotation) { case RotationConstraintType.XAxisOnly: targetRotation.eulerAngles = Vector3.Scale(targetRotation.eulerAngles, Vector3.right); break; case RotationConstraintType.YAxisOnly: targetRotation.eulerAngles = Vector3.Scale(targetRotation.eulerAngles, Vector3.up); break; case RotationConstraintType.ZAxisOnly: targetRotation.eulerAngles = Vector3.Scale(targetRotation.eulerAngles, Vector3.forward); break; } } Vector3 targetPosition; if (IsNearManipulation()) { if (oneHandRotationModeNear == RotateInOneHandType.RotateAboutGrabPoint) { targetPosition = (interactionMapping.PoseData.Rotation * objectToHandTranslation) + interactionMapping.PoseData.Position; } else // RotateAboutCenter or DoNotRotateInOneHand { targetPosition = objectToHandTranslation + interactionMapping.PoseData.Position; } } else { targetPosition = m_moveLogic.Update(GetPointersCentroid(), IsNearManipulation()); } float lerpAmount = GetLerpAmount(); Quaternion smoothedRotation = Quaternion.Lerp(hostTransform.rotation, targetRotation, lerpAmount); Vector3 smoothedPosition = Vector3.Lerp(hostTransform.position, targetPosition, lerpAmount); hostTransform.SetPositionAndRotation(smoothedPosition, smoothedRotation); } } private void HandleTwoHandManipulationStarted(State newState) { var handPositionMap = GetHandPositionMap(); targetRotationTwoHands = hostTransform.rotation; if ((newState & State.Rotating) > 0) { m_rotateLogic.Setup(handPositionMap, hostTransform, ConstraintOnRotation); } if ((newState & State.Moving) > 0) { m_moveLogic.Setup(GetPointersCentroid(), hostTransform.position); } if ((newState & State.Scaling) > 0) { m_scaleLogic.Setup(handPositionMap, hostTransform); } } private void HandleTwoHandManipulationEnded() { } private void HandleOneHandMoveStarted() { Assert.IsTrue(pointerIdToPointerMap.Count == 1); IMixedRealityPointer pointer = pointerIdToPointerMap.Values.First(); m_moveLogic.Setup(GetPointersCentroid(), hostTransform.position); var interactionMapping = GetSpatialGripInfoForController(pointer.Controller); if (interactionMapping != null) { // Calculate relative transform from object to hand. Quaternion worldToPalmRotation = Quaternion.Inverse(interactionMapping.PoseData.Rotation); objectToHandRotation = worldToPalmRotation * hostTransform.rotation; objectToHandTranslation = (hostTransform.position - interactionMapping.PoseData.Position); if (oneHandRotationModeNear == RotateInOneHandType.RotateAboutGrabPoint) { objectToHandTranslation = worldToPalmRotation * objectToHandTranslation; } } startObjectRotationCameraSpace = Quaternion.Inverse(CameraCache.Main.transform.rotation) * hostTransform.rotation; var cameraFlat = CameraCache.Main.transform.forward; cameraFlat.y = 0; var hostForwardFlat = hostTransform.forward; hostForwardFlat.y = 0; var hostRotFlat = Quaternion.LookRotation(hostForwardFlat, Vector3.up); startObjectRotationFlatCameraSpace = Quaternion.Inverse(Quaternion.LookRotation(cameraFlat, Vector3.up)) * hostRotFlat; } private void HandleManipulationStarted() { isNearManipulation = IsNearManipulation(); // TODO: If we are on HoloLens 1, push and pop modal input handler so that we can use old // gaze/gesture/voice manipulation. For HoloLens 2, we don't want to do this. OnManipulationStarted.Invoke(new ManipulationEventData { IsNearInteraction = isNearManipulation }); } private void HandleManipulationEnded() { // TODO: If we are on HoloLens 1, push and pop modal input handler so that we can use old // gaze/gesture/voice manipulation. For HoloLens 2, we don't want to do this. OnManipulationEnded.Invoke(new ManipulationEventData { IsNearInteraction = isNearManipulation }); } #endregion Private Event Handlers #region Unused Event Handlers /// <inheritdoc /> public void OnPointerClicked(MixedRealityPointerEventData eventData) { } #endregion Unused Event Handlers #region Private methods private float GetLerpAmount() { if (smoothingActive == false || smoothingAmountOneHandManip == 0) { return 1; } // Obtained from "Frame-rate independent smoothing" // www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/ // We divide by max value to give the slider a bit more sensitivity. return 1.0f - Mathf.Pow(smoothingAmountOneHandManip, Time.deltaTime); } private Dictionary<uint, Vector3> GetHandPositionMap() { var handPositionMap = new Dictionary<uint, Vector3>(); foreach (var item in pointerIdToPointerMap) { handPositionMap.Add(item.Key, item.Value.Position); } return handPositionMap; } public void OnFocusEnter(FocusEventData eventData) { bool isFar = !(eventData.Pointer is IMixedRealityNearPointer); if (isFar && !AllowFarManipulation) { return; } OnHoverEntered.Invoke(new ManipulationEventData { IsNearInteraction = !isFar }); } public void OnFocusExit(FocusEventData eventData) { bool isFar = !(eventData.Pointer is IMixedRealityNearPointer); if (isFar && !AllowFarManipulation) { return; } OnHoverExited.Invoke(new ManipulationEventData { IsNearInteraction = !isFar }); } #endregion } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ #if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Reflection; using System; using System.Collections; using System.Collections.Generic; /// <summary> ///Scans the project and warns about the following conditions: ///Audio sources > 16 ///Using MSAA levels other than recommended level ///GPU skinning is also probably usually ideal. ///Excessive pixel lights (>1 on Gear VR; >3 on Rift) ///Directional Lightmapping Modes (on Gear; use Non-Directional) ///Preload audio setting on individual audio clips ///Decompressing audio clips on load ///Disabling occlusion mesh ///Android target API level set to 19 or higher ///Unity skybox use (on by default, but if you can't see the skybox switching to Color is much faster on Gear) ///Lights marked as "baked" but that were not included in the last bake (and are therefore realtime). ///Lack of static batching and dynamic batching settings activated. ///Full screen image effects (Gear) ///Warn about large textures that are marked as uncompressed. ///32-bit depth buffer (use 16) ///Use of projectors (Gear; can be used carefully but slow enough to warrant a warning) ///Maybe in the future once quantified: Graphics jobs and IL2CPP on Gear. ///Real-time global illumination ///No texture compression, or non-ASTC texture compression as a global setting (Gear). ///Using deferred rendering ///Excessive texture resolution after LOD bias (>2k on Gear VR; >4k on Rift) ///Not using trilinear or aniso filtering and not generating mipmaps ///Excessive render scale (>1.2) ///Slow physics settings: Sleep Threshold < 0.005, Default Contact Offset < 0.01, Solver Iteration Count > 6 ///Shadows on when approaching the geometry or draw call limits ///Non-static objects with colliders that are missing rigidbodies on themselves or in the parent chain. ///No initialization of GPU/CPU throttling settings, or init to dangerous values (-1 or > 3) (Gear) ///Using inefficient effects: SSAO, motion blur, global fog, parallax mapping, etc. ///Too many Overlay layers ///Use of Standard shader or Standard Specular shader on Gear. More generally, excessive use of multipass shaders (legacy specular, etc). ///Multiple cameras with clears (on Gear, potential for excessive fill cost) ///Excessive shader passes (>2) ///Material pointers that have been instanced in the editor (esp. if we could determine that the instance has no deltas from the original) ///Excessive draw calls (>150 on Gear VR; >2000 on Rift) ///Excessive tris or verts (>100k on Gear VR; >1M on Rift) ///Large textures, lots of prefabs in startup scene (for bootstrap optimization) /// </summary> public class OVRLint : EditorWindow { //TODO: The following require reflection or static analysis. ///Use of ONSP reflections (Gear) ///Use of LoadLevelAsync / LoadLevelAdditiveAsync (on Gear, this kills frame rate so dramatically it's probably better to just go to black and load synchronously) ///Use of Linq in non-editor assemblies (common cause of GCs). Minor: use of foreach. ///Use of Unity WWW (exceptionally high overhead for large file downloads, but acceptable for tiny gets). ///Declared but empty Awake/Start/Update/OnCollisionEnter/OnCollisionExit/OnCollisionStay. Also OnCollision* star methods that declare the Collision argument but do not reference it (omitting it short-circuits the collision contact calculation). public delegate void FixMethodDelegate(UnityEngine.Object obj, bool isLastInSet, int selectedIndex); public struct FixRecord { public string category; public string message; public FixMethodDelegate fixMethod; public UnityEngine.Object targetObject; public string[] buttonNames; public bool complete; public FixRecord(string cat, string msg, FixMethodDelegate fix, UnityEngine.Object target, string[] buttons) { category = cat; message = msg; buttonNames = buttons; fixMethod = fix; targetObject = target; complete = false; } } private static List<FixRecord> mRecords = new List<FixRecord>(); private Vector2 mScrollPosition; [MenuItem("Tools/Oculus/Audit Project for VR Performance Issues")] static void Init () { // Get existing open window or if none, make a new one: EditorWindow.GetWindow (typeof (OVRLint)); } void OnGUI () { GUILayout.Label ("OVR Lint Tool", EditorStyles.boldLabel); if (GUILayout.Button("Run Lint", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { RunCheck(); } string lastCategory = ""; mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition); for (int x = 0; x < mRecords.Count; x++) { FixRecord record = mRecords[x]; if (!record.category.Equals(lastCategory)) // new category { lastCategory = record.category; EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(lastCategory, EditorStyles.label, GUILayout.Width(200)); bool moreThanOne = (x + 1 < mRecords.Count && mRecords[x + 1].category.Equals(lastCategory)); if (record.buttonNames != null && record.buttonNames.Length > 0) { if (moreThanOne) { GUILayout.Label("Apply to all:", EditorStyles.label, GUILayout.Width(75)); for (int y = 0; y < record.buttonNames.Length; y++) { if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(100))) { List<FixRecord> recordsToProcess = new List<FixRecord>(); for (int z = x; z < mRecords.Count; z++) { FixRecord thisRecord = mRecords[z]; bool isLast = false; if (z + 1 >= mRecords.Count || !mRecords[z + 1].category.Equals(lastCategory)) { isLast = true; } if (!thisRecord.complete) { recordsToProcess.Add(thisRecord); } if (isLast) { break; } } UnityEngine.Object[] undoObjects = new UnityEngine.Object[recordsToProcess.Count]; for (int z = 0; z < recordsToProcess.Count; z++) { undoObjects[z] = recordsToProcess[z].targetObject; } Undo.RecordObjects(undoObjects, record.category + " (Multiple)"); for (int z = 0; z < recordsToProcess.Count; z++) { FixRecord thisRecord = recordsToProcess[z]; thisRecord.fixMethod(thisRecord.targetObject, (z + 1 == recordsToProcess.Count), y); thisRecord.complete = true; } } } } } EditorGUILayout.EndHorizontal(); if (moreThanOne || record.targetObject) { GUILayout.Label(record.message); } } EditorGUILayout.BeginHorizontal(); GUI.enabled = !record.complete; if (record.targetObject) { EditorGUILayout.ObjectField(record.targetObject, record.targetObject.GetType(), true); } else { GUILayout.Label(record.message); } for (int y = 0; y < record.buttonNames.Length; y++) { if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(100))) { if (record.targetObject != null) { Undo.RecordObject(record.targetObject, record.category); } record.fixMethod(record.targetObject, true, y); record.complete = true; } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); } static void RunCheck() { mRecords.Clear(); CheckStaticCommonIssues(); #if UNITY_ANDROID CheckStaticAndroidIssues(); #endif if (EditorApplication.isPlaying) { CheckRuntimeCommonIssues(); #if UNITY_ANDROID CheckRuntimeAndroidIssues(); #endif } mRecords.Sort(delegate(FixRecord record1, FixRecord record2) { return record1.category.CompareTo(record2.category); }); } static void AddFix(string category, string message, FixMethodDelegate method, UnityEngine.Object target, params string[] buttons) { mRecords.Add(new FixRecord(category, message, method, target, buttons)); } static void CheckStaticCommonIssues () { if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable) { AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal quality and performance.", delegate(UnityEngine.Object obj, bool last, int selected) { QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable; }, null, "Fix"); } #if UNITY_ANDROID int recommendedPixelLightCount = 1; #else int recommendedPixelLightCount = 3; #endif if (QualitySettings.pixelLightCount > recommendedPixelLightCount) { AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate(UnityEngine.Object obj, bool last, int selected) { QualitySettings.pixelLightCount = recommendedPixelLightCount; }, null, "Fix"); } if (!PlayerSettings.gpuSkinning) { AddFix ("Optimize GPU Skinning", "For CPU performance, please use GPU skinning.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.gpuSkinning = true; }, null, "Fix"); } #if false // Should we recommend this? Seems to be mutually exclusive w/ dynamic batching. if (!PlayerSettings.graphicsJobs) { AddFix ("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.graphicsJobs = true; }, null, "Fix"); } #endif #if UNITY_2017_2_OR_NEWER if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android))) #else if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering)) #endif { AddFix ("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate(UnityEngine.Object obj, bool last, int selected) { #if UNITY_2017_2_OR_NEWER PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true); PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true); #else PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true; #endif }, null, "Fix"); } #if UNITY_5_5_OR_NEWER BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup; var tier = UnityEngine.Rendering.GraphicsTier.Tier1; var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier); if ((tierSettings.renderingPath == RenderingPath.DeferredShading || tierSettings.renderingPath == RenderingPath.DeferredLighting)) { AddFix ("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected) { tierSettings.renderingPath = RenderingPath.Forward; UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings); }, null, "Use Forward"); } #else if (PlayerSettings.renderingPath == RenderingPath.DeferredShading || PlayerSettings.renderingPath == RenderingPath.DeferredLighting || PlayerSettings.mobileRenderingPath == RenderingPath.DeferredShading || PlayerSettings.mobileRenderingPath == RenderingPath.DeferredLighting) { AddFix ("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.renderingPath = PlayerSettings.mobileRenderingPath = RenderingPath.Forward; }, null, "Use Forward"); } #endif #if UNITY_5_5_OR_NEWER if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass) { AddFix ("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing; }, null, "Fix"); } #elif UNITY_5_4_OR_NEWER if (!PlayerSettings.singlePassStereoRendering) { AddFix ("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.singlePassStereoRendering = true; }, null, "Enable Single-Pass"); } #endif if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional) { AddFix ("Optimize Lightmap Directionality", "For GPU performance, please don't use directional lightmaps.", delegate(UnityEngine.Object obj, bool last, int selected) { LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional; }, null, "Switch Lightmap Mode"); } #if UNITY_5_4_OR_NEWER if (Lightmapping.realtimeGI) { AddFix ("Optimize Realtime GI", "For GPU performance, please don't use real-time global illumination. (Set Lightmapping.realtimeGI = false.)", delegate(UnityEngine.Object obj, bool last, int selected) { Lightmapping.realtimeGI = false; }, null, "Disable Realtime GI"); } #endif var lights = GameObject.FindObjectsOfType<Light> (); for (int i = 0; i < lights.Length; ++i) { #if UNITY_5_4_OR_NEWER if (lights [i].type != LightType.Directional && !lights [i].isBaked && IsLightBaked(lights[i])) { AddFix ("Optimize Light Baking", "For GPU performance, please bake lightmaps to avoid realtime lighting cost.", delegate(UnityEngine.Object obj, bool last, int selected) { if (last) { Lightmapping.Bake (); } }, lights[i], "Bake Lightmaps"); } #endif if (lights [i].shadows != LightShadows.None && !IsLightBaked(lights[i])) { AddFix ("Optimize Shadows", "For CPU performance, please disable shadows on realtime lights.", delegate(UnityEngine.Object obj, bool last, int selected) { Light thisLight = (Light)obj; thisLight.shadows = LightShadows.None; }, lights [i], "Disable Shadows"); } } /* // CP: I think this should modify the max number of simultaneous voices in the audio settings rather than // the number of sources. Sources don't cost anything if they aren't playing simultaneously. // Couldn't figure out if there's an API for max voices. var sources = GameObject.FindObjectsOfType<AudioSource> (); if (sources.Length > 16 && EditorUtility.DisplayDialog ("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", "Use recommended", "Skip")) { Array.Sort(sources, (a, b) => { return a.priority.CompareTo(b.priority); }); for (int i = 16; i < sources.Length; ++i) { sources[i].enabled = false; } } */ var clips = GameObject.FindObjectsOfType<AudioClip> (); for (int i = 0; i < clips.Length; ++i) { if (clips [i].loadType == AudioClipLoadType.DecompressOnLoad) { AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate(UnityEngine.Object obj, bool last, int selected) { AudioClip thisClip = (AudioClip)obj; if (selected == 0) { SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last); } else { SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last); } }, clips [i], "Change to Compressed in Memory", "Change to Streaming"); } if (clips [i].preloadAudioData) { AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate(UnityEngine.Object obj, bool last, int selected) { SetAudioPreload(clips[i], false, last); }, clips [i], "Fix"); } } if (Physics.defaultContactOffset < 0.01f) { AddFix ("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.defaultContactOffset = 0.01f; }, null, "Fix"); } if (Physics.sleepThreshold < 0.005f) { AddFix ("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.sleepThreshold = 0.005f; }, null, "Fix"); } #if UNITY_5_4_OR_NEWER if (Physics.defaultSolverIterations > 8) { AddFix ("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate(UnityEngine.Object obj, bool last, int selected) { Physics.defaultSolverIterations = 8; }, null, "Fix"); } #endif var colliders = GameObject.FindObjectsOfType<Collider> (); for (int i = 0; i < colliders.Length; ++i) { // CP: unsure when attachedRigidbody is init'd, so search parents to be sure. if (!colliders [i].gameObject.isStatic && colliders [i].attachedRigidbody == null && colliders[i].GetComponent<Rigidbody>() == null && FindComponentInParents<Rigidbody>(colliders[i].gameObject) == null) { AddFix ("Optimize Nonstatic Collider", "For CPU performance, please make static or attach a Rigidbody to non-static colliders.", delegate(UnityEngine.Object obj, bool last, int selected) { Collider thisCollider = (Collider)obj; if (selected == 0) { thisCollider.gameObject.isStatic = true; } else { var rb = thisCollider.gameObject.AddComponent<Rigidbody> (); rb.isKinematic = true; } }, colliders[i], "Make Static", "Add Rigidbody"); } } var materials = Resources.FindObjectsOfTypeAll<Material> (); for (int i = 0; i < materials.Length; ++i) { if (materials [i].shader.name.Contains ("Parallax") || materials [i].IsKeywordEnabled ("_PARALLAXMAP")) { AddFix ("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate(UnityEngine.Object obj, bool last, int selected) { Material thisMaterial = (Material)obj; if (thisMaterial.IsKeywordEnabled ("_PARALLAXMAP")) { thisMaterial.DisableKeyword ("_PARALLAXMAP"); } if (thisMaterial.shader.name.Contains ("Parallax")) { var newName = thisMaterial.shader.name.Replace ("-ParallaxSpec", "-BumpSpec"); newName = newName.Replace ("-Parallax", "-Bump"); var newShader = Shader.Find (newName); if (newShader) { thisMaterial.shader = newShader; } else { Debug.LogWarning ("Unable to find a replacement for shader " + materials [i].shader.name); } } }, materials[i], "Fix"); } } var renderers = GameObject.FindObjectsOfType<Renderer> (); for (int i = 0; i < renderers.Length; ++i) { if (renderers [i].sharedMaterial == null) { AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers [i]); } } var overlays = GameObject.FindObjectsOfType<OVROverlay> (); if (overlays.Length > 4) { AddFix ("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate(UnityEngine.Object obj, bool last, int selected) { for (int i = 4; i < OVROverlay.instances.Length; ++i) { OVROverlay.instances[i].enabled = false; } }, null, "Fix"); } } static void CheckRuntimeCommonIssues() { if (!OVRPlugin.occlusionMesh) { AddFix ("Optimize Occlusion Mesh", "For GPU performance, please use occlusion mesh.", delegate(UnityEngine.Object obj, bool last, int selected) { OVRPlugin.occlusionMesh = true; }, null, "Fix"); } if (OVRManager.instance != null && !OVRManager.instance.useRecommendedMSAALevel) { AddFix("Optimize MSAA", "OVRManager can select the optimal antialiasing for the installed hardware at runtime. Recommend enabling this.", delegate(UnityEngine.Object obj, bool last, int selected) { OVRManager.instance.useRecommendedMSAALevel = true; }, null, "Fix"); } if (UnityEngine.VR.VRSettings.renderScale > 1.5) { AddFix ("Optimize Render Scale", "For GPU performance, please don't use render scale over 1.5.", delegate(UnityEngine.Object obj, bool last, int selected) { UnityEngine.VR.VRSettings.renderScale = 1.5f; }, null, "Fix"); } } static void CheckStaticAndroidIssues () { AndroidSdkVersions recommendedAndroidSdkVersion = AndroidSdkVersions.AndroidApiLevel19; if ((int)PlayerSettings.Android.minSdkVersion < (int)recommendedAndroidSdkVersion) { AddFix ("Optimize Android API Level", "To avoid legacy work-arounds, please require at least API level " + (int)recommendedAndroidSdkVersion, delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.Android.minSdkVersion = recommendedAndroidSdkVersion; }, null, "Fix"); } if (RenderSettings.skybox) { AddFix ("Optimize Clearing", "For GPU performance, please don't use Unity's built-in Skybox.", delegate(UnityEngine.Object obj, bool last, int selected) { RenderSettings.skybox = null; }, null, "Clear Skybox"); } var materials = Resources.FindObjectsOfTypeAll<Material> (); for (int i = 0; i < materials.Length; ++i) { if (materials [i].IsKeywordEnabled ("_SPECGLOSSMAP") || materials [i].IsKeywordEnabled ("_METALLICGLOSSMAP")) { AddFix ("Optimize Specular Material", "For GPU performance, please don't use specular shader on materials.", delegate(UnityEngine.Object obj, bool last, int selected) { Material thisMaterial = (Material)obj; thisMaterial.DisableKeyword ("_SPECGLOSSMAP"); thisMaterial.DisableKeyword ("_METALLICGLOSSMAP"); }, materials[i], "Fix"); } if (materials [i].passCount > 1) { AddFix ("Material Passes", "Please use 2 or fewer passes in materials.", null, materials[i]); } } #if UNITY_5_5_OR_NEWER ScriptingImplementation backend = PlayerSettings.GetScriptingBackend(UnityEditor.BuildTargetGroup.Android); if (backend != UnityEditor.ScriptingImplementation.IL2CPP) { AddFix ("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.SetScriptingBackend(UnityEditor.BuildTargetGroup.Android, UnityEditor.ScriptingImplementation.IL2CPP); }, null, "Fix"); } #else ScriptingImplementation backend = (ScriptingImplementation)PlayerSettings.GetPropertyInt("ScriptingBackend", UnityEditor.BuildTargetGroup.Android); if (backend != UnityEditor.ScriptingImplementation.IL2CPP) { AddFix ("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.SetPropertyInt("ScriptingBackend", (int)UnityEditor.ScriptingImplementation.IL2CPP, UnityEditor.BuildTargetGroup.Android); }, null, "Fix"); } #endif var monoBehaviours = GameObject.FindObjectsOfType<MonoBehaviour> (); System.Type effectBaseType = System.Type.GetType ("UnityStandardAssets.ImageEffects.PostEffectsBase"); if (effectBaseType != null) { for (int i = 0; i < monoBehaviours.Length; ++i) { if (monoBehaviours [i].GetType ().IsSubclassOf (effectBaseType)) { AddFix ("Image Effects", "Please don't use image effects.", null, monoBehaviours[i]); } } } var textures = Resources.FindObjectsOfTypeAll<Texture2D> (); int maxTextureSize = 1024 * (1 << QualitySettings.masterTextureLimit); maxTextureSize = maxTextureSize * maxTextureSize; for (int i = 0; i < textures.Length; ++i) { if (textures [i].filterMode == FilterMode.Trilinear && textures [i].mipmapCount == 1) { AddFix ("Optimize Texture Filtering", "For GPU performance, please generate mipmaps or disable trilinear filtering for textures.", delegate(UnityEngine.Object obj, bool last, int selected) { Texture2D thisTexture = (Texture2D)obj; if (selected == 0) { thisTexture.filterMode = FilterMode.Bilinear; } else { SetTextureUseMips(thisTexture, true, last); } }, textures[i], "Switch to Bilinear", "Generate Mipmaps"); } } var projectors = GameObject.FindObjectsOfType<Projector> (); if (projectors.Length > 0) { AddFix ("Optimize Projectors", "For GPU performance, please don't use projectors.", delegate(UnityEngine.Object obj, bool last, int selected) { Projector[] thisProjectors = GameObject.FindObjectsOfType<Projector> (); for (int i = 0; i < thisProjectors.Length; ++i) { thisProjectors[i].enabled = false; } }, null, "Disable Projectors"); } if (EditorUserBuildSettings.androidBuildSubtarget != MobileTextureSubtarget.ASTC) { AddFix ("Optimize Texture Compression", "For GPU performance, please use ASTC.", delegate(UnityEngine.Object obj, bool last, int selected) { EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC; }, null, "Fix"); } var cameras = GameObject.FindObjectsOfType<Camera> (); int clearCount = 0; for (int i = 0; i < cameras.Length; ++i) { if (cameras [i].clearFlags != CameraClearFlags.Nothing && cameras [i].clearFlags != CameraClearFlags.Depth) ++clearCount; } if (clearCount > 2) { AddFix ("Camera Clears", "Please use 2 or fewer clears.", null, null); } } static void CheckRuntimeAndroidIssues() { if (UnityStats.usedTextureMemorySize + UnityStats.vboTotalBytes > 1000000) { AddFix ("Graphics Memory", "Please use less than 1GB of vertex and texture memory.", null, null); } if (OVRManager.cpuLevel < 0 || OVRManager.cpuLevel > 3) { AddFix ("Optimize CPU level", "For battery life, please use a safe CPU level.", delegate(UnityEngine.Object obj, bool last, int selected) { OVRManager.cpuLevel = 2; }, null, "Set to CPU2"); } if (OVRManager.gpuLevel < 0 || OVRManager.gpuLevel > 3) { AddFix ("Optimize GPU level", "For battery life, please use a safe GPU level.", delegate(UnityEngine.Object obj, bool last, int selected) { OVRManager.gpuLevel = 2; }, null, "Set to GPU2"); } if (UnityStats.triangles > 100000 || UnityStats.vertices > 100000) { AddFix ("Triangles and Verts", "Please use less than 100000 triangles or vertices.", null, null); } // Warn for 50 if in non-VR mode? if (UnityStats.drawCalls > 100) { AddFix ("Draw Calls", "Please use less than 100 draw calls.", null, null); } } enum LightmapType {Realtime = 4, Baked = 2, Mixed = 1}; static bool IsLightBaked(Light light) { #if UNITY_5_6_OR_NEWER return light.lightmapBakeType == LightmapBakeType.Baked; #elif UNITY_5_5_OR_NEWER return light.lightmappingMode == LightmappingMode.Baked; #else SerializedObject serialObj = new SerializedObject(light); SerializedProperty lightmapProp = serialObj.FindProperty("m_Lightmapping"); return (LightmapType)lightmapProp.intValue == LightmapType.Baked; #endif } static void SetAudioPreload( AudioClip clip, bool preload, bool refreshImmediately) { if ( clip != null ) { string assetPath = AssetDatabase.GetAssetPath( clip ); AudioImporter importer = AssetImporter.GetAtPath( assetPath ) as AudioImporter; if (importer != null) { if (preload != importer.preloadAudioData) { importer.preloadAudioData = preload; AssetDatabase.ImportAsset( assetPath ); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } } static void SetAudioLoadType( AudioClip clip, AudioClipLoadType loadType, bool refreshImmediately) { if ( clip != null ) { string assetPath = AssetDatabase.GetAssetPath( clip ); AudioImporter importer = AssetImporter.GetAtPath( assetPath ) as AudioImporter; if (importer != null) { if (loadType != importer.defaultSampleSettings.loadType) { AudioImporterSampleSettings settings = importer.defaultSampleSettings; settings.loadType = loadType; importer.defaultSampleSettings = settings; AssetDatabase.ImportAsset( assetPath ); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } } public static void SetTextureUseMips( Texture texture, bool useMips, bool refreshImmediately) { if ( texture != null ) { string assetPath = AssetDatabase.GetAssetPath( texture ); TextureImporter tImporter = AssetImporter.GetAtPath( assetPath ) as TextureImporter; if ( tImporter != null && tImporter.mipmapEnabled != useMips) { tImporter.mipmapEnabled = useMips; AssetDatabase.ImportAsset( assetPath ); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } static T FindComponentInParents<T>(GameObject obj) where T : Component { T component = null; if (obj != null) { Transform parent = obj.transform.parent; if (parent != null) { do { component = parent.GetComponent(typeof(T)) as T; parent = parent.parent; } while (parent != null && component == null); } } return component; } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using JetBrains.Annotations; using JoinRpg.Data.Interfaces; using JoinRpg.DataModel; using JoinRpg.Domain; using JoinRpg.Services.Interfaces; using JoinRpg.Web.Controllers.Common; using JoinRpg.Web.Filter; using JoinRpg.Web.Helpers; using JoinRpg.Web.Models; namespace JoinRpg.Web.Controllers { [Authorize] public class ForumController : ControllerGameBase { #region Constructor & Services private IForumService ForumService { get; } private IForumRepository ForumRepository { get; } private IClaimsRepository ClaimsRepository { get; } private IClaimService ClaimService { get; } public ForumController(ApplicationUserManager userManager, IProjectRepository projectRepository, IProjectService projectService, IExportDataService exportDataService, IForumService forumService, IForumRepository forumRepository, IClaimsRepository claimsRepository, IClaimService claimService) : base(userManager, projectRepository, projectService, exportDataService) { ForumService = forumService; ForumRepository = forumRepository; ClaimsRepository = claimsRepository; ClaimService = claimService; } #endregion [MasterAuthorize, HttpGet] public async Task<ActionResult> CreateThread(int projectId, int charactergroupid) { var characterGroup = await ProjectRepository.GetGroupAsync(projectId, charactergroupid); if (characterGroup == null) { return HttpNotFound(); } return View(new CreateForumThreadViewModel(characterGroup.EnsureActive())); } [MasterAuthorize, HttpPost, ValidateAntiForgeryToken] public async Task<ActionResult> CreateThread([NotNull] CreateForumThreadViewModel viewModel) { var group = (await ProjectRepository.GetGroupAsync(viewModel.ProjectId, viewModel.CharacterGroupId)).EnsureActive(); viewModel.CharacterGroupName = group.CharacterGroupName; viewModel.ProjectName = group.Project.ProjectName; if (!ModelState.IsValid) { return View(viewModel); } try { var forumThreadId = await ForumService.CreateThread( viewModel.ProjectId, viewModel.CharacterGroupId, viewModel.Header, viewModel.CommentText, viewModel.HideFromUser, viewModel.EmailEverybody); return RedirectToAction("ViewThread", new {viewModel.ProjectId, forumThreadId }); } catch (Exception exception) { ModelState.AddException(exception); return View(viewModel); } } [Authorize] public async Task<ActionResult> ViewThread(int projectid, int forumThreadId) { var forumThread = await GetForumThread(projectid, forumThreadId); if (forumThread == null) return HttpNotFound(); var viewModel = new ForumThreadViewModel(forumThread, CurrentUserId); return View(viewModel); } private async Task<ForumThread> GetForumThread(int projectid, int forumThreadId) { var forumThread = await ForumRepository.GetThread(projectid, forumThreadId); var isMaster = forumThread.HasMasterAccess(CurrentUserId); var isPlayer = forumThread.IsVisibleToPlayer && (await ClaimsRepository.GetClaimsForPlayer(projectid, ClaimStatusSpec.Approved, CurrentUserId)).Any( claim => claim.IsPartOfGroup(forumThread.CharacterGroupId)); if (!isMaster && !isPlayer) { throw new NoAccessToProjectException(forumThread, CurrentUserId); } return forumThread; } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> CreateComment(AddCommentViewModel viewModel) { CommentDiscussion discussion = await ForumRepository.GetDiscussion(viewModel.ProjectId, viewModel.CommentDiscussionId); discussion.RequestAnyAccess(CurrentUserId); if (discussion == null) return HttpNotFound(); try { if (viewModel.HideFromUser) { discussion.RequestMasterAccess(CurrentUserId); } var claim = discussion.GetClaim(); if (claim != null) { await ClaimService.AddComment(discussion.ProjectId, claim.ClaimId, viewModel.ParentCommentId, !viewModel.HideFromUser, viewModel.CommentText, (FinanceOperationAction) viewModel.FinanceAction); } else { var forumThread = discussion.GetForumThread(); if (forumThread != null) { await ForumService.AddComment(discussion.ProjectId, forumThread.ForumThreadId, viewModel.ParentCommentId, !viewModel.HideFromUser, viewModel.CommentText); } } return ReturnToParent(discussion); } catch { //TODO: Message that comment is not added return ReturnToParent(discussion); } } private ActionResult ReturnToParent(CommentDiscussion discussion, string extra = null) { if (extra == null) { extra = ""; } else { extra = "#" + extra; } var claim = discussion.GetClaim(); if (claim != null) { var actionLink = Url.Action("Edit", "Claim", new {claim.ClaimId, discussion.ProjectId}); return Redirect(actionLink + extra); } var forumThread = discussion.GetForumThread(); if (forumThread != null) { var actionLink = Url.Action("ViewThread", new { discussion.ProjectId, forumThread.ForumThreadId}); return Redirect(actionLink + extra); } return HttpNotFound(); } [Authorize] public async Task<ActionResult> RedirectToDiscussion(int projectid, int? commentid, int? commentDiscussionId) { CommentDiscussion discussion; if (commentid != null) { discussion = await ForumRepository.GetDiscussionByComment(projectid, (int) commentid); } else if (commentDiscussionId != null) { discussion = await ForumRepository.GetDiscussion(projectid, (int) commentDiscussionId); } else { return HttpNotFound(); } if (!discussion.HasAnyAccess(CurrentUserId)) { return NoAccesToProjectView(discussion.Project); } return ReturnToParent(discussion, commentid != null ? $"comment{commentid}" : null); } [HttpGet] public async Task<ActionResult> ListThreads(int projectid) { var project = await ProjectRepository.GetProjectAsync(projectid); if (project == null) { return HttpNotFound(); } var isMaster = project.HasMasterAccess(CurrentUserIdOrDefault); IEnumerable<int> groupIds; if (isMaster) { groupIds = null; } else { var claims = await ClaimsRepository.GetClaimsForPlayer(projectid, ClaimStatusSpec.Approved, CurrentUserId); groupIds = claims.SelectMany(claim => claim.Character.GetGroupsPartOf().Select(g => g.CharacterGroupId)); } var threads = await ForumRepository.GetThreads(projectid, isMaster, groupIds); var viewModel = new ForumThreadListViewModel(project, threads, CurrentUserId); return View(viewModel); } [HttpGet] public async Task<ActionResult> ListThreadsByGroup(int projectid, int characterGroupId) { var group = await ProjectRepository.GetGroupAsync(projectid, characterGroupId); if (group == null) { return HttpNotFound(); } var isMaster = group.HasMasterAccess(CurrentUserIdOrDefault); var threads = await ForumRepository.GetThreads(projectid, isMaster, new [] {characterGroupId}); var viewModel = new ForumThreadListForGroupViewModel(group, threads.Where(t => t.HasAnyAccess(CurrentUserIdOrDefault)), CurrentUserId); return View(viewModel); } public async Task<ActionResult> ConcealComment(int projectid, int commentid, int commentDiscussionId) { await ClaimService.ConcealComment(projectid, commentid, commentDiscussionId, CurrentUserId); return await RedirectToDiscussion(projectid,commentid,commentDiscussionId); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using HetsApi.Authorization; using HetsApi.Helpers; using HetsApi.Model; using HetsData.Helpers; using HetsData.Entities; using HetsReport; using Hangfire; using System.Text; using HetsData.Hangfire; using HetsData.Repositories; using HetsData.Dtos; using AutoMapper; using HetsCommon; namespace HetsApi.Controllers { /// <summary> /// Equipment Controller /// </summary> [Route("api/equipment")] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public class EquipmentController : ControllerBase { private readonly DbAppContext _context; private readonly IConfiguration _configuration; private readonly IMapper _mapper; private readonly IRentalAgreementRepository _rentalAgreementRepo; private readonly IEquipmentRepository _equipmentRepo; private readonly ILogger<EquipmentController> _logger; public EquipmentController(DbAppContext context, IConfiguration configuration, IRentalAgreementRepository rentalAgreementRepo, IEquipmentRepository equipmentRepo, IMapper mapper, ILogger<EquipmentController> logger) { _context = context; _configuration = configuration; _mapper = mapper; _rentalAgreementRepo = rentalAgreementRepo; _equipmentRepo = equipmentRepo; _logger = logger; } /// <summary> /// Get equipment by id /// </summary> /// <param name="id">id of Equipment to fetch</param> [HttpGet] [Route("{id}")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<EquipmentDto> EquipmentIdGet([FromRoute]int id) { return new ObjectResult(new HetsResponse(_equipmentRepo.GetEquipment(id))); } /// <summary> /// Get all approved equipment for this district (lite) /// </summary> [HttpGet] [Route("lite")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<EquipmentExtraLite>> EquipmentGetLite() { // get user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get approved status int? statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get all approved equipment for this district IEnumerable<EquipmentExtraLite> equipment = _context.HetEquipments.AsNoTracking() .Where(x => x.LocalArea.ServiceArea.DistrictId == districtId && x.EquipmentStatusTypeId == statusId) .OrderBy(x => x.EquipmentCode) .Select(x => new EquipmentExtraLite { EquipmentCode = x.EquipmentCode, Id = x.EquipmentId, }); return new ObjectResult(new HetsResponse(equipment)); } /// <summary> /// Get all equipment for this district that are associated with a project (lite) /// </summary> [HttpGet] [Route("liteTs")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<EquipmentLiteList>> EquipmentGetLiteTs() { // get users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get active status int? statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get fiscal year HetDistrictStatus status = _context.HetDistrictStatuses.AsNoTracking() .First(x => x.DistrictId == districtId); int? fiscalYear = status.CurrentFiscalYear; if (fiscalYear == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // fiscal year in the status table stores the "start" of the year DateTime fiscalYearStart = new DateTime((int)fiscalYear, 3, 31); // get all active owners for this district (and any projects they're associated with) var equipments = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.Project) .Include(x => x.Equipment) .Where(x => x.Equipment.LocalArea.ServiceArea.DistrictId == districtId && x.Equipment.EquipmentStatusTypeId == statusId && x.Project.DbCreateTimestamp > fiscalYearStart) .ToList() .GroupBy(x => x.Equipment, (e, agreements) => new EquipmentLiteList { EquipmentCode = e.EquipmentCode, Id = e.EquipmentId, OwnerId = e.OwnerId, LocalAreaId = e.LocalAreaId, ProjectIds = agreements.Select(y => y.ProjectId).Distinct(), DistrictEquipmentTypeId = e.DistrictEquipmentTypeId ?? 0, }); return new ObjectResult(new HetsResponse(equipments)); } /// <summary> /// Get all equipment by district for rental agreement summary filtering /// </summary> [HttpGet] [Route("agreementSummary")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<EquipmentAgreementSummary>> EquipmentGetAgreementSummary() { // get user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); var equipments = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.Equipment) .Where(x => x.DistrictId == districtId && !x.Number.StartsWith("BCBid")) .ToList() .GroupBy(x => x.Equipment, (e, agreements) => new EquipmentAgreementSummary { EquipmentCode = e.EquipmentCode, Id = e.EquipmentId, AgreementIds = agreements.Select(y => y.RentalAgreementId).Distinct().ToList(), ProjectIds = agreements.Select(y => y.ProjectId).Distinct().ToList(), DistrictEquipmentTypeId = e.DistrictEquipmentTypeId ?? 0, }); return new ObjectResult(new HetsResponse(equipments)); } /// <summary> /// Get all equipment for this district that are associated with a rotation list (lite) /// </summary> [HttpGet] [Route("liteHires")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<EquipmentLiteList>> EquipmentGetLiteHires() { // get users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); var equipments = _context.HetRentalRequestRotationLists.AsNoTracking() .Include(x => x.RentalRequest) .ThenInclude(y => y.LocalArea) .ThenInclude(z => z.ServiceArea) .Include(x => x.RentalRequest) .ThenInclude(y => y.Project) .Include(x => x.Equipment) .Where(x => x.RentalRequest.LocalArea.ServiceArea.DistrictId.Equals(districtId)) .ToList() .GroupBy(x => x.Equipment, (e, rotationLists) => new EquipmentLiteList { EquipmentCode = e.EquipmentCode, Id = e.EquipmentId, OwnerId = e.OwnerId, ProjectIds = rotationLists.Select(y => y.RentalRequest.ProjectId).Distinct().ToList(), DistrictEquipmentTypeId = e.DistrictEquipmentTypeId ?? 0, }); return new ObjectResult(new HetsResponse(equipments)); } /// <summary> /// Update equipment /// </summary> /// <param name="id">id of Equipment to update</param> /// <param name="item"></param> [HttpPut] [Route("{id}")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<EquipmentDto> EquipmentIdPut([FromRoute]int id, [FromBody]EquipmentDto item) { if (item == null || id != item.EquipmentId) { // not found return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); } bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get record HetEquipment equipment = _context.HetEquipments .Include(x => x.Owner) .First(x => x.EquipmentId == item.EquipmentId); DateTime? originalSeniorityEffectiveDate = equipment.SeniorityEffectiveDate; float? originalServiceHoursLastYear = equipment.ServiceHoursLastYear; float? originalServiceHoursTwoYearsAgo = equipment.ServiceHoursTwoYearsAgo; float? originalServiceHoursThreeYearsAgo = equipment.ServiceHoursThreeYearsAgo; int? originalLocalAreaId = equipment.LocalAreaId; int? originalDistrictEquipmentTypeId = equipment.DistrictEquipmentTypeId; float? originalYearsOfService = equipment.YearsOfService; // check if we need to rework the equipment's seniority bool rebuildSeniority = (originalSeniorityEffectiveDate == null && item.SeniorityEffectiveDate != null) || (originalSeniorityEffectiveDate != null && item.SeniorityEffectiveDate != null && originalSeniorityEffectiveDate != item.SeniorityEffectiveDate); bool rebuildOldSeniority = false; if (originalLocalAreaId != item.LocalAreaId) { rebuildSeniority = true; rebuildOldSeniority = true; } if (originalDistrictEquipmentTypeId != item.DistrictEquipmentTypeId) { rebuildSeniority = true; rebuildOldSeniority = true; } if ((originalServiceHoursLastYear == null && item.ServiceHoursLastYear != null) || (originalServiceHoursLastYear != null && item.ServiceHoursLastYear != null && originalServiceHoursLastYear != item.ServiceHoursLastYear)) { rebuildSeniority = true; } if ((originalServiceHoursTwoYearsAgo == null && item.ServiceHoursTwoYearsAgo != null) || (originalServiceHoursTwoYearsAgo != null && item.ServiceHoursTwoYearsAgo != null && originalServiceHoursTwoYearsAgo != item.ServiceHoursTwoYearsAgo)) { rebuildSeniority = true; } if ((originalServiceHoursThreeYearsAgo == null && item.ServiceHoursThreeYearsAgo != null) || (originalServiceHoursThreeYearsAgo != null && item.ServiceHoursThreeYearsAgo != null && originalServiceHoursThreeYearsAgo != item.ServiceHoursThreeYearsAgo)) { rebuildSeniority = true; } if ((originalYearsOfService == null && item.YearsOfService != null) || (originalYearsOfService != null && item.YearsOfService != null && originalYearsOfService != item.YearsOfService)) { rebuildSeniority = true; } // HETS-1115 - Do not allow changing seniority affecting entities if an active request exists if (EquipmentHelper.RentalRequestStatus(id, _context) && rebuildSeniority) { return new BadRequestObjectResult(new HetsResponse("HETS-41", ErrorViewModel.GetDescription("HETS-41", _configuration))); } // update equipment record equipment.ConcurrencyControlNumber = item.ConcurrencyControlNumber; equipment.ApprovedDate = item.ApprovedDate; equipment.EquipmentCode = item.EquipmentCode; equipment.Make = item.Make; equipment.Model = item.Model; equipment.Operator = item.Operator; equipment.ReceivedDate = item.ReceivedDate; equipment.LicencePlate = item.LicencePlate; equipment.SerialNumber = item.SerialNumber; equipment.Size = item.Size; equipment.YearsOfService = item.YearsOfService; equipment.Year = item.Year; equipment.LastVerifiedDate = item.LastVerifiedDate; equipment.IsSeniorityOverridden = item.IsSeniorityOverridden; equipment.SeniorityOverrideReason = item.SeniorityOverrideReason; equipment.Type = item.Type; equipment.ServiceHoursLastYear = item.ServiceHoursLastYear; equipment.ServiceHoursTwoYearsAgo = item.ServiceHoursTwoYearsAgo; equipment.ServiceHoursThreeYearsAgo = item.ServiceHoursThreeYearsAgo; equipment.SeniorityEffectiveDate = item.SeniorityEffectiveDate; equipment.LicencedGvw = item.LicencedGvw; equipment.LegalCapacity = item.LegalCapacity; equipment.PupLegalCapacity = item.PupLegalCapacity; equipment.LocalAreaId = item.LocalArea.LocalAreaId; equipment.DistrictEquipmentTypeId = item.DistrictEquipmentTypeId; if (rebuildSeniority) { // update new area EquipmentHelper.RecalculateSeniority(item.LocalAreaId, item.DistrictEquipmentTypeId, _context, _configuration, equipment); // update old area if (rebuildOldSeniority) { EquipmentHelper.RecalculateSeniority((int)originalLocalAreaId, (int)originalDistrictEquipmentTypeId, _context, _configuration, equipment); } } _context.SaveChanges(); // retrieve updated equipment record to return to ui return new ObjectResult(new HetsResponse(_equipmentRepo.GetEquipment(id))); } [HttpPut] [Route("{id}/verifyactive")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<EquipmentDto> VerifyActive([FromRoute]int id) { var equipment = _context.HetEquipments.FirstOrDefault(a => a.EquipmentId == id); // not found if (equipment == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); equipment.LastVerifiedDate = DateTime.UtcNow; _context.SaveChanges(); return new ObjectResult(new HetsResponse(_equipmentRepo.GetEquipment(id))); } /// <summary> /// Update equipment status /// </summary> /// <param name="id">id of Equipment to update</param> /// <param name="item"></param> [HttpPut] [Route("{id}/status")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<EquipmentDto> EquipmentIdStatusPut([FromRoute]int id, [FromBody]EquipmentStatusDto item) { // not found if (item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // HETS-1115 - Do not allow changing seniority affecting entities if an active request exists if (EquipmentHelper.RentalRequestStatus(id, _context)) { return new BadRequestObjectResult(new HetsResponse("HETS-41", ErrorViewModel.GetDescription("HETS-41", _configuration))); } bool recalculateSeniority = false; // get record HetEquipment equipment = _context.HetEquipments .Include(x => x.EquipmentStatusType) .Include(x => x.LocalArea) .Include(x => x.DistrictEquipmentType) .ThenInclude(d => d.EquipmentType) .Include(x => x.Owner) .Include(x => x.HetEquipmentAttachments) .First(a => a.EquipmentId == id); // HETS-1069 - Do not allow an equipment whose Equipment type has been deleted to change status if (equipment.DistrictEquipmentType == null || equipment.DistrictEquipmentType.Deleted) { return new BadRequestObjectResult(new HetsResponse("HETS-39", ErrorViewModel.GetDescription("HETS-39", _configuration))); } // used for seniority recalculation int localAreaId = equipment.LocalArea.LocalAreaId; int districtEquipmentTypeId = equipment.DistrictEquipmentType.DistrictEquipmentTypeId; string oldStatus = equipment.EquipmentStatusType.EquipmentStatusTypeCode; // check the owner status int? ownStatusId = StatusHelper.GetStatusId(HetOwner.StatusApproved, "ownerStatus", _context); if (ownStatusId == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // update equipment status int? statusId = StatusHelper.GetStatusId(item.Status, "equipmentStatus", _context); if (statusId == null) return new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // can't make the status active if the owner is not active if (equipment.Owner.OwnerStatusTypeId != ownStatusId && item.Status == HetEquipment.StatusApproved) { return new ConflictObjectResult(new HetsResponse("HETS-28", ErrorViewModel.GetDescription("HETS-28", _configuration))); } equipment.EquipmentStatusTypeId = (int)statusId; equipment.Status = item.Status; equipment.StatusComment = item.StatusComment; if (equipment.Status.Equals(HetEquipment.StatusArchived)) { equipment.ArchiveCode = "Y"; equipment.ArchiveDate = DateTime.UtcNow; equipment.ArchiveReason = "Equipment Archived"; // recalculate seniority (move out of the block and adjust) recalculateSeniority = true; } else { equipment.ArchiveCode = "N"; equipment.ArchiveDate = null; equipment.ArchiveReason = null; // make sure the seniority is set when shifting to "Active" state // (if this was a new record with no block/seniority yet) if (equipment.BlockNumber == null && equipment.Seniority == null && equipment.Status.Equals(HetEquipment.StatusApproved)) { // per HETS-536 -> ignore and let the user set the "Approved Date" date // recalculation seniority (move into a block) recalculateSeniority = true; } else if ((oldStatus.Equals(HetEquipment.StatusApproved) && !equipment.Status.Equals(HetEquipment.StatusApproved)) || (!oldStatus.Equals(HetEquipment.StatusApproved) && equipment.Status.Equals(HetEquipment.StatusApproved))) { // recalculation seniority (move into or out of a block) recalculateSeniority = true; } } // HETS-1119 - Add change of status comments to Notes string statusNote = $"(Status changed to: {equipment.Status}) {equipment.StatusComment}"; HetNote note = new HetNote { EquipmentId = equipment.EquipmentId, Text = statusNote, IsNoLongerRelevant = false }; _context.HetNotes.Add(note); // recalculation seniority (if required) if (recalculateSeniority) { EquipmentHelper.RecalculateSeniority(localAreaId, districtEquipmentTypeId, _context, _configuration, equipment); } // save the changes _context.SaveChanges(); // retrieve updated equipment record to return to ui return new ObjectResult(new HetsResponse(_equipmentRepo.GetEquipment(id))); } /// <summary> /// Create equipment /// </summary> /// <param name="item"></param> [HttpPost] [Route("")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<EquipmentDto> EquipmentPost([FromBody]EquipmentDto item) { // not found if (item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // set default values for new piece of Equipment // certain fields are set on new record - set defaults (including status = "Inactive") var equipment = _equipmentRepo.CreateNewEquipment(item); // *********************************************************************************** // Calculate Years of Service for new record // *********************************************************************************** // Business Rules: // 1. When the equipment is added the years registered is set to a fraction of the // fiscal left from the registered date to the end of current fiscal // (decimals: 3 places) // 2. On roll over the years registered increments by one for each year the equipment // stays active ((might need use the TO_DATE field to track when last it was rolled over) // TO_DATE = END OF CURRENT FISCAL // determine end of current fiscal year DateTime fiscalEnd; if (DateTime.UtcNow.Month == 1 || DateTime.UtcNow.Month == 2 || DateTime.UtcNow.Month == 3) { fiscalEnd = new DateTime(DateTime.UtcNow.Year, 3, 31); } else { fiscalEnd = new DateTime(DateTime.UtcNow.AddYears(1).Year, 3, 31); } // is this a leap year? if (DateTime.IsLeapYear(fiscalEnd.Year)) { equipment.YearsOfService = (float)Math.Round((fiscalEnd - DateTime.UtcNow).TotalDays / 366, 3); } else { equipment.YearsOfService = (float)Math.Round((fiscalEnd - DateTime.UtcNow).TotalDays / 365, 3); } equipment.ToDate = fiscalEnd; // save record in order to recalculate seniority _context.HetEquipments.Add(equipment); using var transaction = _context.Database.BeginTransaction(); _context.SaveChanges(); // HETS-834 - BVT - New Equipment Added default to APPROVED // * (already Set to approved) // * Update all equipment blocks, etc. // recalculation seniority (if required) int? localAreaId = equipment.LocalAreaId; int? districtEquipmentTypeId = equipment.DistrictEquipmentTypeId; EquipmentHelper.RecalculateSeniority(localAreaId, districtEquipmentTypeId, _context, _configuration); // save the result of the seniority recalculation _context.SaveChanges(); transaction.Commit(); // retrieve updated equipment record to return to ui return new ObjectResult(new HetsResponse(_equipmentRepo.GetEquipment(equipment.EquipmentId))); } /// <summary> /// Recalculate Seniority List for the equipments with the same seniority and received date by equipment code /// </summary> /// <returns></returns> [HttpPost] [Route("recalculatesenioritylist")] [RequiresPermission(HetPermission.DistrictCodeTableManagement, HetPermission.WriteAccess)] public virtual IActionResult RecalculateSeniorityListPost() { IConfigurationSection scoringRules = _configuration.GetSection("SeniorityScoringRules"); string seniorityScoringRules = GetConfigJson(scoringRules); // queue the job BackgroundJob.Enqueue<SeniorityCalculator>(x => x.RecalculateSeniorityList(seniorityScoringRules)); // return ok return new ObjectResult(new HetsResponse("Recalculate job added to hangfire")); } #region Get Scoring Rules private string GetConfigJson(IConfigurationSection scoringRules) { string jsonString = RecurseConfigJson(scoringRules); if (jsonString.EndsWith("},")) { jsonString = jsonString.Substring(0, jsonString.Length - 1); } return jsonString; } private string RecurseConfigJson(IConfigurationSection scoringRules) { StringBuilder temp = new StringBuilder(); temp.Append("{"); // check for children foreach (IConfigurationSection section in scoringRules.GetChildren()) { temp.Append(@"""" + section.Key + @"""" + ":"); if (section.Value == null) { temp.Append(RecurseConfigJson(section)); } else { temp.Append(@"""" + section.Value + @"""" + ","); } } string jsonString = temp.ToString(); if (jsonString.EndsWith(",")) { jsonString = jsonString.Substring(0, jsonString.Length - 1); } jsonString = jsonString + "},"; return jsonString; } #endregion #region Equipment Search /// <summary> /// Search Equipment /// </summary> /// <remarks>Used for the equipment search page.</remarks> /// <param name="localAreas">Local Areas (comma separated list of id numbers)</param> /// <param name="types">Equipment Types (comma separated list of id numbers)</param> /// <param name="equipmentAttachment">Searches equipmentAttachment type</param> /// <param name="owner"></param> /// <param name="status">Status</param> /// <param name="hired">Hired</param> /// <param name="notVerifiedSinceDate">Not Verified Since Date</param> /// <param name="equipmentId">Equipment Code</param> /// <param name="ownerName"></param> /// <param name="projectName"></param> /// <param name="twentyYears"></param> [HttpGet] [Route("search")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<EquipmentLiteDto> EquipmentSearchGet([FromQuery]string localAreas, [FromQuery]string types, [FromQuery]string equipmentAttachment, [FromQuery]int? owner, [FromQuery]string status, [FromQuery]bool? hired, [FromQuery]DateTime? notVerifiedSinceDate, [FromQuery]string equipmentId = null, [FromQuery]string ownerName = null, [FromQuery]string projectName = null, [FromQuery]bool twentyYears = false) { int?[] localAreasArray = ArrayHelper.ParseIntArray(localAreas); int?[] typesArray = ArrayHelper.ParseIntArray(types); // get agreement status int? agreementStatusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (agreementStatusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get initial results - must be limited to user's district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); IQueryable<HetEquipment> data = _context.HetEquipments.AsNoTracking() .Include(x => x.LocalArea) .Include(x => x.DistrictEquipmentType) .ThenInclude(y => y.EquipmentType) .Include(x => x.Owner) .Include(x => x.HetEquipmentAttachments) .Include(x => x.HetRentalAgreements) .ThenInclude(y => y.RentalAgreementStatusType) .Include(x => x.EquipmentStatusType) .Where(x => x.LocalArea.ServiceArea.DistrictId.Equals(districtId)); // filter results based on search criteria if (localAreasArray != null && localAreasArray.Length > 0) { data = data.Where(x => localAreasArray.Contains(x.LocalArea.LocalAreaId)); } if (equipmentAttachment != null) { data = data.Where(x => x.HetEquipmentAttachments .Any(y => y.TypeName.ToLower().Contains(equipmentAttachment.ToLower()))); } if (owner != null) { data = data.Where(x => x.Owner.OwnerId == owner); } if (ownerName != null) { data = data.Where(x => x.Owner.OrganizationName.ToLower().Contains(ownerName.ToLower()) || x.Owner.DoingBusinessAs.ToLower().Contains(ownerName.ToLower()) ); } if (status != null) { int? statusId = StatusHelper.GetStatusId(status, "equipmentStatus", _context); if (statusId != null) { data = data.Where(x => x.EquipmentStatusTypeId == statusId); } } if (projectName != null) { IQueryable<int?> hiredEquipmentQuery = _context.HetRentalAgreements.AsNoTracking() .Where(x => x.Equipment.LocalArea.ServiceArea.DistrictId.Equals(districtId)) .Where(agreement => agreement.RentalAgreementStatusTypeId == agreementStatusId) .Select(agreement => agreement.EquipmentId) .Distinct(); data = data.Where(e => hiredEquipmentQuery.Contains(e.EquipmentId)); data = data.Where(x => x.HetRentalAgreements .Any(y => y.Project.Name.ToLower().Contains(projectName.ToLower()))); } else if (hired == true) { IQueryable<int?> hiredEquipmentQuery = _context.HetRentalAgreements.AsNoTracking() .Where(x => x.Equipment.LocalArea.ServiceArea.DistrictId.Equals(districtId)) .Where(agreement => agreement.RentalAgreementStatusTypeId == agreementStatusId) .Select(agreement => agreement.EquipmentId) .Distinct(); data = data.Where(e => hiredEquipmentQuery.Contains(e.EquipmentId)); } if (typesArray != null && typesArray.Length > 0) { data = data.Where(x => typesArray.Contains(x.DistrictEquipmentType.DistrictEquipmentTypeId)); } if (notVerifiedSinceDate != null) { data = data.Where(x => x.LastVerifiedDate < notVerifiedSinceDate); } // Ministry refer to the EquipmentCode as the "equipmentId" - its not the db id if (equipmentId != null) { data = data.Where(x => x.EquipmentCode.ToLower().Contains(equipmentId.ToLower())); } // convert Equipment Model to the "EquipmentLite" Model SeniorityScoringRules scoringRules = new SeniorityScoringRules(_configuration); List<EquipmentLiteDto> result = new List<EquipmentLiteDto>(); var dataList = data.ToList(); // HETS-942 - Search for Equipment > 20 yrs // ** only return equipment that are 20 years and older (using the equipment Year) if (twentyYears) { var twentyYearsInt = DateTime.Now.Year - 20; dataList = dataList.Where(x => string.IsNullOrWhiteSpace(x.Year) || int.Parse(x.Year) <= twentyYearsInt) .ToList(); } foreach (HetEquipment item in dataList) { result.Add(EquipmentHelper.ToLiteModel(item, scoringRules, (int)agreementStatusId, _context)); } // return to the client return new ObjectResult(new HetsResponse(result)); } #endregion #region Clone Project Agreements /// <summary> /// Get rental agreements associated with an equipment id /// </summary> /// <remarks>Gets as Equipment's Rental Agreements</remarks> /// <param name="id">id of Equipment to fetch agreements for</param> [HttpGet] [Route("{id}/rentalAgreements")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<RentalAgreementDto>> EquipmentIdRentalAgreementsGet([FromRoute]int id) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); List<HetRentalAgreement> agreements = _context.HetRentalAgreements.AsNoTracking() .Include(x => x.Equipment) .ThenInclude(d => d.DistrictEquipmentType) .Include(e => e.Equipment) .ThenInclude(a => a.HetEquipmentAttachments) .Include(e => e.Project) .Where(x => x.EquipmentId == id) .ToList(); // remove all of the additional agreements being returned foreach (HetRentalAgreement agreement in agreements) { agreement.Project.HetRentalAgreements = null; } return new ObjectResult(new HetsResponse(_mapper.Map<List<RentalAgreementDto>>(agreements))); } /// <summary> /// Update a rental agreement by cloning a previous equipment rental agreement /// </summary> /// <param name="id">Project id</param> /// <param name="item"></param> [HttpPost] [Route("{id}/rentalAgreementClone")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<RentalAgreementDto> EquipmentRentalAgreementClonePost([FromRoute]int id, [FromBody]EquipmentRentalAgreementClone item) { // not found if (item == null || id != item.EquipmentId) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // get all agreements for this equipment List<HetRentalAgreement> agreements = _context.HetRentalAgreements .Include(x => x.Equipment) .ThenInclude(d => d.DistrictEquipmentType) .Include(e => e.Equipment) .ThenInclude(a => a.HetEquipmentAttachments) .Include(x => x.HetRentalAgreementRates) .Include(x => x.HetRentalAgreementConditions) .Include(x => x.HetTimeRecords) .Where(x => x.EquipmentId == id) .ToList(); // check that the rental agreements exists (that we want) exists = agreements.Any(a => a.RentalAgreementId == item.RentalAgreementId); // (RENTAL AGREEMENT) not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // check that the rental agreement to clone exist exists = agreements.Any(a => a.RentalAgreementId == item.AgreementToCloneId); // (RENTAL AGREEMENT) not found if (!exists) return new BadRequestObjectResult(new HetsResponse("HETS-11", ErrorViewModel.GetDescription("HETS-11", _configuration))); // get ids int agreementToCloneIndex = agreements.FindIndex(a => a.RentalAgreementId == item.AgreementToCloneId); int newRentalAgreementIndex = agreements.FindIndex(a => a.RentalAgreementId == item.RentalAgreementId); // ****************************************************************** // Business Rules in the backend: // * Can't clone into an Agreement if it isn't Active // * Can't clone into an Agreement if it has existing time records // ****************************************************************** int? statusId = StatusHelper.GetStatusId(HetRentalAgreement.StatusActive, "rentalAgreementStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); if (agreements[newRentalAgreementIndex].RentalAgreementStatusTypeId != statusId) { // (RENTAL AGREEMENT) is not active return new BadRequestObjectResult(new HetsResponse("HETS-12", ErrorViewModel.GetDescription("HETS-12", _configuration))); } if (agreements[newRentalAgreementIndex].HetTimeRecords != null && agreements[newRentalAgreementIndex].HetTimeRecords.Count > 0) { // (RENTAL AGREEMENT) has time records return new BadRequestObjectResult(new HetsResponse("HETS-13", ErrorViewModel.GetDescription("HETS-13", _configuration))); } // ****************************************************************** // clone agreement // ****************************************************************** agreements[newRentalAgreementIndex].AgreementCity = agreements[agreementToCloneIndex].AgreementCity; agreements[newRentalAgreementIndex].EquipmentRate = agreements[agreementToCloneIndex].EquipmentRate; agreements[newRentalAgreementIndex].Note = agreements[agreementToCloneIndex].Note; agreements[newRentalAgreementIndex].RateComment = agreements[agreementToCloneIndex].RateComment; agreements[newRentalAgreementIndex].RatePeriodTypeId = agreements[agreementToCloneIndex].RatePeriodTypeId; // update rates agreements[newRentalAgreementIndex].HetRentalAgreementRates = null; foreach (HetRentalAgreementRate rate in agreements[agreementToCloneIndex].HetRentalAgreementRates) { HetRentalAgreementRate temp = new HetRentalAgreementRate { RentalAgreementId = id, Comment = rate.Comment, ComponentName = rate.ComponentName, Rate = rate.Rate, Set = rate.Set, Overtime = rate.Overtime, Active = rate.Active, IsIncludedInTotal = rate.IsIncludedInTotal, RatePeriodTypeId = rate.RatePeriodTypeId }; if (agreements[newRentalAgreementIndex].HetRentalAgreementRates == null) { agreements[newRentalAgreementIndex].HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreements[newRentalAgreementIndex].HetRentalAgreementRates.Add(temp); } // update overtime rates (and add if they don't exist) List<HetProvincialRateType> overtime = _context.HetProvincialRateTypes.AsNoTracking() .Where(x => x.Overtime) .ToList(); foreach (HetProvincialRateType overtimeRate in overtime) { bool found = false; if (agreements[newRentalAgreementIndex] != null && agreements[newRentalAgreementIndex].HetRentalAgreementRates != null) { found = agreements[newRentalAgreementIndex].HetRentalAgreementRates.Any(x => x.ComponentName == overtimeRate.RateType); } if (found) { HetRentalAgreementRate rate = agreements[newRentalAgreementIndex].HetRentalAgreementRates .First(x => x.ComponentName == overtimeRate.RateType); rate.Rate = overtimeRate.Rate; } else { HetRentalAgreementRate newRate = new HetRentalAgreementRate { RentalAgreementId = id, Comment = overtimeRate.Description, Rate = overtimeRate.Rate, ComponentName = overtimeRate.RateType, Active = overtimeRate.Active, IsIncludedInTotal = overtimeRate.IsIncludedInTotal, Overtime = overtimeRate.Overtime }; if (agreements[newRentalAgreementIndex].HetRentalAgreementRates == null) { agreements[newRentalAgreementIndex].HetRentalAgreementRates = new List<HetRentalAgreementRate>(); } agreements[newRentalAgreementIndex].HetRentalAgreementRates.Add(newRate); } } // remove non-existent overtime rates List<string> remove = (from overtimeRate in agreements[newRentalAgreementIndex].HetRentalAgreementRates.ToList() where overtimeRate.Overtime ?? false let found = overtime.Any(x => x.RateType == overtimeRate.ComponentName) where !found select overtimeRate.ComponentName).ToList(); if (remove.Count > 0 && agreements[newRentalAgreementIndex] != null && agreements[newRentalAgreementIndex].HetRentalAgreementRates != null) { foreach (string component in remove) { agreements[newRentalAgreementIndex].HetRentalAgreementRates.Remove( agreements[newRentalAgreementIndex].HetRentalAgreementRates.First(x => x.ComponentName == component)); } } // update conditions agreements[newRentalAgreementIndex].HetRentalAgreementConditions = null; foreach (HetRentalAgreementCondition condition in agreements[agreementToCloneIndex].HetRentalAgreementConditions) { HetRentalAgreementCondition temp = new HetRentalAgreementCondition { Comment = condition.Comment, ConditionName = condition.ConditionName }; if (agreements[newRentalAgreementIndex].HetRentalAgreementConditions == null) { agreements[newRentalAgreementIndex].HetRentalAgreementConditions = new List<HetRentalAgreementCondition>(); } agreements[newRentalAgreementIndex].HetRentalAgreementConditions.Add(temp); } // save the changes _context.SaveChanges(); // ****************************************************************** // return updated rental agreement to update the screen // ****************************************************************** return new ObjectResult(new HetsResponse(_rentalAgreementRepo.GetRecord(item.RentalAgreementId))); } #endregion #region Duplicate Equipment Records /// <summary> /// Get all duplicate equipment records /// </summary> /// <param name="id">id of Equipment to fetch duplicates for</param> /// <param name="serialNumber"></param> /// <param name="typeId">District Equipment Type Id</param> [HttpGet] [Route("{id}/duplicates/{serialNumber}/{typeId?}")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<DuplicateEquipmentDto>> EquipmentIdEquipmentDuplicatesGet([FromRoute]int id, [FromRoute]string serialNumber, [FromRoute]int? typeId) { bool exists = _context.HetEquipments.Any(x => x.EquipmentId == id); // not found [id > 0 -> need to allow for new records too] if (!exists && id > 0) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // HETS-845 - Verify Duplicate serial # functionality // Validate among the following: // * Same equipment types // * Among approved equipment // get status id int? statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get equipment duplicates List<HetEquipment> equipmentDuplicates; if (typeId != null && typeId > 0) { HetDistrictEquipmentType equipmentType = _context.HetDistrictEquipmentTypes.AsNoTracking() .Include(x => x.EquipmentType) .FirstOrDefault(x => x.DistrictEquipmentTypeId == typeId); int? equipmentTypeId = equipmentType?.EquipmentTypeId; // get equipment duplicates equipmentDuplicates = _context.HetEquipments.AsNoTracking() .Include(x => x.LocalArea.ServiceArea.District) .Include(x => x.Owner) .Include(x => x.DistrictEquipmentType) .Where(x => x.SerialNumber.ToLower() == serialNumber.ToLower() && x.EquipmentId != id && x.DistrictEquipmentType.EquipmentTypeId == equipmentTypeId && x.EquipmentStatusTypeId == statusId) .ToList(); } else { equipmentDuplicates = _context.HetEquipments.AsNoTracking() .Include(x => x.LocalArea.ServiceArea.District) .Include(x => x.Owner) .Include(x => x.DistrictEquipmentType) .Where(x => x.SerialNumber.ToLower() == serialNumber.ToLower() && x.EquipmentId != id && x.EquipmentStatusTypeId == statusId) .ToList(); } List<DuplicateEquipmentDto> duplicates = new List<DuplicateEquipmentDto>(); int idCount = -1; foreach (HetEquipment equipment in equipmentDuplicates) { idCount++; DuplicateEquipmentDto duplicate = new DuplicateEquipmentDto { Id = idCount, SerialNumber = serialNumber, DuplicateEquipment = _mapper.Map<EquipmentDto>(equipment), DistrictName = "" }; if (equipment.LocalArea.ServiceArea.District != null && !string.IsNullOrEmpty(equipment.LocalArea.ServiceArea.District.Name)) { duplicate.DistrictName = equipment.LocalArea.ServiceArea.District.Name; } duplicates.Add(duplicate); } // return to the client return new ObjectResult(new HetsResponse(duplicates)); } #endregion #region Equipment Attachment Records /// <summary> /// Get all equipment attachments for an equipment record /// </summary> /// <param name="id">id of Equipment to fetch EquipmentAttachments for</param> [HttpGet] [Route("{id}/equipmentAttachments")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<EquipmentAttachmentDto>> EquipmentIdEquipmentAttachmentsGet([FromRoute]int id) { bool exists = _context.HetEquipments.Any(x => x.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); List<HetEquipmentAttachment> attachments = _context.HetEquipmentAttachments.AsNoTracking() .Include(x => x.Equipment) .Where(x => x.Equipment.EquipmentId == id) .ToList(); return new ObjectResult(new HetsResponse(_mapper.Map<List<EquipmentAttachmentDto>>( attachments))); } #endregion #region Attachments /// <summary> /// Get all attachments associated with an equipment record /// </summary> /// <remarks>Returns attachments for a particular Equipment</remarks> /// <param name="id">id of Equipment to fetch attachments for</param> [HttpGet] [Route("{id}/attachments")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<DigitalFileDto>> EquipmentIdAttachmentsGet([FromRoute]int id) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetEquipment equipment = _context.HetEquipments.AsNoTracking() .Include(x => x.HetDigitalFiles) .First(a => a.EquipmentId == id); // extract the attachments and update properties for UI List<HetDigitalFile> attachments = new List<HetDigitalFile>(); foreach (HetDigitalFile attachment in equipment.HetDigitalFiles) { if (attachment != null) { attachment.FileSize = attachment.FileContents.Length; attachment.LastUpdateTimestamp = attachment.AppLastUpdateTimestamp; attachment.LastUpdateUserid = attachment.AppLastUpdateUserid; // don't send the file content attachment.FileContents = null; attachment.UserName = UserHelper.GetUserName(attachment.LastUpdateUserid, _context); attachments.Add(attachment); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<DigitalFileDto>>(attachments))); } #endregion #region Equipment History Records /// <summary> /// Get equipment history /// </summary> /// <remarks>Returns History for a particular Equipment</remarks> /// <param name="id">id of Equipment to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> [HttpGet] [Route("{id}/history")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<History>> EquipmentIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); return new ObjectResult(new HetsResponse(EquipmentHelper.GetHistoryRecords(id, offset, limit, _context))); } /// <summary> /// Create equipment history /// </summary> /// <remarks>Add a History record to the Equipment</remarks> /// <param name="id">id of Equipment to add History for</param> /// <param name="item"></param> [HttpPost] [Route("{id}/history")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<History>> EquipmentIdHistoryPost([FromRoute]int id, [FromBody]History item) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); if (exists) { HetHistory history = new HetHistory { HistoryId = 0, HistoryText = item.HistoryText, CreatedDate = DateTime.UtcNow, EquipmentId = id }; _context.HetHistories.Add(history); _context.SaveChanges(); } return new ObjectResult(new HetsResponse(EquipmentHelper.GetHistoryRecords(id, null, null, _context))); } #endregion #region Equipment Note Records /// <summary> /// Get note records associated with equipment /// </summary> /// <param name="id">id of Equipment to fetch Notes for</param> [HttpGet] [Route("{id}/notes")] [RequiresPermission(HetPermission.Login)] public virtual ActionResult<List<NoteDto>> EquipmentIdNotesGet([FromRoute]int id) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); HetEquipment equipment = _context.HetEquipments.AsNoTracking() .Include(x => x.HetNotes) .First(x => x.EquipmentId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in equipment.HetNotes) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes))); } /// <summary> /// Update or create a note associated with equipment /// </summary> /// <remarks>Update a Equipment&#39;s Notes</remarks> /// <param name="id">id of Equipment to update Notes for</param> /// <param name="item">Equipment Note</param> [HttpPost] [Route("{id}/note")] [RequiresPermission(HetPermission.Login, HetPermission.WriteAccess)] public virtual ActionResult<List<NoteDto>> EquipmentIdNotePost([FromRoute]int id, [FromBody]NoteDto item) { bool exists = _context.HetEquipments.Any(a => a.EquipmentId == id); // not found if (!exists || item == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); // add or update note if (item.NoteId > 0) { // get note HetNote note = _context.HetNotes.FirstOrDefault(a => a.NoteId == item.NoteId); // not found if (note == null) return new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))); note.ConcurrencyControlNumber = item.ConcurrencyControlNumber; note.Text = item.Text; note.IsNoLongerRelevant = item.IsNoLongerRelevant; } else // add note { HetNote note = new HetNote { EquipmentId = id, Text = item.Text, IsNoLongerRelevant = item.IsNoLongerRelevant }; _context.HetNotes.Add(note); } _context.SaveChanges(); // return updated note records HetEquipment equipment = _context.HetEquipments.AsNoTracking() .Include(x => x.HetNotes) .First(x => x.EquipmentId == id); List<HetNote> notes = new List<HetNote>(); foreach (HetNote note in equipment.HetNotes) { if (note.IsNoLongerRelevant == false) { notes.Add(note); } } return new ObjectResult(new HetsResponse(_mapper.Map<List<NoteDto>>(notes))); } #endregion #region Seniority List Doc /// <summary> /// Get an openXml version of the seniority list /// </summary> /// <remarks>Returns an openXml version of the seniority list</remarks> /// <param name="localAreas">Local Areas (comma separated list of id numbers)</param> /// <param name="types">Equipment Types (comma separated list of id numbers)</param> /// <param name="counterCopy">If true, use the Counter Copy template</param> [HttpGet] [Route("seniorityListDoc")] [RequiresPermission(HetPermission.Login)] public virtual IActionResult EquipmentSeniorityListDocGet([FromQuery]string localAreas, [FromQuery]string types, [FromQuery]bool counterCopy = false) { int?[] localAreasArray = ArrayHelper.ParseIntArray(localAreas); int?[] typesArray = ArrayHelper.ParseIntArray(types); // get users district int? districtId = UserAccountHelper.GetUsersDistrictId(_context); // get fiscal year HetDistrictStatus districtStatus = _context.HetDistrictStatuses.AsNoTracking() .FirstOrDefault(x => x.DistrictId == districtId); if (districtStatus?.NextFiscalYear == null) return new BadRequestObjectResult(new HetsResponse("HETS-30", ErrorViewModel.GetDescription("HETS-30", _configuration))); //// HETS-1195: Adjust seniority list and rotation list for lists hired between Apr1 and roll over //// ** Need to use the "rollover date" to ensure we don't include records created //// after April 1 (but before rollover) //DateTime fiscalEnd = district.RolloverEndDate ?? new DateTime(0001, 01, 01, 00, 00, 00); //int fiscalYear = Convert.ToInt32(district.NextFiscalYear); // status table uses the start of the year //fiscalEnd = fiscalEnd == new DateTime(0001, 01, 01, 00, 00, 00) ? // new DateTime(fiscalYear, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59) : // new DateTime(fiscalYear, fiscalEnd.Month, fiscalEnd.Day, 23, 59, 59); DateTime fiscalStart = districtStatus.RolloverEndDate ?? new DateTime(0001, 01, 01, 00, 00, 00); int fiscalYear = Convert.ToInt32(districtStatus.NextFiscalYear); if (fiscalStart == new DateTime(0001, 01, 01, 00, 00, 00)) { fiscalYear = Convert.ToInt32(districtStatus.NextFiscalYear); // status table uses the start of the year fiscalStart = new DateTime(fiscalYear - 1, 4, 1); } // get status id int? statusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", _context); if (statusId == null) return new BadRequestObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))); // get equipment record IQueryable<HetEquipment> data = _context.HetEquipments.AsNoTracking() .Include(x => x.LocalArea) .ThenInclude(y => y.ServiceArea) .ThenInclude(z => z.District) .Include(x => x.DistrictEquipmentType) .ThenInclude(y => y.EquipmentType) .Include(x => x.Owner) .Include(x => x.HetRentalAgreements) .Where(x => x.LocalArea.ServiceArea.DistrictId.Equals(districtId) && x.EquipmentStatusTypeId.Equals(statusId)) .OrderBy(x => x.LocalArea.Name) .ThenBy(x => x.DistrictEquipmentType.DistrictEquipmentName) .ThenBy(x => x.BlockNumber) .ThenByDescending(x => x.NumberInBlock); if (localAreasArray != null && localAreasArray.Length > 0) { data = data.Where(x => localAreasArray.Contains(x.LocalArea.LocalAreaId)); } if (typesArray != null && typesArray.Length > 0) { data = data.Where(x => typesArray.Contains(x.DistrictEquipmentType.DistrictEquipmentTypeId)); } // ********************************************************************** // determine the year header values // * use the district status table // ********************************************************************** string yearMinus1 = $"{fiscalYear - 2}/{fiscalYear - 1}"; string yearMinus2 = $"{fiscalYear - 3}/{fiscalYear - 2}"; string yearMinus3 = $"{fiscalYear - 4}/{fiscalYear - 3}"; // ********************************************************************** // convert Equipment Model to Pdf View Model // ********************************************************************** SeniorityListReportViewModel seniorityList = new SeniorityListReportViewModel(); SeniorityScoringRules scoringRules = new SeniorityScoringRules(_configuration); SeniorityListRecord listRecord = new SeniorityListRecord(); // manage the rotation list data int lastCalledEquipmentId = 0; int currentBlock = -1; var items = data.ToList(); foreach (HetEquipment item in items) { if (listRecord.LocalAreaName != item.LocalArea.Name || listRecord.DistrictEquipmentTypeName != item.DistrictEquipmentType.DistrictEquipmentName) { if (!string.IsNullOrEmpty(listRecord.LocalAreaName)) { if (seniorityList.SeniorityListRecords == null) { seniorityList.SeniorityListRecords = new List<SeniorityListRecord>(); } seniorityList.SeniorityListRecords.Add(listRecord); } listRecord = new SeniorityListRecord { LocalAreaName = item.LocalArea.Name, DistrictEquipmentTypeName = item.DistrictEquipmentType.DistrictEquipmentName, YearMinus1 = yearMinus1, YearMinus2 = yearMinus2, YearMinus3 = yearMinus3, SeniorityList = new List<SeniorityViewModel>() }; if (item.LocalArea.ServiceArea?.District != null) { listRecord.DistrictName = item.LocalArea.ServiceArea.District.Name; } // get the rotation info for the first block if (item.BlockNumber != null) currentBlock = (int) item.BlockNumber; lastCalledEquipmentId = GetLastCalledEquipmentId(item.LocalArea.LocalAreaId, item.DistrictEquipmentType.DistrictEquipmentTypeId, currentBlock, fiscalStart); } else if (item.BlockNumber != null && currentBlock != item.BlockNumber) { // get the rotation info for the next block currentBlock = (int)item.BlockNumber; lastCalledEquipmentId = GetLastCalledEquipmentId(item.LocalArea.LocalAreaId, item.DistrictEquipmentType.DistrictEquipmentTypeId, currentBlock, fiscalStart); } listRecord.SeniorityList.Add(SeniorityListHelper.ToSeniorityViewModel(item, scoringRules, lastCalledEquipmentId, _context)); } // add last record if (!string.IsNullOrEmpty(listRecord.LocalAreaName)) { if (seniorityList.SeniorityListRecords == null) { seniorityList.SeniorityListRecords = new List<SeniorityListRecord>(); } seniorityList.SeniorityListRecords.Add(listRecord); } // sort seniority lists if (seniorityList.SeniorityListRecords != null) { foreach (SeniorityListRecord list in seniorityList.SeniorityListRecords) { list.SeniorityList = list.SeniorityList.OrderBy(x => x.SenioritySortOrder).ToList(); } } // classification, print date, type (counterCopy or Year to Date) seniorityList.Classification = $"23010-22/{(fiscalYear - 1).ToString().Substring(2, 2)}-{fiscalYear.ToString().Substring(2, 2)}"; seniorityList.GeneratedOn = $"{DateUtils.ConvertUtcToPacificTime(DateTime.UtcNow):dd-MM-yyyy H:mm:ss}"; seniorityList.SeniorityListType = counterCopy ? "Counter-Copy" : "Year-to-Date"; // convert to open xml document string documentName = $"SeniorityList-{DateTime.Now:yyyy-MM-dd}{(counterCopy ? "-(CounterCopy)" : "")}.docx"; byte[] document = SeniorityList.GetSeniorityList(seniorityList, documentName, counterCopy); // return document FileContentResult result = new FileContentResult(document, "application/vnd.openxmlformats-officedocument.wordprocessingml.document") { FileDownloadName = documentName }; Response.Headers.Add("Content-Disposition", "inline; filename=" + documentName); return result; } private int GetLastCalledEquipmentId(int localAreaId, int districtEquipmentTypeId, int currentBlock, DateTime fiscalStart) { try { // HETS-824 = BVT - Corrections to Seniority List PDF // * This column should contain "Y" against the equipment that // last responded (whether Yes/No) in a block // * For "Forced Hire" there will be no changes to this // column in the seniority list (as if nothing happened and nobody got called) // * Must be this fiscal year HetRentalRequestRotationList blockRotation = _context.HetRentalRequestRotationLists.AsNoTracking() .Include(x => x.Equipment) .Include(x => x.RentalRequest) .OrderByDescending(x => x.RentalRequestId).ThenByDescending(x => x.RotationListSortOrder) .FirstOrDefault(x => x.RentalRequest.DistrictEquipmentTypeId == districtEquipmentTypeId && x.RentalRequest.LocalAreaId == localAreaId && x.RentalRequest.AppCreateTimestamp >= fiscalStart && x.Equipment.BlockNumber == currentBlock && x.WasAsked == true && x.IsForceHire != true); return blockRotation == null ? 0 : (int)blockRotation.EquipmentId; } catch (Exception e) { Console.WriteLine(e); throw; } } #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 System.Text; using Thrift.Transport; namespace Thrift.Protocol { public class TBinaryProtocol : TProtocol { protected const uint VERSION_MASK = 0xffff0000; protected const uint VERSION_1 = 0x80010000; protected bool strictRead_ = false; protected bool strictWrite_ = true; protected int readLength_; protected bool checkReadLength_ = false; #region BinaryProtocol Factory /** * Factory */ public class Factory : TProtocolFactory { protected bool strictRead_ = false; protected bool strictWrite_ = true; public Factory() :this(false, true) { } public Factory(bool strictRead, bool strictWrite) { strictRead_ = strictRead; strictWrite_ = strictWrite; } public TProtocol GetProtocol(TTransport trans) { return new TBinaryProtocol(trans, strictRead_, strictWrite_); } } #endregion public TBinaryProtocol(TTransport trans) : this(trans, false, true) { } public TBinaryProtocol(TTransport trans, bool strictRead, bool strictWrite) :base(trans) { strictRead_ = strictRead; strictWrite_ = strictWrite; } #region Write Methods public override void WriteMessageBegin(TMessage message) { if (strictWrite_) { uint version = VERSION_1 | (uint)(message.Type); WriteI32((int)version); WriteString(message.Name); WriteI32(message.SeqID); } else { WriteString(message.Name); WriteByte((byte)message.Type); WriteI32(message.SeqID); } } public override void WriteMessageEnd() { } public override void WriteStructBegin(TStruct struc) { } public override void WriteStructEnd() { } public override void WriteFieldBegin(TField field) { WriteByte((byte)field.Type); WriteI16(field.ID); } public override void WriteFieldEnd() { } public override void WriteFieldStop() { WriteByte((byte)TType.Stop); } public override void WriteMapBegin(TMap map) { WriteByte((byte)map.KeyType); WriteByte((byte)map.ValueType); WriteI32(map.Count); } public override void WriteMapEnd() { } public override void WriteListBegin(TList list) { WriteByte((byte)list.ElementType); WriteI32(list.Count); } public override void WriteListEnd() { } public override void WriteSetBegin(TSet set) { WriteByte((byte)set.ElementType); WriteI32(set.Count); } public override void WriteSetEnd() { } public override void WriteBool(bool b) { WriteByte(b ? (byte)1 : (byte)0); } private byte[] bout = new byte[1]; public override void WriteByte(byte b) { bout[0] = b; trans.Write(bout, 0, 1); } private byte[] i16out = new byte[2]; public override void WriteI16(short s) { i16out[0] = (byte)(0xff & (s >> 8)); i16out[1] = (byte)(0xff & s); trans.Write(i16out, 0, 2); } private byte[] i32out = new byte[4]; public override void WriteI32(int i32) { i32out[0] = (byte)(0xff & (i32 >> 24)); i32out[1] = (byte)(0xff & (i32 >> 16)); i32out[2] = (byte)(0xff & (i32 >> 8)); i32out[3] = (byte)(0xff & i32); trans.Write(i32out, 0, 4); } private byte[] i64out = new byte[8]; public override void WriteI64(long i64) { i64out[0] = (byte)(0xff & (i64 >> 56)); i64out[1] = (byte)(0xff & (i64 >> 48)); i64out[2] = (byte)(0xff & (i64 >> 40)); i64out[3] = (byte)(0xff & (i64 >> 32)); i64out[4] = (byte)(0xff & (i64 >> 24)); i64out[5] = (byte)(0xff & (i64 >> 16)); i64out[6] = (byte)(0xff & (i64 >> 8)); i64out[7] = (byte)(0xff & i64); trans.Write(i64out, 0, 8); } public override void WriteDouble(double d) { WriteI64(BitConverter.DoubleToInt64Bits(d)); } public override void WriteBinary(byte[] b) { WriteI32(b.Length); trans.Write(b, 0, b.Length); } #endregion #region ReadMethods public override TMessage ReadMessageBegin() { TMessage message = new TMessage(); int size = ReadI32(); if (size < 0) { uint version = (uint)size & VERSION_MASK; if (version != VERSION_1) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Bad version in ReadMessageBegin: " + version); } message.Type = (TMessageType)(size & 0x000000ff); message.Name = ReadString(); message.SeqID = ReadI32(); } else { if (strictRead_) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Missing version in readMessageBegin, old client?"); } message.Name = ReadStringBody(size); message.Type = (TMessageType)ReadByte(); message.SeqID = ReadI32(); } return message; } public override void ReadMessageEnd() { } public override TStruct ReadStructBegin() { return new TStruct(); } public override void ReadStructEnd() { } public override TField ReadFieldBegin() { TField field = new TField(); field.Type = (TType)ReadByte(); if (field.Type != TType.Stop) { field.ID = ReadI16(); } return field; } public override void ReadFieldEnd() { } public override TMap ReadMapBegin() { TMap map = new TMap(); map.KeyType = (TType)ReadByte(); map.ValueType = (TType)ReadByte(); map.Count = ReadI32(); return map; } public override void ReadMapEnd() { } public override TList ReadListBegin() { TList list = new TList(); list.ElementType = (TType)ReadByte(); list.Count = ReadI32(); return list; } public override void ReadListEnd() { } public override TSet ReadSetBegin() { TSet set = new TSet(); set.ElementType = (TType)ReadByte(); set.Count = ReadI32(); return set; } public override void ReadSetEnd() { } public override bool ReadBool() { return ReadByte() == 1; } private byte[] bin = new byte[1]; public override byte ReadByte() { ReadAll(bin, 0, 1); return bin[0]; } private byte[] i16in = new byte[2]; public override short ReadI16() { ReadAll(i16in, 0, 2); return (short)(((i16in[0] & 0xff) << 8) | ((i16in[1] & 0xff))); } private byte[] i32in = new byte[4]; public override int ReadI32() { ReadAll(i32in, 0, 4); return (int)(((i32in[0] & 0xff) << 24) | ((i32in[1] & 0xff) << 16) | ((i32in[2] & 0xff) << 8) | ((i32in[3] & 0xff))); } private byte[] i64in = new byte[8]; public override long ReadI64() { ReadAll(i64in, 0, 8); return (long)(((long)(i64in[0] & 0xff) << 56) | ((long)(i64in[1] & 0xff) << 48) | ((long)(i64in[2] & 0xff) << 40) | ((long)(i64in[3] & 0xff) << 32) | ((long)(i64in[4] & 0xff) << 24) | ((long)(i64in[5] & 0xff) << 16) | ((long)(i64in[6] & 0xff) << 8) | ((long)(i64in[7] & 0xff))); } public override double ReadDouble() { return BitConverter.Int64BitsToDouble(ReadI64()); } public void SetReadLength(int readLength) { readLength_ = readLength; checkReadLength_ = true; } protected void CheckReadLength(int length) { if (checkReadLength_) { readLength_ -= length; if (readLength_ < 0) { throw new Exception("Message length exceeded: " + length); } } } public override byte[] ReadBinary() { int size = ReadI32(); CheckReadLength(size); byte[] buf = new byte[size]; trans.ReadAll(buf, 0, size); return buf; } private string ReadStringBody(int size) { CheckReadLength(size); byte[] buf = new byte[size]; trans.ReadAll(buf, 0, size); return Encoding.UTF8.GetString(buf); } private int ReadAll(byte[] buf, int off, int len) { CheckReadLength(len); return trans.ReadAll(buf, off, len); } #endregion } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. using System.Collections.Generic; using System; using System.Linq; using UnityEngine; using UnityEngine.Serialization; using PolyToolkit; namespace PolyToolkitInternal { // There should be only one instance of this asset in the project: // the one that comes with the Poly Toolkit. #if UNITY_EDITOR [UnityEditor.InitializeOnLoad] #endif public class PtSettings : ScriptableObject { /// <summary> /// Poly Toolkit version number. /// </summary> public static Version Version { get { return new Version { major = 1, minor = 1 }; } } private static PtSettings instance; public static PtSettings Instance { get { if (instance == null) { if (Application.isPlaying) { // We can't lazy-initialize because we don't know if we are on the main thread, and we'd need // to call Resoures.Load to find the PtSettings instance, which can only be called on // the main thread. So we must insist that the developer initialize the API properly. throw new Exception("Poly Toolkit not initialized (failed to get PtSettings). " + "Add a PolyToolkitManager to your scene, or manually call PolyApi.Init from main thread."); } else { // In the Editor, we can lazy-initialize because we only use the main thread. instance = FindPtSettings(); } } return instance; } } #if UNITY_EDITOR static PtSettings() { UnityEditor.EditorApplication.update += UpdateSettings; } static void UpdateSettings() { Init(); if (Instance != null) { if (Instance.playerColorSpace != UnityEditor.PlayerSettings.colorSpace) { Instance.playerColorSpace = UnityEditor.PlayerSettings.colorSpace; UnityEditor.EditorUtility.SetDirty(Instance); } } else { UnityEditor.EditorApplication.update -= UpdateSettings; } } #endif /// <summary> /// Initialize PtSettings. Must be called on main thread. /// </summary> public static void Init() { instance = FindPtSettings(); } /// <summary> /// Finds the singleton PtSettings instance. Works during edit time and run time. /// At edit time, we search for the asset using FindAssets("t:PtSettings"). /// At run time, we load it as a resource. /// </summary> /// <returns>The project's PtSettings instance.</returns> static PtSettings FindPtSettings() { if (Application.isPlaying) { // At run-time, just load the resource. PtSettings ptSettings = Resources.Load<PtSettings>("PtSettings"); if (ptSettings == null) { Debug.LogError("PtSettings not found in Resources. Re-import Poly Toolkit."); } return ptSettings; } #if UNITY_EDITOR // We're in the editor at edit-time, so just search for the asset in the project. string[] foundPaths = UnityEditor.AssetDatabase.FindAssets("t:PtSettings") .Select(UnityEditor.AssetDatabase.GUIDToAssetPath).ToArray(); if (foundPaths.Length == 0) { Debug.LogError("Found no PtSettings assets. Re-import Poly Toolkit"); return null; } else { if (foundPaths.Length > 1) { Debug.LogErrorFormat( "Found multiple PtSettings assets; delete them and re-import Poly Toolkit\n{0}", string.Join("\n", foundPaths)); } return UnityEditor.AssetDatabase.LoadAssetAtPath<PtSettings>( foundPaths[0]); } #else // We are not in the editor but somehow Application.isPlaying is false, which shouldn't happen. Debug.LogError("Unexpected config: UNITY_EDITOR not defined but Application.isPlaying==false."); return null; #endif } // One or the other of material and descriptor should be set. // If both are set, they will be sanity-checked against each other. [Serializable] public struct SurfaceShaderMaterial { public string shaderUrl; #pragma warning disable 0649 // Don't warn about fields that are never assigned to. [SerializeField] private Material material; [SerializeField] private TiltBrushToolkit.BrushDescriptor descriptor; #pragma warning restore 0649 internal Material Material { get { #if UNITY_EDITOR if (material != null && descriptor != null) { if (material != descriptor.Material) { Debug.LogWarningFormat("{0} has conflicting materials", shaderUrl); } } #endif if (material != null) { return material; } else if (descriptor != null) { return descriptor.Material; } else { return null; } } } } [HideInInspector] public ColorSpace playerColorSpace; // IMPORTANT: To make these properties editable by the user, add them to the // appropriate tab in PtSettingsEditor.cs. // Also, since this class is serializable, any changes to the values should be made // directly to the PtSettings asset in the project, *NOT* as default value initializers // on this class (because changes to default values won't apply to instances that are // deserialized from disk!). [Tooltip("Defines which special materials to assign when importing a Blocks object. " + "Materials for non-Blocks objects will be automatically created on import.")] public SurfaceShaderMaterial[] surfaceShaderMaterials = new SurfaceShaderMaterial[0]; [Tooltip("Directory where asset files will be saved.")] public string assetObjectsPath; [Tooltip("Directory where asset source files (GLTF, resources) will be saved.")] public string assetSourcesPath; [Tooltip("Directory where run-time resources will be saved. Last component MUST be 'Resources'.")] public string resourcesPath; [Tooltip("The real-world length that corresponds to 1 unit in your scene. This is used to " + "scale imported objects.")] public LengthWithUnit sceneUnit; [Tooltip("Default import options.")] public EditTimeImportOptions defaultImportOptions; public TiltBrushToolkit.BrushManifest brushManifest; [Tooltip("Base PBR opaque material to use when importing assets.")] [FormerlySerializedAs("basePbrMaterial")] public Material basePbrOpaqueDoubleSidedMaterial; [Tooltip("Base PBR transparent material to use when importing assets.")] [FormerlySerializedAs("basePbrTransparentMaterial")] public Material basePbrBlendDoubleSidedMaterial; [Tooltip("Authentication settings.")] public PolyAuthConfig authConfig; [Tooltip("Cache settings.")] public PolyCacheConfig cacheConfig; [Tooltip("If true, sends anonymous usage data (editor only).")] public bool sendEditorAnalytics; [Header("Warnings")] [Tooltip("If true, warn before overwriting asset source folders. If you never make changes " + "(or add extra files) to asset source folders, you can safely disable this.")] public bool warnOnSourceOverwrite; [Tooltip("Warn when an incompatible API compatibility level is active.")] public bool warnOfApiCompatibility; private Dictionary<string, Material> surfaceShaderMaterialLookup; /// <returns>null if not found</returns> public Material LookupSurfaceShaderMaterial(string url) { if (surfaceShaderMaterialLookup == null) { surfaceShaderMaterialLookup = surfaceShaderMaterials.ToDictionary( elt => elt.shaderUrl, elt => elt.Material); } Material ret; surfaceShaderMaterialLookup.TryGetValue(url, out ret); return ret; } } }
#region License // // VersionLabel.cs July 2008 // // Copyright (C) 2008, Niall Gallagher <niallg@users.sf.net> // // 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 SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>VersionLabel</c> object is used convert any double /// retrieved from an XML attribute to a version revision. The version /// is used to determine how to perform serialization of a composite /// by determining version compatibility. /// </summary> class VersionLabel : Label { /// <summary> /// This is the decorator that is associated with the attribute. /// </summary> private Decorator decorator; /// <summary> /// This contains the details of the annotated contact object. /// </summary> private Signature detail; /// <summary> /// Represents the annotation used to label the field. /// </summary> private Version label; /// <summary> /// This is the type that the field object references. /// </summary> private Class type; /// <summary> /// This is the name of the element for this label instance. /// </summary> private String name; /// <summary> /// Constructor for the <c>VersionLabel</c> object. This is /// used to create a label that can convert from a double to an /// XML attribute and vice versa. This requires the annotation and /// contact extracted from the XML schema class. /// </summary> /// <param name="contact"> /// this is the field from the XML schema class /// </param> /// <param name="label"> /// represents the annotation for the field /// </param> public VersionLabel(Contact contact, Version label) { this.detail = new Signature(contact, this); this.decorator = new Qualifier(contact); this.type = contact.Type; this.name = label.name(); this.label = label; } /// <summary> /// This is used to acquire the <c>Decorator</c> for this. /// A decorator is an object that adds various details to the /// node without changing the overall structure of the node. For /// example comments and namespaces can be added to the node with /// a decorator as they do not affect the deserialization. /// </summary> /// <returns> /// this returns the decorator associated with this /// </returns> public Decorator Decorator { get { return decorator; } } //public Decorator GetDecorator() { // return decorator; //} /// Creates a <c>Converter</c> that can convert an attribute /// to a double value. This requires the context object used for /// the current instance of XML serialization being performed. /// </summary> /// <param name="context"> /// this is context object used for serialization /// </param> /// <returns> /// this returns the converted for this attribute object /// </returns> public Converter GetConverter(Context context) { String ignore = GetEmpty(context); Type type = Contact; if(!context.isFloat(type)) { throw new AttributeException("Cannot use %s to represent %s", label, type); } return new Primitive(context, type, ignore); } /// <summary> /// This is used to provide a configured empty value used when the /// annotated value is null. This ensures that XML can be created /// with required details regardless of whether values are null or /// not. It also provides a means for sensible default values. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns the string to use for default values /// </returns> public String GetEmpty(Context context) { return null; } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <param name="context"> /// the context object used to style the name /// </param> /// <returns> /// returns the name that is used for the XML property /// </returns> public String GetName(Context context) { Style style = context.getStyle(); String name = detail.GetName(); return style.getAttribute(name); } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String Name { get { return detail.GetName(); } } //public String GetName() { // return detail.GetName(); //} /// This is used to acquire the name of the element or attribute /// as taken from the annotation. If the element or attribute /// explicitly specifies a name then that name is used for the /// XML element or attribute used. If however no overriding name /// is provided then the method or field is used for the name. /// </summary> /// <returns> /// returns the name of the annotation for the contact /// </returns> public String Override { get { return name; } } //public String GetOverride() { // return name; //} /// This is used to acquire the contact object for this label. The /// contact retrieved can be used to set any object or primitive that /// has been deserialized, and can also be used to acquire values to /// be serialized in the case of object persistence. All contacts /// that are retrieved from this method will be accessible. /// </summary> /// <returns> /// returns the contact that this label is representing /// </returns> public Contact Contact { get { return detail.Contact; } } //public Contact GetContact() { // return detail.Contact; //} /// This acts as a convenience method used to determine the type of /// the contact this represents. This will be a primitive type of a /// primitive type from the <c>java.lang</c> primitives. /// </summary> /// <returns> /// this returns the type of the contact class /// </returns> public Class Type { get { return type; } } //public Class GetType() { // return type; //} /// This is typically used to acquire the entry value as acquired /// from the annotation. However given that the annotation this /// represents does not have a entry attribute this will always /// provide a null value for the entry string. /// </summary> /// <returns> /// this will always return null for the entry value /// </returns> public String Entry { get { return null; } } //public String GetEntry() { // return null; //} /// This is used to acquire the dependent class for this label. /// This returns null as there are no dependents to the attribute /// annotation as it can only hold primitives with no dependents. /// </summary> /// <returns> /// this is used to return the dependent type of null /// </returns> public Type Dependent { get { return null; } } //public Type GetDependent() { // return null; //} /// This method is used to determine if the label represents an /// attribute. This is used to style the name so that elements /// are styled as elements and attributes are styled as required. /// </summary> /// <returns> /// this is used to determine if this is an attribute /// </returns> public bool IsAttribute() { return true; } /// <summary> /// This is used to determine if the label is a collection. If the /// label represents a collection then any original assignment to /// the field or method can be written to without the need to /// create a new collection. This allows obscure collections to be /// used and also allows initial entries to be maintained. /// </summary> /// <returns> /// true if the label represents a collection value /// </returns> public bool IsCollection() { return false; } /// <summary> /// This is used to determine whether the attribute is required. /// This ensures that if an attribute is missing from a document /// that deserialization can continue. Also, in the process of /// serialization, if a value is null it does not need to be /// written to the resulting XML document. /// </summary> /// <returns> /// true if the label represents a some required data /// </returns> public bool IsRequired() { return label.required(); } /// <summary> /// Because the attribute can contain only simple text values it /// is never required to specified as anything other than text. /// Therefore this will always return false as CDATA does not /// apply to the attribute values. /// </summary> /// <returns> /// this will always return false for XML attributes /// </returns> public bool IsData() { return false; } /// <summary> /// This method is used by the deserialization process to check /// to see if an annotation is inline or not. If an annotation /// represents an inline XML entity then the deserialization /// and serialization process ignores overrides and special /// attributes. By default all attributes are not inline items. /// </summary> /// <returns> /// this always returns false for attribute labels /// </returns> public bool IsInline() { return false; } /// <summary> /// This is used to describe the annotation and method or field /// that this label represents. This is used to provide error /// messages that can be used to debug issues that occur when /// processing a method. This will provide enough information /// such that the problem can be isolated correctly. /// </summary> /// <returns> /// this returns a string representation of the label /// </returns> public String ToString() { return detail.ToString(); } } }
using System; using Rhino.DistributedHashTable.Internal; using Rhino.DistributedHashTable.Parameters; using Rhino.Mocks; using Rhino.PersistentHashTable; using Xunit; namespace Rhino.DistributedHashTable.IntegrationTests { public class DistributedHashTableStorageTest { public class ReadingValues : EsentTestBase, IDisposable { private readonly DistributedHashTableStorage distributedHashTableStorage; private readonly IDistributedHashTableNode node; private readonly int topologyVersion; public ReadingValues() { node = MockRepository.GenerateStub<IDistributedHashTableNode>(); topologyVersion = 1; node.Stub(x => x.GetTopologyVersion()).Return(topologyVersion); distributedHashTableStorage = new DistributedHashTableStorage("test.esent", node); distributedHashTableStorage.Put(topologyVersion, new ExtendedPutRequest { Key = "test", Bytes = new byte[]{1,2,4}, Segment = 0, }); } [Fact] public void WillReturnNullForMissingValue() { var values = distributedHashTableStorage.Get(topologyVersion, new ExtendedGetRequest { Key = "missing-value", Segment = 0 }); Assert.Empty(values[0]); } [Fact] public void WillReturnValueForExistingValue() { var values = distributedHashTableStorage.Get(topologyVersion, new ExtendedGetRequest { Key = "test", Segment = 0 }); Assert.NotEmpty(values[0]); } public void Dispose() { distributedHashTableStorage.Dispose(); } } public class WritingValues : EsentTestBase, IDisposable { private readonly DistributedHashTableStorage distributedHashTableStorage; private readonly IDistributedHashTableNode node; private readonly int topologyVersion; public WritingValues() { node = MockRepository.GenerateStub<IDistributedHashTableNode>(); topologyVersion = 2; node.Stub(x => x.GetTopologyVersion()).Return(topologyVersion); distributedHashTableStorage = new DistributedHashTableStorage("test.esent", node); } [Fact] public void WillGetVersionNumberFromPut() { var results = distributedHashTableStorage.Put(topologyVersion, new ExtendedPutRequest { Key = "test", Bytes = new byte[] { 1, 2, 4 }, Segment = 0, }); Assert.NotNull(results[0].Version); } [Fact] public void WillReplicateToOtherSystems() { node.Stub(x => x.IsSegmentOwned(0)).Return(true); var request = new ExtendedPutRequest { Key = "test", Bytes = new byte[] { 1, 2, 4 }, Segment = 0, }; distributedHashTableStorage.Put(topologyVersion, request); node.AssertWasCalled(x=>x.SendToAllOtherBackups(0, request)); } [Fact] public void WillReplicateToOwnerWhenFailedOverToAnotherNode() { node.Stub(x => x.IsSegmentOwned(0)).Return(false); var request = new ExtendedPutRequest { Key = "test", Bytes = new byte[] { 1, 2, 4 }, Segment = 0, }; distributedHashTableStorage.Put(topologyVersion, request); node.AssertWasCalled(x => x.SendToOwner(0, request)); } [Fact] public void WillReplicateToOtherBackupsWhenFailedOverToAnotherNode() { node.Stub(x => x.IsSegmentOwned(0)).Return(false); var request = new ExtendedPutRequest { Key = "test", Bytes = new byte[] { 1, 2, 4 }, Segment = 0, }; distributedHashTableStorage.Put(topologyVersion, request); node.AssertWasCalled(x => x.SendToAllOtherBackups(0, request)); } public void Dispose() { distributedHashTableStorage.Dispose(); } } public class RemovingValues : EsentTestBase, IDisposable { private readonly DistributedHashTableStorage distributedHashTableStorage; private readonly IDistributedHashTableNode node; private readonly int topologyVersion; private ValueVersion version; public RemovingValues() { node = MockRepository.GenerateStub<IDistributedHashTableNode>(); topologyVersion = 1; node.Stub(x => x.GetTopologyVersion()).Return(topologyVersion); distributedHashTableStorage = new DistributedHashTableStorage("test.esent", node); var results = distributedHashTableStorage.Put(topologyVersion, new ExtendedPutRequest { Key = "test", Bytes = new byte[] { 1, 2, 4 }, Segment = 0, }); version = results[0].Version; } [Fact] public void WillConfirmRemovalOfExistingValue() { var results = distributedHashTableStorage.Remove(topologyVersion, new ExtendedRemoveRequest { Key = "test", SpecificVersion = version, Segment = 0, }); Assert.True(results[0]); } [Fact] public void WillNotConfirmRemovalOfNonExistingValue() { var results = distributedHashTableStorage.Remove(topologyVersion, new ExtendedRemoveRequest { Key = "test2", SpecificVersion = version, Segment = 0, }); Assert.False(results[0]); } [Fact] public void WillReplicateToOtherSystems() { node.Stub(x => x.IsSegmentOwned(0)).Return(true); var request = new ExtendedRemoveRequest() { Key = "test", SpecificVersion = version, Segment = 0, }; distributedHashTableStorage.Remove(topologyVersion, request); node.AssertWasCalled(x => x.SendToAllOtherBackups(0, request)); } [Fact] public void WillReplicateToOwnerWhenFailedOverToAnotherNode() { node.Stub(x => x.IsSegmentOwned(0)).Return(false); var request = new ExtendedRemoveRequest() { Key = "test", SpecificVersion = version, Segment = 0, }; distributedHashTableStorage.Remove(topologyVersion, request); node.AssertWasCalled(x => x.SendToOwner(0, request)); } [Fact] public void WillReplicateToOtherBackupsWhenFailedOverToAnotherNode() { node.Stub(x => x.IsSegmentOwned(0)).Return(false); var request = new ExtendedRemoveRequest() { Key = "test", SpecificVersion = version, Segment = 0, }; distributedHashTableStorage.Remove(topologyVersion, request); node.AssertWasCalled(x => x.SendToAllOtherBackups(0, request)); } public void Dispose() { distributedHashTableStorage.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MLRecommendAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Runtime.InteropServices; using SharpDX.Mathematics.Interop; namespace SharpDX.DirectWrite { public partial class TextAnalyzer { /// <summary> /// Returns an interface for performing text analysis. /// </summary> /// <param name="factory">A reference to a DirectWrite factory <see cref="Factory"/></param> /// <unmanaged>HRESULT IDWriteFactory::CreateTextAnalyzer([Out] IDWriteTextAnalyzer** textAnalyzer)</unmanaged> public TextAnalyzer(Factory factory) { factory.CreateTextAnalyzer(this); } /// <summary> /// Gets the glyphs (TODO doc) /// </summary> /// <param name="textString">The text string.</param> /// <param name="textLength">Length of the text.</param> /// <param name="fontFace">The font face.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="numberSubstitution">The number substitution.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="maxGlyphCount">The max glyph count.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="actualGlyphCount">The actual glyph count.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphs([In, Buffer] const wchar_t* textString,[In] unsigned int textLength,[In] IDWriteFontFace* fontFace,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] IDWriteNumberSubstitution* numberSubstitution,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[In] unsigned int maxGlyphCount,[Out, Buffer] unsigned short* clusterMap,[Out, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[Out, Buffer] unsigned short* glyphIndices,[Out, Buffer] DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[Out] unsigned int* actualGlyphCount)</unmanaged> public void GetGlyphs(string textString, int textLength, SharpDX.DirectWrite.FontFace fontFace, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, SharpDX.DirectWrite.NumberSubstitution numberSubstitution, FontFeature[][] features, int[] featureRangeLengths, int maxGlyphCount, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, out int actualGlyphCount) { var pFeatures = AllocateFeatures(features); try { GetGlyphs( textString, textLength, fontFace, isSideways, isRightToLeft, scriptAnalysis, localeName, numberSubstitution, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, maxGlyphCount, clusterMap, textProps, glyphIndices, glyphProps, out actualGlyphCount); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font in ems.</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Gets the GDI compatible glyph placements. /// </summary> /// <param name="textString">The text string.</param> /// <param name="clusterMap">The cluster map.</param> /// <param name="textProps">The text props.</param> /// <param name="textLength">Length of the text.</param> /// <param name="glyphIndices">The glyph indices.</param> /// <param name="glyphProps">The glyph props.</param> /// <param name="glyphCount">The glyph count.</param> /// <param name="fontFace">The font face.</param> /// <param name="fontEmSize">Size of the font em.</param> /// <param name="pixelsPerDip">The pixels per dip.</param> /// <param name="transform">The transform.</param> /// <param name="useGdiNatural">if set to <c>true</c> [use GDI natural].</param> /// <param name="isSideways">if set to <c>true</c> [is sideways].</param> /// <param name="isRightToLeft">if set to <c>true</c> [is right to left].</param> /// <param name="scriptAnalysis">The script analysis.</param> /// <param name="localeName">Name of the locale.</param> /// <param name="features">The features.</param> /// <param name="featureRangeLengths">The feature range lengths.</param> /// <param name="glyphAdvances">The glyph advances.</param> /// <param name="glyphOffsets">The glyph offsets.</param> /// <returns> /// If the method succeeds, it returns <see cref="Result.Ok"/>. /// </returns> /// <unmanaged>HRESULT IDWriteTextAnalyzer::GetGdiCompatibleGlyphPlacements([In, Buffer] const wchar_t* textString,[In, Buffer] const unsigned short* clusterMap,[In, Buffer] DWRITE_SHAPING_TEXT_PROPERTIES* textProps,[In] unsigned int textLength,[In, Buffer] const unsigned short* glyphIndices,[In, Buffer] const DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProps,[In] unsigned int glyphCount,[In] IDWriteFontFace* fontFace,[In] float fontEmSize,[In] float pixelsPerDip,[In, Optional] const DWRITE_MATRIX* transform,[In] BOOL useGdiNatural,[In] BOOL isSideways,[In] BOOL isRightToLeft,[In] const DWRITE_SCRIPT_ANALYSIS* scriptAnalysis,[In, Buffer, Optional] const wchar_t* localeName,[In, Optional] const void** features,[In, Buffer, Optional] const unsigned int* featureRangeLengths,[In] unsigned int featureRanges,[Out, Buffer] float* glyphAdvances,[Out, Buffer] DWRITE_GLYPH_OFFSET* glyphOffsets)</unmanaged> public void GetGdiCompatibleGlyphPlacements(string textString, short[] clusterMap, SharpDX.DirectWrite.ShapingTextProperties[] textProps, int textLength, short[] glyphIndices, SharpDX.DirectWrite.ShapingGlyphProperties[] glyphProps, int glyphCount, SharpDX.DirectWrite.FontFace fontFace, float fontEmSize, float pixelsPerDip, RawMatrix3x2? transform, bool useGdiNatural, bool isSideways, bool isRightToLeft, SharpDX.DirectWrite.ScriptAnalysis scriptAnalysis, string localeName, FontFeature[][] features, int[] featureRangeLengths, float[] glyphAdvances, SharpDX.DirectWrite.GlyphOffset[] glyphOffsets) { var pFeatures = AllocateFeatures(features); try { GetGdiCompatibleGlyphPlacements( textString, clusterMap, textProps, textLength, glyphIndices, glyphProps, glyphCount, fontFace, fontEmSize, pixelsPerDip, transform, useGdiNatural, isSideways, isRightToLeft, scriptAnalysis, localeName, pFeatures, featureRangeLengths, featureRangeLengths == null ? 0 : featureRangeLengths.Length, glyphAdvances, glyphOffsets ); } finally { if (pFeatures != IntPtr.Zero) Marshal.FreeHGlobal(pFeatures); } } /// <summary> /// Allocates the features from the jagged array.. /// </summary> /// <param name="features">The features.</param> /// <returns>A pointer to the allocated native features or 0 if features is null or empty.</returns> private static IntPtr AllocateFeatures(FontFeature[][] features) { unsafe { var pFeatures = (byte*)0; if (features != null && features.Length > 0) { // Calculate the total size of the buffer to allocate: // (0) (1) (2) // ------------------------------------------------------------- // | array | TypographicFeatures || FontFeatures || // | ptr to (1) | | | || || // | | ptr to FontFeatures || || // ------------------------------------------------------------- // Offset in bytes to (1) int offsetToTypographicFeatures = sizeof(IntPtr) * features.Length; // Add offset (1) and Size in bytes to (1) int calcSize = offsetToTypographicFeatures + sizeof(TypographicFeatures) * features.Length; // Calculate size (2) foreach (var fontFeature in features) { if (fontFeature == null) throw new ArgumentNullException("features", "FontFeature[] inside features array cannot be null."); // calcSize += typographicFeatures.Length * sizeof(FontFeature) calcSize += sizeof(FontFeature) * fontFeature.Length; } // Allocate the whole buffer pFeatures = (byte*)Marshal.AllocHGlobal(calcSize); // Pointer to (1) var pTypographicFeatures = (TypographicFeatures*)(pFeatures + offsetToTypographicFeatures); // Pointer to (2) var pFontFeatures = (FontFeature*)(pTypographicFeatures + features.Length); // Iterate on features and copy them to (2) for (int i = 0; i < features.Length; i++) { // Write array pointers in (0) ((void**)pFeatures)[i] = pTypographicFeatures; var featureSet = features[i]; // Write TypographicFeatures in (1) pTypographicFeatures->Features = (IntPtr)pFontFeatures; pTypographicFeatures->FeatureCount = featureSet.Length; pTypographicFeatures++; // Write FontFeatures in (2) for (int j = 0; j < featureSet.Length; j++) { *pFontFeatures = featureSet[j]; pFontFeatures++; } } } return (IntPtr)pFeatures; } } } }
using System; using System.Diagnostics; using System.Globalization; using Microsoft.Msagl.Core.Geometry.Curves; namespace Microsoft.Msagl.Core.Geometry { /// <summary> /// Two dimensional point /// </summary> #if TEST_MSAGL [Serializable] #endif [DebuggerDisplay("({X},{Y})")] public struct Point : IComparable<Point> { /// <summary> /// overrides the equality /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (!(obj is Point)) return false; return (Point)obj == this; } static internal Point P(double xCoordinate, double yCoordinate) { return new Point(xCoordinate, yCoordinate); } /// <summary> /// /// </summary> /// <returns></returns> public override int GetHashCode() { uint hc = (uint)X.GetHashCode(); return (int)((hc << 5 | hc >> 27) + (uint)Y.GetHashCode()); } /// <summary> /// the point norm /// </summary> public double Length { get { return (double)Math.Sqrt(X * X + Y * Y); } } /// <summary> /// point norm squared (faster to compute than Length) /// </summary> public double LengthSquared { get { return X * X + Y * Y; } } /// <summary> /// overrides the equality /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator ==(Point point0, Point point1) { return point0.X == point1.X && point0.Y == point1.Y; } /// <summary> /// overrides the less operator /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator <(Point point0, Point point1) { return point0.CompareTo(point1) < 0; } /// <summary> /// overrides the less or equal operator /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator <=(Point point0, Point point1) { return point0.CompareTo(point1) <= 0; } /// <summary> /// overrides the greater or equal operator /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator >=(Point point0, Point point1) { return point0.CompareTo(point1) >= 0; } /// <summary> /// overrides the greater operator /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator >(Point point0, Point point1) { return point0.CompareTo(point1) > 0; } /// <summary> /// the inequality operator /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static bool operator !=(Point point0, Point point1) { return !(point0 == point1); } /// <summary> /// the negation operator /// </summary> /// <param name="point0"></param> /// <returns></returns> public static Point operator -(Point point0) { return new Point(-point0.X, -point0.Y); } /// <summary> /// the negation operator /// </summary> /// <returns></returns> public Point Negate() { return -this; } /// <summary> /// the addition /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static Point operator +(Point point0, Point point1) { return new Point(point0.X + point1.X, point0.Y + point1.Y); } /// <summary> /// the addition /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static Point Add(Point point0, Point point1) { return point0 + point1; } /// <summary> /// overrides the substraction /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static Point operator -(Point point0, Point point1) { return new Point(point0.X - point1.X, point0.Y - point1.Y); } /// <summary> /// overrides the substraction /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static Point Subtract(Point point0, Point point1) { return point0 - point1; } /// <summary> /// othe internal product /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static double operator *(Point point0, Point point1) { return point0.X * point1.X + point0.Y * point1.Y; } /// <summary> /// cross product /// </summary> /// <param name="point0"></param> /// <param name="point1"></param> /// <returns></returns> public static double CrossProduct(Point point0, Point point1) { return point0.X * point1.Y - point0.Y * point1.X; } /// <summary> /// the multipliction by scalar in x and y /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")] public static Point Scale(double xScale, double yScale, Point point) { return new Point(xScale * point.X, yScale * point.Y); } /// <summary> /// the multipliction by scalar /// </summary> /// <param name="coefficient"></param> /// <param name="point"></param> /// <returns></returns> public static Point operator *(double coefficient, Point point) { return new Point(coefficient * point.X, coefficient * point.Y); } /// <summary> /// multiplication on coefficient scalar /// </summary> /// <param name="point"></param> /// <param name="coefficient"></param> /// <returns></returns> public static Point operator *(Point point, double coefficient) { return new Point(coefficient * point.X, coefficient * point.Y); } /// <summary> /// multiplication on coefficient scalar /// </summary> /// <param name="coefficient"></param> /// <param name="point"></param> /// <returns></returns> public static Point Multiply(double coefficient, Point point) { return new Point(coefficient * point.X, coefficient * point.Y); } /// <summary> /// multiplication on coefficient scalar /// </summary> /// <param name="point"></param> /// <param name="coefficient"></param> /// <returns></returns> public static Point Multiply(Point point, double coefficient) { return new Point(coefficient * point.X, coefficient * point.Y); } /// <summary> /// division on coefficient scalar /// </summary> /// <param name="point"></param> /// <param name="coefficient"></param> /// <returns></returns> public static Point operator /(Point point, double coefficient) { return new Point(point.X / coefficient, point.Y / coefficient); } /// <summary> /// division on coefficient scalar /// </summary> /// <param name="coefficient"></param> /// <param name="point"></param> /// <returns></returns> public static Point operator /(double coefficient, Point point) { return new Point(point.X / coefficient, point.Y / coefficient); } /// <summary> /// division on coefficient scalar /// </summary> /// <param name="point"></param> /// <param name="coefficient"></param> /// <returns></returns> public static Point Divide(Point point, double coefficient) { return new Point(point.X / coefficient, point.Y / coefficient); } /// <summary> /// division on coefficient scalar /// </summary> /// <param name="coefficient"></param> /// <param name="point"></param> /// <returns></returns> public static Point Divide(double coefficient, Point point) { return new Point(point.X / coefficient, point.Y / coefficient); } static internal string DoubleToString(double d) { return (Math.Abs(d) < 1e-11) ? "0" : d.ToString("#.##########", CultureInfo.InvariantCulture); } /// <summary> /// Rounded representation of the points. DebuggerDisplay shows the unrounded form. /// </summary> /// <returns></returns> public override string ToString() { return "(" + DoubleToString(X) + "," + DoubleToString(Y) + ")"; } /// <summary> /// the x coordinate /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "X")] #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=369 // Filippo: because structs become by-ref in SharpKit, assigning to the coordinates directly can be really dangerous. If you assign Point P1 to Point P2, and then // modify P2, in .NET you're modifying a copy, but in JS you're modifying the content of a reference. For this reason, I need to take a look every instance of // assignment to a Point coordinate and make sure it's not accidentally using a reference in the JS version (in this case, the assignment where the Point was // created must be converted to a call to Clone()). private double m_X; public double X { get { return m_X; } set { m_X = value; UpdateHashKey(); } } #else public double X; // This is member accessed a lot. Using a field instead of a property for performance. #endif /// <summary> /// the y coordinate /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Y")] #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=369 private double m_Y; public double Y { get { return m_Y; } set { m_Y = value; UpdateHashKey(); } } #else public double Y; // This is member accessed a lot. Using a field instead of a property for performance. #endif #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=289 //SharpKit/Colin - hashing private SharpKit.JavaScript.JsString _hashKey; private void UpdateHashKey() { _hashKey = "(" + X + "," + Y + ")"; } public Point Clone() { return new Point(m_X, m_Y); } #endif /// <summary> /// construct the point from x and y coordinates /// </summary> /// <param name="xCoordinate"></param> /// <param name="yCoordinate"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "y")] public Point(double xCoordinate, double yCoordinate) { #if SHARPKIT //https://code.google.com/p/sharpkit/issues/detail?id=289 m_X = xCoordinate; m_Y = yCoordinate; _hashKey = null; UpdateHashKey(); #else X = xCoordinate; Y = yCoordinate; #endif } static internal bool ParallelWithinEpsilon(Point a, Point b, double eps) { double alength = a.Length; double blength = b.Length; if (alength < eps || blength < eps) return true; a /= alength; b /= blength; return Math.Abs(-a.X * b.Y + a.Y * b.X) < eps; } /// <summary> /// returns this rotated by the angle counterclockwise; does not change "this" value /// </summary> /// <param name="angle"></param> /// <returns></returns> public Point Rotate(double angle) { double c = Math.Cos(angle); double s = Math.Sin(angle); return new Point(c * X - s * Y, s * X + c * Y); } /// <summary> /// creates coefficient new point with the norm 1, does not change "this" point /// </summary> /// <returns></returns> public Point Normalize() { var length = Length; if (length < ApproximateComparer.Tolerance) throw new InvalidOperationException(); //the vector is too short to be normalized return this / length; } /// <summary> /// The counter-clockwise angle when rotating point1 towards point3 around point2 /// </summary> /// <returns></returns> static public double Angle(Point point1, Point center, Point point3) { return Angle(point1 - center, point3 - center); } public static double Dot(Point v1, Point v2) { return v1.X*v2.X + v1.Y*v2.Y; } /// <summary> /// The angle you need to turn "side0" counterclockwise to make it collinear with "side1" /// </summary> /// <param name="side0"></param> /// <param name="side1"></param> /// <returns></returns> static public double Angle(Point side0, Point side1) { var ax = side0.X; var ay = side0.Y; var bx = side1.X; var by = side1.Y; double cross = ax * by - ay * bx; double dot = ax * bx + ay * by; if (Math.Abs(dot) < ApproximateComparer.Tolerance) { if (Math.Abs(cross) < ApproximateComparer.Tolerance) return 0; if (cross < -ApproximateComparer.Tolerance) return 3 * Math.PI / 2; return Math.PI / 2; } if (Math.Abs(cross) < ApproximateComparer.Tolerance) { if (dot < -ApproximateComparer.Tolerance) return Math.PI; return 0.0; } double atan2 = Math.Atan2(cross, dot); if (cross >= -ApproximateComparer.Tolerance) return atan2; return Math.PI * 2.0 + atan2; } /// <summary> /// computes orientation of three vectors with a common source /// (compare polar angles of v1 and v2 with respect to v0) /// </summary> /// <returns> /// -1 if the orientation is v0 v1 v2 /// 1 if the orientation is v0 v2 v1 /// 0 if v1 and v2 are collinear and codirectinal /// </returns> static public int GetOrientationOf3Vectors(Point vector0, Point vector1, Point vector2) { const double multiplier = 1000; //TODO, need to fix it? vector0 *= multiplier; vector1 *= multiplier; vector2 *= multiplier; double xp2 = Point.CrossProduct(vector0, vector2); double dotp2 = vector0 * vector2; double xp1 = Point.CrossProduct(vector0, vector1); double dotp1 = vector0 * vector1; // v1 is collinear with v0 if (ApproximateComparer.Close(xp1, 0.0) && ApproximateComparer.GreaterOrEqual(dotp1, 0.0)) { if (ApproximateComparer.Close(xp2, 0.0) && ApproximateComparer.GreaterOrEqual(dotp2, 0.0)) return 0; return 1; } // v2 is collinear with v0 if (ApproximateComparer.Close(xp2, 0.0) && ApproximateComparer.GreaterOrEqual(dotp2, 0.0)) { return -1; } if (ApproximateComparer.Close(xp1, 0.0) || ApproximateComparer.Close(xp2, 0.0) || xp1 * xp2 > 0.0) { // both on same side of v0, compare to each other return ApproximateComparer.Compare(Point.CrossProduct(vector2, vector1), 0.0); } // vectors "less than" zero degrees are actually large, near 2 pi return -ApproximateComparer.Compare(Math.Sign(xp1), 0.0); } /// <summary> /// If the area is negative then C lies to the right of the line [cornerA, cornerB] or, in another words, the triangle (A , B, C) is oriented clockwize /// If it is positive then C lies ot he left of the line [A,B] another words, the triangle A,B,C is oriented counter-clockwize. /// Otherwise A ,B and C are collinear. /// </summary> /// <param name="cornerA"></param> /// <param name="cornerB"></param> /// <param name="cornerC"></param> /// <returns></returns> static public double SignedDoubledTriangleArea(Point cornerA, Point cornerB, Point cornerC) { return (cornerB.X - cornerA.X) * (cornerC.Y - cornerA.Y) - (cornerC.X - cornerA.X) * (cornerB.Y - cornerA.Y); } /// <summary> /// figures out the triangle on the plane orientation: positive- counterclockwise, negative - clockwise /// </summary> /// <param name="cornerA"></param> /// <param name="cornerB"></param> /// <param name="cornerC"></param> /// <returns></returns> static public TriangleOrientation GetTriangleOrientation(Point cornerA, Point cornerB, Point cornerC) { double area = SignedDoubledTriangleArea(cornerA, cornerB, cornerC); if (area > ApproximateComparer.DistanceEpsilon) return TriangleOrientation.Counterclockwise; if (area < -ApproximateComparer.DistanceEpsilon) return TriangleOrientation.Clockwise; return TriangleOrientation.Collinear; } /// <summary> /// figures out the triangle on the plane orientation: positive- counterclockwise, negative - clockwise /// </summary> /// <param name="cornerA"></param> /// <param name="cornerB"></param> /// <param name="cornerC"></param> /// <returns></returns> static public TriangleOrientation GetTriangleOrientationWithIntersectionEpsilon(Point cornerA, Point cornerB, Point cornerC) { var area = Point.SignedDoubledTriangleArea(cornerA, cornerB, cornerC); if (area > ApproximateComparer.IntersectionEpsilon) return TriangleOrientation.Counterclockwise; if (area < -ApproximateComparer.IntersectionEpsilon) return TriangleOrientation.Clockwise; return TriangleOrientation.Collinear; } /// <summary> /// figures out the triangle on the plane orientation: positive- counterclockwise, negative - clockwise /// </summary> /// <param name="cornerA"></param> /// <param name="cornerB"></param> /// <param name="cornerC"></param> /// <returns></returns> static public TriangleOrientation GetTriangleOrientationWithNoEpsilon(Point cornerA, Point cornerB, Point cornerC) { var area = Point.SignedDoubledTriangleArea(cornerA, cornerB, cornerC); if (area > 0) return TriangleOrientation.Counterclockwise; if (area < 0) return TriangleOrientation.Clockwise; return TriangleOrientation.Collinear; } /// <summary> /// returns true if an orthogonal projection of point on [segmentStart,segmentEnd] exists /// </summary> /// <param name="point"></param> /// <param name="segmentStart"></param> /// <param name="segmentEnd"></param> /// <returns></returns> public static bool CanProject(Point point, Point segmentStart, Point segmentEnd) { Point bc = segmentEnd - segmentStart; Point ba = point - segmentStart; if (ba * bc < 0) // point belongs to the halfplane before the segment return false; Point ca = point - segmentEnd; if (ca * bc > 0) //point belongs to the halfplane after the segment return false; return true; } //returns true if there is an intersection lying in the inner part of the segment static internal bool IntervalIntersectsRay(Point segStart, Point segEnd, Point rayOrigin, Point rayDirection, out Point x) { if (!LineLineIntersection(segStart, segEnd, rayOrigin, rayOrigin + rayDirection, out x)) return false; var ds = segStart - x; var de = x - segEnd; if (ds * de <= 0) return false; if ((x - rayOrigin) * rayDirection < 0) return false; return ds * ds > ApproximateComparer.SquareOfDistanceEpsilon && de * de >= ApproximateComparer.SquareOfDistanceEpsilon; } //returns true if there is an intersection lying in the inner part of rays static internal bool RayIntersectsRayInteriors(Point aOrig, Point aDirection, Point bOrig, Point bDirection, out Point x) { return Point.LineLineIntersection(aOrig, aOrig + aDirection, bOrig, bOrig + bDirection, out x) && (x - aOrig) * aDirection / aDirection.L1 > ApproximateComparer.DistanceEpsilon && (x - bOrig) * bDirection / bDirection.L1 > ApproximateComparer.DistanceEpsilon; } static internal bool RayIntersectsRay(Point aOrig, Point aDirection, Point bOrig, Point bDirection, out Point x) { return Point.LineLineIntersection(aOrig, aOrig + aDirection, bOrig, bOrig + bDirection, out x) && (x - aOrig) * aDirection >= -ApproximateComparer.Tolerance && (x - bOrig) * bDirection >= -ApproximateComparer.Tolerance; } /// <summary> /// projects a point to an infinite line /// </summary> /// <param name="pointOnLine0"> a point on the line </param> /// <param name="pointOnLine1"> a point on the line </param> /// <param name="point"> the point to project </param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "OnLine")] static public Point ProjectionToLine(Point pointOnLine0, Point pointOnLine1, Point point) { var d = pointOnLine1 - pointOnLine0; var dLen = d.Length; if (dLen < ApproximateComparer.DistanceEpsilon) return pointOnLine0; d /= dLen; var pr = (point - pointOnLine0) * d; //projection var ret = pointOnLine0 + pr * d; Debug.Assert(Math.Abs((point - ret) * d) < ApproximateComparer.DistanceEpsilon); return ret; } /// <summary> /// The closest point on the segment [segmentStart,segmentEnd] to "point". /// See the drawing DistToLineSegment.gif. /// </summary> /// <param name="point"></param> /// <param name="segmentStart"></param> /// <param name="segmentEnd"></param> /// <param name="parameter">the parameter of the closest point</param> /// <returns></returns> static internal double DistToLineSegment(Point point, Point segmentStart, Point segmentEnd, out double parameter) { Point bc = segmentEnd - segmentStart; Point ba = point - segmentStart; double c1, c2; if ((c1 = bc * ba) <= 0.0 + ApproximateComparer.Tolerance) { parameter = 0; return ba.Length; } if ((c2 = bc * bc) <= c1 + ApproximateComparer.Tolerance) { parameter = 1; return (point - segmentEnd).Length; } parameter = c1 / c2; return (ba - parameter * bc).Length; } /// <summary> /// The closest point on the segment [segmentStart,segmentEnd] to "point". /// See the drawing DistToLineSegment.gif. /// </summary> /// <param name="point"></param> /// <param name="segmentStart"></param> /// <param name="segmentEnd"></param> /// <returns></returns> static public Point ClosestPointAtLineSegment(Point point, Point segmentStart, Point segmentEnd) { Point bc = segmentEnd - segmentStart; Point ba = point - segmentStart; double c1, c2; if ((c1 = bc * ba) <= 0.0 + ApproximateComparer.Tolerance) return segmentStart; if ((c2 = bc * bc) <= c1 + ApproximateComparer.Tolerance) return segmentEnd; double parameter = c1 / c2; return segmentStart + parameter * bc; } /// <summary> /// return parameter on the segment [segStart, segEnd] which is closest to the "point" /// see the drawing DistToLineSegment.gif /// </summary> /// <param name="point"></param> /// <param name="segmentStart"></param> /// <param name="segmentEnd"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "seg"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "OnLine")] static public double ClosestParameterOnLineSegment(Point point, Point segmentStart, Point segmentEnd) { Point bc = segmentEnd - segmentStart; Point ba = point - segmentStart; double c1, c2; if ((c1 = bc * ba) <= 0.0 + ApproximateComparer.Tolerance) return 0; if ((c2 = bc * bc) <= c1 + ApproximateComparer.Tolerance) return 1; return c1 / c2; } /// <summary> /// get the intersection of two infinite lines /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="d"></param> /// <param name="x"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "4#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "d"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")] static public bool LineLineIntersection(Point a, Point b, Point c, Point d, out Point x) { //look for the solution in the form a+u*(b-a)=c+v*(d-c) double u, v; Point ba = b - a; Point cd = c - d; Point ca = c - a; bool ret = LinearSystem2.Solve(ba.X, cd.X, ca.X, ba.Y, cd.Y, ca.Y, out u, out v); if (ret) { x = a + u * ba; return true; } else { x = new Point(); return false; } } /// <summary> /// get the intersection of two line segments /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="d"></param> /// <param name="x"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "4#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "d"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "c"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "b"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "a")] static public bool SegmentSegmentIntersection(Point a, Point b, Point c, Point d, out Point x) { //look for the solution in the form a+u*(b-a)=c+v*(d-c) double u, v; Point ba = b - a; Point cd = c - d; Point ca = c - a; bool ret = LinearSystem2.Solve(ba.X, cd.X, ca.X, ba.Y, cd.Y, ca.Y, out u, out v); double eps = ApproximateComparer.Tolerance; if (ret && u > -eps && u < 1.0 + eps && v > -eps && v < 1.0 + eps) { x = a + u * ba; return true; } else { x = new Point(); return false; } } /// <summary> ///returns true if "point" lies to the left of or on the line linePoint0, linePoint1 /// </summary> /// <param name="point"></param> /// <param name="linePoint0"></param> /// <param name="linePoint1"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702")] public static bool PointToTheLeftOfLineOrOnLine(Point point, Point linePoint0, Point linePoint1) { return SignedDoubledTriangleArea(point, linePoint0, linePoint1) >= 0; } ///<summary> /// returns true if "point" lies to the left of the line linePoint0, linePoint1 ///</summary> ///<returns></returns> public static bool PointToTheLeftOfLine(Point point, Point linePoint0, Point linePoint1) { return SignedDoubledTriangleArea(point, linePoint0, linePoint1) > 0; } /// <summary> ///returns true if "point" lies to the right of the line linePoint0, linePoint1 /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704")] public static bool PointToTheRightOfLineOrOnLine(Point point, Point linePoint0, Point linePoint1) { return SignedDoubledTriangleArea(linePoint0, linePoint1, point) <= 0; } ///<summary> ///</summary> ///<returns></returns> public static bool PointToTheRightOfLine(Point point, Point linePoint0, Point linePoint1) { return SignedDoubledTriangleArea(linePoint0, linePoint1, point) < 0; } #region IComparable<Point> Members /// <summary> /// compares two points in the lexigraphical order /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(Point other) { var r = X.CompareTo(other.X); return r != 0 ? r : Y.CompareTo(other.Y); } /// <summary> /// /// </summary> internal Directions CompassDirection { get { return CompassVector.VectorDirection(this); } } /// <summary> /// the L1 norm /// </summary> public double L1 { get { return Math.Abs(X) + Math.Abs(Y); } } #endregion ///<summary> ///rotates the point 90 degrees counterclockwise ///</summary> public Point Rotate90Ccw() { return new Point(-Y, X); } ///<summary> ///rotates the point 90 degrees counterclockwise ///</summary> public Point Rotate90Cw() { return new Point(Y, -X); } internal static bool PointIsInsideCone(Point p, Point apex, Point leftSideConePoint, Point rightSideConePoint) { return PointToTheRightOfLineOrOnLine(p, apex, leftSideConePoint) && PointToTheLeftOfLineOrOnLine(p, apex, rightSideConePoint); } static Random rnd = new Random(1); ///<summary> ///creates random unit point ///</summary> internal static Point RandomPoint() { double x = -1 + 2 * rnd.NextDouble(); double y = -1 + 2 * rnd.NextDouble(); return new Point(x, y).Normalize(); } } }
/*************************************************************************** * TrackViewColumn.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <abockover@novell.com> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using Mono.Unix; using Gtk; using Banshee.Base; using Banshee.Configuration; namespace Banshee.TrackView.Columns { public enum TrackColumnID { TrackNumber, Artist, Title, Album, Duration, Rating, Genre, Year, PlayCount, LastPlayed, Uri } public class TrackViewColumn : TreeViewColumn, IComparable<TrackViewColumn> { public class IDComparer : IComparer<TrackViewColumn> { public int Compare(TrackViewColumn a, TrackViewColumn b) { return a.ColumnID.CompareTo(b.ColumnID); } } protected delegate int ModelCompareHandler(PlaylistModel model, TreeIter a, TreeIter b); private int id; private int order; private bool preference; // User preference private bool hidden; // Source preference private PlaylistModel model; private CellRenderer renderer; private Menu menu; protected string [] fixed_width_strings; protected virtual ModelCompareHandler CompareHandler { get { return null; } } protected virtual SchemaEntry<int> WidthSchema { get { return SchemaEntry<int>.Zero; } } protected virtual SchemaEntry<int> OrderSchema { get { return SchemaEntry<int>.Zero; } } protected virtual SchemaEntry<bool> VisibleSchema { get { return SchemaEntry<bool>.Zero; } } public TrackViewColumn(string title, CellRenderer renderer, int order) : base() { this.order = order; this.id = order; this.renderer = renderer; Title = title; Resizable = true; Reorderable = true; Sizing = TreeViewColumnSizing.Fixed; if(renderer is CellRendererText) { ((CellRendererText)renderer).Ellipsize = Pango.EllipsizeMode.End; } PackStart(renderer, true); Clickable = true; SortColumnId = id; int fixed_width = !WidthSchema.Equals(SchemaEntry<int>.Zero) ? WidthSchema.Get() : 75; FixedWidth = fixed_width <= 0 ? 75 : fixed_width; preference = Visible = !VisibleSchema.Equals(SchemaEntry<bool>.Zero) ? VisibleSchema.Get() : true; if(!OrderSchema.Equals(SchemaEntry<int>.Zero)) { this.order = OrderSchema.Get(); } } public void CreatePopupableHeader() { Widget = new Label(Title); Widget.Show(); Widget parent_widget = Widget.Parent; Button parent_button = parent_widget as Button; while(parent_widget != null && parent_button == null) { parent_widget = parent_widget.Parent; parent_button = parent_widget as Button; } if(parent_button != null) { parent_button.ButtonPressEvent += OnLabelButtonPressEvent; menu = new Menu(); MenuItem columns_item = new MenuItem(Catalog.GetString("Columns...")); // Translators: {0} is the title of the column, e.g. 'Hide Artist' MenuItem hide_item = new MenuItem(String.Format(Catalog.GetString("Hide {0}"), Title)); columns_item.Activated += delegate { Globals.ActionManager["ColumnsAction"].Activate(); }; hide_item.Activated += delegate { VisibilityPreference = !VisibilityPreference; }; menu.Add(columns_item); menu.Add(hide_item); menu.ShowAll(); } } [GLib.ConnectBefore] private void OnLabelButtonPressEvent(object o, ButtonPressEventArgs args) { if(args.Event.Button == 3 && menu != null) { menu.Popup(); args.RetVal = false; } } public void Save(TreeViewColumn [] columns) { // find current order int order_t = 0, n = columns.Length; for(; order_t < n; order_t++) if(columns[order_t].Equals(this)) break; if(!VisibleSchema.Equals(SchemaEntry<bool>.Zero)) { VisibleSchema.Set(preference); } if(!WidthSchema.Equals(SchemaEntry<int>.Zero)) { WidthSchema.Set(Width); } if(!OrderSchema.Equals(SchemaEntry<int>.Zero)) { OrderSchema.Set(order_t); } } protected void SetRendererAttributes(CellRendererText renderer, string text, TreeIter iter) { renderer.Text = text; renderer.Weight = iter.Equals(model.PlayingIter) ? (int)Pango.Weight.Bold : (int)Pango.Weight.Normal; renderer.Foreground = null; renderer.Sensitive = true; TrackInfo ti = model.IterTrackInfo(iter); if(ti == null) { return; } renderer.Sensitive = ti.CanPlay && ti.PlaybackError == TrackPlaybackError.None; } public void SetMaxFixedWidth(TreeView view) { int max_width = 0; if(fixed_width_strings == null) { return; } foreach(string str in fixed_width_strings) { int width, height; Pango.Layout layout = new Pango.Layout(view.PangoContext); layout.SetText(str); layout.GetPixelSize(out width, out height); if(width > max_width) { max_width = width; } } FixedWidth = (int)Math.Ceiling(max_width * 1.4); } public int CompareTo(TrackViewColumn column) { return Order.CompareTo(column.Order); } protected int TreeIterCompareFunc(TreeModel _model, TreeIter a, TreeIter b) { return CompareHandler != null ? CompareHandler(model, a, b) : 0; } public static int LongFieldCompare(long a, long b) { return a < b ? -1 : (a == b ? 0 : 1); } public static int DefaultTreeIterCompareFunc(TreeModel model, TreeIter a, TreeIter b) { return 0; } // This is what the user wants (and what's stored in GConf) public bool VisibilityPreference { set { preference = value; Visible = (preference && !hidden); } get { return preference; } } // This can be set by the source, to hide a specific column public bool Hidden { set { hidden = value; Visible = (preference && !hidden); } get { return hidden; } } public int Order { get { return order; } } public int ColumnID { get { return id; } } public PlaylistModel Model { get { return model; } set { model = value; if(CompareHandler != null) { model.SetSortFunc(ColumnID, new TreeIterCompareFunc(TreeIterCompareFunc)); } } } public CellRenderer Renderer { get { return renderer; } } } public class TrackViewColumnText : TrackViewColumn { public TrackViewColumnText(string title, int order) : base(title, new CellRendererText(), order) { } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class WriteTo : IMFTestInterface { private bool _fileSystemInit; [SetUp] public InitializeResult Initialize() { // These tests rely on underlying file system so we need to make // sure we can format it before we start the tests. If we can't // format it, then we assume there is no FS to test on this platform. // delete the directory DOTNETMF_FS_EMULATION try { IOTests.IntializeVolume(); _fileSystemInit = true; } catch (Exception ex) { Log.Exception("Skipping: Unable to initialize file system", ex); _fileSystemInit = false; } return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } #region Test Cases [TestMethod] public MFTestResults InvalidArgs() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream"); MemoryStreamHelper.Write(ms, 1000); try { Log.Comment("null stream"); ms.WriteTo(null); Log.Exception( "Expected ArgumentNullException" ); return MFTestResults.Fail; } catch (ArgumentNullException ane) { /* pass case */ Log.Comment( "Got correct exception: " + ane.Message ); result = MFTestResults.Pass; } if (_fileSystemInit) { try { Log.Comment("pass in read-only stream"); using (FileStream fs = new FileStream("readonly", FileMode.OpenOrCreate, FileAccess.Read)) { ms.WriteTo(fs); } } catch (NotSupportedException nse) { /* pass case */ Log.Comment( "Got correct exception: " + nse.Message ); result = MFTestResults.Pass; } } try { Log.Comment("Target Stream closed"); MemoryStream mst = new MemoryStream(); mst.Close(); ms.WriteTo(mst); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } try { Log.Comment("Current Stream closed"); ms.Close(); using (MemoryStream mst = new MemoryStream()) { ms.WriteTo(mst); Log.Exception( "Expected ObjectDisposedException" ); return MFTestResults.Fail; } } catch (ObjectDisposedException ode) { /* pass case */ Log.Comment( "Got correct exception: " + ode.Message ); result = MFTestResults.Pass; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WriteTo_FileStream() { // Don't run test if no FileSystem if (!_fileSystemInit) return MFTestResults.Skip; MFTestResults result = MFTestResults.Pass; string fileName = "WriteTo_FileStream.txt"; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (FileStream fs = new FileStream(fileName, FileMode.Create)) { Log.Comment("WriteTo FileStream"); ms.WriteTo(fs); } Log.Comment("Verify closed file"); using (FileStream fs = new FileStream(fileName, FileMode.Open)) { if (fs.Length != 1234) { Log.Exception( "Expected 1234 bytes, but got " + fs.Length ); return MFTestResults.Fail; } if (!MemoryStreamHelper.VerifyRead(fs)) return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults WriteTo_MemoryStream() { MFTestResults result = MFTestResults.Pass; try { using (MemoryStream ms = new MemoryStream()) { Log.Comment("Initialize stream with 1234 bytes"); MemoryStreamHelper.Write(ms, 1234); using (MemoryStream ms2 = new MemoryStream()) { Log.Comment("WriteTo MemoryStream"); ms.WriteTo(ms2); Log.Comment("Verify 2nd MemoryStream"); if (ms2.Length != 1234) { Log.Exception( "Expected 1234 bytes, but got " + ms2.Length ); return MFTestResults.Fail; } ms2.Position = 0; if (!MemoryStreamHelper.VerifyRead(ms2)) return MFTestResults.Fail; } } } catch (Exception ex) { Log.Exception("Unexpected exception", ex); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( InvalidArgs, "InvalidArgs" ), new MFTestMethod( WriteTo_FileStream, "WriteTo_FileStream" ), new MFTestMethod( WriteTo_MemoryStream, "WriteTo_MemoryStream" ), }; } } } }
// // Copyright (c) 2004-2016 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.UnitTests.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class AutoFlushTargetWrapperTests : NLogTestBase { [Fact] public void AutoFlushTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var wrapper = new AutoFlushTargetWrapper { WrappedTarget = myTarget, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(1, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myTarget.FlushCount); } [Fact] public void AutoFlushTargetWrapperAsyncWithExceptionTest1() { var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var wrapper = new AutoFlushTargetWrapper(myTarget); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); // no flush on exception Assert.Equal(0, myTarget.FlushCount); Assert.Equal(1, myTarget.WriteCount); continuationHit.Reset(); lastException = null; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType(typeof(InvalidOperationException), lastException); Assert.Equal(0, myTarget.FlushCount); Assert.Equal(2, myTarget.WriteCount); } class MyAsyncTarget : Target { public int FlushCount { get; private set; } public int WriteCount { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } protected override void Write(LogEventInfo logEvent) { Assert.True(this.FlushCount <= this.WriteCount); this.WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com namespace DSPUtil { // Constructs an impulse for parametric EQ filter [Serializable] public struct FreqGain { private double _freq; /// <summary> /// Frequency, Hz /// </summary> public double Freq { get { return _freq; } set { _freq = value; } } private double _gain; /// <summary> /// Gain, dB /// </summary> public double Gain { get { return _gain; } set { _gain = value; } } /// <summary> /// Frequency/Gain pair /// </summary> /// <param name="freq">Frequency, Hz</param> /// <param name="gain">Gain, dB</param> public FreqGain(double freq, double gain) { _freq = freq; _gain = gain; } } public class FilterProfile : List<FreqGain> { public FilterProfile() : base() { } /// <summary> /// Copy constructor /// </summary> /// <param name="lfg"></param> public FilterProfile(FilterProfile lfg) : base(lfg) { } /// <summary> /// Compute the filter profile of an impulse. /// NOTE: very memory-intensive! /// </summary> /// <param name="impulse">The impulse file</param> /// <param name="fractionsOfERB">1.0 for ERB-spaced bands. Smaller for less smoothing</param> public FilterProfile(ISoundObj impulse, double fractionsOfERB) : base() { /* double[] muff = magbands(impulse, 300); // smooth the muff double[] smoo = ERB.smooth(muff, (int)(38 / fractionsOfERB)); // sample frequency response at ERB band centers FilterProfile lfg = ERB.profile(smoo, impulse.SampleRate, fractionsOfERB); */ FilterProfile lfg = Smoothing.Profile(impulse, SmoothingType.OCTAVE, fractionsOfERB); AddRange(lfg); } private static double[] magbands(ISoundObj impulse, double bins) { uint nSR = impulse.SampleRate; uint nSR2 = nSR / 2; int nn = (int)bins + 1; double[] muff = new double[nn]; ushort nChannels = impulse.NumChannels; for (ushort c = 0; c < nChannels; c++) { // Read channel into a buffer SingleChannel channel = impulse.Channel(c); SoundBuffer buff = new SoundBuffer(channel); buff.ReadAll(); // And then double in length to prevent wraparound buff.PadTo(buff.Count * 2); // Pad to next higher power of two buff.PadToPowerOfTwo(); // Read out into array of complex Complex[][] data = buff.ToComplexArray(); Complex[] cdata = data[0]; // Then we're done with the buffer for this channel buff = null; GC.Collect(); // FFT in place Fourier.FFT(cdata.Length, cdata); int n = cdata.Length / 2; // Drop the FFT magnitudes into the 'muff' array // according to an ERB-based scale (near-logarithmic). // Then smoothing is easy. double binw = (nSR2 / (double)n); int prevbin = 0; int nbin = 0; double v = 0; for (int j = 0; j < n; j++) { double f = (double)j * binw; // equiv freq, Hz int bin = (int)ERB.f2bin(f, nSR, bins); // the bin we drop this sample in v += cdata[j].Magnitude; nbin++; if ((bin > prevbin) || (j == n - 1)) { muff[prevbin] += (v / nbin); v = 0; nbin = 0; prevbin = bin; } } } // Now muff is sum(all channels) of average-magnitude-per-bin. // Divide it all by the number of channels, so our gains are averaged... for (int j = 0; j < muff.Length; j++) { muff[j] = muff[j] / nChannels; } return muff; } /// <summary> /// Find the maximum gain. /// </summary> /// <returns></returns> public double MaxGain() { double g = double.MinValue; foreach (FreqGain fg in this) { if (fg.Gain > g) { g = fg.Gain; } } return g; } /// <summary> /// Find the minimum gain. /// </summary> /// <returns></returns> public double MinGain() { double g = double.MaxValue; foreach (FreqGain fg in this) { if (fg.Gain < g) { g = fg.Gain; } } return g; } /// <summary> /// Create a subset of the profile, within the given frequency range. /// </summary> /// <param name="fMin"></param> /// <param name="fMax"></param> /// <returns></returns> public FilterProfile FreqRange(double fMin, double fMax) { FilterProfile lfg = new FilterProfile(); foreach (FreqGain fg in this) { if (fg.Freq >= fMin && fg.Freq <= fMax) { lfg.Add(fg); } } return lfg; } /// <summary> /// Invert the profile. /// </summary> /// <returns></returns> public FilterProfile Inverse() { return Inverse(0); } public FilterProfile Inverse(double maxGain) { FilterProfile lfg = new FilterProfile(); foreach (FreqGain fg in this) { double newGain = -fg.Gain; if (maxGain != 0) { // Don't make more than +/-maxGain dB difference! newGain = Math.Min(newGain, maxGain); newGain = Math.Max(newGain, -maxGain); lfg.Add(new FreqGain(fg.Freq, newGain)); } } return lfg; } /// <summary> /// Multiply the profile by the given gain factor. /// </summary> /// <param name="scale"></param> /// <returns></returns> public FilterProfile Scale(double scale) { FilterProfile lfg = new FilterProfile(); for (int j = 0; j < lfg.Count; j++) { FreqGain fg = lfg[j]; lfg.Add(new FreqGain(fg.Freq, fg.Gain * scale)); } return lfg; } public static FilterProfile operator *(FilterProfile c1, double num) { return c1.Scale(num); } public static FilterProfile operator *(double num, FilterProfile c1) { return c1.Scale(num); } /// <summary> /// Subtract one profile from another. /// Only valid if they share the same frequency set. /// </summary> /// <param name="c1"></param> /// <param name="c2"></param> /// <returns></returns> public static FilterProfile operator -(FilterProfile c1, FilterProfile c2) { if (c1.Count != c2.Count) { return null; } FilterProfile newProfile = new FilterProfile(); for (int j = 0; j < c1.Count; j++) { if (c1[j].Freq != c2[j].Freq) { return null; } double g1 = c1[j].Gain; double g2 = c2[j].Gain; newProfile.Add(new FreqGain(c1[j].Freq, g1 - g2)); } return newProfile; } /// <summary> /// Convert to a JSON string /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <returns></returns> public string ToJSONString(string name, string description) { StringBuilder sb = new StringBuilder(); sb.AppendLine("\"" + name + "\": \"" + description + "\","); sb.Append("\"" + name + "_loop\":[ "); bool first = true; foreach (FreqGain fg in this) { double gain = fg.Gain; if (!Double.IsNaN(gain) && !Double.IsInfinity(gain)) { if (first) { first = false; } else { sb.Append(", "); } sb.Append("{\""); sb.AppendFormat("{0:f2}", fg.Freq); sb.Append("\":"); sb.AppendFormat("{0:f2}", gain); sb.Append("}"); } } sb.AppendLine(" ]"); return sb.ToString(); } } // Comparer, compares frequency portion only public class FreqGainComparer : Comparer<FreqGain> { public override int Compare(FreqGain x, FreqGain y) { return x.Freq.CompareTo(y.Freq); } } public enum FilterInterpolation { COSINE = 0, SPLINE = 1 } [Serializable] public class FilterImpulse : SoundObj { int _nSamples; FilterProfile _coeffs; bool _allZero; FilterInterpolation _int; /// <summary> /// Create a linear-phase filter impulse. /// </summary> /// <param name="nSize">Size: determines length of the final filter - suggest 4096 or 8192 (or 0 to auto-set)</param> /// <param name="coefficients">List of {frequency Hz, gain dB}</param> /// <param name="interpolation">type of interpolation (cosine)</param> public FilterImpulse(int nSize, FilterProfile coefficients, FilterInterpolation interpolation, uint sampleRate) { if (sampleRate == 0) { throw new Exception("Sample rate cannot be zero"); } _nSamples = nSize; _coeffs = coefficients; _int = interpolation; SampleRate = sampleRate; // Check the coefficients are sorted and non-overlapping _coeffs.Sort(new FreqGainComparer()); FilterProfile co = new FilterProfile(); _allZero = true; double prevFreq = -1; double freqDiff = double.MaxValue; foreach (FreqGain fg in _coeffs) { if (fg.Freq > prevFreq && fg.Freq >= 0) { co.Add(fg); freqDiff = Math.Min(freqDiff, fg.Freq - prevFreq); prevFreq = fg.Freq; } if (fg.Gain != 0) { _allZero = false; } } _coeffs = co; if (_nSamples == 0) { // Make up a length from 4k to 32k, based on the closest-together frequencies _nSamples = _allZero ? 1024 : Math.Max(4096, (int)Math.Min(32768.0, 327680 / freqDiff)); } _nSamples = MathUtil.NextPowerOfTwo(_nSamples); } #region Overrides /// <summary> Number of iterations expected to do the signal processing </summary> public override int Iterations { get { return _nSamples; } } public override ushort NumChannels { get { ushort nc = base.NumChannels; if (nc == 0) return 1; return nc; } set { base.NumChannels = value; } } #endregion public override IEnumerator<ISample> Samples { get { int j; // Make a Dirac impulse Complex[] data = new Complex[_nSamples]; int centerpoint = (_nSamples / 2) -1; data[centerpoint] = new Complex(1, 0); Complex[][] ddata = new Complex[1][]; ddata[0] = data; ISoundObj cbr; if (!_allZero) { // FFT it Fourier.FFT((int)_nSamples, data); // Make a buffer from the FFT data cbr = new ComplexBufferReader(ddata, 1, 0, _nSamples / 2, ComplexBufferFlags.Both); ISoundObj shape = cbr; cbr = new CallbackSource(1, SampleRate, delegate(long i){ if (i > _nSamples / 2) { return null; } return new Sample(1.0); }); if (_int == FilterInterpolation.COSINE) { // Construct a series of shelf envelopes over the FFT data to match the coefficients, // with each shelf "section" feeding from the previous. // So for example // (-12@60, -3*1k,+12@15k) gives // shelf(0, 15) <- shelf(-12, -3) <- cbr LogBasisShelfEnvelope rcsePrev = null; for (j = 1; j < _coeffs.Count; j++) { double freq1 = _coeffs[j - 1].Freq; double freq2 = _coeffs[j].Freq; // gains in dB double gain1 = _coeffs[j - 1].Gain; double gain2 = _coeffs[j].Gain; // Since we're chaining these filters together, // we actually want to adjust for pre-sweep == 0dB, then end-sweep=(difference) double gainEnd = gain2 - gain1; int startSample = (int)Math.Round(freq1 * _nSamples / SampleRate); int endSample = (int)Math.Round(freq2 * _nSamples / SampleRate); if (endSample <= startSample) { endSample = startSample + 1; } LogBasisShelfEnvelope rcse = new LogBasisShelfEnvelope((j == 1) ? gain1 : 0, (j == 1) ? gain2 : gainEnd, startSample, endSample); // Input of this shelf is output of the previous shelf // (or, for the first shelf, the sweep) if (rcsePrev == null) { rcse.Input = cbr; } else { rcse.Input = rcsePrev; } rcsePrev = rcse; } shape = (rcsePrev == null) ? cbr : rcsePrev as ISoundObj; } else if (_int == FilterInterpolation.SPLINE) { throw new Exception("Not implemented"); } // Apply the shelf filters to the data j = 0; foreach (ISample sample in shape) { if (j + j < _nSamples) { double val = sample[0]; data[j].mul(val); // = new Complex(sample[0], sample[1]); data[_nSamples - j - 1].mul(val); // = new Complex(sample[0], sample[1]); } j++; } // IFFT to get the filter's impulse response Fourier.IFFT((int)_nSamples, data); // Scale to unity gain (ignoring the imaginary portion) double mul = 2; // Math.Log(_nSamples / 4); for (j = 0; j < _nSamples; j++) { data[j].mul(mul); } } // Make a buffer of the real portion cbr = new ComplexBufferReader(ddata, 1, 0, _nSamples, ComplexBufferFlags.RealOnly); // Window to attenuate the extremities // SoundObj envelope = new NormalWindow(centerpoint, _nSamples / 14); // SoundObj envelope = new BlackmanHarris(centerpoint, centerpoint); // envelope.Input = cbr; ushort nc = NumChannels; if (nc <= 1) { // Yield samples from the windowed impulse foreach (ISample sample in cbr /* envelope */) { yield return sample; } } else { foreach (ISample sample in cbr /* envelope */) { ISample s = (nc == 2) ? new Sample2() : new Sample(nc) as ISample; for (int c = 0; c < nc; c++) { s[c] = sample[0]; } yield return s; } } } } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace Rotorz.ReorderableList { /// <summary> /// Utility class for drawing reorderable lists. /// </summary> public static class ReorderableListGUI { /// <summary> /// Default list item height is 18 pixels. /// </summary> public const float DefaultItemHeight = 18; /// <summary> /// Gets or sets the zero-based index of the last item that was changed. A value of -1 /// indicates that no item was changed by list. /// </summary> /// <remarks> /// <para>This property should not be set when items are added or removed.</para> /// </remarks> public static int IndexOfChangedItem { get; internal set; } /// <summary> /// Gets the control ID of the list that is currently being drawn. /// </summary> public static int CurrentListControlID { get { return ReorderableListControl.CurrentListControlID; } } /// <summary> /// Gets the position of the list control that is currently being drawn. /// </summary> /// <remarks> /// <para>The value of this property should be ignored for <see cref="EventType.Layout"/> /// type events when using reorderable list controls with automatic layout.</para> /// </remarks> /// <see cref="CurrentItemTotalPosition"/> public static Rect CurrentListPosition { get { return ReorderableListControl.CurrentListPosition; } } /// <summary> /// Gets the zero-based index of the list item that is currently being drawn; /// or a value of -1 if no item is currently being drawn. /// </summary> public static int CurrentItemIndex { get { return ReorderableListControl.CurrentItemIndex; } } /// <summary> /// Gets the total position of the list item that is currently being drawn. /// </summary> /// <remarks> /// <para>The value of this property should be ignored for <see cref="EventType.Layout"/> /// type events when using reorderable list controls with automatic layout.</para> /// </remarks> /// <see cref="CurrentItemIndex"/> /// <see cref="CurrentListPosition"/> public static Rect CurrentItemTotalPosition { get { return ReorderableListControl.CurrentItemTotalPosition; } } #region Basic Item Drawers /// <summary> /// Default list item drawer implementation. /// </summary> /// <remarks> /// <para>Always presents the label "Item drawer not implemented.".</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Unmodified value of list item. /// </returns> /// <typeparam name="T">Type of list item.</typeparam> public static T DefaultItemDrawer<T>(Rect position, T item) { GUI.Label(position, "Item drawer not implemented."); return item; } /// <summary> /// Draws text field allowing list items to be edited. /// </summary> /// <remarks> /// <para>Null values are automatically changed to empty strings since null /// values cannot be edited using a text field.</para> /// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item /// is modified.</para> /// </remarks> /// <param name="position">Position to draw list item control(s).</param> /// <param name="item">Value of list item.</param> /// <returns> /// Modified value of list item. /// </returns> public static string TextFieldItemDrawer(Rect position, string item) { if (item == null) { item = ""; GUI.changed = true; } return EditorGUI.TextField(position, item); } #endregion /// <summary> /// Gets the default list control implementation. /// </summary> private static ReorderableListControl DefaultListControl { get; set; } static ReorderableListGUI() { DefaultListControl = new ReorderableListControl(); // Duplicate default styles to prevent user scripts from interferring with // the default list control instance. DefaultListControl.ContainerStyle = new GUIStyle(ReorderableListStyles.Container); DefaultListControl.FooterButtonStyle = new GUIStyle(ReorderableListStyles.FooterButton); DefaultListControl.ItemButtonStyle = new GUIStyle(ReorderableListStyles.ItemButton); IndexOfChangedItem = -1; } private static GUIContent s_Temp = new GUIContent(); #region Title Control /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title(titleContent); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Content for title control.</param> public static void Title(GUIContent title) { Rect position = GUILayoutUtility.GetRect(title, ReorderableListStyles.Title); Title(position, title); GUILayout.Space(-1); } /// <summary> /// Draw title control for list field. /// </summary> /// <remarks> /// <para>When needed, should be shown immediately before list field.</para> /// </remarks> /// <example> /// <code language="csharp"><![CDATA[ /// ReorderableListGUI.Title("Your Title"); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// <code language="unityscript"><![CDATA[ /// ReorderableListGUI.Title('Your Title'); /// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer); /// ]]></code> /// </example> /// <param name="title">Text for title control.</param> public static void Title(string title) { s_Temp.text = title; Title(s_Temp); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="title">Content for title control.</param> public static void Title(Rect position, GUIContent title) { if (Event.current.type == EventType.Repaint) ReorderableListStyles.Title.Draw(position, title, false, false, false, false); } /// <summary> /// Draw title control for list field with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="text">Text for title control.</param> public static void Title(Rect position, string text) { s_Temp.text = text; Title(position, s_Temp); } #endregion #region List<T> Control /// <summary> /// Draw list field control. /// </summary> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) { var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight); ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control with absolute positioning. /// </summary> /// <param name="position">Position of control.</param> /// <param name="list">The list which can be reordered.</param> /// <param name="drawItem">Callback to draw list item.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="itemHeight">Height of a single list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <typeparam name="T">Type of list item.</typeparam> private static void DoListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) { var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight); ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) { DoListField<T>(list, drawItem, drawEmpty, itemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight) { DoListField<T>(list, drawItem, drawEmpty, itemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty) { DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) { DoListField<T>(list, drawItem, null, itemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) { DoListField<T>(list, drawItem, null, itemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) { DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, 0); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) { DoListField<T>(list, drawItem, null, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) { DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, flags); } /// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/> public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) { DoListField<T>(list, drawItem, null, DefaultItemHeight, 0); } /// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/> public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) { DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, 0); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="itemCount">Count of items in list.</param> /// <param name="itemHeight">Fixed height of list item.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(int itemCount, float itemHeight, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = DefaultListControl.Flags; try { DefaultListControl.Flags = flags; return DefaultListControl.CalculateListHeight(itemCount, itemHeight); } finally { DefaultListControl.Flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount, ReorderableListFlags flags) { return CalculateListFieldHeight(itemCount, DefaultItemHeight, flags); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount, float itemHeight) { return CalculateListFieldHeight(itemCount, itemHeight, 0); } /// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/> public static float CalculateListFieldHeight(int itemCount) { return CalculateListFieldHeight(itemCount, DefaultItemHeight, 0); } #endregion #region SerializedProperty Control /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight); ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control for serializable property array. /// </summary> /// <param name="position">Position of control.</param> /// <param name="arrayProperty">Serializable property.</param> /// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight); ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(arrayProperty, 0, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(arrayProperty, 0, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, 0); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, ReorderableListFlags flags) { DoListField(arrayProperty, 0, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, 0, null, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty) { DoListField(arrayProperty, 0, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty) { DoListFieldAbsolute(position, arrayProperty, 0, null, 0); } /// <summary> /// Calculate height of list field for absolute positioning. /// </summary> /// <param name="arrayProperty">Serializable property.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(SerializedProperty arrayProperty, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = DefaultListControl.Flags; try { DefaultListControl.Flags = flags; return DefaultListControl.CalculateListHeight(new SerializedPropertyAdaptor(arrayProperty)); } finally { DefaultListControl.Flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/> public static float CalculateListFieldHeight(SerializedProperty arrayProperty) { return CalculateListFieldHeight(arrayProperty, 0); } #endregion #region SerializedProperty Control (Fixed Item Height) /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(arrayProperty, fixedItemHeight, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(arrayProperty, fixedItemHeight, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, 0); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) { DoListField(arrayProperty, fixedItemHeight, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, flags); } /// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight) { DoListField(arrayProperty, fixedItemHeight, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight) { DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, 0); } #endregion #region Adaptor Control /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags = 0) { ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags); } /// <summary> /// Draw list field control for adapted collection. /// </summary> /// <param name="position">Position of control.</param> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param> /// <param name="flags">Optional flags to pass into list field.</param> private static void DoListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags = 0) { ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) { DoListField(adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) { DoListFieldAbsolute(position, adaptor, drawEmpty, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty) { DoListField(adaptor, drawEmpty, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty) { DoListFieldAbsolute(position, adaptor, drawEmpty, 0); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor, ReorderableListFlags flags) { DoListField(adaptor, null, flags); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags) { DoListFieldAbsolute(position, adaptor, null, flags); } /// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/> public static void ListField(IReorderableListAdaptor adaptor) { DoListField(adaptor, null, 0); } /// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/> public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor) { DoListFieldAbsolute(position, adaptor, null, 0); } /// <summary> /// Calculate height of list field for adapted collection. /// </summary> /// <param name="adaptor">Reorderable list adaptor.</param> /// <param name="flags">Optional flags to pass into list field.</param> /// <returns> /// Required list height in pixels. /// </returns> public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor, ReorderableListFlags flags) { // We need to push/pop flags so that nested controls are properly calculated. var restoreFlags = DefaultListControl.Flags; try { DefaultListControl.Flags = flags; return DefaultListControl.CalculateListHeight(adaptor); } finally { DefaultListControl.Flags = restoreFlags; } } /// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/> public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor) { return CalculateListFieldHeight(adaptor, 0); } #endregion } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Playable; using IRTaktiks.Components.Scenario; using IRTaktiks.Components.Action; using System.Collections.Generic; using IRTaktiks.Components.Logic; namespace IRTaktiks.Components.Manager { /// <summary> /// Manager of items. /// </summary> public class ItemManager { #region Singleton /// <summary> /// The instance of the class. /// </summary> private static ItemManager InstanceField; /// <summary> /// The instance of the class. /// </summary> public static ItemManager Instance { get { if (InstanceField == null) InstanceField = new ItemManager(); return InstanceField; } } /// <summary> /// Private constructor. /// </summary> private ItemManager() { this.Random = new Random(); } #endregion #region Properties /// <summary> /// Random number generator. /// </summary> private Random Random; #endregion #region Construct /// <summary> /// Construct the list of the items based on attributes. /// </summary> /// <param name="unit">The unit that the items will be constructed.</param> /// <returns>The list of items.</returns> public List<Item> Construct(Unit unit) { List<Item> items = new List<Item>(); #region Same items in all Jobs /* switch (unit.Attributes.Job) { case Job.Assasin: { return attacks; } case Job.Knight: { return attacks; } case Job.Monk: { return attacks; } case Job.Paladin: { return attacks; } case Job.Priest: { return attacks; } case Job.Wizard: { return attacks; } default: { return attacks; } } */ #endregion items.Add(new Item(unit, "Potion", 10, Item.ItemType.Target, Potion)); items.Add(new Item(unit, "Ether", 5, Item.ItemType.Target, Ether)); items.Add(new Item(unit, "Elixir", 1, Item.ItemType.Self, Elixir)); return items; } #endregion #region Item /// <summary> /// Restores 500 life points. /// </summary> /// <param name="command">Item used.</param> /// <param name="caster">The caster of the item.</param> /// <param name="target">The target of the item.</param> /// <param name="position">The position of the target.</param> private void Potion(Command command, Unit caster, Unit target, Vector2 position) { // Obtain the game instance. IRTGame game = caster.Game as IRTGame; // Show the animation. Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8); AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Item, animationPosition); // Effects on caster. caster.Time = 0; // Effects on target. if (target != null) { target.Life += 500; // Show the damage. game.DamageManager.Queue(new Damage(500, null, target.Position, Damage.DamageType.Benefit)); } } /// <summary> /// Restore 350 mana points. /// </summary> /// <param name="command">Item used.</param> /// <param name="caster">The caster of the item.</param> /// <param name="target">The target of the item.</param> /// <param name="position">The position of the target.</param> private void Ether(Command command, Unit caster, Unit target, Vector2 position) { // Obtain the game instance. IRTGame game = caster.Game as IRTGame; // Show the animation. Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8); AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Item, animationPosition); // Effects on caster. caster.Time = 0; // Effects on target. if (target != null) { target.Mana += 350; // Show the damage. game.DamageManager.Queue(new Damage(350, "MP", target.Position, Damage.DamageType.Benefit)); } } /// <summary> /// Restore all life points and mana poins. /// </summary> /// <param name="command">Item used.</param> /// <param name="caster">The caster of the item.</param> /// <param name="target">The target of the item.</param> /// <param name="position">The position of the target.</param> private void Elixir(Command command, Unit caster, Unit target, Vector2 position) { // Obtain the game instance. IRTGame game = caster.Game as IRTGame; // Show the animation. Vector2 animationPosition = target == null ? position : new Vector2(target.Position.X + target.Texture.Width / 2, target.Position.Y + target.Texture.Height / 8); AnimationManager.Instance.QueueAnimation(AnimationManager.AnimationType.Elixir, animationPosition); // Effects on caster. caster.Time = 0; // Effects on target. if (target != null) { target.Life = target.Attributes.MaximumLife; target.Mana = target.Attributes.MaximumMana; // Show the damage. game.DamageManager.Queue(new Damage("WOHOO", target.Position, Damage.DamageType.Benefit)); } } #endregion } }
// $Id$ // // 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 Org.Apache.Etch.Bindings.Csharp.Msg; using NUnit.Framework; namespace Org.Apache.Etch.Bindings.Csharp.Support { [TestFixture] public class TestValidator_short { private readonly ValueFactory vf = new DummyValueFactory(); [TestFixtureSetUp] public void First() { Console.WriteLine(); Console.Write( "TestValidator_short" ); } [Test] public void constructor1() { testconstructor( 0, "short[0]", typeof(short) ); testconstructor( 1, "short[1]", typeof(short[]) ); testconstructor( 2, "short[2]", typeof(short[][]) ); testconstructor( 3, "short[3]", typeof(short[][][]) ); testconstructor( 4, "short[4]", typeof(short[][][][]) ); testconstructor( 5, "short[5]", typeof(short[][][][][]) ); testconstructor( 6, "short[6]", typeof(short[][][][][][]) ); testconstructor( 7, "short[7]", typeof(short[][][][][][][]) ); testconstructor( 8, "short[8]", typeof(short[][][][][][][][]) ); testconstructor( 9, "short[9]", typeof(short[][][][][][][][][]) ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testconstructor( int n, String descr, Type expectedClass ) { TypeValidator v = Validator_short.Get( n ); Assert.AreEqual( n, v.GetNDims() ); Assert.AreSame( expectedClass, v.GetExpectedClass() ); Assert.AreEqual( descr, v.ToString() ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void constructor2() { Validator_short.Get( -1 ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void constructor3() { Validator_short.Get( Validator.MAX_NDIMS+1 ); } [Test] public void elementvalidator1() { testelementvalidator( 1, "short[0]", typeof(short) ); testelementvalidator( 2, "short[1]", typeof(short[]) ); testelementvalidator( 3, "short[2]", typeof(short[][]) ); testelementvalidator( 4, "short[3]", typeof(short[][][]) ); testelementvalidator( 5, "short[4]", typeof(short[][][][]) ); testelementvalidator( 6, "short[5]", typeof(short[][][][][]) ); testelementvalidator( 7, "short[6]", typeof(short[][][][][][]) ); testelementvalidator( 8, "short[7]", typeof(short[][][][][][][])); testelementvalidator( 9, "short[8]", typeof(short[][][][][][][][]) ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testelementvalidator( int n, String descr, Type expectedClass ) { TypeValidator v = (TypeValidator) Validator_short.Get( n ).ElementValidator(); Assert.AreEqual( n-1, v.GetNDims() ); Assert.AreSame( expectedClass, v.GetExpectedClass() ); Assert.AreEqual( descr, v.ToString() ); } /** @ */ [Test] [ExpectedException( typeof( ArgumentOutOfRangeException ) )] public void elementvalidator2() { Validator_short.Get( 0 ).ElementValidator(); } /** @ */ [Test] public void good_scalar() { // BYTES testgoodvalue( 0, (sbyte) 0 ); testgoodvalue( 0, (sbyte) 1 ); testgoodvalue( 0, (sbyte) 64 ); testgoodvalue( 0, SByte.MaxValue ); testgoodvalue( 0, (sbyte) -1 ); testgoodvalue( 0, (sbyte) -64 ); testgoodvalue( 0, SByte.MinValue ); // SHORTS testgoodvalue( 0, (short) 0 ); testgoodvalue( 0, (short) 1 ); testgoodvalue( 0, (short) 64 ); testgoodvalue( 0, (short) SByte.MaxValue ); testgoodvalue( 0, (short) 2222 ); testgoodvalue( 0, Int16.MaxValue ); testgoodvalue( 0, (short) -1 ); testgoodvalue( 0, (short) -64 ); testgoodvalue( 0, (short) SByte.MinValue ); testgoodvalue( 0, (short) -2222 ); testgoodvalue( 0, Int16.MinValue ); // INTS testgoodvalue( 0, 0 ); testgoodvalue( 0, 1 ); testgoodvalue( 0, 64 ); testgoodvalue( 0, (int) SByte.MaxValue ); testgoodvalue( 0, 2222 ); testgoodvalue( 0, (int) Int16.MaxValue ); testgoodvalue( 0, -1 ); testgoodvalue( 0, -64 ); testgoodvalue( 0, (int) SByte.MinValue ); testgoodvalue( 0, -2222 ); testgoodvalue( 0, (int) Int16.MinValue ); // LONGS testgoodvalue( 0, (long) 0 ); testgoodvalue( 0, (long) 1 ); testgoodvalue( 0, (long) 64 ); testgoodvalue( 0, (long) SByte.MaxValue ); testgoodvalue( 0, (long) 2222 ); testgoodvalue( 0, (long) Int16.MaxValue ); testgoodvalue( 0, (long) -1 ); testgoodvalue( 0, (long) -64 ); testgoodvalue( 0, (long) SByte.MinValue ); testgoodvalue( 0, (long) -2222 ); testgoodvalue( 0, (long) Int16.MinValue ); } /** @ */ [Test] public void good_array() { testgoodvalue( 1, new short[] {} ); testgoodvalue( 2, new short[][] {} ); testgoodvalue( 3, new short[][][] {} ); testgoodvalue( 4, new short[][][][] {} ); testgoodvalue( 5, new short[][][][][] {} ); testgoodvalue( 6, new short[][][][][][] {} ); testgoodvalue( 7, new short[][][][][][][] {} ); testgoodvalue( 8, new short[][][][][][][][] {} ); testgoodvalue( 9, new short[][][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testgoodvalue( int n, Object value ) { TypeValidator v = Validator_short.Get( n ); Assert.IsTrue( v.Validate( value ) ); Assert.IsTrue( validateValueOk( v, value ) ); } /** @ */ [Test] public void bad_scalar() { testbadvalue( 0, null ); testbadvalue( 0, false ); testbadvalue( 0, true ); // testbadvalue( 0, (byte) 1 ); good! // testbadvalue( 0, (short) 2222 ); good! testbadvalue( 0, 33333333 ); testbadvalue( 0, 4444444444444444L ); testbadvalue( 0, 5.5f ); testbadvalue( 0, 6.6 ); testbadvalue( 0, "" ); testbadvalue( 0, "abc" ); testbadvalue( 0, new Object() ); testbadvalue(0, new StructValue(new XType("abc"), vf)); testbadvalue( 0, new DateTime() ); testbadvalue( 1, null ); testbadvalue( 1, false ); testbadvalue( 1, true ); testbadvalue( 1, (byte) 1 ); testbadvalue( 1, (short) 2222 ); testbadvalue( 1, 333333 ); testbadvalue( 1, 4444444444444444L ); testbadvalue( 1, 5.5f ); testbadvalue( 1, 6.6 ); testbadvalue( 1, "" ); testbadvalue( 1, "abc" ); testbadvalue( 1, new Object() ); testbadvalue(1, new StructValue(new XType("abc"), vf)); testbadvalue( 1, new DateTime() ); } /** @ */ [Test] public void bad_array() { testbadvalue( 0, new short[] {} ); testbadvalue( 1, new short[][] {} ); testbadvalue( 2, new short[][][] {} ); testbadvalue( 3, new short[][][][] {} ); testbadvalue( 4, new short[][][][][] {} ); testbadvalue( 5, new short[][][][][][] {} ); testbadvalue( 6, new short[][][][][][][] {} ); testbadvalue( 7, new short[][][][][][][][] {} ); testbadvalue( 8, new short[][][][][][][][][] {} ); testbadvalue( 9, new short[][][][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); testbadvalue( 2, new short[] {} ); testbadvalue( 3, new short[][] {} ); testbadvalue( 4, new short[][][] {} ); testbadvalue( 5, new short[][][][] {} ); testbadvalue( 6, new short[][][][][] {} ); testbadvalue( 7, new short[][][][][][] {} ); testbadvalue( 8, new short[][][][][][][] {} ); testbadvalue( 9, new short[][][][][][][][] {} ); Assert.AreEqual( 9, Validator.MAX_NDIMS ); } private void testbadvalue( int n, Object value ) { TypeValidator v = Validator_short.Get( n ); Assert.IsFalse( v.Validate( value ) ); Assert.IsFalse( validateValueOk( v, value ) ); } private bool validateValueOk( Validator v, Object value ) { try { Object x = v.ValidateValue( value ); Assert.AreEqual( value, x ); return true; } catch ( Exception ) { return false; } } } }
#region File Description //----------------------------------------------------------------------------- // YachtGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; using GameStateManagement; using Microsoft.Phone.Shell; using System.IO.IsolatedStorage; using System.IO; using System.Runtime.Serialization; using System.Xml; using YachtServices; using System.Xml.Serialization; #endregion namespace Yacht { /// <summary> /// The main game type. /// </summary> /// public class YachtGame : Game { #region Static Properties public static SpriteFont RegularFont { get; private set; } public static SpriteFont ScoreFont { get; private set; } public static SpriteFont ScoreFontBold { get; private set; } public static SpriteFont LeaderScoreFont { get; private set; } public static SpriteFont Font { get; private set; } #endregion #region Fields GraphicsDeviceManager graphics; ScreenManager screenManager; #endregion #region Initializations public YachtGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); graphics.IsFullScreen = true; screenManager = new ScreenManager(this); Components.Add(screenManager); // Set the orientation of the view to portrait. graphics.SupportedOrientations = DisplayOrientation.Portrait; graphics.PreferredBackBufferHeight = 800; graphics.PreferredBackBufferWidth = 480; // Initialize the display orientation of the touch TouchPanel.DisplayOrientation = DisplayOrientation.Portrait; // Subscribe to the application's lifecycle events PhoneApplicationService.Current.Activated += GameActivated; PhoneApplicationService.Current.Deactivated += GameDeactivated; PhoneApplicationService.Current.Closing += GameClosed; PhoneApplicationService.Current.Launching += GameLaunched; } /// <summary> /// Initialize the game. /// </summary> protected override void Initialize() { // Initialize the accelerometer. Accelerometer.Initialize(); // Initialize Audio AudioManager.Initialize(this); AudioManager.LoadSounds(); base.Initialize(); } #endregion #region Loading /// <summary> /// Load content which will be used by the game. /// </summary> protected override void LoadContent() { RegularFont = Content.Load<SpriteFont>(@"Fonts\Regular"); ScoreFont = Content.Load<SpriteFont>(@"Fonts\ScoreFont"); ScoreFontBold = Content.Load<SpriteFont>(@"Fonts\ScoreFontBold"); LeaderScoreFont = Content.Load<SpriteFont>(@"Fonts\LeaderScoreFont"); Font = Content.Load<SpriteFont>(@"Fonts\MenuFont"); base.LoadContent(); } #endregion #region Tombstoning /// <summary> /// Saves necessary data to isolated storage before the game is deactivated. /// </summary> void GameDeactivated(object sender, DeactivatedEventArgs e) { if (PhoneApplicationService.Current.State.ContainsKey(Constants.YachtStateKey)) { SaveGameState(); } } /// <summary> /// Loads game state data from isolated storage once the game is activated. If an online game was in progress, /// reconnects to the server. If no stored data is available, starts the game normally. /// </summary> void GameActivated(object sender, ActivatedEventArgs e) { // Check if we were in the middle of an online game if (LoadGameState(GameTypes.Online)) { // Remove stored online data DeleteIsolatedStorageFile(Constants.YachtStateFileNameOnline); // The network manager is updated according to the game state loaded so try to connect NetworkManager.Instance.Registered += RegisteredWithServer; NetworkManager.Instance.ServiceError += ServerErrorOccurred; NetworkManager.Instance.Connect(NetworkManager.Instance.name); return; } // Check if we were in the middle of an offline game if (LoadGameState(GameTypes.Offline)) { // Remove stored offline data DeleteIsolatedStorageFile(Constants.YachtStateFileNameOffline); screenManager.AddScreen(new GameplayScreen(GameTypes.Offline), null); return; } // There is no game state data, so display the main menu screenManager.AddScreen(new MainMenuScreen(), null); } /// <summary> /// Save the game state to isolated storage when closing the game. /// </summary> void GameClosed(object sender, ClosingEventArgs e) { if (PhoneApplicationService.Current.State.ContainsKey(Constants.YachtStateKey)) { SaveGameState(); } } /// <summary> /// Moves to the main menu screen. /// </summary> void GameLaunched(object sender, LaunchingEventArgs e) { // Check if we were in the middle of an online game if (LoadGameState(GameTypes.Online)) { // Remove stored online data DeleteIsolatedStorageFile(Constants.YachtStateFileNameOnline); // The network manager is updated according to the game state loaded so try to connect NetworkManager.Instance.Registered += RegisteredWithServer; NetworkManager.Instance.ServiceError += ServerErrorOccurred; NetworkManager.Instance.Connect(NetworkManager.Instance.name); return; } // Start the game normally, at the main menu screenManager.AddScreen(new MainMenuScreen(), null); } #endregion #region Server Communication Handlers /// <summary> /// Called when there is an error contacting the game server. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ServerErrorOccurred(object sender, ExceptionEventArgs e) { // We no longer need to be notified of server events (the main menu screen will handle that) NetworkManager.Instance.Registered -= RegisteredWithServer; NetworkManager.Instance.ServiceError -= ServerErrorOccurred; screenManager.AddScreen(new MainMenuScreen(), null); Guide.BeginShowMessageBox("The server is unavailable", " ", new String[] { "OK" }, 0, MessageBoxIcon.Alert, null, null); } /// <summary> /// Called once registration with the game server is successful. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void RegisteredWithServer(object sender, BooleanEventArgs e) { // We no longer need to be notified of server events (the gameplay screen will handle that) NetworkManager.Instance.Registered -= RegisteredWithServer; NetworkManager.Instance.ServiceError -= ServerErrorOccurred; screenManager.AddScreen(new GameplayScreen(GameTypes.Online), null); } #endregion #region Private Methods /// <summary> /// Saves the game-state data from the game's state object in isolated storage. Assumes the game state object /// contains game-state data. /// </summary> public static void SaveGameState() { if (PhoneApplicationService.Current.State.ContainsKey(Constants.YachtStateKey)) { try { using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) { YachtState yachtState = (YachtState)PhoneApplicationService.Current.State[Constants.YachtStateKey]; string fileName = yachtState.YachGameState.GameType == GameTypes.Offline ? Constants.YachtStateFileNameOffline : Constants.YachtStateFileNameOnline; using (IsolatedStorageFileStream fileStream = isolatedStorageFile.CreateFile(fileName)) { using (XmlWriter writer = XmlWriter.Create(fileStream)) { yachtState.WriteXml(writer); } } } } catch { // There was an error saving data to isolated storage. Not much that we can do about it. } } } /// <summary> /// Loads a game-state object from isolated storage and places it in the game's state object. /// </summary> /// <param name="gameType">The type of game for which to load the data.</param> /// <returns>True if game data was successfully loaded from isolated storage and false otherwise.</returns> public static bool LoadGameState(GameTypes gameType) { string fileName; switch (gameType) { case GameTypes.Offline: fileName = Constants.YachtStateFileNameOffline; break; case GameTypes.Online: fileName = Constants.YachtStateFileNameOnline; break; default: fileName = null; break; } try { using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) { // Check whether or not the data file exists if (isolatedStorageFile.FileExists(fileName)) { // If the file exits, open it and read its contents using (IsolatedStorageFileStream fileStream = isolatedStorageFile.OpenFile(fileName, FileMode.Open)) { using (XmlReader reader = XmlReader.Create(fileStream)) { YachtState yachtState = new YachtState(); // Read the xml declaration to get it out of the way reader.Read(); yachtState.ReadXml(reader); PhoneApplicationService.Current.State[Constants.YachtStateKey] = yachtState; } } return true; } } return false; } catch { return false; } } /// <summary> /// Cleans a specific file from isolated storage. /// </summary> /// <param name="fileName">The name of the file to clean from isolated storage.</param> public static void DeleteIsolatedStorageFile(string fileName) { using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isolatedStorageFile.FileExists(fileName)) { isolatedStorageFile.DeleteFile(fileName); } } } #endregion } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.SimpleMessageStream { /// <summary> /// Multiplexes messages to mutiple different producers in the same grain over one grain-extension interface. /// /// On the silo, we have one extension per activation and this extesion multiplexes all streams on this activation /// (different stream ids and different stream providers). /// On the client, we have one extension per stream (we bind an extesion for every StreamProducer, therefore every stream has its own extension). /// </summary> [Serializable] internal class SimpleMessageStreamProducerExtension : IStreamProducerExtension { private readonly Dictionary<StreamId, StreamConsumerExtensionCollection> remoteConsumers; private readonly IStreamProviderRuntime providerRuntime; private readonly bool fireAndForgetDelivery; private readonly Logger logger; internal SimpleMessageStreamProducerExtension(IStreamProviderRuntime providerRt, bool fireAndForget) { providerRuntime = providerRt; fireAndForgetDelivery = fireAndForget; remoteConsumers = new Dictionary<StreamId, StreamConsumerExtensionCollection>(); logger = providerRuntime.GetLogger(GetType().Name); } internal void AddStream(StreamId streamId) { StreamConsumerExtensionCollection obs; // no need to lock on _remoteConsumers, since on the client we have one extension per stream (per StreamProducer) // so this call is only made once, when StreamProducer is created. if (remoteConsumers.TryGetValue(streamId, out obs)) return; obs = new StreamConsumerExtensionCollection(); remoteConsumers.Add(streamId, obs); } internal void RemoveStream(StreamId streamId) { remoteConsumers.Remove(streamId); } internal void AddSubscribers(StreamId streamId, ICollection<PubSubSubscriptionState> newSubscribers) { if (logger.IsVerbose) logger.Verbose("{0} AddSubscribers {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), Utils.EnumerableToString(newSubscribers), streamId); StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { foreach (var newSubscriber in newSubscribers) { consumers.AddRemoteSubscriber(newSubscriber.SubscriptionId, newSubscriber.Consumer, newSubscriber.Filter); } } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } } internal Task DeliverItem(StreamId streamId, object item) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { // Note: This is the main hot code path, // and the caller immediately does await on the Task // returned from this method, so we can just direct return here // without incurring overhead of additional await. return consumers.DeliverItem(streamId, item, fireAndForgetDelivery); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return TaskDone.Done; } internal Task CompleteStream(StreamId streamId) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { return consumers.CompleteStream(streamId, fireAndForgetDelivery); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return TaskDone.Done; } internal Task ErrorInStream(StreamId streamId, Exception exc) { StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { return consumers.ErrorInStream(streamId, exc, fireAndForgetDelivery); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return TaskDone.Done; } // Called by rendezvous when new remote subsriber subscribes to this stream. public Task AddSubscriber(GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { if (logger.IsVerbose) { logger.Verbose("{0} AddSubscriber {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), streamConsumer, streamId); } StreamConsumerExtensionCollection consumers; if (remoteConsumers.TryGetValue(streamId, out consumers)) { consumers.AddRemoteSubscriber(subscriptionId, streamConsumer, filter); } else { // We got an item when we don't think we're the subscriber. This is a normal race condition. // We can drop the item on the floor, or pass it to the rendezvous, or log a warning. } return TaskDone.Done; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { if (logger.IsVerbose) { logger.Verbose("{0} RemoveSubscription {1}", providerRuntime.ExecutingEntityIdentity(), subscriptionId); } foreach (StreamConsumerExtensionCollection consumers in remoteConsumers.Values) { consumers.RemoveRemoteSubscriber(subscriptionId); } return TaskDone.Done; } [Serializable] internal class StreamConsumerExtensionCollection { private readonly ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> consumers; internal StreamConsumerExtensionCollection() { consumers = new ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>>(); } internal void AddRemoteSubscriber(GuidId subscriptionId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { consumers.TryAdd(subscriptionId, Tuple.Create(streamConsumer, filter)); } internal void RemoveRemoteSubscriber(GuidId subscriptionId) { Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper> ignore; consumers.TryRemove(subscriptionId, out ignore); if (consumers.Count == 0) { // Unsubscribe from PubSub? } } internal Task DeliverItem(StreamId streamId, object item, bool fireAndForgetDelivery) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); var immutableItem = new Immutable<object>(item); foreach (KeyValuePair<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> subscriptionKvp in consumers) { IStreamConsumerExtension remoteConsumer = subscriptionKvp.Value.Item1; // Apply filter(s) to see if we should forward this item to this consumer IStreamFilterPredicateWrapper filter = subscriptionKvp.Value.Item2; if (filter != null) { if (!filter.ShouldReceive(streamId, filter.FilterData, item)) continue; } Task task = remoteConsumer.DeliverItem(subscriptionKvp.Key, immutableItem, null); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks); } internal Task CompleteStream(StreamId streamId, bool fireAndForgetDelivery) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); foreach (GuidId subscriptionId in consumers.Keys) { var data = consumers[subscriptionId]; IStreamConsumerExtension remoteConsumer = data.Item1; Task task = remoteConsumer.CompleteStream(subscriptionId); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks); } internal Task ErrorInStream(StreamId streamId, Exception exc, bool fireAndForgetDelivery) { var tasks = fireAndForgetDelivery ? null : new List<Task>(); foreach (GuidId subscriptionId in consumers.Keys) { var data = consumers[subscriptionId]; IStreamConsumerExtension remoteConsumer = data.Item1; Task task = remoteConsumer.ErrorInStream(subscriptionId, exc); if (fireAndForgetDelivery) task.Ignore(); else tasks.Add(task); } // If there's no subscriber, presumably we just drop the item on the floor return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks); } } } }
// // RangeCollectionTests.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 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. // #if ENABLE_TESTS using System; using System.Collections.Generic; using NUnit.Framework; using Hyena.Collections; namespace Hyena.Collections.Tests { [TestFixture] public class RangeCollectionTests { [Test] public void SingleRanges () { _TestRanges (new RangeCollection (), new int [] { 1, 11, 5, 7, 15, 32, 3, 9, 34 }); } [Test] public void MergedRanges () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 7, 5, 9, 1, 6, 8, 2, 10, 12 }; _TestRanges (range, indexes); Assert.AreEqual (3, range.RangeCount); int i= 0; foreach (RangeCollection.Range r in range.Ranges) { switch (i++) { case 0: Assert.AreEqual (0, r.Start); Assert.AreEqual (2, r.End); break; case 1: Assert.AreEqual (5, r.Start); Assert.AreEqual (10, r.End); break; case 2: Assert.AreEqual (12, r.Start); Assert.AreEqual (12, r.End); break; default: Assert.Fail ("This should not be reached!"); break; } } } [Test] public void LargeSequentialContains () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i++) { range.Add (i); } for (i = 0; i < n; i++) { Assert.AreEqual (true, range.Contains (i)); } } [Test] public void LargeSequential () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i++) { range.Add (i); Assert.AreEqual (1, range.RangeCount); } Assert.AreEqual (n, range.Count); i = 0; foreach (int j in range) { Assert.AreEqual (i++, j); } Assert.AreEqual (n, i); } [Test] public void LargeNonAdjacent () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i += 2) { range.Add (i); } Assert.AreEqual (n / 2, range.Count); i = 0; foreach (int j in range) { Assert.AreEqual (i, j); i += 2; } Assert.AreEqual (n, i); } private static void _TestRanges (RangeCollection range, int [] indexes) { foreach (int index in indexes) { range.Add (index); } Assert.AreEqual (indexes.Length, range.Count); Array.Sort (indexes); int i = 0; foreach (int index in range) { Assert.AreEqual (indexes[i++], index); } #pragma warning disable 0618 i = 0; foreach (int index in range.Indexes) { Assert.AreEqual (indexes[i++], index); } for (i = 0; i < range.Indexes.Length; i++) { Assert.AreEqual (indexes[i], range.Indexes[i]); } #pragma warning restore 0618 } [Test] public void RemoveSingles () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 2, 4, 6, 8, 10, 12, 14 }; foreach (int index in indexes) { range.Add (index); } foreach (int index in indexes) { Assert.AreEqual (true, range.Remove (index)); } } [Test] public void RemoveStarts () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (true, range.Contains (0)); range.Remove (0); Assert.AreEqual (false, range.Contains (0)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (true, range.Contains (2)); range.Remove (2); Assert.AreEqual (false, range.Contains (2)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (3, range.Ranges[0].Start); Assert.AreEqual (5, range.Ranges[0].End); Assert.AreEqual (true, range.Contains (14)); range.Remove (14); Assert.AreEqual (false, range.Contains (14)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (15, range.Ranges[2].Start); Assert.AreEqual (15, range.Ranges[2].End); } [Test] public void RemoveEnds () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (true, range.Contains (5)); range.Remove (5); Assert.AreEqual (false, range.Contains (5)); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (2, range.Ranges[1].Start); Assert.AreEqual (4, range.Ranges[1].End); Assert.AreEqual (true, range.Contains (15)); range.Remove (15); Assert.AreEqual (false, range.Contains (15)); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (14, range.Ranges[3].Start); Assert.AreEqual (14, range.Ranges[3].End); } [Test] public void RemoveMids () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (14, range.Ranges[3].Start); Assert.AreEqual (15, range.Ranges[3].End); Assert.AreEqual (true, range.Contains (9)); range.Remove (9); Assert.AreEqual (false, range.Contains (9)); Assert.AreEqual (6, range.RangeCount); Assert.AreEqual (7, range.Ranges[2].Start); Assert.AreEqual (8, range.Ranges[2].End); Assert.AreEqual (10, range.Ranges[3].Start); Assert.AreEqual (11, range.Ranges[3].End); Assert.AreEqual (14, range.Ranges[4].Start); Assert.AreEqual (15, range.Ranges[4].End); } private static RangeCollection _SetupTestRemoveMerges () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19 }; foreach (int index in indexes) { range.Add (index); } int i = 0; foreach (RangeCollection.Range r in range.Ranges) { switch (i++) { case 0: Assert.AreEqual (0, r.Start); Assert.AreEqual (0, r.End); break; case 1: Assert.AreEqual (2, r.Start); Assert.AreEqual (5, r.End); break; case 2: Assert.AreEqual (7, r.Start); Assert.AreEqual (11, r.End); break; case 3: Assert.AreEqual (14, r.Start); Assert.AreEqual (15, r.End); break; case 4: Assert.AreEqual (17, r.Start); Assert.AreEqual (19, r.End); break; default: Assert.Fail ("Should never reach here"); break; } } return range; } #pragma warning disable 0618 [Test] public void IndexesCacheGeneration () { RangeCollection range = new RangeCollection (); int [] index_cache = range.Indexes; Assert.AreSame (index_cache, range.Indexes); range.Add (0); range.Add (5); if (index_cache == range.Indexes) { Assert.Fail ("Indexes Cache not regenerated after change"); } index_cache = range.Indexes; range.Remove (0); range.Add (3); if (index_cache == range.Indexes) { Assert.Fail ("Indexes Cache not regenerated after change"); } } #pragma warning restore 0618 [Test] public void IndexOf () { RangeCollection range = new RangeCollection (); range.Add (0); range.Add (2); range.Add (3); range.Add (5); range.Add (6); range.Add (7); range.Add (8); range.Add (11); range.Add (12); range.Add (13); Assert.AreEqual (0, range.IndexOf (0)); Assert.AreEqual (1, range.IndexOf (2)); Assert.AreEqual (2, range.IndexOf (3)); Assert.AreEqual (3, range.IndexOf (5)); Assert.AreEqual (4, range.IndexOf (6)); Assert.AreEqual (5, range.IndexOf (7)); Assert.AreEqual (6, range.IndexOf (8)); Assert.AreEqual (7, range.IndexOf (11)); Assert.AreEqual (8, range.IndexOf (12)); Assert.AreEqual (9, range.IndexOf (13)); Assert.AreEqual (-1, range.IndexOf (99)); } [Test] public void IndexerForGoodIndexes () { RangeCollection range = new RangeCollection (); /* Range Idx Value 0-2 0 -> 0 1 -> 1 2 -> 2 7-9 3 -> 7 4 -> 8 5 -> 9 11-13 6 -> 11 7 -> 12 8 -> 13 */ range.Add (0); range.Add (1); range.Add (2); range.Add (7); range.Add (8); range.Add (9); range.Add (11); range.Add (12); range.Add (13); Assert.AreEqual (0, range[0]); Assert.AreEqual (1, range[1]); Assert.AreEqual (2, range[2]); Assert.AreEqual (7, range[3]); Assert.AreEqual (8, range[4]); Assert.AreEqual (9, range[5]); Assert.AreEqual (11, range[6]); Assert.AreEqual (12, range[7]); Assert.AreEqual (13, range[8]); } [Test] public void StressForGoodIndexes () { Random random = new Random (0xbeef); RangeCollection ranges = new RangeCollection (); List<int> indexes = new List<int> (); for (int i = 0, n = 75000; i < n; i++) { int value = random.Next (n); if (ranges.Add (value)) { CollectionExtensions.SortedInsert (indexes, value); } } Assert.AreEqual (indexes.Count, ranges.Count); for (int i = 0; i < indexes.Count; i++) { Assert.AreEqual (indexes[i], ranges[i]); } } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForNegativeBadIndex () { RangeCollection range = new RangeCollection (); Assert.AreEqual (0, range[1]); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForZeroBadIndex () { RangeCollection range = new RangeCollection (); Assert.AreEqual (0, range[0]); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForPositiveBadIndex () { RangeCollection range = new RangeCollection (); range.Add (1); Assert.AreEqual (0, range[1]); } [Test] public void ExplicitInterface () { ICollection<int> range = new RangeCollection (); range.Add (1); range.Add (2); range.Add (5); range.Add (6); Assert.AreEqual (4, range.Count); } [Test] public void NegativeIndices () { RangeCollection c = new RangeCollection (); c.Add (-10); c.Add (-5); c.Add (5); c.Add (-8); c.Add (10); c.Add (-9); c.Add (-11); Assert.IsTrue (c.Contains(-10), "#1"); Assert.IsTrue (c.Contains(-5), "#2"); Assert.IsTrue (c.Contains(5), "#3"); Assert.IsTrue (c.Contains(-8), "#4"); Assert.AreEqual (4, c.RangeCount, "#5"); Assert.AreEqual (new RangeCollection.Range (-11, -8), c.Ranges[0], "#6"); Assert.AreEqual (new RangeCollection.Range (-5, -5), c.Ranges[1], "#7"); Assert.AreEqual (new RangeCollection.Range (5, 5), c.Ranges[2], "#8"); Assert.AreEqual (new RangeCollection.Range (10, 10), c.Ranges[3], "#9"); Assert.AreEqual (0, c.FindRangeIndexForValue (-9), "#10"); Assert.IsTrue (c.FindRangeIndexForValue (-7) < 0, "#11"); } [Test] public void IPAddressRanges () { RangeCollection ranges = new RangeCollection (); int start = GetAddress ("127.0.0.1"); int end = GetAddress ("127.0.0.50"); for (int i = start; i <= end; i++) { ranges.Add (i); } Assert.IsTrue (ranges.Contains (GetAddress ("127.0.0.15"))); Assert.IsFalse (ranges.Contains (GetAddress ("127.0.0.0"))); Assert.IsFalse (ranges.Contains (GetAddress ("127.0.0.51"))); } private static int GetAddress (string addressStr) { System.Net.IPAddress address = System.Net.IPAddress.Parse (addressStr); return (int)(System.Net.IPAddress.NetworkToHostOrder ( BitConverter.ToInt32 (address.GetAddressBytes (), 0)) >> 32); } } } #endif
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.BarChart.BarChart File: BarChartMessageAdapter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.BarChart { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Net; using System.Security; using System.Xml.Linq; using ddfplus; using ddfplus.HistoricalData; using ddfplus.Net; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Serialization; using Ecng.Web; using StockSharp.Algo; using StockSharp.Localization; using StockSharp.Messages; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; /// <summary> /// The message adapter for BarChart. /// </summary> [Icon("BarChart_logo.png")] // TODO //[Doc("")] [DisplayName("BarChart")] [CategoryLoc(LocalizedStrings.AmericaKey)] [DescriptionLoc(LocalizedStrings.Str1770Key, "BarChart")] public class BarChartMessageAdapter : MessageAdapter { private string _streamAddress; private string _historicalAddress; private string _extrasAddress; private string _newsAddress; private const string _defaultTimeFormatRequest = "yyyyMMddHHmmss"; private Client _client; /// <summary> /// Initializes a new instance of the <see cref="BarChartMessageAdapter"/>. /// </summary> /// <param name="transactionIdGenerator">Transaction id generator.</param> public BarChartMessageAdapter(IdGenerator transactionIdGenerator) : base(transactionIdGenerator) { this.AddMarketDataSupport(); } /// <summary> /// Login. /// </summary> [CategoryLoc(LocalizedStrings.Str174Key)] [DisplayNameLoc(LocalizedStrings.LoginKey)] [DescriptionLoc(LocalizedStrings.LoginKey, true)] [PropertyOrder(1)] public string Login { get; set; } /// <summary> /// Password. /// </summary> [CategoryLoc(LocalizedStrings.Str174Key)] [DisplayNameLoc(LocalizedStrings.PasswordKey)] [DescriptionLoc(LocalizedStrings.PasswordKey, true)] [PropertyOrder(2)] public SecureString Password { get; set; } private static readonly HashSet<TimeSpan> _timeFrames = new HashSet<TimeSpan>(new[] { TimeSpan.FromMinutes(1), TimeSpan.FromDays(1), }); /// <summary> /// Available time frames. /// </summary> [Browsable(false)] public static IEnumerable<TimeSpan> TimeFrames { get { return _timeFrames; } } private void DisposeClient() { _client.Error -= ClientOnError; _client.NewBookQuote -= ClientOnNewBookQuote; _client.NewOHLCQuote -= ClientOnNewOhlcQuote; _client.NewQuote -= ClientOnNewQuote; _client = null; } /// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { if (_client != null) { DisposeClient(); } try { Connection.Close(); Connection.ClearCache(); } catch (Exception ex) { SendOutError(ex); } Connection.StatusChange -= ConnectionOnStatusChange; SendOutMessage(new ResetMessage()); break; } case MessageTypes.Connect: { if (_client != null) throw new InvalidOperationException(LocalizedStrings.Str3378); var doc = XDocument.Load("http://www.ddfplus.com/getusersettings.php?username={0}&password={1}".Put(Login, Password.To<string>())); var loginElem = doc.Element("usersettings").Elements("login").First(); if (loginElem.GetAttributeValue<string>("status") != "ok") throw new InvalidOperationException(LocalizedStrings.UnknownServerError); if (loginElem.GetAttributeValue<string>("credentials") != "ok") throw new InvalidOperationException(LocalizedStrings.Str3350); foreach (var elem in doc.Element("usersettings").Element("servers").Elements()) { switch (elem.GetAttributeValue<string>("type")) { case "stream": _streamAddress = elem.GetAttributeValue<string>("primary"); break; case "historicalv2": _historicalAddress = elem.GetAttributeValue<string>("primary"); break; case "extras": _extrasAddress = elem.GetAttributeValue<string>("primary"); break; case "news": _newsAddress = elem.GetAttributeValue<string>("primary"); break; } } SendOutMessage(new ConnectMessage()); Connection.StatusChange += ConnectionOnStatusChange; Connection.Properties["streamingversion"] = "3"; _client = new Client(); _client.Error += ClientOnError; _client.NewBookQuote += ClientOnNewBookQuote; _client.NewOHLCQuote += ClientOnNewOhlcQuote; _client.NewQuote += ClientOnNewQuote; Connection.Username = Login; Connection.Password = Password.To<string>(); Connection.Mode = ConnectionMode.TCPClient; break; } case MessageTypes.Disconnect: { if (_client == null) throw new InvalidOperationException(LocalizedStrings.Str1856); DisposeClient(); Connection.Close(); break; } case MessageTypes.SecurityLookup: { var lookupMsg = (SecurityLookupMessage)message; XDocument doc = null; if (!lookupMsg.SecurityId.SecurityCode.IsEmpty()) { doc = XDocument.Load("{0}/instruments/?lookup={1}".Put(_extrasAddress, lookupMsg.SecurityId.SecurityCode)); } else if (!lookupMsg.SecurityId.BoardCode.IsEmpty()) { doc = XDocument.Load("{0}/instruments/?exchange={1}".Put(_extrasAddress, lookupMsg.SecurityId.BoardCode)); } if (doc != null) { foreach (var element in doc.Element("instruments").Elements()) { SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = element.GetAttributeValue<string>("guid"), BoardCode = element.GetAttributeValue<string>("exchange"), }, Name = element.GetAttributeValue<string>("symbol_description"), OriginalTransactionId = lookupMsg.TransactionId, SecurityType = TraderHelper.FromIso10962(element.GetAttributeValue<string>("symbol_cfi")), PriceStep = element.GetAttributeValue<decimal?>("tick_increment"), Multiplier = element.GetAttributeValue<decimal?>("point_value"), Currency = element.GetAttributeValue<CurrencyTypes?>("currency") }); } } SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = lookupMsg.TransactionId, }); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; switch (mdMsg.DataType) { case MarketDataTypes.Level1: break; case MarketDataTypes.MarketDepth: break; case MarketDataTypes.Trades: { if (mdMsg.Count != null || mdMsg.From != null || mdMsg.To != null) { var url = new Url("{0}/queryticks.ashx".Put(_historicalAddress)); url.QueryString .Append("username", Login) .Append("password", Password.To<string>()) .Append("symbol", mdMsg.SecurityId.SecurityCode) .Append("order", "asc"); if (mdMsg.Count != null) url.QueryString.Append("maxrecords", mdMsg.Count.Value); if (mdMsg.From != null) url.QueryString.Append("start", mdMsg.From.Value.FromDateTimeOffset(_defaultTimeFormatRequest)); if (mdMsg.To != null) url.QueryString.Append("end", mdMsg.To.Value.FromDateTimeOffset(_defaultTimeFormatRequest)); using (var client = new WebClient()) { var lines = client.DownloadString(url) .Split("\n") .Where(l => l != "\r") .ToArray(); var i = 0; foreach (var line in lines) { var columns = line.Split(','); try { var msg = new ExecutionMessage { SecurityId = mdMsg.SecurityId, OriginalTransactionId = mdMsg.TransactionId, ExecutionType = ExecutionTypes.Tick, ServerTime = columns[0].ToDateTime("yyyy-MM-dd HH:mm:ss.fff"), TradePrice = columns[3].To<decimal>(), TradeVolume = columns[4].To<decimal>(), }; msg.AddValue("IsFinished", ++i == lines.Length); SendOutMessage(msg); } catch (Exception ex) { throw new InvalidOperationException(LocalizedStrings.Str2141Params.Put(line), ex); } } } } break; } case MarketDataTypes.News: break; case MarketDataTypes.CandleTimeFrame: { var tf = (TimeSpan)mdMsg.Arg; string serviceName; string timeFormatRequest = _defaultTimeFormatRequest; string timeFormatResponse = "yyyy-MM-dd"; if (tf == TimeSpan.FromMinutes(1)) { serviceName = "queryminutes"; timeFormatResponse = "yyyy-MM-dd HH:mm"; } else if (tf == TimeSpan.FromDays(1)) { serviceName = "queryeod"; timeFormatRequest = "yyyyMMdd"; } else throw new InvalidOperationException(LocalizedStrings.Str2102); var url = new Url("{0}/{1}.ashx".Put(_historicalAddress, serviceName)); url.QueryString .Append("username", Login) .Append("password", Password.To<string>()) .Append("symbol", mdMsg.SecurityId.SecurityCode) .Append("order", "asc"); if (mdMsg.Count != null) url.QueryString.Append("maxrecords", mdMsg.Count.Value); if (mdMsg.From != null) url.QueryString.Append("start", mdMsg.From.Value.FromDateTimeOffset(timeFormatRequest)); if (mdMsg.To != null) url.QueryString.Append("end", mdMsg.To.Value.FromDateTimeOffset(timeFormatRequest)); using (var client = new WebClient()) { var lines = client.DownloadString(url) .Split("\n") .Where(l => l != "\r") .ToArray(); var i = 0; foreach (var line in lines) { var columns = line.Split(','); try { SendOutMessage(new TimeFrameCandleMessage { SecurityId = mdMsg.SecurityId, OriginalTransactionId = mdMsg.TransactionId, OpenTime = columns[tf == TimeSpan.FromMinutes(1) ? 0 : 1].ToDateTime(timeFormatResponse).ApplyTimeZone(TimeHelper.Est), OpenPrice = columns[2].To<decimal>(), HighPrice = columns[3].To<decimal>(), LowPrice = columns[4].To<decimal>(), ClosePrice = columns[5].To<decimal>(), TotalVolume = columns[6].To<decimal>(), OpenInterest = columns.Length > 7 ? columns[7].To<decimal>() : (decimal?)null, IsFinished = ++i == lines.Length }); } catch (Exception ex) { throw new InvalidOperationException(LocalizedStrings.Str2141Params.Put(line), ex); } } } break; } default: { SendOutMarketDataNotSupported(mdMsg.TransactionId); return; } } SendOutMessage(new MarketDataMessage { OriginalTransactionId = mdMsg.TransactionId }); break; } } } private void ClientOnNewQuote(object sender, Client.NewQuoteEventArgs e) { SendOutMessage(new Level1ChangeMessage { SecurityId = new SecurityId { SecurityCode = e.Quote.Symbol, BoardCode = e.Quote.ExchangeCode }, ServerTime = e.Quote.Timestamp.ApplyTimeZone(TimeHelper.Est) } .TryAdd(Level1Fields.BestBidPrice, e.Quote.Bid.ToDecimal()) .TryAdd(Level1Fields.BestBidVolume, (decimal)e.Quote.BidSize) .TryAdd(Level1Fields.BestAskPrice, e.Quote.Ask.ToDecimal()) .TryAdd(Level1Fields.BestAskVolume, (decimal)e.Quote.AskSize)); } private void ClientOnNewOhlcQuote(object sender, Client.NewOHLCQuoteEventArgs e) { SendOutMessage(new TimeFrameCandleMessage { SecurityId = new SecurityId { SecurityCode = e.OHLCQuote.Symbol, BoardCode = AssociatedBoardCode, }, OpenTime = e.OHLCQuote.Timestamp.ApplyTimeZone(TimeHelper.Est), OpenPrice = e.OHLCQuote.Open.ToDecimal() ?? 0, HighPrice = e.OHLCQuote.High.ToDecimal() ?? 0, LowPrice = e.OHLCQuote.Low.ToDecimal() ?? 0, ClosePrice = e.OHLCQuote.Close.ToDecimal() ?? 0, TotalVolume = e.OHLCQuote.Volume, OpenInterest = e.OHLCQuote.OpenInterest }); } private void ClientOnNewBookQuote(object sender, Client.NewBookQuoteEventArgs e) { SendOutMessage(new QuoteChangeMessage { SecurityId = new SecurityId { SecurityCode = e.BookQuote.Symbol, BoardCode = AssociatedBoardCode }, ServerTime = e.BookQuote.Timestamp.ApplyTimeZone(TimeHelper.Est), Bids = e.BookQuote.BidPrices.Select((p, i) => new QuoteChange(Sides.Buy, p.ToDecimal() ?? 0, e.BookQuote.BidSizes[i])).ToArray(), Asks = e.BookQuote.AskPrices.Select((p, i) => new QuoteChange(Sides.Sell, p.ToDecimal() ?? 0, e.BookQuote.AskSizes[i])).ToArray() }); } private void ClientOnError(object sender, Client.ErrorEventArgs e) { SendOutError(LocalizedStrings.Str1701Params.Put(e.Error, e.Description)); } private void ConnectionOnStatusChange(object sender, StatusChangeEventArgs e) { switch (e.NewStatus) { case Status.Disconnected: SendOutMessage(new DisconnectMessage()); break; //case Status.Connected: // SendOutMessage(new ConnectMessage()); // break; case Status.Connecting: case Status.Disconnecting: case Status.Retrying: break; case Status.Error: SendOutMessage(new ConnectMessage { Error = new InvalidOperationException(LocalizedStrings.Str2959) }); break; default: SendOutError(LocalizedStrings.Str1838Params.Put(e.NewStatus)); break; } } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(Login), Login); storage.SetValue(nameof(Password), Password); } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); Login = storage.GetValue<string>(nameof(Login)); Password = storage.GetValue<SecureString>(nameof(Password)); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion using ServiceStack.FluentValidation; using ServiceStack.FluentValidation.Resources; using ServiceStack.FluentValidation.Results; using ServiceStack.FluentValidation.Validators; namespace FluentValidation.Mvc { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web.Mvc; public class FluentValidationModelMetadataProvider : DataAnnotationsModelMetadataProvider { readonly IValidatorFactory factory; public FluentValidationModelMetadataProvider(IValidatorFactory factory) { this.factory = factory; } protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, PropertyDescriptor propertyDescriptor) { var attributes = ConvertFVMetaDataToAttributes(containerType, propertyDescriptor.Name); return CreateMetadata(attributes, containerType, modelAccessor, propertyDescriptor.PropertyType, propertyDescriptor.Name); } IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type, string name) { var validator = factory.GetValidator(type); if (validator == null) { return Enumerable.Empty<Attribute>(); } IEnumerable<IPropertyValidator> validators; // if (name == null) { //validators = validator.CreateDescriptor().GetMembersWithValidators().SelectMany(x => x); // validators = Enumerable.Empty<IPropertyValidator>(); // } // else { validators = validator.CreateDescriptor().GetValidatorsForMember(name); // } var attributes = validators.OfType<IAttributeMetadataValidator>() .Select(x => x.ToAttribute()) .Concat(SpecialCaseValidatorConversions(validators)); return attributes.ToList(); } IEnumerable<Attribute> SpecialCaseValidatorConversions(IEnumerable<IPropertyValidator> validators) { //Email Validator should be convertible to DataType EmailAddress. var emailValidators = validators .OfType<IEmailValidator>() .Select(x => new DataTypeAttribute(DataType.EmailAddress)) .Cast<Attribute>(); var requiredValidators = validators.OfType<INotNullValidator>().Cast<IPropertyValidator>() .Concat(validators.OfType<INotEmptyValidator>().Cast<IPropertyValidator>()) .Select(x => new RequiredAttribute()) .Cast<Attribute>(); return requiredValidators.Concat(emailValidators); } /*IEnumerable<Attribute> ConvertFVMetaDataToAttributes(Type type) { return ConvertFVMetaDataToAttributes(type, null); }*/ /*public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType) { var attributes = ConvertFVMetaDataToAttributes(modelType); return CreateMetadata(attributes, null /* containerType ?1?, modelAccessor, modelType, null /* propertyName ?1?); }*/ } public interface IAttributeMetadataValidator : IPropertyValidator { Attribute ToAttribute(); } internal class AttributeMetadataValidator : IAttributeMetadataValidator { readonly Attribute attribute; public AttributeMetadataValidator(Attribute attributeConverter) { attribute = attributeConverter; } public IStringSource ErrorMessageSource { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string ErrorCode { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) { return Enumerable.Empty<ValidationFailure>(); } public string ErrorMessageTemplate { get { return null; } set { } } public ICollection<Func<object, object>> CustomMessageFormatArguments { get { return null; } } public bool SupportsStandaloneValidation { get { return false; } } public Func<object, object> CustomStateProvider { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public Attribute ToAttribute() { return attribute; } } } namespace FluentValidation.Mvc.MetadataExtensions { using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; public static class MetadataExtensions { public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute())); } public static IRuleBuilder<T, TProperty> HiddenInput<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool displayValue) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new HiddenInputAttribute { DisplayValue = displayValue })); } public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint))); } public static IRuleBuilder<T, TProperty> UIHint<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string hint, string presentationLayer) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new UIHintAttribute(hint, presentationLayer))); } public static IRuleBuilder<T, TProperty> Scaffold<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool scaffold) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ScaffoldColumnAttribute(scaffold))); } public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, DataType dataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(dataType))); } public static IRuleBuilder<T, TProperty> DataType<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string customDataType) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DataTypeAttribute(customDataType))); } public static IRuleBuilder<T, TProperty> DisplayName<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, string name) { #if NET4 return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayAttribute { Name = name })); #else return ruleBuilder.SetValidator(new AttributeMetadataValidator(new DisplayNameAttribute(name))); #endif } public static IDisplayFormatBuilder<T, TProperty> DisplayFormat<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) { return new DisplayFormatBuilder<T, TProperty>(ruleBuilder); } public static IRuleBuilder<T, TProperty> ReadOnly<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder, bool readOnly) { return ruleBuilder.SetValidator(new AttributeMetadataValidator(new ReadOnlyAttribute(readOnly))); } public interface IDisplayFormatBuilder<T, TProperty> : IRuleBuilder<T, TProperty> { IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text); IDisplayFormatBuilder<T, TProperty> DataFormatString(string text); IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply); IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert); } private class DisplayFormatBuilder<T, TProperty> : IDisplayFormatBuilder<T, TProperty> { readonly IRuleBuilder<T, TProperty> builder; readonly DisplayFormatAttribute attribute = new DisplayFormatAttribute(); public DisplayFormatBuilder(IRuleBuilder<T, TProperty> builder) { this.builder = builder; builder.SetValidator(new AttributeMetadataValidator(attribute)); } public IRuleBuilderOptions<T, TProperty> SetValidator(IPropertyValidator validator) { return builder.SetValidator(validator); } [Obsolete] public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator validator) { return builder.SetValidator(validator); } public IRuleBuilderOptions<T, TProperty> SetValidator(IValidator<TProperty> validator) { return builder.SetValidator(validator); } public IDisplayFormatBuilder<T, TProperty> NullDisplayText(string text) { attribute.NullDisplayText = text; return this; } public IDisplayFormatBuilder<T, TProperty> DataFormatString(string text) { attribute.DataFormatString = text; return this; } public IDisplayFormatBuilder<T, TProperty> ApplyFormatInEditMode(bool apply) { attribute.ApplyFormatInEditMode = apply; return this; } public IDisplayFormatBuilder<T, TProperty> ConvertEmptyStringToNull(bool convert) { attribute.ConvertEmptyStringToNull = convert; return this; } } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Cloud Billing API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/billing/'>Google Cloud Billing API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20151222 (355) * <tr><th>API Docs * <td><a href='https://cloud.google.com/billing/'> * https://cloud.google.com/billing/</a> * <tr><th>Discovery Name<td>cloudbilling * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Cloud Billing API can be found at * <a href='https://cloud.google.com/billing/'>https://cloud.google.com/billing/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Cloudbilling.v1 { /// <summary>The Cloudbilling Service.</summary> public class CloudbillingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudbillingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudbillingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { billingAccounts = new BillingAccountsResource(this); projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "cloudbilling"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://cloudbilling.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } /// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Billing API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly BillingAccountsResource billingAccounts; /// <summary>Gets the BillingAccounts resource.</summary> public virtual BillingAccountsResource BillingAccounts { get { return billingAccounts; } } private readonly ProjectsResource projects; /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get { return projects; } } } ///<summary>A base abstract class for Cloudbilling requests.</summary> public abstract class CloudbillingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new CloudbillingBaseServiceRequest instance.</summary> protected CloudbillingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual string Xgafv { get; set; } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual string Alt { get; set; } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Cloudbilling parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "billingAccounts" collection of methods.</summary> public class BillingAccountsResource { private const string Resource = "billingAccounts"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BillingAccountsResource(Google.Apis.Services.IClientService service) { this.service = service; projects = new ProjectsResource(service); } private readonly ProjectsResource projects; /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get { return projects; } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Lists the projects associated with a billing account. The current authenticated user must be an /// [owner of the billing account](https://support.google.com/cloud/answer/4430947).</summary> /// <param name="name">The resource name of the billing account associated with the projects that you want to list. For /// example, `billingAccounts/012345-567890-ABCDEF`.</param> public virtual ListRequest List(string name) { return new ListRequest(service, name); } /// <summary>Lists the projects associated with a billing account. The current authenticated user must be an /// [owner of the billing account](https://support.google.com/cloud/answer/4430947).</summary> public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListProjectBillingInfoResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The resource name of the billing account associated with the projects that you want to /// list. For example, `billingAccounts/012345-567890-ABCDEF`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token identifying a page of results to be returned. This should be a `next_page_token` /// value returned from a previous `ListProjectBillingInfo` call. If unspecified, the first page of /// results is returned.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}/projects"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^billingAccounts/[^/]*$", }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Gets information about a billing account. The current authenticated user must be an [owner of the /// billing account](https://support.google.com/cloud/answer/4430947).</summary> /// <param name="name">The resource name of the billing account to retrieve. For example, /// `billingAccounts/012345-567890-ABCDEF`.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets information about a billing account. The current authenticated user must be an [owner of the /// billing account](https://support.google.com/cloud/answer/4430947).</summary> public class GetRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.BillingAccount> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The resource name of the billing account to retrieve. For example, /// `billingAccounts/012345-567890-ABCDEF`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^billingAccounts/[^/]*$", }); } } /// <summary>Lists the billing accounts that the current authenticated user /// [owns](https://support.google.com/cloud/answer/4430947).</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists the billing accounts that the current authenticated user /// [owns](https://support.google.com/cloud/answer/4430947).</summary> public class ListRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ListBillingAccountsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Requested page size. The maximum page size is 100; this is also the default.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>A token identifying a page of results to return. This should be a `next_page_token` value /// returned from a previous `ListBillingAccounts` call. If unspecified, the first page of results is /// returned.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/billingAccounts"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets the billing information for a project. The current authenticated user must have [permission to /// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary> /// <param name="name">The resource name of the project for which billing information is retrieved. For example, /// `projects/tokyo-rain-123`.</param> public virtual GetBillingInfoRequest GetBillingInfo(string name) { return new GetBillingInfoRequest(service, name); } /// <summary>Gets the billing information for a project. The current authenticated user must have [permission to /// view the project](https://cloud.google.com/docs/permissions-overview#h.bgs0oxofvnoo ).</summary> public class GetBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo> { /// <summary>Constructs a new GetBillingInfo request.</summary> public GetBillingInfoRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The resource name of the project for which billing information is retrieved. For example, /// `projects/tokyo-rain-123`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "getBillingInfo"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}/billingInfo"; } } /// <summary>Initializes GetBillingInfo parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]*$", }); } } /// <summary>Sets or updates the billing account associated with a project. You specify the new billing account /// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing /// account. Associating a project with an open billing account enables billing on the project and allows /// charges for resource usage. If the project already had a billing account, this method changes the billing /// account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the /// transaction history of the Google Developers Console may be billed to the new billing account, even if the /// charge occurred before the new billing account was assigned to the project. The current authenticated user /// must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions- /// overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You /// can disable billing on the project by setting the `billing_account_name` field to empty. This action /// disassociates the current billing account from the project. Any billable activity of your in-use services /// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be /// billed to the previously associated account. The current authenticated user must be either an owner of the /// project or an owner of the billing account for the project. Note that associating a project with a *closed* /// billing account will have much the same effect as disabling billing on the project: any paid resources used /// by the project will be shut down. Thus, unless you wish to disable billing, you should always call this /// method with the name of an *open* billing account.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the project associated with the billing information that you want to update. /// For example, `projects/tokyo-rain-123`.</param> public virtual UpdateBillingInfoRequest UpdateBillingInfo(Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name) { return new UpdateBillingInfoRequest(service, body, name); } /// <summary>Sets or updates the billing account associated with a project. You specify the new billing account /// by setting the `billing_account_name` in the `ProjectBillingInfo` resource to the resource name of a billing /// account. Associating a project with an open billing account enables billing on the project and allows /// charges for resource usage. If the project already had a billing account, this method changes the billing /// account used for resource usage charges. *Note:* Incurred charges that have not yet been reported in the /// transaction history of the Google Developers Console may be billed to the new billing account, even if the /// charge occurred before the new billing account was assigned to the project. The current authenticated user /// must have ownership privileges for both the [project](https://cloud.google.com/docs/permissions- /// overview#h.bgs0oxofvnoo ) and the [billing account](https://support.google.com/cloud/answer/4430947). You /// can disable billing on the project by setting the `billing_account_name` field to empty. This action /// disassociates the current billing account from the project. Any billable activity of your in-use services /// will stop, and your application could stop functioning as expected. Any unbilled charges to date will be /// billed to the previously associated account. The current authenticated user must be either an owner of the /// project or an owner of the billing account for the project. Note that associating a project with a *closed* /// billing account will have much the same effect as disabling billing on the project: any paid resources used /// by the project will be shut down. Thus, unless you wish to disable billing, you should always call this /// method with the name of an *open* billing account.</summary> public class UpdateBillingInfoRequest : CloudbillingBaseServiceRequest<Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo> { /// <summary>Constructs a new UpdateBillingInfo request.</summary> public UpdateBillingInfoRequest(Google.Apis.Services.IClientService service, Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the project associated with the billing information that you want to /// update. For example, `projects/tokyo-rain-123`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Cloudbilling.v1.Data.ProjectBillingInfo Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "updateBillingInfo"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}/billingInfo"; } } /// <summary>Initializes UpdateBillingInfo parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]*$", }); } } } } namespace Google.Apis.Cloudbilling.v1.Data { /// <summary>A billing account in [Google Developers Console](https://console.developers.google.com/). You can /// assign a billing account to one or more projects.</summary> public class BillingAccount : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The display name given to the billing account, such as `My Billing Account`. This name is displayed /// in the Google Developers Console.</summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The resource name of the billing account. The resource name has the form /// `billingAccounts/{billing_account_id}`. For example, `billingAccounts/012345-567890-ABCDEF` would be the /// resource name for billing account `012345-567890-ABCDEF`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>True if the billing account is open, and will therefore be charged for any usage on associated /// projects. False if the billing account is closed, and therefore projects associated with it will be unable /// to use paid services.</summary> [Newtonsoft.Json.JsonPropertyAttribute("open")] public virtual System.Nullable<bool> Open { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for `ListBillingAccounts`.</summary> public class ListBillingAccountsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A list of billing accounts.</summary> [Newtonsoft.Json.JsonPropertyAttribute("billingAccounts")] public virtual System.Collections.Generic.IList<BillingAccount> BillingAccounts { get; set; } /// <summary>A token to retrieve the next page of results. To retrieve the next page, call `ListBillingAccounts` /// again with the `page_token` field set to this value. This field is empty if there are no more results to /// retrieve.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for `ListProjectBillingInfoResponse`.</summary> public class ListProjectBillingInfoResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A token to retrieve the next page of results. To retrieve the next page, call /// `ListProjectBillingInfo` again with the `page_token` field set to this value. This field is empty if there /// are no more results to retrieve.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of `ProjectBillingInfo` resources representing the projects associated with the billing /// account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectBillingInfo")] public virtual System.Collections.Generic.IList<ProjectBillingInfo> ProjectBillingInfo { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Encapsulation of billing information for a Developers Console project. A project has at most one /// associated billing account at a time (but a billing account can be assigned to multiple projects).</summary> public class ProjectBillingInfo : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The resource name of the billing account associated with the project, if any. For example, /// `billingAccounts/012345-567890-ABCDEF`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("billingAccountName")] public virtual string BillingAccountName { get; set; } /// <summary>True if the project is associated with an open billing account, to which usage on the project is /// charged. False if the project is associated with a closed billing account, or no billing account at all, and /// therefore cannot use paid services. This field is read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("billingEnabled")] public virtual System.Nullable<bool> BillingEnabled { get; set; } /// <summary>The resource name for the `ProjectBillingInfo`; has the form `projects/{project_id}/billingInfo`. /// For example, the resource name for the billing information for project `tokyo-rain-123` would be `projects /// /tokyo-rain-123/billingInfo`. This field is read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ID of the project that this `ProjectBillingInfo` represents, such as `tokyo-rain-123`. This is /// a convenience field so that you don't need to parse the `name` field to obtain a project ID. This field is /// read-only.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Strategies.Testing.Algo File: EmulationSettings.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Strategies.Testing { using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using Ecng.Common; using Ecng.Serialization; using StockSharp.Algo.Testing; using StockSharp.Logging; using StockSharp.Localization; /// <summary> /// Emulation settings. /// </summary> [DisplayNameLoc(LocalizedStrings.SettingsKey)] [DescriptionLoc(LocalizedStrings.Str1408Key)] public class EmulationSettings : MarketEmulatorSettings { private DateTime _startTime = DateTime.Today.AddYears(-1); /// <summary> /// Date in history for starting the paper trading. /// </summary> [Browsable(false)] public DateTime StartTime { get => _startTime; set { _startTime = value; NotifyPropertyChanged(nameof(StartTime)); } } private DateTime _stopTime = DateTime.Today; /// <summary> /// Date in history to stop the paper trading (date is included). /// </summary> [Browsable(false)] public DateTime StopTime { get => _stopTime; set { _stopTime = value; NotifyPropertyChanged(nameof(StopTime)); } } #region Emulation private TimeSpan _marketTimeChangedInterval; /// <summary> /// Time change interval. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str175Key, Description = LocalizedStrings.Str1409Key, GroupName = LocalizedStrings.Str1174Key, Order = 100)] public TimeSpan MarketTimeChangedInterval { get => _marketTimeChangedInterval; set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219); _marketTimeChangedInterval = value; NotifyPropertyChanged(nameof(MarketTimeChangedInterval)); } } private TimeSpan? _unrealizedPnLInterval; /// <summary> /// Unrealized profit recalculation interval. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str1410Key, Description = LocalizedStrings.Str1411Key, GroupName = LocalizedStrings.Str1174Key, Order = 101)] [DefaultValue(typeof(TimeSpan), "00:01:00")] public TimeSpan? UnrealizedPnLInterval { get => _unrealizedPnLInterval; set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str1219); _unrealizedPnLInterval = value; NotifyPropertyChanged(nameof(UnrealizedPnLInterval)); } } private EmulationMarketDataModes _tradeDataMode; /// <summary> /// What trades to use. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str985Key, Description = LocalizedStrings.Str1413Key, GroupName = LocalizedStrings.Str1174Key, Order = 102)] public EmulationMarketDataModes TradeDataMode { get => _tradeDataMode; set { _tradeDataMode = value; NotifyPropertyChanged(nameof(TradeDataMode)); } } private EmulationMarketDataModes _depthDataMode; /// <summary> /// What market depths to use. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MarketDepthsKey, Description = LocalizedStrings.Str1415Key, GroupName = LocalizedStrings.Str1174Key, Order = 103)] public EmulationMarketDataModes DepthDataMode { get => _depthDataMode; set { _depthDataMode = value; NotifyPropertyChanged(nameof(DepthDataMode)); } } private EmulationMarketDataModes _orderLogDataMode; /// <summary> /// Use orders log. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.OrderLogKey, Description = LocalizedStrings.Str1417Key, GroupName = LocalizedStrings.Str1174Key, Order = 104)] public EmulationMarketDataModes OrderLogDataMode { get => _orderLogDataMode; set { _orderLogDataMode = value; NotifyPropertyChanged(nameof(OrderLogDataMode)); } } private int _batchSize = Environment.ProcessorCount * 2; /// <summary> /// Number of simultaneously tested strategies. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str1418Key, Description = LocalizedStrings.Str1419Key, GroupName = LocalizedStrings.Str1174Key, Order = 105)] public int BatchSize { get => _batchSize; set { _batchSize = value; NotifyPropertyChanged(nameof(BatchSize)); } } private bool _checkTradableDates = true; /// <summary> /// Check loading dates are they tradable. /// </summary> [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CheckDatesKey, Description = LocalizedStrings.CheckDatesDescKey, GroupName = LocalizedStrings.Str1174Key, Order = 106)] public bool CheckTradableDates { get => _checkTradableDates; set { _checkTradableDates = value; NotifyPropertyChanged(nameof(CheckTradableDates)); } } #endregion #region Debug private LogLevels _logLevel; /// <summary> /// Logging level. /// </summary> [CategoryLoc(LocalizedStrings.Str12Key)] [Display( ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str9Key, Description = LocalizedStrings.Str9Key + LocalizedStrings.Dot, GroupName = LocalizedStrings.Str12Key, Order = 200)] public LogLevels LogLevel { get => _logLevel; set { _logLevel = value; NotifyPropertyChanged(nameof(LogLevel)); } } #endregion /// <summary> /// Initializes a new instance of the <see cref="EmulationSettings"/>. /// </summary> public EmulationSettings() { MarketTimeChangedInterval = TimeSpan.FromMinutes(1); LogLevel = LogLevels.Info; } /// <summary> /// To save the state of paper trading parameters. /// </summary> /// <param name="storage">Storage.</param> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(StartTime), StartTime); storage.SetValue(nameof(StopTime), StopTime); storage.SetValue(nameof(OrderLogDataMode), OrderLogDataMode.To<string>()); storage.SetValue(nameof(DepthDataMode), DepthDataMode.To<string>()); storage.SetValue(nameof(MarketTimeChangedInterval), MarketTimeChangedInterval); storage.SetValue(nameof(UnrealizedPnLInterval), UnrealizedPnLInterval); storage.SetValue(nameof(LogLevel), LogLevel.To<string>()); storage.SetValue(nameof(TradeDataMode), TradeDataMode.To<string>()); storage.SetValue(nameof(BatchSize), BatchSize); storage.SetValue(nameof(CheckTradableDates), CheckTradableDates); } /// <summary> /// To load the state of paper trading parameters. /// </summary> /// <param name="storage">Storage.</param> public override void Load(SettingsStorage storage) { base.Load(storage); StartTime = storage.GetValue(nameof(StartTime), StartTime); StopTime = storage.GetValue(nameof(StopTime), StopTime); OrderLogDataMode = storage.GetValue(nameof(OrderLogDataMode), OrderLogDataMode); DepthDataMode = storage.GetValue(nameof(DepthDataMode), DepthDataMode); MarketTimeChangedInterval = storage.GetValue(nameof(MarketTimeChangedInterval), MarketTimeChangedInterval); UnrealizedPnLInterval = storage.GetValue(nameof(UnrealizedPnLInterval), UnrealizedPnLInterval); LogLevel = storage.GetValue(nameof(LogLevel), LogLevel); TradeDataMode = storage.GetValue(nameof(TradeDataMode), TradeDataMode); BatchSize = storage.GetValue(nameof(BatchSize), BatchSize); CheckTradableDates = storage.GetValue(nameof(CheckTradableDates), CheckTradableDates); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using NewRelic.Microsoft.SqlServer.Plugin.Configuration; using NewRelic.Microsoft.SqlServer.Plugin.Core.Extensions; using NewRelic.Microsoft.SqlServer.Plugin.Properties; using NewRelic.Microsoft.SqlServer.Plugin.QueryTypes; using NewRelic.Platform.Sdk.Utils; using NewRelic.Platform.Sdk.Configuration; namespace NewRelic.Microsoft.SqlServer.Plugin { public abstract class SqlEndpointBase : ISqlEndpoint { private static readonly Logger _log = Logger.GetLogger(typeof(MetricCollector).Name); private SqlQuery[] _queries; protected SqlEndpointBase(string name, string connectionString) { Name = name; ConnectionString = connectionString; SqlDmlActivityHistory = new Dictionary<string, SqlDmlActivity>(); IncludedDatabases = new Database[0]; ExcludedDatabaseNames = new string[0]; } protected abstract string ComponentGuid { get; } protected Dictionary<string, SqlDmlActivity> SqlDmlActivityHistory { get; set; } public Database[] IncludedDatabases { get; protected set; } public string[] IncludedDatabaseNames { get { return IncludedDatabases.Select(d => d.Name).ToArray(); } } public string[] ExcludedDatabaseNames { get; protected set; } public string Name { get; private set; } public string ConnectionString { get; private set; } public void SetQueries(IEnumerable<SqlQuery> queries) { _queries = FilterQueries(queries).ToArray(); } public virtual IEnumerable<IQueryContext> ExecuteQueries() { return ExecuteQueries(_queries, ConnectionString); } public virtual void ToLog() { // Remove password from logging var safeConnectionString = new SqlConnectionStringBuilder(ConnectionString); if (!string.IsNullOrEmpty(safeConnectionString.Password)) { safeConnectionString.Password = "[redacted]"; } _log.Info(" {0}: {1}", Name, safeConnectionString); // Validate that connection string do not provide both Trusted Security AND user/password bool hasUserCreds = !string.IsNullOrEmpty(safeConnectionString.UserID) || !string.IsNullOrEmpty(safeConnectionString.Password); if (safeConnectionString.IntegratedSecurity == hasUserCreds) { _log.Error("=================================================="); _log.Error("Connection string for '{0}' may not contain both Integrated Security and User ID/Password credentials. " + "Review the readme.md and update the config file.", safeConnectionString.DataSource); _log.Error("=================================================="); } } protected IEnumerable<IQueryContext> ExecuteQueries(SqlQuery[] queries, string connectionString) { // Remove password from logging var safeConnectionString = new SqlConnectionStringBuilder(connectionString); if (!string.IsNullOrEmpty(safeConnectionString.Password)) { safeConnectionString.Password = "[redacted]"; } _log.Info("Connecting with {0}", safeConnectionString); using (var conn = new SqlConnection(connectionString)) { foreach (SqlQuery query in queries) { object[] results; try { // Raw results from the database results = query.Query(conn, this).ToArray(); // Log them LogVerboseSqlResults(query, results); // Allow them to be transformed results = OnQueryExecuted(query, results); } catch (Exception e) { _log.Error(string.Format("Error with query '{0}' at endpoint '{1}'", query.QueryName, safeConnectionString), e); LogErrorSummary(e, query); continue; } yield return CreateQueryContext(query, results); } } } protected static void LogVerboseSqlResults(ISqlQuery query, IEnumerable<object> results) { // This could be slow, so only proceed if it actually gets logged if (Logger.LogLevel != LogLevel.Debug) return; var verboseLogging = new StringBuilder(); verboseLogging.AppendFormat("Executed {0}", query.ResourceName).AppendLine(); foreach (object result in results) { verboseLogging.AppendLine(result.ToString()); } _log.Info(verboseLogging.ToString()); } internal QueryContext CreateQueryContext(IMetricQuery query, IEnumerable<object> results) { return new QueryContext(query) {Results = results, ComponentName = Name, ComponentGuid = ComponentGuid }; } protected internal abstract IEnumerable<SqlQuery> FilterQueries(IEnumerable<SqlQuery> queries); protected virtual object[] OnQueryExecuted(ISqlQuery query, object[] results) { // TODO: We should be able to remove the special casing of SqlDmlActivity here, but simply changing it to a delta counter doe return query.QueryType == typeof (SqlDmlActivity) ? CalculateSqlDmlActivityIncrease(results) : results; } public override string ToString() { return string.Format("Name: {0}, ConnectionString: {1}", Name, ConnectionString); } internal object[] CalculateSqlDmlActivityIncrease(object[] inputResults) { if (inputResults == null || inputResults.Length == 0) { _log.Error("No values passed to CalculateSqlDmlActivityIncrease"); return inputResults; } SqlDmlActivity[] sqlDmlActivities = inputResults.OfType<SqlDmlActivity>().ToArray(); if (!sqlDmlActivities.Any()) { _log.Error("In trying to Process results for SqlDmlActivity, results were NULL or not of the appropriate type"); return inputResults; } Dictionary<string, SqlDmlActivity> currentValues = sqlDmlActivities .GroupBy(a => string.Format("{0}:{1}:{2}:{3}", BitConverter.ToString(a.PlanHandle), BitConverter.ToString(a.SqlStatementHash), a.CreationTime.Ticks, a.QueryType)) .Select(a => new { a.Key, //If we ever gets dupes, sum Excution Count Activity = new SqlDmlActivity { CreationTime = a.First().CreationTime, SqlStatementHash = a.First().SqlStatementHash, PlanHandle = a.First().PlanHandle, QueryType = a.First().QueryType, ExecutionCount = a.Sum(dml => dml.ExecutionCount), } }) .ToDictionary(a => a.Key, a => a.Activity); long reads = 0; long writes = 0; // If this is the first time through, reads and writes are definitely 0 if (SqlDmlActivityHistory.Count > 0) { currentValues .ForEach(a => { long increase; // Find a matching previous value for a delta SqlDmlActivity previous; if (!SqlDmlActivityHistory.TryGetValue(a.Key, out previous)) { // Nothing previous, the delta is the absolute value here increase = a.Value.ExecutionCount; } else if (a.Value.QueryType == previous.QueryType) { // Calculate the delta increase = a.Value.ExecutionCount - previous.ExecutionCount; // Only record positive deltas, though theoretically impossible here if (increase <= 0) return; } else { return; } switch (a.Value.QueryType) { case "Writes": writes += increase; break; case "Reads": reads += increase; break; } }); } //Current Becomes the new history SqlDmlActivityHistory = currentValues; _log.Info("SQL DML Activity: Reads={0} Writes={1}", reads, writes); _log.Info(""); //return the sum of all increases for reads and writes //if there is was no history (first time for this db) then reads and writes will be 0 return new object[] { new SqlDmlActivity { Reads = reads, Writes = writes, }, }; } private void LogErrorSummary(Exception e, ISqlQuery query) { var sqlException = e.InnerException as SqlException; if (sqlException == null) return; SqlErrorReporter.LogSqlException(sqlException, query, ConnectionString); } } }
/** * @(#) SLAgentCS.cs * * Copyright (c) 2008-2009, Christian Bayer, christian_bay@gmx.de * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team 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. * * * This Software incorporates source code copyrighted (c) by Second Life Reverse Engineering Team, 2006-2008 * and though must include this notice: * * Copyright (c) 2006-2008, Second Life Reverse Engineering Team * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Nwc.XmlRpc; using libsecondlife; using libsecondlife.Packets; using libsecondlife.Imaging; namespace CSSLAgentServer { public class SLAgentCS : SecondLife { // XML-RPC stuff string XmlRpcAgencyConnectorUrl = "http://127.0.0.1:5051"; XmlRpcRequest XmlRpcAgencyConnector = new XmlRpcRequest(); string agentName; /// <summary> /// <c>LoggerDelegate</c> compliant method that does logging to Console. /// This method filters out the <c>LogLevel.Information</c> chatter. /// </summary> public void writeEntry(string msg, LogLevel level) { if (level > LogLevel.Information) // ignore debug msgs Console.WriteLine("{0}: {1}", level, msg); } // Avatar name to LUUID mapping async -> sync helpers string toAvatarName = string.Empty; ManualResetEvent nameSearchEvent = new ManualResetEvent(false); Dictionary<string, LLUUID> name2Key = new Dictionary<string, LLUUID>(); // Avatar Appearance helpers Dictionary<LLUUID, AvatarAppearancePacket> appearances = new Dictionary<LLUUID, AvatarAppearancePacket>(); uint SerialNum = 2; // Group IM init async -> sync helpers LLUUID toGroupID = LLUUID.Zero; ManualResetEvent waitForSessionStart = new ManualResetEvent(false); // Master handling LLUUID masterKey = LLUUID.Zero; // Teleport Queue Helper Event ManualResetEvent waitOnEventQueueEvent = new ManualResetEvent(false); // Is Avatar Online Helper Event ManualResetEvent ReceivedAvatarPropertiesEvent = new ManualResetEvent(false); Avatar.AvatarProperties avatarProperties; void onChatMessageReceive(string message, ChatAudibleLevel audible, ChatType type, ChatSourceType sourceType, string fromName, LLUUID id, LLUUID ownerid, LLVector3 position) { if ((message.Length != 0) && (message != null) && (message != String.Empty) && !(id == Self.AgentID)) { Self.AutoPilotCancel(); string[] sender = fromName.Split(' '); XmlRpcAgencyConnector.MethodName = "XmlRpcAgencyConnector.onChatMessageReceive"; XmlRpcAgencyConnector.Params.Clear(); XmlRpcAgencyConnector.Params.Add(agentName); XmlRpcAgencyConnector.Params.Add(message); XmlRpcAgencyConnector.Params.Add((int)position.X); XmlRpcAgencyConnector.Params.Add((int)position.Y); XmlRpcAgencyConnector.Params.Add((int)position.Z); XmlRpcAgencyConnector.Params.Add(sender[0]); XmlRpcAgencyConnector.Params.Add(sender[1]); try { #if DEBUG Console.WriteLine("Request: " + XmlRpcAgencyConnector); #endif XmlRpcResponse response = XmlRpcAgencyConnector.Send(XmlRpcAgencyConnectorUrl); #if DEBUG Console.WriteLine("Response: " + response); #endif if (response.IsFault) { #if DEBUG Console.WriteLine("Fault {0}: {1}", response.FaultCode, response.FaultString); #endif } else { #if DEBUG Console.WriteLine("Returned: " + response.Value); #endif } } catch (Exception e) { Console.WriteLine("Exception " + e); } } } void onIMReceive(InstantMessage im, Simulator simulator) { #if DEBUG Console.WriteLine("<{0} ({1})> {2}: {3} (@{4}:{5})", im.GroupIM ? "GroupIM" : "IM", im.Dialog, im.FromAgentName, im.Message, im.RegionID, im.Position); #endif string[] sender = im.FromAgentName.Split(' '); XmlRpcAgencyConnector.MethodName = "XmlRpcAgencyConnector.onIMReceive"; XmlRpcAgencyConnector.Params.Clear(); XmlRpcAgencyConnector.Params.Add(agentName); XmlRpcAgencyConnector.Params.Add(im.Message); XmlRpcAgencyConnector.Params.Add(sender[0]); XmlRpcAgencyConnector.Params.Add(sender[1]); try { #if DEBUG Console.WriteLine("Request: " + XmlRpcAgencyConnector); #endif XmlRpcResponse response = XmlRpcAgencyConnector.Send(XmlRpcAgencyConnectorUrl); #if DEBUG Console.WriteLine("Response: " + response); #endif if (response.IsFault) { #if DEBUG Console.WriteLine("Fault {0}: {1}", response.FaultCode, response.FaultString); #endif } else { #if DEBUG Console.WriteLine("Returned: " + response.Value); #endif } } catch (Exception e) { Console.WriteLine("Exception " + e); } } // synchronous public bool teleportToPosition(string island, int x, int y, int z) { waitOnEventQueueEvent.WaitOne(6000, false); waitOnEventQueueEvent.Reset(); island = island.Trim(); if (Self.Teleport(island, new LLVector3((float)x, (float)y, (float)z))) { #if DEBUG Console.Out.WriteLine("Teleported to {0}", Network.CurrentSim); #endif return true; } else { #if DEBUG Console.Out.WriteLine("Teleport failed: {0}", Self.TeleportMessage); #endif return false; } } public bool clone(String firstName, String lastName) { string targetName = String.Empty; List<DirectoryManager.AgentSearchData> matches; targetName = firstName + " " + lastName; targetName = targetName.TrimEnd(); if (targetName.Length == 0) return false; if (Directory.PeopleSearch(DirectoryManager.DirFindFlags.People, targetName, 0, 1000 * 10, out matches) && matches.Count > 0) { LLUUID target = matches[0].AgentID; targetName += String.Format(" ({0})", target); return clone(target); } else { #if DEBUG Console.Out.WriteLine("Couldn't find avatar {0}", targetName); #endif return false; } } bool clone(LLUUID target) { if (appearances.ContainsKey(target)) { #region AvatarAppearance to AgentSetAppearance AvatarAppearancePacket appearance = appearances[target]; AgentSetAppearancePacket set = new AgentSetAppearancePacket(); set.AgentData.AgentID = Self.AgentID; set.AgentData.SessionID = Self.SessionID; set.AgentData.SerialNum = SerialNum++; set.AgentData.Size = new LLVector3(2f, 2f, 2f); // HACK set.WearableData = new AgentSetAppearancePacket.WearableDataBlock[0]; set.VisualParam = new AgentSetAppearancePacket.VisualParamBlock[appearance.VisualParam.Length]; for (int i = 0; i < appearance.VisualParam.Length; i++) { set.VisualParam[i] = new AgentSetAppearancePacket.VisualParamBlock(); set.VisualParam[i].ParamValue = appearance.VisualParam[i].ParamValue; } set.ObjectData.TextureEntry = appearance.ObjectData.TextureEntry; #endregion AvatarAppearance to AgentSetAppearance // Detach everything we are currently wearing Appearance.AddAttachments(new List<InventoryBase>(), true); // Send the new appearance packet Network.SendPacket(set); #if DEBUG Console.Out.WriteLine("Cloned {0}", target.ToString()); #endif return true; } else { #if DEBUG Console.Out.WriteLine("Don't know the appearance of avatar {0}", target.ToString()); #endif return false; } } public bool isAvatarOnline(String firstName, String lastName) { LLUUID avatarKey = LLUUID.Zero; lock (toAvatarName) { toAvatarName = firstName + " " + lastName; if (!name2Key.ContainsKey(toAvatarName.ToLower())) { // Send the Query Avatars.RequestAvatarNameSearch(toAvatarName, LLUUID.Random()); nameSearchEvent.WaitOne(6000, false); } if (name2Key.ContainsKey(toAvatarName.ToLower())) { avatarKey = name2Key[toAvatarName.ToLower()]; Avatars.RequestAvatarProperties(avatarKey); ReceivedAvatarPropertiesEvent.Reset(); ReceivedAvatarPropertiesEvent.WaitOne(5000, false); return avatarProperties.Online; } else { #if DEBUG Console.Out.WriteLine("Name lookup for {0} failed", toAvatarName); #endif return false; } } } void onAvatarProperties(LLUUID avatarID, Avatar.AvatarProperties properties) { lock (ReceivedAvatarPropertiesEvent) { avatarProperties = properties; ReceivedAvatarPropertiesEvent.Set(); } } // synchronous public bool setMaster(string masterFirstName, string masterLastName) { lock (toAvatarName) { toAvatarName = masterFirstName + " " + masterLastName; if (!name2Key.ContainsKey(toAvatarName.ToLower())) { // Send the Query Avatars.RequestAvatarNameSearch(toAvatarName, LLUUID.Random()); nameSearchEvent.WaitOne(6000, false); } if (name2Key.ContainsKey(toAvatarName.ToLower())) { masterKey = name2Key[toAvatarName.ToLower()]; return clone(masterKey); } else { #if DEBUG Console.Out.WriteLine("Name lookup for {0} failed", toAvatarName); #endif return false; } } } // synchronous // Only works with non-LUUID-recipients if these recipients are logged in!! // if recipientLastName == "LLUUID", recipientFirstName is expected to contain a valid LLUUID // for instant messagin while avatar isn't online public bool sendIM(string message, string recipientFirstName, string recipientLastName) { LLUUID id = LLUUID.Zero; // passed LLUUID directly if (recipientLastName.Equals("LLUUID")) { if (!LLUUID.TryParse(recipientFirstName, out id)) { #if DEBUG Console.Out.WriteLine("LLUUID parsing for {0} failed", recipientFirstName); #endif return false; } } // get LLUUID by friedship list lookup else if (Friends.FriendList.Count > 0) { Friends.FriendList.ForEach(delegate(FriendInfo friend) { #if DEBUG Console.Out.WriteLine(friend.Name); #endif String tmpAvatarName = recipientFirstName + " " + recipientLastName; if (friend.Name.ToLower() == tmpAvatarName.ToLower()) { id = friend.UUID; } }); } // lookup LLUUID through system, only works if recipients are logged in!! if (id == LLUUID.Zero) { lock (toAvatarName) { toAvatarName = recipientFirstName + " " + recipientLastName; if (!name2Key.ContainsKey(toAvatarName.ToLower())) { // Send the Query Avatars.RequestAvatarNameSearch(toAvatarName, LLUUID.Random()); nameSearchEvent.WaitOne(6000, false); } if (name2Key.ContainsKey(toAvatarName.ToLower())) { id = name2Key[toAvatarName.ToLower()]; } else { #if DEBUG Console.Out.WriteLine("Name lookup for {0} failed", toAvatarName); #endif return false; } } } // Build the message message = message.TrimEnd(); if (message.Length > 1023) message = message.Remove(1023); Self.InstantMessage(id, message); #if DEBUG Console.Out.WriteLine("Instant Messaged {0} with message: {1}", id.ToString(), message); #endif return true; } public bool sendGroupIM(string message, string groupUUID) { message = message.TrimEnd(); if (message.Length > 1023) message = message.Remove(1023); Self.OnGroupChatJoin += new AgentManager.GroupChatJoined(onGroupChatJoin); if (!Self.GroupChatSessions.ContainsKey(toGroupID)) { waitForSessionStart.Reset(); Self.RequestJoinGroupChat(toGroupID); } else { waitForSessionStart.Set(); } if (waitForSessionStart.WaitOne(10000, false)) { Self.InstantMessageGroup(toGroupID, message); } else { #if DEBUG Console.Out.WriteLine("Timeout waiting for group session start"); #endif Self.OnGroupChatJoin -= new AgentManager.GroupChatJoined(onGroupChatJoin); return false; } Self.OnGroupChatJoin -= new AgentManager.GroupChatJoined(onGroupChatJoin); #if DEBUG Console.Out.WriteLine("Instant Messaged group {0} with message: {1}", toGroupID.ToString(), message); #endif return true; } public bool sendChatMessage(string message) { switch (message) { case "/kmb" : Self.AnimationStart(Animations.KISS_MY_BUTT, true); break; case "/yes!": Self.AnimationStart(Animations.YES, true); break; case "/no": Self.AnimationStart(Animations.NO, true); break; case "/pointme": Self.AnimationStart(Animations.POINT_ME, true); break; case "/pointyou": Self.AnimationStart(Animations.POINT_YOU, true); break; case "/bow": Self.AnimationStart(Animations.BOW, true); break; case "/stretch": Self.AnimationStart(Animations.STRETCH, true); break; case "/muscle": Self.AnimationStart(Animations.MUSCLE_BEACH, true); break; default: Self.Chat(message, 0, ChatType.Normal); break; } #if DEBUG Console.Out.WriteLine("Said {0}", message); #endif return true; } public bool moveToPosition(int x, int y, int z) { /* uint regionX, regionY; Helpers.LongToUInts(Network.CurrentSim.Handle, out regionX, out regionY); // Convert the local coordinates to global ones by adding the region handle parts to x and y x += (double)regionX; y += (double)regionY; LLVector3 pos = Self.SimPosition; Self.AutoPilotLocal((int)(pos.X + x), (int)(pos.Y + y), (float)z); */ Self.AutoPilotLocal(x, y, z); #if DEBUG Console.Out.WriteLine("Attempting to move to <{0},{1},{2}>", x, y, z); #endif return true; } // still asynchronous, but no use in waiting for logout message... public bool logout() { Network.Logout(); return true; } // synchronous public bool connectWithLogin(string agentName, string firstName, string lastName, string password) { #if DEBUG Console.WriteLine("{0}, {1}, {2}", firstName, lastName, password); LoginParams loginParams = Network.DefaultLoginParams(firstName, lastName, password, "CSSLAgentServer", "1.0.0"); #endif this.agentName = agentName; return Network.Login(loginParams); } void onAvatarNameSearch(LLUUID queryID, Dictionary<LLUUID, string> avatars) { foreach (KeyValuePair<LLUUID, string> kvp in avatars) { if (kvp.Value.ToLower() == toAvatarName.ToLower()) { name2Key[toAvatarName.ToLower()] = kvp.Key; nameSearchEvent.Set(); return; } } } void onGroupChatJoin(LLUUID groupChatSessionID, LLUUID tmpSessionID, bool success) { if (success) { #if DEBUG Console.WriteLine("Join Group Chat Success!"); #endif waitForSessionStart.Set(); } else { #if DEBUG Console.WriteLine("Join Group Chat failed :("); #endif } } void avatarAppearanceHandler(Packet packet, Simulator simulator) { AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet; lock (appearances) appearances[appearance.Sender.ID] = appearance; } void alertMessageHandler(Packet packet, Simulator simulator) { AlertMessagePacket message = (AlertMessagePacket)packet; libsecondlife.Logger.Log("[AlertMessage] " + Helpers.FieldToUTF8String(message.AlertData.Message), Helpers.LogLevel.Info, this); } void onEventQueueRunning(Simulator simulator) { if (simulator == Network.CurrentSim) { Console.WriteLine("Event queue connected for the primary simulator, ready for teleport"); waitOnEventQueueEvent.Set(); } } void onLogout(NetworkManager.DisconnectType type, string message) { XmlRpcAgencyConnector.MethodName = "XmlRpcAgencyConnector.onLogout"; XmlRpcAgencyConnector.Params.Clear(); XmlRpcAgencyConnector.Params.Add(agentName); try { #if DEBUG Console.WriteLine("Request: " + XmlRpcAgencyConnector); #endif XmlRpcResponse response = XmlRpcAgencyConnector.Send(XmlRpcAgencyConnectorUrl); #if DEBUG Console.WriteLine("Response: " + response); #endif if (response.IsFault) { #if DEBUG Console.WriteLine("Fault {0}: {1}", response.FaultCode, response.FaultString); #endif } else { #if DEBUG Console.WriteLine("Returned: " + response.Value); #endif } } catch (Exception e) { Console.WriteLine("Exception " + e); } } public SLAgentCS() { //Settings.MULTIPLE_SIMS = false; // Throttle unnecessary things down Throttle.Wind = 0; Throttle.Cloud = 0; Throttle.Land = 1000000; Throttle.Task = 1000000; Settings.LOG_RESENDS = false; Settings.STORE_LAND_PATCHES = true; Settings.ALWAYS_DECODE_OBJECTS = true; Settings.ALWAYS_REQUEST_OBJECTS = true; Settings.SEND_AGENT_UPDATES = true; Settings.USE_TEXTURE_CACHE = true; Self.OnInstantMessage += new AgentManager.InstantMessageCallback(onIMReceive); Self.OnChat += new AgentManager.ChatCallback(onChatMessageReceive); Avatars.OnAvatarNameSearch += new AvatarManager.AvatarNameSearchCallback(onAvatarNameSearch); Avatars.OnAvatarProperties += new AvatarManager.AvatarPropertiesCallback(onAvatarProperties); Network.RegisterCallback(PacketType.AvatarAppearance, new NetworkManager.PacketCallback(avatarAppearanceHandler)); Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(alertMessageHandler)); Network.OnDisconnected += new NetworkManager.DisconnectedCallback(onLogout); Network.OnEventQueueRunning += new NetworkManager.EventQueueRunningCallback(onEventQueueRunning); //Groups.OnCurrentGroups += new GroupManager.CurrentGroupsCallback(OnCurrentGroups); //Network.OnLogin += new NetworkManager.LoginCallback(OnLogin); } ~SLAgentCS() { Self.OnInstantMessage -= new AgentManager.InstantMessageCallback(onIMReceive); Self.OnChat -= new AgentManager.ChatCallback(onChatMessageReceive); Avatars.OnAvatarNameSearch -= new AvatarManager.AvatarNameSearchCallback(onAvatarNameSearch); //Network.Logout(); } } }
//! \file YuzCrypt.cs //! \date 2018 Apr 01 //! \brief YuzuSoft KiriKiri encryption schemes. // // Copyright (C) 2018 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Text; using GameRes.Compression; using GameRes.Utility; namespace GameRes.Formats.KiriKiri { [Serializable] public class SenrenCxCrypt : CxEncryption { public SenrenCxCrypt (CxScheme scheme) : base (scheme) { } public virtual string NamesSectionId { get { return "sen:"; } } internal virtual void ReadYuzNames (byte[] yuz, FilenameMap filename_map) { using (var ystream = new MemoryStream (yuz)) using (var zstream = ZLibCompressor.DeCompress (ystream)) using (var input = new BinaryReader (zstream, Encoding.Unicode)) { long dir_offset = 0; while (-1 != input.PeekChar()) { uint entry_signature = input.ReadUInt32(); long entry_size = input.ReadInt64(); if (entry_size < 0) return; dir_offset += 12 + entry_size; uint hash = input.ReadUInt32(); int name_size = input.ReadInt16(); if (name_size > 0) { entry_size -= 6; if (name_size * 2 <= entry_size) { var filename = new string (input.ReadChars (name_size)); filename_map.Add (hash, filename); } } input.BaseStream.Position = dir_offset; } filename_map.AddShortcut ("$", "startup.tjs"); } } } [Serializable] public class CabbageCxCrypt : SenrenCxCrypt { uint m_random_seed; public CabbageCxCrypt (CxScheme scheme, uint seed) : base (scheme) { m_random_seed = seed; } public override string NamesSectionId { get { return "cbg:"; } } internal override CxProgram NewProgram (uint seed) { return new CxProgramNana (seed, m_random_seed, ControlBlock); } } [Serializable] public class NanaCxCrypt : CabbageCxCrypt { public uint[] YuzKey; public NanaCxCrypt (CxScheme scheme, uint seed) : base (scheme, seed) { } public override string NamesSectionId { get { return "dls:"; } } internal override void ReadYuzNames (byte[] yuz, FilenameMap filename_map) { if (null == YuzKey) throw new InvalidEncryptionScheme(); var decryptor = CreateNameListDecryptor(); decryptor.Decrypt (yuz, Math.Min (yuz.Length, 0x100)); base.ReadYuzNames (yuz, filename_map); } internal virtual INameListDecryptor CreateNameListDecryptor () { return new NanaDecryptor (YuzKey, YuzKey[4], YuzKey[5]); } } [Serializable] public class RiddleCxCrypt : NanaCxCrypt { public RiddleCxCrypt (CxScheme scheme, uint seed) : base (scheme, seed) { } public override string NamesSectionId { get { return "yuz:"; } } public override void Decrypt (Xp3Entry entry, long offset, byte[] buffer, int pos, int count) { ProcessFirstBytes (entry, offset, buffer, pos, count); base.Decrypt (entry, offset, buffer, pos, count); } public override void Encrypt (Xp3Entry entry, long offset, byte[] buffer, int pos, int count) { base.Encrypt (entry, offset, buffer, pos, count); ProcessFirstBytes (entry, offset, buffer, pos, count); } public override byte Decrypt (Xp3Entry entry, long offset, byte value) { if (offset < 8) { var buffer = new byte[1] { value }; this.Decrypt (entry, offset, buffer, 0, 1); return buffer[0]; } else { return base.Decrypt (entry, offset, value); } } internal void ProcessFirstBytes (Xp3Entry entry, long offset, byte[] buffer, int pos, int count) { if (offset < 8 && count > 0) { ulong key = GetKeyFromHash (entry.Hash); key >>= (int)offset << 3; int first_chunk = Math.Min (count, 8 - (int)offset); for (int i = 0; i < first_chunk; ++i) { buffer[pos+i] ^= (byte)key; key >>= 8; } } } internal ulong GetKeyFromHash (uint hash) { uint lo = hash ^ 0x55555555; uint hi = (hash << 13) ^ hash; hi ^= hi >> 17; hi ^= (hi << 5) ^ 0xAAAAAAAA; return (ulong)hi << 32 | lo; } internal override INameListDecryptor CreateNameListDecryptor () { return new YuzDecryptor (ControlBlock, YuzKey, YuzKey[4], YuzKey[5]); } } internal interface INameListDecryptor { void Decrypt (byte[] data, int length); } internal class YuzDecryptor : INameListDecryptor { byte[] m_state; public YuzDecryptor (uint[] key1, uint[] key2, uint seed1, uint seed2) { m_state = new byte[64]; Buffer.BlockCopy (key2, 0, m_state, 0, 16); Buffer.BlockCopy (key1, 0, m_state, 16, 32); LittleEndian.Pack (~0, m_state, 48); LittleEndian.Pack (~0, m_state, 52); LittleEndian.Pack (~seed1, m_state, 56); LittleEndian.Pack (~seed2, m_state, 60); } public void Decrypt (byte[] data, int length) { var state1 = new byte[64]; var state2 = new byte[64]; int i = 0; ulong offset = 0; while (length > 0) { Buffer.BlockCopy (m_state, 0, state1, 0, 64); LittleEndian.Pack (~offset++, state1, 48); TransformState (state1, state2, 8); int count = Math.Min (0x40, length); for (int j = 0; j < count; ++j) { data[i++] ^= state2[j]; } length -= count; } } uint[] tmp = new uint[16]; void TransformState (byte[] state1, byte[] target, int length) { for (int i = 0; i < 16; ++i) { tmp[i] = ~LittleEndian.ToUInt32 (state1, i * 4); } if (length > 0) { for (int count = ((length - 1) >> 1) + 1; count > 0; --count) { uint t1 = tmp[4] + tmp[0]; uint t2 = Binary.RotL (t1 ^ tmp[12], 16); uint t3 = t2 + tmp[8]; uint t4 = Binary.RotL (tmp[4] ^ t3, 12); uint t5 = t4 + t1; uint t6 = Binary.RotL (t5 ^ t2, 8); tmp[12] = t6; t6 += t3; tmp[4] = Binary.RotL (t4 ^ t6, 7); t4 = Binary.RotL ((tmp[5] + tmp[1]) ^ tmp[13], 16); t3 = Binary.RotL (tmp[5] ^ (t4 + tmp[9]), 12); t2 = t3 + tmp[5] + tmp[1]; tmp[13] = Binary.RotL (t2 ^ t4, 8); tmp[9] += tmp[13] + t4; tmp[5] = Binary.RotL (t3 ^ tmp[9], 7); t4 = Binary.RotL ((tmp[6] + tmp[2]) ^ tmp[14], 16); tmp[10] += t4; t1 = Binary.RotL (tmp[6] ^ tmp[10], 12); t3 = t1 + tmp[6] + tmp[2]; tmp[14] = Binary.RotL (t3 ^ t4, 8); tmp[6] = Binary.RotL (t1 ^ (tmp[14] + tmp[10]), 7); tmp[10] += tmp[14]; t4 = (tmp[7] + tmp[3]) ^ tmp[15]; tmp[3] += tmp[7]; t4 = Binary.RotL (t4, 16); tmp[11] += t4; t1 = Binary.RotL (tmp[7] ^ tmp[11], 12); t4 ^= t1 + tmp[3]; tmp[3] += t1; t4 = Binary.RotL (t4, 8); tmp[11] += t4; t1 = Binary.RotL (t1 ^ tmp[11], 7); t5 += tmp[5]; t2 += tmp[6]; t4 = Binary.RotL (t5 ^ t4, 16); tmp[10] += t4; tmp[5] = Binary.RotL (tmp[5] ^ tmp[10], 12); tmp[0] = tmp[5] + t5; t4 = Binary.RotL (tmp[0] ^ t4, 8); tmp[15] = t4; tmp[10] += t4; tmp[5] = Binary.RotL (tmp[5] ^ tmp[10], 7); tmp[12] = Binary.RotL (tmp[12] ^ t2, 16); tmp[11] += tmp[12]; t4 = Binary.RotL (tmp[11] ^ tmp[6], 12); tmp[1] = t4 + t2; tmp[12] = Binary.RotL (tmp[12] ^ tmp[1], 8); tmp[11] += tmp[12]; tmp[6] = Binary.RotL (t4 ^ tmp[11], 7); t3 += t1; t4 = Binary.RotL (tmp[13] ^ t3, 16); t2 = t4 + t6; t1 = Binary.RotL (t2 ^ t1, 12); tmp[2] = t1 + t3; tmp[13] = Binary.RotL (t4 ^ tmp[2], 8); tmp[8] = tmp[13] + t2; tmp[7] = Binary.RotL (tmp[8] ^ t1, 7); t6 = Binary.RotL (tmp[14] ^ (tmp[4] + tmp[3]), 16); t1 = Binary.RotL (tmp[4] ^ (t6 + tmp[9]), 12); tmp[3] += t1 + tmp[4]; t3 = Binary.RotL (t6 ^ tmp[3], 8); tmp[9] += t3 + t6; tmp[4] = Binary.RotL (t1 ^ tmp[9], 7); tmp[14] = t3; } } int pos = 0; for (int i = 0; i < 16; ++i) { uint x = tmp[i] + ~LittleEndian.ToUInt32 (state1, pos); LittleEndian.Pack (x, target, pos); pos += 4; } } } internal class NanaDecryptor : INameListDecryptor { uint[] m_state; ulong m_seed; public NanaDecryptor (uint[] key, uint seed1, uint seed2) { m_state = new uint[27]; m_seed = (ulong)seed2 << 32 | seed1; var s = new uint[3]; uint k = key[0]; s[0] = key[1]; s[1] = key[2]; s[2] = key[3]; m_state[0] = k; int dst = 1; for (uint i = 0; i < 26; ++i) { int src = (int)i % 3; uint m = Binary.RotR (s[src], 8); uint n = i ^ (k + m); k = n ^ Binary.RotL (k, 3); m_state[dst++] = k; s[src] = n; } } public void Decrypt (byte[] data, int length) { int i = 0; ulong offset = 0; while (length > 0) { ulong key = ++offset ^ m_seed; key = TransformKey (key); int count = Math.Min (8, length); for (int j = 0; j < count; ++j) { data[i++] ^= (byte)key; key >>= 8; } length -= count; } } ulong TransformKey (ulong key) { uint lo = (uint)key; uint hi = (uint)(key >> 32); for (int i = 0; i < 27; ++i) { hi = Binary.RotR (hi, 8); hi += lo; hi ^= m_state[i]; lo = Binary.RotL (lo, 3); lo ^= hi; } return (ulong)hi << 32 | lo; } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using Encog.ML.EA.Genome; using Encog.ML.EA.Species; using Encog.ML.Prg.ExpValue; using Encog.ML.Prg.Ext; using Encog.ML.Prg.Train; using Encog.Persist; using Encog.Util; using Encog.Util.CSV; namespace Encog.ML.Prg { /// <summary> /// Persist a population of Encog programs. /// </summary> public class PersistPrgPopulation : IEncogPersistor { /// <inheritdoc /> public int FileVersion { get { return 1; } } /// <inheritdoc /> public String PersistClassString { get { return "PrgPopulation"; } } /// <inheritdoc /> public Object Read(Stream istream) { var context = new EncogProgramContext(); var result = new PrgPopulation(context, 0); var reader = new EncogReadHelper(istream); EncogFileSection section; int count = 0; ISpecies lastSpecies = null; while ((section = reader.ReadNextSection()) != null) { if (section.SectionName.Equals("BASIC") && section.SubSectionName.Equals("PARAMS")) { IDictionary<string, string> prms = section.ParseParams(); EngineArray.PutAll(prms, result.Properties); } else if (section.SectionName.Equals("BASIC") && section.SubSectionName.Equals("EPL-POPULATION")) { foreach (string line in section.Lines) { IList<String> cols = EncogFileSection.SplitColumns(line); if (String.Compare(cols[0], "s", StringComparison.OrdinalIgnoreCase) == 0) { lastSpecies = new BasicSpecies { Age = int.Parse(cols[1]), BestScore = CSVFormat.EgFormat.Parse(cols[2]), Population = result, GensNoImprovement = int.Parse(cols[3]) }; result.Species.Add(lastSpecies); } else if (cols[0].Equals("p")) { double score; double adjustedScore; if (String.Compare(cols[1], "nan", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(cols[2], "nan", StringComparison.OrdinalIgnoreCase) == 0) { score = Double.NaN; adjustedScore = Double.NaN; } else { score = CSVFormat.EgFormat.Parse(cols[1]); adjustedScore = CSVFormat.EgFormat.Parse(cols[2]); } String code = cols[3]; var prg = new EncogProgram(context); prg.CompileEPL(code); prg.Score = score; prg.Species = lastSpecies; prg.AdjustedScore = adjustedScore; if (lastSpecies == null) { throw new EncogError( "Have not defined a species yet"); } lastSpecies.Add(prg); count++; } } } else if (section.SectionName.Equals("BASIC") && section.SubSectionName.Equals("EPL-OPCODES")) { foreach (String line in section.Lines) { IList<string> cols = EncogFileSection.SplitColumns(line); String name = cols[0]; int args = int.Parse(cols[1]); result.Context.Functions.AddExtension(name, args); } } else if (section.SectionName.Equals("BASIC") && section.SubSectionName.Equals("EPL-SYMBOLIC")) { bool first = true; foreach (string line in section.Lines) { if (!first) { IList<String> cols = EncogFileSection.SplitColumns(line); String name = cols[0]; String t = cols[1]; var vt = EPLValueType.Unknown; if (string.Compare(t, "f", true) == 0) { vt = EPLValueType.FloatingType; } else if (string.Compare(t, "b", true) == 0) { vt = EPLValueType.BooleanType; } else if (string.Compare(t, "i", true) == 0) { vt = EPLValueType.IntType; } else if (string.Compare(t, "s", true) == 0) { vt = EPLValueType.StringType; } else if (string.Compare(t, "e", true) == 0) { vt = EPLValueType.EnumType; } int enumType = int.Parse(cols[2]); int enumCount = int.Parse(cols[3]); var mapping = new VariableMapping( name, vt, enumType, enumCount); if (mapping.Name.Length > 0) { result.Context.DefineVariable(mapping); } else { result.Context.Result = mapping; } } else { first = false; } } } } result.PopulationSize = count; // set the best genome, should be the first genome in the first species if (result.Species.Count > 0) { ISpecies species = result.Species[0]; if (species.Members.Count > 0) { result.BestGenome = species.Members[0]; } // set the leaders foreach (ISpecies sp in result.Species) { if (sp.Members.Count > 0) { sp.Leader = sp.Members[0]; } } } return result; } /// <inheritdoc /> public void Save(Stream ostream, Object obj) { var writer = new EncogWriteHelper(ostream); var pop = (PrgPopulation) obj; writer.AddSection("BASIC"); writer.AddSubSection("PARAMS"); writer.AddProperties(pop.Properties); writer.AddSubSection("EPL-OPCODES"); foreach (IProgramExtensionTemplate temp in pop.Context .Functions.OpCodes) { writer.AddColumn(temp.Name); writer.AddColumn(temp.ChildNodeCount); writer.WriteLine(); } writer.AddSubSection("EPL-SYMBOLIC"); writer.AddColumn("name"); writer.AddColumn("type"); writer.AddColumn("enum"); writer.AddColumn("enum_type"); writer.AddColumn("enum_count"); writer.WriteLine(); // write the first line, the result writer.AddColumn(""); writer.AddColumn(GetType(pop.Context.Result)); writer.AddColumn(pop.Context.Result.EnumType); writer.AddColumn(pop.Context.Result.EnumValueCount); writer.WriteLine(); // write the next lines, the variables foreach (VariableMapping mapping in pop.Context.DefinedVariables) { writer.AddColumn(mapping.Name); writer.AddColumn(GetType(mapping)); writer.AddColumn(mapping.EnumType); writer.AddColumn(mapping.EnumValueCount); writer.WriteLine(); } writer.AddSubSection("EPL-POPULATION"); foreach (ISpecies species in pop.Species) { if (species.Members.Count > 0) { writer.AddColumn("s"); writer.AddColumn(species.Age); writer.AddColumn(species.BestScore); writer.AddColumn(species.GensNoImprovement); writer.WriteLine(); foreach (IGenome genome in species.Members) { var prg = (EncogProgram) genome; writer.AddColumn("p"); if (Double.IsInfinity(prg.Score) || Double.IsNaN(prg.Score)) { writer.AddColumn("NaN"); writer.AddColumn("NaN"); } else { writer.AddColumn(prg.Score); writer.AddColumn(prg.AdjustedScore); } writer.AddColumn(prg.GenerateEPL()); writer.WriteLine(); } } } writer.Flush(); } /// <inheritdoc /> public Type NativeType { get { return typeof (PrgPopulation); } } /// <summary> /// Get the type string for the specified variable mapping. /// </summary> /// <param name="mapping">The mapping.</param> /// <returns>The value.</returns> private string GetType(VariableMapping mapping) { switch (mapping.VariableType) { case EPLValueType.FloatingType: return "f"; case EPLValueType.StringType: return "s"; case EPLValueType.BooleanType: return "b"; case EPLValueType.IntType: return "i"; case EPLValueType.EnumType: return "e"; } throw new EncogError("Unknown type: " + mapping.VariableType.ToString()); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using HttpServer.Exceptions; using HttpServer.Sessions; using Xunit; namespace HttpServer.MVC.Controllers { /// <summary> /// Used to simply testing of controls. /// </summary> public class ControllerTester { /// <summary> /// Fake host name, default is "http://localhost" /// </summary> public string HostName = "http://localhost"; private static readonly IHttpClientContext TestContext = new MyContext(); /// <summary> /// Session used if null have been specified as argument to one of the class methods. /// </summary> public IHttpSession DefaultSession = new MemorySession("abc"); /// <summary> /// Send a GET request to a controller. /// </summary> /// <param name="controller">Controller receiving the post request.</param> /// <param name="uri">Uri visited.</param> /// <param name="response">Response from the controller.</param> /// <param name="session">Session used during the test. null = <see cref="DefaultSession"/> is used.</param> /// <returns>body posted by the response object</returns> /// <example> /// <code> /// void MyTest() /// { /// ControllerTester tester = new ControllerTester(); /// /// MyController controller = new MyController(); /// IHttpResponse response; /// string text = Get(controller, "/my/hello/1?hello=world", out response, null); /// Assert.Equal("world|1", text); /// } /// </code> /// </example> public string Get(RequestController controller, string uri, out IHttpResponse response, IHttpSession session) { return Invoke(controller, Method.Get, uri, out response, session); } /// <summary> /// Send a POST request to a controller. /// </summary> /// <param name="controller">Controller receiving the post request.</param> /// <param name="uri">Uri visited.</param> /// <param name="form">Form being processed by controller.</param> /// <param name="response">Response from the controller.</param> /// <param name="session">Session used during the test. null = <see cref="DefaultSession"/> is used.</param> /// <returns>body posted by the response object</returns> /// <example> /// <code> /// void MyTest() /// { /// // Create a controller. /// MyController controller = new MyController(); /// /// // build up a form that is used by the controller. /// HttpForm form = new HttpForm(); /// form.Add("user[firstName]", "Jonas"); /// /// // Invoke the request /// ControllerTester tester = new ControllerTester(); /// IHttpResponse response; /// string text = tester.Get(controller, "/user/create/", form, out response, null); /// /// // validate response back from controller. /// Assert.Equal("User 'Jonas' has been created.", text); /// } /// </code> /// </example> public string Post(RequestController controller, string uri, HttpForm form, out IHttpResponse response, IHttpSession session) { return Invoke(controller, Method.Post, uri, form, out response, session); } private string Invoke(RequestController controller, string httpMetod, string uri, out IHttpResponse response, IHttpSession session) { return Invoke(controller, httpMetod, uri, null, out response, session); } // ReSharper disable SuggestBaseTypeForParameter /// <exception cref="NotFoundException"><c>NotFoundException</c>.</exception> private string Invoke(RequestController controller, string httpMetod, string uri, HttpForm form, out IHttpResponse response, IHttpSession session) // ReSharper restore SuggestBaseTypeForParameter { HttpRequest request = new HttpRequest { HttpVersion = "HTTP/1.1", UriPath = uri, Method = httpMetod, Uri = new Uri(HostName + uri) }; response = request.CreateResponse(TestContext); /* request.AssignForm(form); if(!controller.Process(request, response, session)) throw new NotFoundException("404 could not find processor for: " + uri); response.Body.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(response.Body); return reader.ReadToEnd(); * */ return null; } [Fact] private void TestGet() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; string text = Get(controller, "/my/hello/1?hello=world", out response, session); Assert.Equal("world|1", text); } [Fact] private void TestPost() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; HttpForm form = new HttpForm(); form.Add("user[firstName]", "jonas"); string text = Post(controller, "/my/hello/id", form, out response, session); Assert.Equal("jonas", text); } private class MyController : RequestController { //controller method. // ReSharper disable UnusedMemberInPrivateClass public string Hello() // ReSharper restore UnusedMemberInPrivateClass { Assert.False(string.IsNullOrEmpty(Id)); if (Request.Method == Method.Post) return Request.Form["user"]["firstName"].Value; return Request.QueryString["hello"].Value + "|" + Id; } public override object Clone() { return new MyController(); } } private class MyContext : IHttpClientContext { private const bool _secured = false; /// <summary> /// Using SSL or other encryption method. /// </summary> public bool Secured { get { return _secured; } } /// <summary> /// Using SSL or other encryption method. /// </summary> public bool IsSecured { get { return _secured; } } /// <summary> /// Disconnect from client /// </summary> /// <param name="error">error to report in the <see cref="Disconnected"/> event.</param> public void Disconnect(SocketError error) { } /// <summary> /// Send a response. /// </summary> /// <param name="httpVersion">Either HttpHelper.HTTP10 or HttpHelper.HTTP11</param> /// <param name="statusCode">http status code</param> /// <param name="reason">reason for the status code.</param> /// <param name="body">html body contents, can be null or empty.</param> /// <param name="contentType">A content type to return the body as, ie 'text/html' or 'text/plain', defaults to 'text/html' if null or empty</param> /// <exception cref="ArgumentException">If httpVersion is invalid.</exception> public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) { } /// <summary> /// Send a response. /// </summary> /// <param name="httpVersion">Either HttpHelper.HTTP10 or HttpHelper.HTTP11</param> /// <param name="statusCode">http status code</param> /// <param name="reason">reason for the status code.</param> public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) { } /// <summary> /// Send a response. /// </summary> /// <exception cref="ArgumentNullException"></exception> public void Respond(string body) { } /// <summary> /// send a whole buffer /// </summary> /// <param name="buffer">buffer to send</param> /// <exception cref="ArgumentNullException"></exception> public void Send(byte[] buffer) { } /// <summary> /// Send data using the stream /// </summary> /// <param name="buffer">Contains data to send</param> /// <param name="offset">Start position in buffer</param> /// <param name="size">number of bytes to send</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public void Send(byte[] buffer, int offset, int size) { } public void ShutupWarnings() { Disconnected(this, null); RequestReceived(this, null); } public event EventHandler<DisconnectedEventArgs> Disconnected; public event EventHandler<RequestEventArgs> RequestReceived; } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System.Collections.Generic; using System.Drawing; namespace ArcGISRuntimeXamarin.Samples.SpatialOperations { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Perform spatial operations", category: "Geometry", description: "Find the union, intersection, or difference of two geometries.", instructions: "The sample provides an option to select a spatial operation. When an operation is selected, the resulting geometry is shown in red. The 'reset operation' button undoes the action and allow selecting a different operation.", tags: new[] { "analysis", "combine", "difference", "geometry", "intersection", "merge", "polygon", "union" })] public class SpatialOperations : Activity { // Hold a reference to the map view. private MapView _myMapView; // GraphicsOverlay to hold the polygon graphics. private GraphicsOverlay _polygonsOverlay; // Polygon graphics to run spatial operations on. private Graphic _graphicOne; private Graphic _graphicTwo; // Graphic to display the spatial operation result polygon. private Graphic _resultGraphic; // Picker control to choose a spatial operation. private Spinner _operationPicker; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Spatial operations"; // Create the UI. CreateLayout(); // Create a new map, add polygon graphics, and fill the spatial operations list. Initialize(); } private void Initialize() { // Create the map with a gray canvas basemap and an initial location centered on London, UK. Map myMap = new Map(BasemapType.LightGrayCanvas, 51.5017, -0.12714, 14); // Add the map to the map view. _myMapView.Map = myMap; // Create and add two overlapping polygon graphics to operate on. CreatePolygonsOverlay(); } private void CreateLayout() { // Create a label to prompt for the spatial operation. TextView operationLabel = new TextView(this) { Text = "Choose a spatial operation:", TextAlignment = TextAlignment.ViewStart }; // Create a list of spatial operations and use it to create an array adapter. List<string> operationsList = new List<string> { "", "Difference", "Intersection", "Symmetric difference", "Union" }; ArrayAdapter operationsAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, operationsList); // Create a picker (Spinner) to show the list of operations. _operationPicker = new Spinner(this) { Adapter = operationsAdapter }; _operationPicker.SetPadding(5, 10, 0, 10); // Handle the selection event to apply the selected operation. _operationPicker.ItemSelected += OperationsPicker_ItemSelected; // Create a button to clear the spatial operation result. Button resetOperationButton = new Button(this) { Text = "Reset" }; resetOperationButton.Click += ResetOperationButton_Click; // Create a layout for the app tools. LinearLayout toolsLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; toolsLayout.SetPadding(10, 0, 0, 0); toolsLayout.SetMinimumHeight(250); // Add the controls to the tools layout (label, picker, button). toolsLayout.AddView(operationLabel); toolsLayout.AddView(_operationPicker); toolsLayout.AddView(resetOperationButton); // Create a new vertical layout for the app UI. LinearLayout mainLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add the tools layout and map view to the main layout. mainLayout.AddView(toolsLayout); _myMapView = new MapView(this); mainLayout.AddView(_myMapView); // Show the layout in the app. SetContentView(mainLayout); } private void ResetOperationButton_Click(object sender, System.EventArgs e) { // Remove any currently displayed result. _polygonsOverlay.Graphics.Remove(_resultGraphic); // Clear the selected spatial operation. _operationPicker.SetSelection(0); } private void OperationsPicker_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { // If an operation hasn't been selected, return. if (_operationPicker.SelectedItem.ToString() == "") { return; } // Remove any currently displayed result. _polygonsOverlay.Graphics.Remove(_resultGraphic); // Polygon geometry from the input graphics. Geometry polygonOne = _graphicOne.Geometry; Geometry polygonTwo = _graphicTwo.Geometry; // Result polygon for spatial operations. Geometry resultPolygon = null; // Run the selected spatial operation on the polygon graphics and get the result geometry. string selectedOperation = _operationPicker.SelectedItem.ToString(); switch (selectedOperation) { case "Union": resultPolygon = GeometryEngine.Union(polygonOne, polygonTwo); break; case "Difference": resultPolygon = GeometryEngine.Difference(polygonOne, polygonTwo); break; case "Symmetric difference": resultPolygon = GeometryEngine.SymmetricDifference(polygonOne, polygonTwo); break; case "Intersection": resultPolygon = GeometryEngine.Intersection(polygonOne, polygonTwo); break; } // Create a black outline symbol to use for the result polygon. SimpleLineSymbol outlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); // Create a solid red fill symbol for the result polygon graphic. SimpleFillSymbol resultSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Red, outlineSymbol); // Create the result polygon graphic and add it to the graphics overlay. _resultGraphic = new Graphic(resultPolygon, resultSymbol); _polygonsOverlay.Graphics.Add(_resultGraphic); } private void CreatePolygonsOverlay() { // Create a black outline symbol to use for the polygons. SimpleLineSymbol outlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); // Create a point collection to define polygon vertices. PointCollection polygonVertices = new PointCollection(SpatialReferences.WebMercator) { new MapPoint(-13960, 6709400), new MapPoint(-14660, 6710000), new MapPoint(-13760, 6710730), new MapPoint(-13300, 6710500), new MapPoint(-13160, 6710100) }; // Create a polygon graphic with a blue fill. SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Vertical, Color.Blue, outlineSymbol); Polygon polygonOne = new Polygon(polygonVertices); _graphicOne = new Graphic(polygonOne, fillSymbol); // Create a point collection to define outer polygon ring vertices. PointCollection outerRingVerticesCollection = new PointCollection(SpatialReferences.WebMercator) { new MapPoint(-13060, 6711030), new MapPoint(-12160, 6710730), new MapPoint(-13160, 6709700), new MapPoint(-14560, 6710730) }; // Create a point collection to define inner polygon ring vertices ("donut hole"). PointCollection innerRingVerticesCollection = new PointCollection(SpatialReferences.WebMercator) { new MapPoint(-13060, 6710910), new MapPoint(-14160, 6710630), new MapPoint(-13160, 6709900), new MapPoint(-12450, 6710660) }; // Create a list to contain the inner and outer ring point collections. List<PointCollection> polygonParts = new List<PointCollection> { outerRingVerticesCollection, innerRingVerticesCollection }; // Create a polygon graphic with a green fill. fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Horizontal, Color.Green, outlineSymbol); _graphicTwo = new Graphic(new Polygon(polygonParts), fillSymbol); // Create a graphics overlay in the map view to hold the polygons. _polygonsOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(_polygonsOverlay); // Add the polygons to the graphics overlay. _polygonsOverlay.Graphics.Add(_graphicOne); _polygonsOverlay.Graphics.Add(_graphicTwo); } } }
/* * CredentialUI.cs - Windows Credential UI Helper * * License: Public Domain * */ using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Misuzilla.Security { /// <summary> /// Credential UI Helper /// </summary> /// <example> /// var credentials = CredentialUI.Prompt("Caption", "Message", "DOMAIN\\KazariUiharu", "P@ssw0rd1"); // Vista or 7: PromptForWindowsCredentials / 2000 or XP or 2003: PromptForCredentials /// var credentials2 = CredentialUI.PromptForWindowsCredentials("Caption", "Message"); /// Console.WriteLine("UserName: {0}", credentials2.UserName); /// Console.WriteLine("DomainName: {0}", credentials2.DomainName); /// Console.WriteLine("Password: {0}", credentials2.Password); /// </example> public static class CredentialUI { /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsResult Prompt(String caption, String message) { return Prompt(caption, message, null, null); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsResult Prompt(String caption, String message, IntPtr hwndParent) { return Prompt(caption, message, hwndParent, null, null); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult Prompt(String caption, String message, String userName, String password) { return Prompt(caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsResult Prompt(String caption, String message, IntPtr hwndParent, String userName, String password) { if (Environment.OSVersion.Version.Major >= 6) { // Windows Vista or 2008 or 7 or later return PromptForWindowsCredentials(caption, message, hwndParent, userName, password); } else { // Windows 2000 or 2003 or XP return PromptForCredentials(Environment.UserDomainName, caption, message, hwndParent, userName, password); } } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptWithSecureString(String caption, String message) { return PromptWithSecureString(caption, message, IntPtr.Zero); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptWithSecureString(String caption, String message, IntPtr hwndParent) { return PromptWithSecureString(caption, message, IntPtr.Zero, null, null); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptWithSecureString(String caption, String message, SecureString userName, SecureString password) { return PromptWithSecureString(caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Show dialog box for generic credential. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptWithSecureString(String caption, String message, IntPtr hwndParent, SecureString userName, SecureString password) { if (Environment.OSVersion.Version.Major >= 6) { // Windows Vista or 2008 or 7 or later return PromptForWindowsCredentialsWithSecureString(caption, message, hwndParent, userName, password); } else { // Windows 2000 or 2003 or XP return PromptForCredentialsWithSecureString(Environment.UserDomainName, caption, message, hwndParent, userName, password); } } #region Method: PromptForWindowsCredentials /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsResult PromptForWindowsCredentials(String caption, String message) { return PromptForWindowsCredentials(caption, message, String.Empty, String.Empty); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsResult PromptForWindowsCredentials(String caption, String message, IntPtr hwndParent) { return PromptForWindowsCredentials(caption, message, hwndParent); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForWindowsCredentials(String caption, String message, String userName, String password) { return PromptForWindowsCredentials(caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForWindowsCredentials(String caption, String message, IntPtr hwndParent, String userName, String password) { PromptForWindowsCredentialsOptions options = new PromptForWindowsCredentialsOptions(caption, message) { HwndParent = hwndParent, IsSaveChecked = false }; return PromptForWindowsCredentials(options, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="options"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForWindowsCredentials(PromptForWindowsCredentialsOptions options, String userName, String password) { if (String.IsNullOrEmpty(userName) && String.IsNullOrEmpty(password)) return PromptForWindowsCredentialsInternal<PromptCredentialsResult>(options, null, null); using (SecureString userNameS = new SecureString()) using (SecureString passwordS = new SecureString()) { if (!String.IsNullOrEmpty(userName)) { foreach (var c in userName) userNameS.AppendChar(c); } if (!String.IsNullOrEmpty(password)) { foreach (var c in password) passwordS.AppendChar(c); } userNameS.MakeReadOnly(); passwordS.MakeReadOnly(); return PromptForWindowsCredentialsInternal<PromptCredentialsResult>(options, userNameS, passwordS); } } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForWindowsCredentialsWithSecureString(String caption, String message) { return PromptForWindowsCredentialsWithSecureString(caption, message, IntPtr.Zero, null, null); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForWindowsCredentialsWithSecureString(String caption, String message, IntPtr hwndParent) { return PromptForWindowsCredentialsWithSecureString(caption, message, hwndParent, null, null); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForWindowsCredentialsWithSecureString(String caption, String message, SecureString userName, SecureString password) { return PromptForWindowsCredentialsWithSecureString(caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForWindowsCredentialsWithSecureString(String caption, String message, IntPtr hwndParent, SecureString userName, SecureString password) { PromptForWindowsCredentialsOptions options = new PromptForWindowsCredentialsOptions(caption, message) { HwndParent = hwndParent, IsSaveChecked = false }; return PromptForWindowsCredentialsWithSecureString(options, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that allows users to supply credential information by using any credential provider installed on the local computer. /// </summary> /// <param name="options"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForWindowsCredentialsWithSecureString(PromptForWindowsCredentialsOptions options, SecureString userName, SecureString password) { return PromptForWindowsCredentialsInternal<PromptCredentialsSecureStringResult>(options, userName, password); } private static T PromptForWindowsCredentialsInternal<T>(PromptForWindowsCredentialsOptions options, SecureString userName, SecureString password) where T : class, IPromptCredentialsResult { NativeMethods.CREDUI_INFO creduiInfo = new NativeMethods.CREDUI_INFO() { pszCaptionText = options.Caption, pszMessageText = options.Message, hwndParent = options.HwndParent, hbmBanner = options.HbmBanner }; PromptForWindowsCredentialsFlag credentialsFlag = options.Flags; IntPtr userNamePtr = IntPtr.Zero; IntPtr passwordPtr = IntPtr.Zero; Int32 authPackage = 0; IntPtr outAuthBuffer = IntPtr.Zero; Int32 outAuthBufferSize = 0; IntPtr inAuthBuffer = IntPtr.Zero; Int32 inAuthBufferSize = 0; Boolean save = options.IsSaveChecked; try { if (userName != null || password != null) { if (userName == null) userName = new SecureString(); if (password == null) password = new SecureString(); userNamePtr = Marshal.SecureStringToCoTaskMemUnicode(userName); passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password); } // prefilled with UserName or Password if (userNamePtr != IntPtr.Zero || passwordPtr != IntPtr.Zero) { inAuthBufferSize = 1024; inAuthBuffer = Marshal.AllocCoTaskMem(inAuthBufferSize); if ( !NativeMethods.CredPackAuthenticationBuffer(0x00, userNamePtr, passwordPtr, inAuthBuffer, ref inAuthBufferSize)) { var win32Error = Marshal.GetLastWin32Error(); if (win32Error == 122 /*ERROR_INSUFFICIENT_BUFFER*/) { inAuthBuffer = Marshal.ReAllocCoTaskMem(inAuthBuffer, inAuthBufferSize); if ( !NativeMethods.CredPackAuthenticationBuffer(0x00, userNamePtr, passwordPtr, inAuthBuffer, ref inAuthBufferSize)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } else { throw new Win32Exception(win32Error); } } } var retVal = NativeMethods.CredUIPromptForWindowsCredentials(creduiInfo, options.AuthErrorCode, ref authPackage, inAuthBuffer, inAuthBufferSize, out outAuthBuffer, out outAuthBufferSize, ref save, credentialsFlag ); switch (retVal) { case NativeMethods.CredUIPromptReturnCode.Cancelled: return null; case NativeMethods.CredUIPromptReturnCode.Success: break; default: throw new Win32Exception((Int32)retVal); } if (typeof(T) == typeof(PromptCredentialsSecureStringResult)) { var credResult = NativeMethods.CredUnPackAuthenticationBufferWrapSecureString(true, outAuthBuffer, outAuthBufferSize); credResult.IsSaveChecked = save; return credResult as T; } else { var credResult = NativeMethods.CredUnPackAuthenticationBufferWrap(true, outAuthBuffer, outAuthBufferSize); credResult.IsSaveChecked = save; return credResult as T; } } finally { if (inAuthBuffer != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(inAuthBuffer); if (outAuthBuffer != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(outAuthBuffer); if (userNamePtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(userNamePtr); if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr); } } #endregion #region Method: PromptForCredentials /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(String targetName, String caption, String message) { return PromptForCredentials(new PromptForCredentialsOptions(targetName, caption, message)); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(String targetName, String caption, String message, IntPtr hwndParent) { return PromptForCredentials(targetName, caption, message, hwndParent); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(String targetName, String caption, String message, String userName, String password) { return PromptForCredentials(targetName, caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(String targetName, String caption, String message, IntPtr hwndParent, String userName, String password) { return PromptForCredentials(new PromptForCredentialsOptions(targetName, caption, message) { HwndParent = hwndParent }, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="options"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(PromptForCredentialsOptions options) { return PromptForCredentials(options, null, null); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="options"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsResult PromptForCredentials(PromptForCredentialsOptions options, String userName, String password) { using (SecureString userNameS = new SecureString()) using (SecureString passwordS = new SecureString()) { if (!String.IsNullOrEmpty(userName)) { foreach (var c in userName) userNameS.AppendChar(c); } if (!String.IsNullOrEmpty(password)) { foreach (var c in password) passwordS.AppendChar(c); } userNameS.MakeReadOnly(); passwordS.MakeReadOnly(); return PromptForCredentialsInternal<PromptCredentialsResult>(options, userNameS, passwordS); } } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(String targetName, String caption, String message) { return PromptForCredentialsWithSecureString(new PromptForCredentialsOptions(targetName, caption, message)); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(String targetName, String caption, String message, IntPtr hwndParent) { return PromptForCredentialsWithSecureString(targetName, caption, message, hwndParent, null, null); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(String targetName, String caption, String message, SecureString userName, SecureString password) { return PromptForCredentialsWithSecureString(targetName, caption, message, IntPtr.Zero, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="targetName"></param> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="hwndParent"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(String targetName, String caption, String message, IntPtr hwndParent, SecureString userName, SecureString password) { return PromptForCredentialsWithSecureString(new PromptForCredentialsOptions(targetName, caption, message) { HwndParent = hwndParent }, userName, password); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="options"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(PromptForCredentialsOptions options) { return PromptForCredentialsInternal<PromptCredentialsSecureStringResult>(options, null, null); } /// <summary> /// Creates and displays a configurable dialog box that accepts credentials information from a user. /// </summary> /// <param name="options"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static PromptCredentialsSecureStringResult PromptForCredentialsWithSecureString(PromptForCredentialsOptions options, SecureString userName, SecureString password) { return PromptForCredentialsInternal<PromptCredentialsSecureStringResult>(options, userName, password); } private static T PromptForCredentialsInternal<T>(PromptForCredentialsOptions options, SecureString userName, SecureString password) where T : class, IPromptCredentialsResult { if (options == null) throw new ArgumentNullException("options"); if (userName != null && (userName.Length > NativeMethods.CREDUI_MAX_USERNAME_LENGTH)) throw new ArgumentOutOfRangeException("userName", "CREDUI_MAX_USERNAME_LENGTH"); if (password != null && (password.Length > NativeMethods.CREDUI_MAX_PASSWORD_LENGTH)) throw new ArgumentOutOfRangeException("password", "CREDUI_MAX_PASSWORD_LENGTH"); NativeMethods.CREDUI_INFO creduiInfo = new NativeMethods.CREDUI_INFO() { pszCaptionText = options.Caption, pszMessageText = options.Message, hwndParent = options.HwndParent, hbmBanner = options.HbmBanner }; IntPtr userNamePtr = IntPtr.Zero; IntPtr passwordPtr = IntPtr.Zero; Boolean save = options.IsSaveChecked; try { // The maximum number of characters that can be copied to (pszUserName|szPassword) including the terminating null character. if (userName == null) { userNamePtr = Marshal.AllocCoTaskMem((NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1) * sizeof(Int16)); Marshal.WriteInt16(userNamePtr, 0, 0x00); } else { userNamePtr = Marshal.SecureStringToCoTaskMemUnicode(userName); userNamePtr = Marshal.ReAllocCoTaskMem(userNamePtr, (NativeMethods.CREDUI_MAX_USERNAME_LENGTH + 1) * sizeof(Int16)); } if (password == null) { passwordPtr = Marshal.AllocCoTaskMem((NativeMethods.CREDUI_MAX_PASSWORD_LENGTH + 1) * sizeof(Int16)); Marshal.WriteInt16(passwordPtr, 0, 0x00); } else { passwordPtr = Marshal.SecureStringToCoTaskMemUnicode(password); passwordPtr = Marshal.ReAllocCoTaskMem(passwordPtr, (NativeMethods.CREDUI_MAX_PASSWORD_LENGTH + 1) * sizeof(Int16)); } Marshal.WriteInt16(userNamePtr, NativeMethods.CREDUI_MAX_USERNAME_LENGTH * sizeof(Int16), 0x00); Marshal.WriteInt16(passwordPtr, NativeMethods.CREDUI_MAX_PASSWORD_LENGTH * sizeof(Int16), 0x00); var retVal = NativeMethods.CredUIPromptForCredentials(creduiInfo, options.TargetName, IntPtr.Zero, options.AuthErrorCode, userNamePtr, NativeMethods.CREDUI_MAX_USERNAME_LENGTH, passwordPtr, NativeMethods.CREDUI_MAX_PASSWORD_LENGTH, ref save, options.Flags); switch (retVal) { case NativeMethods.CredUIPromptReturnCode.Cancelled: return null; case NativeMethods.CredUIPromptReturnCode.InvalidParameter: throw new Win32Exception((Int32)retVal); case NativeMethods.CredUIPromptReturnCode.InvalidFlags: throw new Win32Exception((Int32)retVal); case NativeMethods.CredUIPromptReturnCode.Success: break; default: throw new Win32Exception((Int32)retVal); } if (typeof(T) == typeof(PromptCredentialsSecureStringResult)) { return new PromptCredentialsSecureStringResult { UserName = NativeMethods.PtrToSecureString(userNamePtr), Password = NativeMethods.PtrToSecureString(passwordPtr), IsSaveChecked = save } as T; } else { return new PromptCredentialsResult { UserName = Marshal.PtrToStringUni(userNamePtr), Password = Marshal.PtrToStringUni(passwordPtr), IsSaveChecked = save } as T; } } finally { if (userNamePtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(userNamePtr); if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr); } } #endregion /// <summary> /// /// </summary> [Flags] public enum PromptForWindowsCredentialsFlag { /// <summary> /// Plain text username/password is being requested /// </summary> CREDUIWIN_GENERIC = 0x00000001, /// <summary> /// Show the Save Credential checkbox /// </summary> CREDUIWIN_CHECKBOX = 0x00000002, /// <summary> /// Only Cred Providers that support the input auth package should enumerate /// </summary> CREDUIWIN_AUTHPACKAGE_ONLY = 0x00000010, /// <summary> /// Only the incoming cred for the specific auth package should be enumerated /// </summary> CREDUIWIN_IN_CRED_ONLY = 0x00000020, /// <summary> /// Cred Providers should enumerate administrators only /// </summary> CREDUIWIN_ENUMERATE_ADMINS = 0x00000100, /// <summary> /// Only the incoming cred for the specific auth package should be enumerated /// </summary> CREDUIWIN_ENUMERATE_CURRENT_USER = 0x00000200, /// <summary> /// The Credui prompt should be displayed on the secure desktop /// </summary> CREDUIWIN_SECURE_PROMPT = 0x00001000, /// <summary> /// Tell the credential provider it should be packing its Auth Blob 32 bit even though it is running 64 native /// </summary> CREDUIWIN_PACK_32_WOW = 0x10000000 } /// <summary> /// /// </summary> [Flags] public enum PromptForCredentialsFlag { /// <summary> /// indicates the username is valid, but password is not /// </summary> CREDUI_FLAGS_INCORRECT_PASSWORD = 0x00001, /// <summary> /// Do not show "Save" checkbox, and do not persist credentials /// </summary> CREDUI_FLAGS_DO_NOT_PERSIST = 0x00002, /// <summary> /// Populate list box with admin accounts /// </summary> CREDUI_FLAGS_REQUEST_ADMINISTRATOR = 0x00004, /// <summary> /// do not include certificates in the drop list /// </summary> CREDUI_FLAGS_EXCLUDE_CERTIFICATES = 0x00008, /// <summary> /// /// </summary> CREDUI_FLAGS_REQUIRE_CERTIFICATE = 0x00010, /// <summary> /// /// </summary> CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX = 0x00040, /// <summary> /// /// </summary> CREDUI_FLAGS_ALWAYS_SHOW_UI = 0x00080, /// <summary> /// /// </summary> CREDUI_FLAGS_REQUIRE_SMARTCARD = 0x00100, /// <summary> /// /// </summary> CREDUI_FLAGS_PASSWORD_ONLY_OK = 0x00200, /// <summary> /// /// </summary> CREDUI_FLAGS_VALIDATE_USERNAME = 0x00400, /// <summary> /// /// </summary> CREDUI_FLAGS_COMPLETE_USERNAME = 0x00800, /// <summary> /// Do not show "Save" checkbox, but persist credentials anyway /// </summary> CREDUI_FLAGS_PERSIST = 0x01000, /// <summary> /// /// </summary> CREDUI_FLAGS_SERVER_CREDENTIAL = 0x04000, /// <summary> /// do not persist unless caller later confirms credential via CredUIConfirmCredential() api /// </summary> CREDUI_FLAGS_EXPECT_CONFIRMATION = 0x20000, /// <summary> /// Credential is a generic credential /// </summary> CREDUI_FLAGS_GENERIC_CREDENTIALS = 0x40000, /// <summary> /// Credential has a username as the target /// </summary> CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS = 0x80000, /// <summary> /// don't allow the user to change the supplied username /// </summary> CREDUI_FLAGS_KEEP_USERNAME = 0x100000 } /// <summary> /// /// </summary> public class PromptForWindowsCredentialsOptions { private String _caption; private String _message; public String Caption { get { return _caption; } set { if (value.Length > NativeMethods.CREDUI_MAX_CAPTION_LENGTH) throw new ArgumentOutOfRangeException("value"); _caption = value; } } public String Message { get { return _message; } set { if (value.Length > NativeMethods.CREDUI_MAX_MESSAGE_LENGTH) throw new ArgumentOutOfRangeException("value"); _message = value; } } public IntPtr HwndParent { get; set; } public IntPtr HbmBanner { get; set; } public Boolean IsSaveChecked { get; set; } public PromptForWindowsCredentialsFlag Flags { get; set; } public Int32 AuthErrorCode { get; set; } public PromptForWindowsCredentialsOptions(String caption, String message) { if (String.IsNullOrEmpty(caption)) throw new ArgumentNullException("caption"); if (String.IsNullOrEmpty(message)) throw new ArgumentNullException("message"); Caption = caption; Message = message; Flags = PromptForWindowsCredentialsFlag.CREDUIWIN_GENERIC; } } /// <summary> /// /// </summary> public class PromptForCredentialsOptions { private String _caption; private String _message; public String Caption { get { return _caption; } set { if (value.Length > NativeMethods.CREDUI_MAX_CAPTION_LENGTH) throw new ArgumentOutOfRangeException("value"); _caption = value; } } public String Message { get { return _message; } set { if (value.Length > NativeMethods.CREDUI_MAX_MESSAGE_LENGTH) throw new ArgumentOutOfRangeException("value"); _message = value; } } public String TargetName { get; set; } public IntPtr HwndParent { get; set; } public IntPtr HbmBanner { get; set; } public Boolean IsSaveChecked { get; set; } public PromptForCredentialsFlag Flags { get; set; } public Int32 AuthErrorCode { get; set; } public PromptForCredentialsOptions(String targetName, String caption, String message) { if (String.IsNullOrEmpty(targetName)) throw new ArgumentNullException("targetName"); if (String.IsNullOrEmpty(caption)) throw new ArgumentNullException("caption"); if (String.IsNullOrEmpty(message)) throw new ArgumentNullException("message"); TargetName = targetName; Caption = caption; Message = message; Flags = PromptForCredentialsFlag.CREDUI_FLAGS_GENERIC_CREDENTIALS | PromptForCredentialsFlag.CREDUI_FLAGS_DO_NOT_PERSIST; } } private static class NativeMethods { public const Int32 CREDUI_MAX_MESSAGE_LENGTH = 32767; public const Int32 CREDUI_MAX_CAPTION_LENGTH = 128; public const Int32 CRED_MAX_USERNAME_LENGTH = (256 + 1 + 256); public const Int32 CREDUI_MAX_USERNAME_LENGTH = CRED_MAX_USERNAME_LENGTH; public const Int32 CREDUI_MAX_PASSWORD_LENGTH = (512 / 2); public enum CredUIPromptReturnCode { Success = 0, Cancelled = 1223, InvalidParameter = 87, InvalidFlags = 1004 } [StructLayout(LayoutKind.Sequential)] public class CREDUI_INFO { public Int32 cbSize; public IntPtr hwndParent; [MarshalAs(UnmanagedType.LPWStr)] public String pszMessageText; [MarshalAs(UnmanagedType.LPWStr)] public String pszCaptionText; public IntPtr hbmBanner; public CREDUI_INFO() { cbSize = Marshal.SizeOf(typeof(CREDUI_INFO)); } } // // CredUIPromptForCredentials ------------------------------------- // [DllImport("credui.dll", CharSet = CharSet.Unicode)] public static extern CredUIPromptReturnCode CredUIPromptForCredentials( CREDUI_INFO pUiInfo, String pszTargetName, IntPtr Reserved, Int32 dwAuthError, IntPtr pszUserName, Int32 ulUserNameMaxChars, IntPtr pszPassword, Int32 ulPasswordMaxChars, ref Boolean pfSave, PromptForCredentialsFlag dwFlags ); // // CredUIPromptForWindowsCredentials ------------------------------ // [DllImport("credui.dll", CharSet = CharSet.Unicode)] public static extern CredUIPromptReturnCode CredUIPromptForWindowsCredentials( CREDUI_INFO pUiInfo, Int32 dwAuthError, ref Int32 pulAuthPackage, IntPtr pvInAuthBuffer, Int32 ulInAuthBufferSize, out IntPtr ppvOutAuthBuffer, out Int32 pulOutAuthBufferSize, ref Boolean pfSave, PromptForWindowsCredentialsFlag dwFlags ); [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CredPackAuthenticationBuffer( Int32 dwFlags, String pszUserName, String pszPassword, IntPtr pPackedCredentials, ref Int32 pcbPackedCredentials ); [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CredPackAuthenticationBuffer( Int32 dwFlags, IntPtr pszUserName, IntPtr pszPassword, IntPtr pPackedCredentials, ref Int32 pcbPackedCredentials ); [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CredUnPackAuthenticationBuffer( Int32 dwFlags, IntPtr pAuthBuffer, Int32 cbAuthBuffer, StringBuilder pszUserName, ref Int32 pcchMaxUserName, StringBuilder pszDomainName, ref Int32 pcchMaxDomainame, StringBuilder pszPassword, ref Int32 pcchMaxPassword ); [DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern Boolean CredUnPackAuthenticationBuffer( Int32 dwFlags, IntPtr pAuthBuffer, Int32 cbAuthBuffer, IntPtr pszUserName, ref Int32 pcchMaxUserName, IntPtr pszDomainName, ref Int32 pcchMaxDomainame, IntPtr pszPassword, ref Int32 pcchMaxPassword ); public static PromptCredentialsResult CredUnPackAuthenticationBufferWrap(Boolean decryptProtectedCredentials, IntPtr authBufferPtr, Int32 authBufferSize) { StringBuilder sbUserName = new StringBuilder(255); StringBuilder sbDomainName = new StringBuilder(255); StringBuilder sbPassword = new StringBuilder(255); Int32 userNameSize = sbUserName.Capacity; Int32 domainNameSize = sbDomainName.Capacity; Int32 passwordSize = sbPassword.Capacity; //#define CRED_PACK_PROTECTED_CREDENTIALS 0x1 //#define CRED_PACK_WOW_BUFFER 0x2 //#define CRED_PACK_GENERIC_CREDENTIALS 0x4 Boolean result = CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0), authBufferPtr, authBufferSize, sbUserName, ref userNameSize, sbDomainName, ref domainNameSize, sbPassword, ref passwordSize ); if (!result) { var win32Error = Marshal.GetLastWin32Error(); if (win32Error == 122 /*ERROR_INSUFFICIENT_BUFFER*/) { sbUserName.Capacity = userNameSize; sbPassword.Capacity = passwordSize; sbDomainName.Capacity = domainNameSize; result = CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0), authBufferPtr, authBufferSize, sbUserName, ref userNameSize, sbDomainName, ref domainNameSize, sbPassword, ref passwordSize ); if (!result) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } else { throw new Win32Exception(win32Error); } } return new PromptCredentialsResult { UserName = sbUserName.ToString(), DomainName = sbDomainName.ToString(), Password = sbPassword.ToString() }; } public static PromptCredentialsSecureStringResult CredUnPackAuthenticationBufferWrapSecureString(Boolean decryptProtectedCredentials, IntPtr authBufferPtr, Int32 authBufferSize) { Int32 userNameSize = 255; Int32 domainNameSize = 255; Int32 passwordSize = 255; IntPtr userNamePtr = IntPtr.Zero; IntPtr domainNamePtr = IntPtr.Zero; IntPtr passwordPtr = IntPtr.Zero; try { userNamePtr = Marshal.AllocCoTaskMem(userNameSize); domainNamePtr = Marshal.AllocCoTaskMem(domainNameSize); passwordPtr = Marshal.AllocCoTaskMem(passwordSize); //#define CRED_PACK_PROTECTED_CREDENTIALS 0x1 //#define CRED_PACK_WOW_BUFFER 0x2 //#define CRED_PACK_GENERIC_CREDENTIALS 0x4 Boolean result = CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0), authBufferPtr, authBufferSize, userNamePtr, ref userNameSize, domainNamePtr, ref domainNameSize, passwordPtr, ref passwordSize ); if (!result) { var win32Error = Marshal.GetLastWin32Error(); if (win32Error == 122 /*ERROR_INSUFFICIENT_BUFFER*/) { userNamePtr = Marshal.ReAllocCoTaskMem(userNamePtr, userNameSize); domainNamePtr = Marshal.ReAllocCoTaskMem(domainNamePtr, domainNameSize); passwordPtr = Marshal.ReAllocCoTaskMem(passwordPtr, passwordSize); result = CredUnPackAuthenticationBuffer((decryptProtectedCredentials ? 0x1 : 0x0), authBufferPtr, authBufferSize, userNamePtr, ref userNameSize, domainNamePtr, ref domainNameSize, passwordPtr, ref passwordSize); if (!result) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } else { throw new Win32Exception(win32Error); } } return new PromptCredentialsSecureStringResult { UserName = PtrToSecureString(userNamePtr, userNameSize), DomainName = PtrToSecureString(domainNamePtr, domainNameSize), Password = PtrToSecureString(passwordPtr, passwordSize) }; } finally { if (userNamePtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(userNamePtr); if (domainNamePtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(domainNamePtr); if (passwordPtr != IntPtr.Zero) Marshal.ZeroFreeCoTaskMemUnicode(passwordPtr); } } #region Utility Methods public static SecureString PtrToSecureString(IntPtr p) { SecureString s = new SecureString(); Int32 i = 0; while (true) { Char c = (Char)Marshal.ReadInt16(p, ((i++) * sizeof(Int16))); if (c == '\u0000') break; s.AppendChar(c); } s.MakeReadOnly(); return s; } public static SecureString PtrToSecureString(IntPtr p, Int32 length) { SecureString s = new SecureString(); for (var i = 0; i < length; i++) s.AppendChar((Char)Marshal.ReadInt16(p, i * sizeof(Int16))); s.MakeReadOnly(); return s; } #endregion } } /// <summary> /// /// </summary> public interface IPromptCredentialsResult { } /// <summary> /// /// </summary> public class PromptCredentialsResult : IPromptCredentialsResult { public String UserName { get; internal set; } public String DomainName { get; internal set; } public String Password { get; internal set; } public Boolean IsSaveChecked { get; set; } } /// <summary> /// /// </summary> public class PromptCredentialsSecureStringResult : IPromptCredentialsResult { public SecureString UserName { get; internal set; } public SecureString DomainName { get; internal set; } public SecureString Password { get; internal set; } public Boolean IsSaveChecked { get; set; } } }
/* * Copyright 2010-2013 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. */ using System; using Amazon.CloudWatch; using Amazon.CloudWatch.Model; namespace Amazon.CloudWatch { /// <summary> /// Interface for accessing AmazonCloudWatch. /// /// Amazon CloudWatch <para>This is the <i>Amazon CloudWatch API Reference</i> . This guide provides detailed information about Amazon /// CloudWatch actions, data types, parameters, and errors. For detailed information about Amazon CloudWatch features and their associated API /// calls, go to the Amazon CloudWatch Developer Guide. </para> <para>Amazon CloudWatch is a web service that enables you to publish, monitor, /// and manage various metrics, as well as configure alarm actions based on data from metrics. For more information about this product go to /// http://aws.amazon.com/cloudwatch. </para> <para> For information about the namespace, metric names, and dimensions that other Amazon Web /// Services products use to send metrics to Cloudwatch, go to Amazon CloudWatch Metrics, Namespaces, and Dimensions Reference in the <i>Amazon /// CloudWatch Developer Guide</i> . /// </para> <para>Use the following links to get started using the <i>Amazon CloudWatch API Reference</i> :</para> /// <ul> /// <li> Actions: An alphabetical list of all Amazon CloudWatch actions.</li> /// <li> Data Types: An alphabetical list of all Amazon CloudWatch data types.</li> /// <li> Common Parameters: Parameters that all Query actions can use.</li> /// <li> Common Errors: Client and server errors that all actions can return.</li> /// <li> Regions and Endpoints: Itemized regions and endpoints for all AWS products.</li> /// <li> WSDL Location: http://monitoring.amazonaws.com/doc/2010-08-01/CloudWatch.wsdl</li> /// /// </ul> /// </summary> public interface AmazonCloudWatch : IDisposable { #region PutMetricAlarm /// <summary> /// <para> Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric. Optionally, this operation can associate /// one or more Amazon Simple Notification Service resources with the alarm. </para> <para> When this operation creates an alarm, the alarm /// state is immediately set to <c>INSUFFICIENT_DATA</c> . The alarm is evaluated and its <c>StateValue</c> is set appropriately. Any actions /// associated with the <c>StateValue</c> is then executed. </para> <para><b>NOTE:</b> When updating an existing alarm, its StateValue is left /// unchanged. </para> /// </summary> /// /// <param name="putMetricAlarmRequest">Container for the necessary parameters to execute the PutMetricAlarm service method on /// AmazonCloudWatch.</param> /// /// <exception cref="LimitExceededException"/> PutMetricAlarmResponse PutMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest); /// <summary> /// Initiates the asynchronous execution of the PutMetricAlarm operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricAlarm"/> /// </summary> /// /// <param name="putMetricAlarmRequest">Container for the necessary parameters to execute the PutMetricAlarm operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginPutMetricAlarm(PutMetricAlarmRequest putMetricAlarmRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the PutMetricAlarm operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricAlarm"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricAlarm.</param> PutMetricAlarmResponse EndPutMetricAlarm(IAsyncResult asyncResult); #endregion #region PutMetricData /// <summary> /// <para> Publishes metric data points to Amazon CloudWatch. Amazon Cloudwatch associates the data points with the specified metric. If the /// specified metric does not exist, Amazon CloudWatch creates the metric. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. </para> <para> The size of a /// PutMetricData request is limited to 8 KB for HTTP GET requests and 40 KB for HTTP POST requests. </para> <para><b>IMPORTANT:</b> Although /// the Value parameter accepts numbers of type Double, Amazon CloudWatch truncates values with very large exponents. Values with base-10 /// exponents greater than 126 (1 x 10^126) are truncated. Likewise, values with base-10 exponents less than -130 (1 x 10^-130) are also /// truncated. </para> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData service method on /// AmazonCloudWatch.</param> /// /// <exception cref="InvalidParameterValueException"/> /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterCombinationException"/> /// <exception cref="MissingRequiredParameterException"/> PutMetricDataResponse PutMetricData(PutMetricDataRequest putMetricDataRequest); /// <summary> /// Initiates the asynchronous execution of the PutMetricData operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricData"/> /// </summary> /// /// <param name="putMetricDataRequest">Container for the necessary parameters to execute the PutMetricData operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginPutMetricData(PutMetricDataRequest putMetricDataRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the PutMetricData operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.PutMetricData"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPutMetricData.</param> PutMetricDataResponse EndPutMetricData(IAsyncResult asyncResult); #endregion #region ListMetrics /// <summary> /// <para> Returns a list of valid metrics stored for the AWS account owner. Returned metrics can be used with GetMetricStatistics to obtain /// statistical data for a given metric. </para> <para><b>NOTE:</b> Up to 500 results are returned for any one call. To retrieve further /// results, use returned NextToken values with subsequent ListMetrics operations. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. Statistics about the metric, /// however, are available sooner using GetMetricStatistics. </para> /// </summary> /// /// <param name="listMetricsRequest">Container for the necessary parameters to execute the ListMetrics service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the ListMetrics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterValueException"/> ListMetricsResponse ListMetrics(ListMetricsRequest listMetricsRequest); /// <summary> /// Initiates the asynchronous execution of the ListMetrics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.ListMetrics"/> /// </summary> /// /// <param name="listMetricsRequest">Container for the necessary parameters to execute the ListMetrics operation on AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListMetrics /// operation.</returns> IAsyncResult BeginListMetrics(ListMetricsRequest listMetricsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListMetrics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.ListMetrics"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListMetrics.</param> /// /// <returns>Returns a ListMetricsResult from AmazonCloudWatch.</returns> ListMetricsResponse EndListMetrics(IAsyncResult asyncResult); /// <summary> /// <para> Returns a list of valid metrics stored for the AWS account owner. Returned metrics can be used with GetMetricStatistics to obtain /// statistical data for a given metric. </para> <para><b>NOTE:</b> Up to 500 results are returned for any one call. To retrieve further /// results, use returned NextToken values with subsequent ListMetrics operations. </para> <para><b>NOTE:</b> If you create a metric with the /// PutMetricData action, allow up to fifteen minutes for the metric to appear in calls to the ListMetrics action. Statistics about the metric, /// however, are available sooner using GetMetricStatistics. </para> /// </summary> /// /// <returns>The response from the ListMetrics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterValueException"/> ListMetricsResponse ListMetrics(); #endregion #region GetMetricStatistics /// <summary> /// <para> Gets statistics for the specified metric. </para> <para><b>NOTE:</b> The maximum number of data points returned from a single /// GetMetricStatistics request is 1,440. If a request is made that generates more than 1,440 data points, Amazon CloudWatch returns an error. /// In such a case, alter the request by narrowing the specified time range or increasing the specified period. Alternatively, make multiple /// requests across adjacent time ranges. </para> <para> Amazon CloudWatch aggregates data points based on the length of the <c>period</c> that /// you specify. For example, if you request statistics with a one-minute granularity, Amazon CloudWatch aggregates data points with time stamps /// that fall within the same one-minute period. In such a case, the data points queried can greatly outnumber the data points returned. </para> /// <para><b>NOTE:</b> The maximum number of data points that can be queried is 50,850; whereas the maximum number of data points returned is /// 1,440. </para> <para> The following examples show various statistics allowed by the data point query maximum of 50,850 when you call /// <c>GetMetricStatistics</c> on Amazon EC2 instances with detailed (one-minute) monitoring enabled: </para> /// <ul> /// <li>Statistics for up to 400 instances for a span of one hour</li> /// <li>Statistics for up to 35 instances over a span of 24 hours</li> /// <li>Statistics for up to 2 instances over a span of 2 weeks</li> /// /// </ul> /// <para> For information about the namespace, metric names, and dimensions that other Amazon Web Services products use to send metrics to /// Cloudwatch, go to Amazon CloudWatch Metrics, Namespaces, and Dimensions Reference in the <i>Amazon CloudWatch Developer Guide</i> . /// </para> /// </summary> /// /// <param name="getMetricStatisticsRequest">Container for the necessary parameters to execute the GetMetricStatistics service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the GetMetricStatistics service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidParameterValueException"/> /// <exception cref="InternalServiceException"/> /// <exception cref="InvalidParameterCombinationException"/> /// <exception cref="MissingRequiredParameterException"/> GetMetricStatisticsResponse GetMetricStatistics(GetMetricStatisticsRequest getMetricStatisticsRequest); /// <summary> /// Initiates the asynchronous execution of the GetMetricStatistics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.GetMetricStatistics"/> /// </summary> /// /// <param name="getMetricStatisticsRequest">Container for the necessary parameters to execute the GetMetricStatistics operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndGetMetricStatistics operation.</returns> IAsyncResult BeginGetMetricStatistics(GetMetricStatisticsRequest getMetricStatisticsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetMetricStatistics operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.GetMetricStatistics"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetMetricStatistics.</param> /// /// <returns>Returns a GetMetricStatisticsResult from AmazonCloudWatch.</returns> GetMetricStatisticsResponse EndGetMetricStatistics(IAsyncResult asyncResult); #endregion #region DisableAlarmActions /// <summary> /// <para> Disables actions for the specified alarms. When an alarm's actions are disabled the alarm's state may change, but none of the alarm's /// actions will execute. </para> /// </summary> /// /// <param name="disableAlarmActionsRequest">Container for the necessary parameters to execute the DisableAlarmActions service method on /// AmazonCloudWatch.</param> /// DisableAlarmActionsResponse DisableAlarmActions(DisableAlarmActionsRequest disableAlarmActionsRequest); /// <summary> /// Initiates the asynchronous execution of the DisableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DisableAlarmActions"/> /// </summary> /// /// <param name="disableAlarmActionsRequest">Container for the necessary parameters to execute the DisableAlarmActions operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginDisableAlarmActions(DisableAlarmActionsRequest disableAlarmActionsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DisableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DisableAlarmActions"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisableAlarmActions.</param> DisableAlarmActionsResponse EndDisableAlarmActions(IAsyncResult asyncResult); #endregion #region DescribeAlarms /// <summary> /// <para> Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by /// using only a prefix for the alarm name, the alarm state, or a prefix for any action. </para> /// </summary> /// /// <param name="describeAlarmsRequest">Container for the necessary parameters to execute the DescribeAlarms service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarms service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> DescribeAlarmsResponse DescribeAlarms(DescribeAlarmsRequest describeAlarmsRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarms"/> /// </summary> /// /// <param name="describeAlarmsRequest">Container for the necessary parameters to execute the DescribeAlarms operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDescribeAlarms /// operation.</returns> IAsyncResult BeginDescribeAlarms(DescribeAlarmsRequest describeAlarmsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarms"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarms.</param> /// /// <returns>Returns a DescribeAlarmsResult from AmazonCloudWatch.</returns> DescribeAlarmsResponse EndDescribeAlarms(IAsyncResult asyncResult); /// <summary> /// <para> Retrieves alarms with the specified names. If no name is specified, all alarms for the user are returned. Alarms can be retrieved by /// using only a prefix for the alarm name, the alarm state, or a prefix for any action. </para> /// </summary> /// /// <returns>The response from the DescribeAlarms service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> DescribeAlarmsResponse DescribeAlarms(); #endregion #region DescribeAlarmsForMetric /// <summary> /// <para> Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the set of alarms further. </para> /// </summary> /// /// <param name="describeAlarmsForMetricRequest">Container for the necessary parameters to execute the DescribeAlarmsForMetric service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarmsForMetric service method, as returned by AmazonCloudWatch.</returns> /// DescribeAlarmsForMetricResponse DescribeAlarmsForMetric(DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeAlarmsForMetric operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmsForMetric"/> /// </summary> /// /// <param name="describeAlarmsForMetricRequest">Container for the necessary parameters to execute the DescribeAlarmsForMetric operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeAlarmsForMetric operation.</returns> IAsyncResult BeginDescribeAlarmsForMetric(DescribeAlarmsForMetricRequest describeAlarmsForMetricRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeAlarmsForMetric operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmsForMetric"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmsForMetric.</param> /// /// <returns>Returns a DescribeAlarmsForMetricResult from AmazonCloudWatch.</returns> DescribeAlarmsForMetricResponse EndDescribeAlarmsForMetric(IAsyncResult asyncResult); #endregion #region DescribeAlarmHistory /// <summary> /// <para> Retrieves history for the specified alarm. Filter alarms by date range or item type. If an alarm name is not specified, Amazon /// CloudWatch returns histories for all of the owner's alarms. </para> <para><b>NOTE:</b> Amazon CloudWatch retains the history of an alarm for /// two weeks, whether or not you delete the alarm. </para> /// </summary> /// /// <param name="describeAlarmHistoryRequest">Container for the necessary parameters to execute the DescribeAlarmHistory service method on /// AmazonCloudWatch.</param> /// /// <returns>The response from the DescribeAlarmHistory service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> DescribeAlarmHistoryResponse DescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest); /// <summary> /// Initiates the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/> /// </summary> /// /// <param name="describeAlarmHistoryRequest">Container for the necessary parameters to execute the DescribeAlarmHistory operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking /// EndDescribeAlarmHistory operation.</returns> IAsyncResult BeginDescribeAlarmHistory(DescribeAlarmHistoryRequest describeAlarmHistoryRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DescribeAlarmHistory operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DescribeAlarmHistory"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDescribeAlarmHistory.</param> /// /// <returns>Returns a DescribeAlarmHistoryResult from AmazonCloudWatch.</returns> DescribeAlarmHistoryResponse EndDescribeAlarmHistory(IAsyncResult asyncResult); /// <summary> /// <para> Retrieves history for the specified alarm. Filter alarms by date range or item type. If an alarm name is not specified, Amazon /// CloudWatch returns histories for all of the owner's alarms. </para> <para><b>NOTE:</b> Amazon CloudWatch retains the history of an alarm for /// two weeks, whether or not you delete the alarm. </para> /// </summary> /// /// <returns>The response from the DescribeAlarmHistory service method, as returned by AmazonCloudWatch.</returns> /// /// <exception cref="InvalidNextTokenException"/> DescribeAlarmHistoryResponse DescribeAlarmHistory(); #endregion #region EnableAlarmActions /// <summary> /// <para> Enables actions for the specified alarms. </para> /// </summary> /// /// <param name="enableAlarmActionsRequest">Container for the necessary parameters to execute the EnableAlarmActions service method on /// AmazonCloudWatch.</param> /// EnableAlarmActionsResponse EnableAlarmActions(EnableAlarmActionsRequest enableAlarmActionsRequest); /// <summary> /// Initiates the asynchronous execution of the EnableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.EnableAlarmActions"/> /// </summary> /// /// <param name="enableAlarmActionsRequest">Container for the necessary parameters to execute the EnableAlarmActions operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginEnableAlarmActions(EnableAlarmActionsRequest enableAlarmActionsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the EnableAlarmActions operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.EnableAlarmActions"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableAlarmActions.</param> EnableAlarmActionsResponse EndEnableAlarmActions(IAsyncResult asyncResult); #endregion #region DeleteAlarms /// <summary> /// <para> Deletes all specified alarms. In the event of an error, no alarms are deleted. </para> /// </summary> /// /// <param name="deleteAlarmsRequest">Container for the necessary parameters to execute the DeleteAlarms service method on /// AmazonCloudWatch.</param> /// /// <exception cref="ResourceNotFoundException"/> DeleteAlarmsResponse DeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest); /// <summary> /// Initiates the asynchronous execution of the DeleteAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DeleteAlarms"/> /// </summary> /// /// <param name="deleteAlarmsRequest">Container for the necessary parameters to execute the DeleteAlarms operation on AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginDeleteAlarms(DeleteAlarmsRequest deleteAlarmsRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteAlarms operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.DeleteAlarms"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteAlarms.</param> DeleteAlarmsResponse EndDeleteAlarms(IAsyncResult asyncResult); #endregion #region SetAlarmState /// <summary> /// <para> Temporarily sets the state of an alarm. When the updated <c>StateValue</c> differs from the previous value, the action configured for /// the appropriate state is invoked. This is not a permanent change. The next periodic alarm check (in about a minute) will set the alarm to /// its actual state. </para> /// </summary> /// /// <param name="setAlarmStateRequest">Container for the necessary parameters to execute the SetAlarmState service method on /// AmazonCloudWatch.</param> /// /// <exception cref="ResourceNotFoundException"/> /// <exception cref="InvalidFormatException"/> SetAlarmStateResponse SetAlarmState(SetAlarmStateRequest setAlarmStateRequest); /// <summary> /// Initiates the asynchronous execution of the SetAlarmState operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.SetAlarmState"/> /// </summary> /// /// <param name="setAlarmStateRequest">Container for the necessary parameters to execute the SetAlarmState operation on /// AmazonCloudWatch.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> IAsyncResult BeginSetAlarmState(SetAlarmStateRequest setAlarmStateRequest, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the SetAlarmState operation. /// <seealso cref="Amazon.CloudWatch.AmazonCloudWatch.SetAlarmState"/> /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginSetAlarmState.</param> SetAlarmStateResponse EndSetAlarmState(IAsyncResult asyncResult); #endregion } }
using System; using Android.OS; using Android.App; using Android.Views; using Android.Widget; using System.Net.Http; using System.Threading.Tasks; using Microsoft.WindowsAzure.MobileServices; using Xamarin.Controls; using ZXing; using ZXing.Mobile; namespace skandoService { [Activity (MainLauncher = true, Icon="@drawable/ic_launcher", Label="@string/app_name", Theme="@style/AppTheme")] public class ToDoActivity : Activity { //Mobile Service Client reference private MobileServiceClient client; //Mobile Service Table used to access data private IMobileServiceTable<ToDoItem> toDoTable; //Adapter to sync the items list with the view private ToDoItemAdapter adapter; //EditText containing the "New ToDo" text private EditText textNewToDo; //Progress spinner to use for table operations private ProgressBar progressBar; const string applicationURL = @"https://skandoservice.azure-mobile.net/"; const string applicationKey = @"ZwaPawlftdKLDCIAocvNXzXkqnXSvW52"; MobileBarcodeScanner scanner; protected override async void OnCreate (Bundle bundle) { base.OnCreate (bundle); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Activity_To_Do); scanner = new MobileBarcodeScanner(this); // botao de scan Button button = FindViewById<Button> (Resource.Id.scanBNT); button.Click += async delegate { base.OnCreate (bundle); AlertCenter.Default.Init (Application); AlertCenter.Default.PostMessage ("Abre o scan", "Iniciando scaneamento do produto", Resource.Drawable.icon); //Tell our scanner to use the default overlay scanner.UseCustomOverlay = true; scanner.TopText = "Hold the camera up to the barcode\nAbout 6 inches away"; scanner.BottomText = "Wait for the barcode to automatically scan!"; var result = await scanner.Scan(); HandleScanResult(result); }; progressBar = FindViewById<ProgressBar> (Resource.Id.loadingProgressBar); // Initialize the progress bar progressBar.Visibility = ViewStates.Gone; // Create ProgressFilter to handle busy state var progressHandler = new ProgressHandler (); progressHandler.BusyStateChange += (busy) => { if (progressBar != null) progressBar.Visibility = busy ? ViewStates.Visible : ViewStates.Gone; }; try { CurrentPlatform.Init (); // Create the Mobile Service Client instance, using the provided // Mobile Service URL and key client = new MobileServiceClient ( applicationURL, applicationKey, progressHandler); // Get the Mobile Service Table instance to use toDoTable = client.GetTable <ToDoItem> (); textNewToDo = FindViewById<EditText> (Resource.Id.textNewToDo); // Create an adapter to bind the items with the view adapter = new ToDoItemAdapter (this, Resource.Layout.Row_List_To_Do); var listViewToDo = FindViewById<ListView> (Resource.Id.listViewToDo); listViewToDo.Adapter = adapter; // Load the items from the Mobile Service await RefreshItemsFromTableAsync (); } catch (Java.Net.MalformedURLException) { CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error"); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } //Initializes the activity menu public override bool OnCreateOptionsMenu (IMenu menu) { MenuInflater.Inflate (Resource.Menu.activity_main, menu); return true; } //Select an option from the menu public override bool OnOptionsItemSelected (IMenuItem item) { if (item.ItemId == Resource.Id.menu_refresh) { OnRefreshItemsSelected (); } return true; } // Called when the refresh menu opion is selected async void OnRefreshItemsSelected () { await RefreshItemsFromTableAsync (); } //Refresh the list with the items in the Mobile Service Table async Task RefreshItemsFromTableAsync () { try { // Get the items that weren't marked as completed and add them in the // adapter var list = await toDoTable.Where (item => item.Complete == false).ToListAsync (); adapter.Clear (); foreach (ToDoItem current in list) adapter.Add (current); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } public async Task CheckItem (ToDoItem item) { if (client == null) { return; } // Set the item as completed and update it in the table item.Complete = true; try { await toDoTable.UpdateAsync (item); if (item.Complete) adapter.Remove (item); } catch (Exception e) { CreateAndShowDialog (e, "Error"); } } [Java.Interop.Export()] public async void AddItem (View view) { if (client == null || string.IsNullOrWhiteSpace (textNewToDo.Text)) { return; } // Create a new item var item = new ToDoItem { Text = textNewToDo.Text, Complete = false }; try { // Insert the new item await toDoTable.InsertAsync (item); if (!item.Complete) { adapter.Add (item); } } catch (Exception e) { CreateAndShowDialog (e, "Error"); } textNewToDo.Text = ""; } void CreateAndShowDialog (Exception exception, String title) { CreateAndShowDialog (exception.Message, title); } void CreateAndShowDialog (string message, string title) { AlertDialog.Builder builder = new AlertDialog.Builder (this); builder.SetMessage (message); builder.SetTitle (title); builder.Create ().Show (); } class ProgressHandler : DelegatingHandler { int busyCount = 0; public event Action<bool> BusyStateChange; #region implemented abstract members of HttpMessageHandler protected override async Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { //assumes always executes on UI thread if (busyCount++ == 0 && BusyStateChange != null) BusyStateChange (true); var response = await base.SendAsync (request, cancellationToken); // assumes always executes on UI thread if (--busyCount == 0 && BusyStateChange != null) BusyStateChange (false); return response; } #endregion } void HandleScanResult (ZXing.Result result) { string msg = ""; if (result != null && !string.IsNullOrEmpty(result.Text)) msg = "Found Barcode: " + result.Text; else msg = "Scanning Canceled!"; this.RunOnUiThread(() => Toast.MakeText(this, msg, ToastLength.Short).Show()); } } }
// Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.OS; using Android.Views; using Android.Widget; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; namespace ArcGISRuntimeXamarin.Samples.SketchOnMap { [Activity] public class SketchOnMap : Activity { // Create and hold reference to the used MapView private MapView _myMapView = new MapView(); // Dictionary to hold sketch mode enum names and values private Dictionary<string, int> _sketchModeDictionary; // Graphics overlay to host sketch graphics private GraphicsOverlay _sketchOverlay; // Buttons for interacting with the SketchEditor private Button _editButton; private Button _undoButton; private Button _redoButton; private Button _doneButton; private Button _clearButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Sketch on map"; // Create the UI CreateLayout(); // Initialize controls, set up event handlers, etc. Initialize(); } private void Initialize() { // Create a light gray canvas map Map myMap = new Map(Basemap.CreateLightGrayCanvas()); // Create graphics overlay to display sketch geometry _sketchOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(_sketchOverlay); // Assign the map to the MapView _myMapView.Map = myMap; // Set the sketch editor configuration to allow vertex editing, resizing, and moving var config = _myMapView.SketchEditor.EditConfiguration; config.AllowVertexEditing = true; config.ResizeMode = SketchResizeMode.Uniform; config.AllowMove = true; // Listen to the sketch editor tools CanExecuteChange so controls can be enabled/disabled _myMapView.SketchEditor.UndoCommand.CanExecuteChanged += CanExecuteChanged; _myMapView.SketchEditor.RedoCommand.CanExecuteChanged += CanExecuteChanged; _myMapView.SketchEditor.CompleteCommand.CanExecuteChanged += CanExecuteChanged; // Listen to collection changed event on the graphics overlay to enable/disable controls that require a graphic _sketchOverlay.Graphics.CollectionChanged += GraphicsChanged; } private void CreateLayout() { // Create horizontal layouts for the buttons at the top var buttonLayoutOne = new LinearLayout(this) { Orientation = Orientation.Horizontal }; var buttonLayoutTwo = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Button to sketch a selected geometry type on the map view var sketchButton = new Button(this); sketchButton.Text = "Sketch"; sketchButton.Click += OnSketchClicked; // Button to edit an existing graphic's geometry _editButton = new Button(this); _editButton.Text = "Edit"; _editButton.Click += OnEditClicked; _editButton.Enabled = false; // Buttons to Undo/Redo sketch and edit operations _undoButton = new Button(this); _undoButton.Text = "Undo"; _undoButton.Click += OnUndoClicked; _undoButton.Enabled = false; _redoButton = new Button(this); _redoButton.Text = "Redo"; _redoButton.Click += OnRedoClicked; _redoButton.Enabled = false; // Button to complete the sketch or edit _doneButton = new Button(this); _doneButton.Text = "Done"; _doneButton.Click += OnCompleteClicked; _doneButton.Enabled = false; // Button to clear all graphics and sketches _clearButton = new Button(this); _clearButton.Text = "Clear"; _clearButton.Click += OnClearClicked; _clearButton.Enabled = false; // Add all sketch controls (buttons) to the button bars buttonLayoutOne.AddView(sketchButton); buttonLayoutOne.AddView(_editButton); buttonLayoutOne.AddView(_clearButton); // Second button bar buttonLayoutTwo.AddView(_undoButton); buttonLayoutTwo.AddView(_redoButton); buttonLayoutTwo.AddView(_doneButton); // Create a new vertical layout for the app (buttons followed by map view) var mainLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add the button layouts mainLayout.AddView(buttonLayoutOne); mainLayout.AddView(buttonLayoutTwo); // Add the map view to the layout mainLayout.AddView(_myMapView); // Show the layout in the app SetContentView(mainLayout); } private void OnSketchClicked(object sender, EventArgs e) { var sketchButton = sender as Button; // Create a dictionary of enum names and values var enumValues = Enum.GetValues(typeof(SketchCreationMode)).Cast<int>(); _sketchModeDictionary = enumValues.ToDictionary(v => Enum.GetName(typeof(SketchCreationMode), v), v => v); // Create a menu to show sketch modes var sketchModesMenu = new PopupMenu(sketchButton.Context, sketchButton); sketchModesMenu.MenuItemClick += OnSketchModeItemClicked; // Create a menu option for each basemap type foreach (var mode in _sketchModeDictionary) { sketchModesMenu.Menu.Add(mode.Key); } // Show menu in the view sketchModesMenu.Show(); } private async void OnSketchModeItemClicked(object sender, PopupMenu.MenuItemClickEventArgs e) { try { // Get the title of the selected menu item (sketch mode) var sketchModeName = e.Item.TitleCondensedFormatted.ToString(); // Let the user draw on the map view using the chosen sketch mode SketchCreationMode creationMode = (SketchCreationMode)_sketchModeDictionary[sketchModeName]; Esri.ArcGISRuntime.Geometry.Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true); // Create and add a graphic from the geometry the user drew Graphic graphic = CreateGraphic(geometry); _sketchOverlay.Graphics.Add(graphic); } catch (TaskCanceledException) { // Ignore ... let the user cancel drawing } catch (Exception ex) { // Report exceptions var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error drawing graphic shape"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } } private async void OnEditClicked(object sender, EventArgs e) { try { // Allow the user to select a graphic Graphic editGraphic = await GetGraphicAsync(); if (editGraphic == null) { return; } // Let the user make changes to the graphic's geometry, await the result (updated geometry) Esri.ArcGISRuntime.Geometry.Geometry newGeometry = await _myMapView.SketchEditor.StartAsync(editGraphic.Geometry); // Display the updated geometry in the graphic editGraphic.Geometry = newGeometry; } catch (TaskCanceledException) { // Ignore ... let the user cancel editing } catch (Exception ex) { // Report exceptions var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error editing shape"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } } private void OnClearClicked(object sender, EventArgs e) { // Remove all graphics from the graphics overlay _sketchOverlay.Graphics.Clear(); // Cancel any uncompleted sketch if (_myMapView.SketchEditor.CancelCommand.CanExecute(null)) { _myMapView.SketchEditor.CancelCommand.Execute(null); } } private void OnCompleteClicked(object sender, EventArgs e) { // Execute the CompleteCommand on the sketch editor if (_myMapView.SketchEditor.CompleteCommand.CanExecute(null)) { _myMapView.SketchEditor.CompleteCommand.Execute(null); } } private void OnRedoClicked(object sender, EventArgs e) { // Execute the RedoCommand on the sketch editor if (_myMapView.SketchEditor.RedoCommand.CanExecute(null)) { _myMapView.SketchEditor.RedoCommand.Execute(null); } } private void OnUndoClicked(object sender, EventArgs e) { // Execute the UndoCommand on the sketch editor if (_myMapView.SketchEditor.UndoCommand.CanExecute(null)) { _myMapView.SketchEditor.UndoCommand.Execute(null); } } private void GraphicsChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { // Enable or disable the clear and edit buttons depending on whether or not graphics exist bool haveGraphics = _sketchOverlay.Graphics.Count > 0; _editButton.Enabled = haveGraphics; _clearButton.Enabled = haveGraphics; } private void CanExecuteChanged(object sender, EventArgs e) { // Enable or disable the corresponding command for the sketch editor var command = sender as System.Windows.Input.ICommand; if (command == _myMapView.SketchEditor.UndoCommand) { _undoButton.Enabled = command.CanExecute(null); } else if (command == _myMapView.SketchEditor.RedoCommand) { _redoButton.Enabled = command.CanExecute(null); } else if (command == _myMapView.SketchEditor.CompleteCommand) { _doneButton.Enabled = command.CanExecute(null); } } #region Graphic and symbol helpers private Graphic CreateGraphic(Esri.ArcGISRuntime.Geometry.Geometry geometry) { // Create a graphic to display the specified geometry Symbol symbol = null; switch (geometry.GeometryType) { // Symbolize with a fill symbol case GeometryType.Envelope: case GeometryType.Polygon: { symbol = new SimpleFillSymbol() { Color = Color.Red, Style = SimpleFillSymbolStyle.Solid, }; break; } // Symbolize with a line symbol case GeometryType.Polyline: { symbol = new SimpleLineSymbol() { Color = Color.Red, Style = SimpleLineSymbolStyle.Solid, Width = 5d }; break; } // Symbolize with a marker symbol case GeometryType.Point: case GeometryType.Multipoint: { symbol = new SimpleMarkerSymbol() { Color = Color.Red, Style = SimpleMarkerSymbolStyle.Circle, Size = 15d }; break; } } // pass back a new graphic with the appropriate symbol return new Graphic(geometry, symbol); } private async Task<Graphic> GetGraphicAsync() { // Wait for the user to click a location on the map var mapPoint = (MapPoint)await _myMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false); // Convert the map point to a screen point var screenCoordinate = _myMapView.LocationToScreen(mapPoint); // Identify graphics in the graphics overlay using the point var results = await _myMapView.IdentifyGraphicsOverlaysAsync(screenCoordinate, 2, false); // If results were found, get the first graphic Graphic graphic = null; IdentifyGraphicsOverlayResult idResult = results.FirstOrDefault(); if (idResult != null && idResult.Graphics.Count > 0) { graphic = idResult.Graphics.FirstOrDefault(); } // Return the graphic (or null if none were found) return graphic; } #endregion private async void SketchGeometry(string sketchModeName) { try { // Let the user draw on the map view using the chosen sketch mode SketchCreationMode creationMode = (SketchCreationMode)_sketchModeDictionary[sketchModeName]; Esri.ArcGISRuntime.Geometry.Geometry geometry = await _myMapView.SketchEditor.StartAsync(creationMode, true); // Create and add a graphic from the geometry the user drew Graphic graphic = CreateGraphic(geometry); _sketchOverlay.Graphics.Add(graphic); } catch (TaskCanceledException) { // Ignore ... let the user cancel drawing } catch (Exception ex) { // Report exceptions var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error drawing graphic shape"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } } private async void EditGraphic() { try { // Allow the user to select a graphic Graphic editGraphic = await GetGraphicAsync(); if (editGraphic == null) { return; } // Let the user make changes to the graphic's geometry, await the result (updated geometry) Esri.ArcGISRuntime.Geometry.Geometry newGeometry = await _myMapView.SketchEditor.StartAsync(editGraphic.Geometry); // Display the updated geometry in the graphic editGraphic.Geometry = newGeometry; } catch (TaskCanceledException) { // Ignore ... let the user cancel editing } catch (Exception ex) { // Report exceptions var alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetTitle("Error editing shape"); alertBuilder.SetMessage(ex.Message); alertBuilder.Show(); } } } }
// // SqlDoubleTest.cs - NUnit Test Cases for System.Data.SqlTypes.SqlDouble // // Authors: // Ville Palo (vi64pa@koti.soon.fi) // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data.SqlTypes; using System.Threading; using System.Globalization; namespace MonoTests.System.Data.SqlTypes { [TestFixture] public class SqlDoubleTest : Assertion { [SetUp] public void SetUp () { Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US"); } // Test constructor [Test] public void Create() { SqlDouble Test= new SqlDouble ((double)34.87); AssertEquals ("#A01", 34.87D, Test.Value); Test = new SqlDouble (-9000.6543); AssertEquals ("#A02", -9000.6543D, Test.Value); } // Test public fields [Test] public void PublicFields() { AssertEquals ("#B01", 1.7976931348623157e+308, SqlDouble.MaxValue.Value); AssertEquals ("#B02", -1.7976931348623157e+308, SqlDouble.MinValue.Value); Assert ("#B03", SqlDouble.Null.IsNull); AssertEquals ("#B04", 0d, SqlDouble.Zero.Value); } // Test properties [Test] public void Properties() { SqlDouble Test5443 = new SqlDouble (5443e12); SqlDouble Test1 = new SqlDouble (1); Assert ("#C01", SqlDouble.Null.IsNull); AssertEquals ("#C02", 5443e12, Test5443.Value); AssertEquals ("#C03", (double)1, Test1.Value); } // PUBLIC METHODS [Test] public void ArithmeticMethods() { SqlDouble Test0 = new SqlDouble (0); SqlDouble Test1 = new SqlDouble (15E+108); SqlDouble Test2 = new SqlDouble (-65E+64); SqlDouble Test3 = new SqlDouble (5E+64); SqlDouble Test4 = new SqlDouble (5E+108); SqlDouble TestMax = new SqlDouble (SqlDouble.MaxValue.Value); // Add() AssertEquals ("#D01A", 15E+108, SqlDouble.Add (Test1, Test0).Value); AssertEquals ("#D02A", 1.5E+109, SqlDouble.Add (Test1, Test2).Value); try { SqlDouble test = SqlDouble.Add (SqlDouble.MaxValue, SqlDouble.MaxValue); Fail ("#D03A"); } catch (Exception e) { AssertEquals ("#D04A", typeof (OverflowException), e.GetType ()); } // Divide() AssertEquals ("#D01B", (SqlDouble)3, SqlDouble.Divide (Test1, Test4)); AssertEquals ("#D02B", -13d, SqlDouble.Divide (Test2, Test3).Value); try { SqlDouble test = SqlDouble.Divide(Test1, Test0).Value; Fail ("#D03B"); } catch(Exception e) { AssertEquals ("#D04B", typeof (DivideByZeroException), e.GetType ()); } // Multiply() AssertEquals ("#D01D", (double)(75E+216), SqlDouble.Multiply (Test1, Test4).Value); AssertEquals ("#D02D", (double)0, SqlDouble.Multiply (Test1, Test0).Value); try { SqlDouble test = SqlDouble.Multiply (TestMax, Test1); Fail ("#D03D"); } catch (Exception e) { AssertEquals ("#D04D", typeof (OverflowException), e.GetType ()); } // Subtract() AssertEquals ("#D01F", (double)1.5E+109, SqlDouble.Subtract (Test1, Test3).Value); try { SqlDouble test = SqlDouble.Subtract(SqlDouble.MinValue, SqlDouble.MaxValue); Fail ("D02F"); } catch (Exception e) { AssertEquals ("#D03F", typeof (OverflowException), e.GetType ()); } } [Test] public void CompareTo() { SqlDouble Test1 = new SqlDouble (4e64); SqlDouble Test11 = new SqlDouble (4e64); SqlDouble Test2 = new SqlDouble (-9e34); SqlDouble Test3 = new SqlDouble (10000); SqlString TestString = new SqlString ("This is a test"); Assert ("#E01", Test1.CompareTo (Test3) > 0); Assert ("#E02", Test2.CompareTo (Test3) < 0); Assert ("#E03", Test1.CompareTo (Test11) == 0); Assert ("#E04", Test11.CompareTo (SqlDouble.Null) > 0); try { Test1.CompareTo (TestString); Fail("#E05"); } catch(Exception e) { AssertEquals ("#E06", typeof (ArgumentException), e.GetType ()); } } [Test] public void EqualsMethods() { SqlDouble Test0 = new SqlDouble (0); SqlDouble Test1 = new SqlDouble (1.58e30); SqlDouble Test2 = new SqlDouble (1.8e180); SqlDouble Test22 = new SqlDouble (1.8e180); Assert ("#F01", !Test0.Equals (Test1)); Assert ("#F02", !Test1.Equals (Test2)); Assert ("#F03", !Test2.Equals (new SqlString ("TEST"))); Assert ("#F04", Test2.Equals (Test22)); // Static Equals()-method Assert ("#F05", SqlDouble.Equals (Test2, Test22).Value); Assert ("#F06", !SqlDouble.Equals (Test1, Test2).Value); } [Test] public void GetHashCodeTest() { SqlDouble Test15 = new SqlDouble (15); // FIXME: Better way to test HashCode AssertEquals ("#G01", Test15.GetHashCode (), Test15.GetHashCode ()); } [Test] public void GetTypeTest() { SqlDouble Test = new SqlDouble (84); AssertEquals ("#H01", "System.Data.SqlTypes.SqlDouble", Test.GetType ().ToString ()); AssertEquals ("#H02", "System.Double", Test.Value.GetType ().ToString ()); } [Test] public void Greaters() { SqlDouble Test1 = new SqlDouble (1e100); SqlDouble Test11 = new SqlDouble (1e100); SqlDouble Test2 = new SqlDouble (64e164); // GreateThan () Assert ("#I01", !SqlDouble.GreaterThan (Test1, Test2).Value); Assert ("#I02", SqlDouble.GreaterThan (Test2, Test1).Value); Assert ("#I03", !SqlDouble.GreaterThan (Test1, Test11).Value); // GreaterTharOrEqual () Assert ("#I04", !SqlDouble.GreaterThanOrEqual (Test1, Test2).Value); Assert ("#I05", SqlDouble.GreaterThanOrEqual (Test2, Test1).Value); Assert ("#I06", SqlDouble.GreaterThanOrEqual (Test1, Test11).Value); } [Test] public void Lessers() { SqlDouble Test1 = new SqlDouble (1.8e100); SqlDouble Test11 = new SqlDouble (1.8e100); SqlDouble Test2 = new SqlDouble (64e164); // LessThan() Assert ("#J01", !SqlDouble.LessThan (Test1, Test11).Value); Assert ("#J02", !SqlDouble.LessThan (Test2, Test1).Value); Assert ("#J03", SqlDouble.LessThan (Test11, Test2).Value); // LessThanOrEqual () Assert ("#J04", SqlDouble.LessThanOrEqual (Test1, Test2).Value); Assert ("#J05", !SqlDouble.LessThanOrEqual (Test2, Test1).Value); Assert ("#J06", SqlDouble.LessThanOrEqual (Test11, Test1).Value); Assert ("#J07", SqlDouble.LessThanOrEqual (Test11, SqlDouble.Null).IsNull); } [Test] public void NotEquals() { SqlDouble Test1 = new SqlDouble (1280000000001); SqlDouble Test2 = new SqlDouble (128e10); SqlDouble Test22 = new SqlDouble (128e10); Assert ("#K01", SqlDouble.NotEquals (Test1, Test2).Value); Assert ("#K02", SqlDouble.NotEquals (Test2, Test1).Value); Assert ("#K03", SqlDouble.NotEquals (Test22, Test1).Value); Assert ("#K04", !SqlDouble.NotEquals (Test22, Test2).Value); Assert ("#K05", !SqlDouble.NotEquals (Test2, Test22).Value); Assert ("#K06", SqlDouble.NotEquals (SqlDouble.Null, Test22).IsNull); Assert ("#K07", SqlDouble.NotEquals (SqlDouble.Null, Test22).IsNull); } [Test] public void Parse() { try { SqlDouble.Parse (null); Fail ("#L01"); } catch (Exception e) { AssertEquals ("#L02", typeof (ArgumentNullException), e.GetType ()); } try { SqlDouble.Parse ("not-a-number"); Fail ("#L03"); } catch (Exception e) { AssertEquals ("#L04", typeof (FormatException), e.GetType ()); } try { SqlDouble.Parse ("9e400"); Fail ("#L05"); } catch (Exception e) { AssertEquals ("#L06", typeof (OverflowException), e.GetType ()); } AssertEquals("#L07", (double)150, SqlDouble.Parse ("150").Value); } [Test] public void Conversions() { SqlDouble Test0 = new SqlDouble (0); SqlDouble Test1 = new SqlDouble (250); SqlDouble Test2 = new SqlDouble (64e64); SqlDouble Test3 = new SqlDouble (64e164); SqlDouble TestNull = SqlDouble.Null; // ToSqlBoolean () Assert ("#M01A", Test1.ToSqlBoolean ().Value); Assert ("#M02A", !Test0.ToSqlBoolean ().Value); Assert ("#M03A", TestNull.ToSqlBoolean ().IsNull); // ToSqlByte () AssertEquals ("#M01B", (byte)250, Test1.ToSqlByte ().Value); AssertEquals ("#M02B", (byte)0, Test0.ToSqlByte ().Value); try { SqlByte b = (byte)Test2.ToSqlByte (); Fail ("#M03B"); } catch (Exception e) { AssertEquals ("#M04B", typeof (OverflowException), e.GetType ()); } // ToSqlDecimal () AssertEquals ("#M01C", 250.00000000000000M, Test1.ToSqlDecimal ().Value); AssertEquals ("#M02C", (decimal)0, Test0.ToSqlDecimal ().Value); try { SqlDecimal test = Test3.ToSqlDecimal ().Value; Fail ("#M03C"); } catch (Exception e) { AssertEquals ("#M04C", typeof (OverflowException), e.GetType ()); } // ToSqlInt16 () AssertEquals ("#M01D", (short)250, Test1.ToSqlInt16 ().Value); AssertEquals ("#M02D", (short)0, Test0.ToSqlInt16 ().Value); try { SqlInt16 test = Test2.ToSqlInt16().Value; Fail ("#M03D"); } catch (Exception e) { AssertEquals ("#M04D", typeof (OverflowException), e.GetType ()); } // ToSqlInt32 () AssertEquals ("#M01E", (int)250, Test1.ToSqlInt32 ().Value); AssertEquals ("#M02E", (int)0, Test0.ToSqlInt32 ().Value); try { SqlInt32 test = Test2.ToSqlInt32 ().Value; Fail ("#M03E"); } catch (Exception e) { AssertEquals ("#M04E", typeof (OverflowException), e.GetType ()); } // ToSqlInt64 () AssertEquals ("#M01F", (long)250, Test1.ToSqlInt64 ().Value); AssertEquals ("#M02F", (long)0, Test0.ToSqlInt64 ().Value); try { SqlInt64 test = Test2.ToSqlInt64 ().Value; Fail ("#M03F"); } catch (Exception e) { AssertEquals ("#M04F", typeof (OverflowException), e.GetType ()); } // ToSqlMoney () AssertEquals ("#M01G", 250.0000M, Test1.ToSqlMoney ().Value); AssertEquals ("#M02G", (decimal)0, Test0.ToSqlMoney ().Value); try { SqlMoney test = Test2.ToSqlMoney ().Value; Fail ("#M03G"); } catch (Exception e) { AssertEquals ("#M04G", typeof (OverflowException), e.GetType ()); } // ToSqlSingle () AssertEquals ("#M01H", (float)250, Test1.ToSqlSingle ().Value); AssertEquals ("#M02H", (float)0, Test0.ToSqlSingle ().Value); try { SqlSingle test = Test2.ToSqlSingle().Value; Fail ("#MO3H"); } catch (Exception e) { AssertEquals ("#M04H", typeof (OverflowException), e.GetType ()); } // ToSqlString () AssertEquals ("#M01I", "250", Test1.ToSqlString ().Value); AssertEquals ("#M02I", "0", Test0.ToSqlString ().Value); AssertEquals ("#M03I", "6.4E+65", Test2.ToSqlString ().Value); // ToString () AssertEquals ("#M01J", "250", Test1.ToString ()); AssertEquals ("#M02J", "0", Test0.ToString ()); AssertEquals ("#M03J", "6.4E+65", Test2.ToString ()); } // OPERATORS [Test] public void ArithmeticOperators() { SqlDouble Test0 = new SqlDouble (0); SqlDouble Test1 = new SqlDouble (24E+100); SqlDouble Test2 = new SqlDouble (64E+164); SqlDouble Test3 = new SqlDouble (12E+100); SqlDouble Test4 = new SqlDouble (1E+10); SqlDouble Test5 = new SqlDouble (2E+10); // "+"-operator AssertEquals ("#N01", (SqlDouble)3E+10, Test4 + Test5); try { SqlDouble test = SqlDouble.MaxValue + SqlDouble.MaxValue; Fail ("#N02"); } catch (Exception e) { AssertEquals ("#N03", typeof (OverflowException), e.GetType ()); } // "/"-operator AssertEquals ("#N04", (SqlDouble)2, Test1 / Test3); try { SqlDouble test = Test3 / Test0; Fail ("#N05"); } catch (Exception e) { AssertEquals ("#N06", typeof (DivideByZeroException), e.GetType ()); } // "*"-operator AssertEquals ("#N07", (SqlDouble)2e20, Test4 * Test5); try { SqlDouble test = SqlDouble.MaxValue * Test1; Fail ("#N08"); } catch (Exception e) { AssertEquals ("#N09", typeof (OverflowException), e.GetType ()); } // "-"-operator AssertEquals ("#N10", (SqlDouble)12e100, Test1 - Test3); try { SqlDouble test = SqlDouble.MinValue - SqlDouble.MaxValue; Fail ("#N11"); } catch (Exception e) { AssertEquals ("#N12", typeof (OverflowException), e.GetType ()); } } [Test] public void ThanOrEqualOperators() { SqlDouble Test1 = new SqlDouble (1E+164); SqlDouble Test2 = new SqlDouble (9.7E+100); SqlDouble Test22 = new SqlDouble (9.7E+100); SqlDouble Test3 = new SqlDouble (2E+200); // == -operator Assert ("#O01", (Test2 == Test22).Value); Assert ("#O02", !(Test1 == Test2).Value); Assert ("#O03", (Test1 == SqlDouble.Null).IsNull); // != -operator Assert ("#O04", !(Test2 != Test22).Value); Assert ("#O05", (Test2 != Test3).Value); Assert ("#O06", (Test1 != Test3).Value); Assert ("#O07", (Test1 != SqlDouble.Null).IsNull); // > -operator Assert ("#O08", (Test1 > Test2).Value); Assert ("#O09", !(Test1 > Test3).Value); Assert ("#O10", !(Test2 > Test22).Value); Assert ("#O11", (Test1 > SqlDouble.Null).IsNull); // >= -operator Assert ("#O12", !(Test1 >= Test3).Value); Assert ("#O13", (Test3 >= Test1).Value); Assert ("#O14", (Test2 >= Test22).Value); Assert ("#O15", (Test1 >= SqlDouble.Null).IsNull); // < -operator Assert ("#O16", !(Test1 < Test2).Value); Assert ("#O17", (Test1 < Test3).Value); Assert ("#O18", !(Test2 < Test22).Value); Assert ("#O19", (Test1 < SqlDouble.Null).IsNull); // <= -operator Assert ("#O20", (Test1 <= Test3).Value); Assert ("#O21", !(Test3 <= Test1).Value); Assert ("#O22", (Test2 <= Test22).Value); Assert ("#O23", (Test1 <= SqlDouble.Null).IsNull); } [Test] public void UnaryNegation() { SqlDouble Test = new SqlDouble (2000000001); SqlDouble TestNeg = new SqlDouble (-3000); SqlDouble Result = -Test; AssertEquals ("#P01", (double)(-2000000001), Result.Value); Result = -TestNeg; AssertEquals ("#P02", (double)3000, Result.Value); } [Test] public void SqlBooleanToSqlDouble() { SqlBoolean TestBoolean = new SqlBoolean (true); SqlDouble Result; Result = (SqlDouble)TestBoolean; AssertEquals ("#Q01", (double)1, Result.Value); Result = (SqlDouble)SqlBoolean.Null; Assert ("#Q02", Result.IsNull); } [Test] public void SqlDoubleToDouble() { SqlDouble Test = new SqlDouble (12e12); Double Result = (double)Test; AssertEquals ("#R01", 12e12, Result); } [Test] public void SqlStringToSqlDouble() { SqlString TestString = new SqlString ("Test string"); SqlString TestString100 = new SqlString ("100"); AssertEquals ("#S01", (double)100, ((SqlDouble)TestString100).Value); try { SqlDouble test = (SqlDouble)TestString; Fail ("#S02"); } catch(Exception e) { AssertEquals ("#S03", typeof (FormatException), e.GetType ()); } } [Test] public void DoubleToSqlDouble() { double Test1 = 5e64; SqlDouble Result = (SqlDouble)Test1; AssertEquals ("#T01", 5e64, Result.Value); } [Test] public void ByteToSqlDouble() { short TestShort = 14; AssertEquals ("#U01", (double)14, ((SqlDouble)TestShort).Value); } [Test] public void SqlDecimalToSqlDouble() { SqlDecimal TestDecimal64 = new SqlDecimal (64); AssertEquals ("#V01", (double)64, ((SqlDouble)TestDecimal64).Value); AssertEquals ("#V02", SqlDouble.Null, ((SqlDouble)SqlDecimal.Null)); } [Test] public void SqlIntToSqlDouble() { SqlInt16 Test64 = new SqlInt16 (64); SqlInt32 Test640 = new SqlInt32 (640); SqlInt64 Test64000 = new SqlInt64 (64000); AssertEquals ("#W01", (double)64, ((SqlDouble)Test64).Value); AssertEquals ("#W02", (double)640, ((SqlDouble)Test640).Value); AssertEquals ("#W03", (double)64000, ((SqlDouble)Test64000).Value); } [Test] public void SqlMoneyToSqlDouble() { SqlMoney TestMoney64 = new SqlMoney(64); AssertEquals ("#X01", (double)64, ((SqlDouble)TestMoney64).Value); } [Test] public void SqlSingleToSqlDouble() { SqlSingle TestSingle64 = new SqlSingle (64); AssertEquals ("#Y01", (double)64, ((SqlDouble)TestSingle64).Value); } } }
/* * 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.Threading; using System.Collections.Generic; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; using Apache.Geode.Client.UnitTests; using Region = Apache.Geode.Client.IRegion<Object, Object>; using Apache.Geode.Client.Tests; #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* class CSTXListener<TKey, TVal> : TransactionListenerAdapter<TKey, TVal> { public CSTXListener(string cacheName) { m_cacheName = cacheName; } public override void AfterCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterCommitEvents++; afterCommitKeyEvents += te.Events.Length; } public override void AfterFailedCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterFailedCommitEvents++; afterFailedCommitKeyEvents += te.Events.Length; } public override void AfterRollback(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; afterRollbackEvents++; afterRollbackKeyEvents += te.Events.Length; } public override void Close() { closeEvent++; } public void ShowTallies() { Util.Log("CSTXListener state: (afterCommitEvents = {0}, afterRollbackEvents = {1}, afterFailedCommitEvents = {2}, afterCommitRegionEvents = {3}, afterRollbackRegionEvents = {4}, afterFailedCommitRegionEvents = {5}, closeEvent = {6})", afterCommitEvents, afterRollbackEvents, afterFailedCommitEvents, afterCommitKeyEvents, afterRollbackKeyEvents, afterFailedCommitKeyEvents, closeEvent); } public int AfterCommitEvents { get { return afterCommitEvents; } } public int AfterRollbackEvents { get { return afterRollbackEvents; } } public int AfterFailedCommitEvents { get { return afterFailedCommitEvents; } } public int AfterCommitKeyEvents { get { return afterCommitKeyEvents; } } public int AfterRollbackKeyEvents { get { return afterRollbackKeyEvents; } } public int AfterFailedCommitKeyEvents { get { return afterFailedCommitKeyEvents; } } public int CloseEvent { get { return closeEvent; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } private int afterCommitEvents = 0; private int afterRollbackEvents = 0; private int afterFailedCommitEvents = 0; private int afterCommitKeyEvents = 0; private int afterRollbackKeyEvents = 0; private int afterFailedCommitKeyEvents = 0; private int closeEvent = 0; private string m_cacheName = null; private bool incorrectCacheName = false; } class CSTXWriter<TKey, TVal> : TransactionWriterAdapter<TKey, TVal> { public CSTXWriter(string cacheName, string instanceName) { m_instanceName = instanceName; m_cacheName = cacheName; } public override void BeforeCommit(TransactionEvent<TKey, TVal> te) { if (te.Cache.Name != m_cacheName) incorrectCacheName = true; beforeCommitEvents++; beforeCommitKeyEvents += te.Events.Length; } public int BeforeCommitEvents { get { return beforeCommitEvents; } } public int BeforeCommitKeyEvents { get { return beforeCommitKeyEvents; } } public string InstanceName { get { return m_instanceName; } } public bool IncorrectCacheName { get { return incorrectCacheName; } } public void ShowTallies() { Util.Log("CSTXWriter state: (beforeCommitEvents = {0}, beforeCommitRegionEvents = {1}, instanceName = {2})", beforeCommitEvents, beforeCommitKeyEvents, m_instanceName); } private int beforeCommitEvents = 0; private int beforeCommitKeyEvents = 0; private string m_cacheName = null; private string m_instanceName; private bool incorrectCacheName = false; } */ #endregion [TestFixture] [Category("group1")] [Category("unicast_only")] public class ThinClientCSTX : ThinClientRegionSteps { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /*private CSTXWriter<object, object> m_writer1; private CSTXWriter<object, object> m_writer2; private CSTXListener<object, object> m_listener1; private CSTXListener<object, object> m_listener2;*/ #endregion RegionOperation o_region1; RegionOperation o_region2; private TallyListener<object, object> m_listener; private static string[] cstxRegions = new string[] { "cstx1", "cstx2", "cstx3" }; private UnitProcess m_client1; protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); return new ClientBase[] { m_client1 }; } public void CreateRegion(string regionName, string locators, bool listener) { if (listener) m_listener = new TallyListener<object, object>(); else m_listener = null; Region region = null; region = CacheHelper.CreateTCRegion_Pool<object, object>(regionName, false, false, m_listener, locators, "__TESTPOOL1_", false); } #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* public void ValidateCSTXListenerWriter() { Util.Log("tallies for listener 1"); m_listener1.ShowTallies(); Util.Log("tallies for writer 1"); m_writer1.ShowTallies(); Util.Log("tallies for listener 2"); m_listener2.ShowTallies(); Util.Log("tallies for writer 2"); m_writer2.ShowTallies(); // listener 1 Assert.AreEqual(4, m_listener1.AfterCommitEvents, "Should be 4"); Assert.AreEqual(14, m_listener1.AfterCommitKeyEvents, "Should be 14"); Assert.AreEqual(0, m_listener1.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener1.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener1.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener1.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener1.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener1.IncorrectCacheName, "Incorrect cache name in the events"); // listener 2 Assert.AreEqual(2, m_listener2.AfterCommitEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterCommitKeyEvents, "Should be 6"); Assert.AreEqual(0, m_listener2.AfterFailedCommitEvents, "Should be 0"); Assert.AreEqual(0, m_listener2.AfterFailedCommitKeyEvents, "Should be 0"); Assert.AreEqual(2, m_listener2.AfterRollbackEvents, "Should be 2"); Assert.AreEqual(6, m_listener2.AfterRollbackKeyEvents, "Should be 6"); Assert.AreEqual(1, m_listener2.CloseEvent, "Should be 1"); Assert.AreEqual(false, m_listener2.IncorrectCacheName, "Incorrect cache name in the events"); // writer 1 Assert.AreEqual(3, m_writer1.BeforeCommitEvents, "Should be 3"); Assert.AreEqual(10, m_writer1.BeforeCommitKeyEvents, "Should be 10"); Assert.AreEqual(false, m_writer1.IncorrectCacheName, "Incorrect cache name in the events"); // writer 2 Assert.AreEqual(1, m_writer2.BeforeCommitEvents, "Should be 1"); Assert.AreEqual(4, m_writer2.BeforeCommitKeyEvents, "Should be 4"); Assert.AreEqual(false, m_writer2.IncorrectCacheName, "Incorrect cache name in the events"); } */ #endregion public void ValidateListener() { o_region1 = new RegionOperation(cstxRegions[2]); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key3", "value1", null); o_region1.Region.Put("key4", "value2", null); o_region1.Region.Remove("key4"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 create Assert.AreEqual(1, m_listener.Creates, "Should be 1 creates"); Assert.AreEqual(1, m_listener.Destroys, "Should be 1 destroys"); CacheHelper.CSTXManager.Begin(); o_region1.Region.Put("key1", "value1", null); o_region1.Region.Put("key2", "value2", null); o_region1.Region.Invalidate("key1"); o_region1.Region.Invalidate("key3"); CacheHelper.CSTXManager.Commit(); // server is conflating the events on the same key hence only 1 invalidate Assert.AreEqual(3, m_listener.Creates, "Should be 3 creates"); Assert.AreEqual(1, m_listener.Invalidates, "Should be 1 invalidates"); } public void SuspendResumeRollback() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Rollback(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, 3000), false, "Transaction should not be resumed"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback"); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); } public void SuspendResumeInThread() { AutoResetEvent txEvent = new AutoResetEvent(false); AutoResetEvent txIdUpdated = new AutoResetEvent(false); SuspendTransactionThread susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); Thread susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); ResumeTransactionThread resObj = new ResumeTransactionThread(susObj.Tid, false, false, txEvent); Thread resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(false, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, false, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, false, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); susObj = new SuspendTransactionThread(true, txEvent, txIdUpdated); susThread = new Thread(new ThreadStart(susObj.ThreadStart)); susThread.Start(); txIdUpdated.WaitOne(); resObj = new ResumeTransactionThread(susObj.Tid, true, true, txEvent); resThread = new Thread(new ThreadStart(resObj.ThreadStart)); resThread.Start(); susThread.Join(); resThread.Join(); Assert.AreEqual(resObj.IsFailed, false, resObj.Error); } public void SuspendResumeCommit() { o_region1 = new RegionOperation(cstxRegions[0]); o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(CacheHelper.CSTXManager.TransactionId), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(CacheHelper.CSTXManager.TransactionId), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); TransactionId tid = CacheHelper.CSTXManager.Suspend(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), true, "Transaction should be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(0, o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend"); Assert.AreEqual(0, o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend"); CacheHelper.CSTXManager.Resume(tid); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "The transaction should not have been resumed again."); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), true, "Transaction should exist"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be two values in the region before commit"); Assert.AreEqual(2, o_region2.Region.Keys.Count, "There should be two values in the region before commit"); o_region2.PutOp(2, null); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region before commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region before commit"); CacheHelper.CSTXManager.Commit(); Assert.AreEqual(CacheHelper.CSTXManager.IsSuspended(tid), false, "Transaction should not be suspended"); Assert.AreEqual(CacheHelper.CSTXManager.Exists(tid), false, "Transaction should NOT exist"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid), false, "Transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.TryResume(tid, 3000), false, "Transaction should not be resumed"); Assert.AreEqual(2, o_region1.Region.Keys.Count, "There should be four values in the region after commit"); Assert.AreEqual(4, o_region2.Region.Keys.Count, "There should be four values in the region after commit"); o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); bool resumeEx = false; try { CacheHelper.CSTXManager.Resume(tid); } catch (IllegalStateException) { resumeEx = true; } Assert.AreEqual(resumeEx, true, "The transaction should not be resumed"); Assert.AreEqual(CacheHelper.CSTXManager.Suspend(), null, "The transaction should not be suspended"); } public void CallOp() { #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_writer1 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter1"); m_writer2 = new CSTXWriter<object, object>(CacheHelper.DCache.Name, "cstxWriter2"); m_listener1 = new CSTXListener<object, object>(CacheHelper.DCache.Name); m_listener2 = new CSTXListener<object, object>(CacheHelper.DCache.Name); CacheHelper.CSTXManager.AddListener<object, object>(m_listener1); CacheHelper.CSTXManager.AddListener<object, object>(m_listener2); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer1); // test two listener one writer for commit on two regions Util.Log(" test two listener one writer for commit on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); o_region1.PutOp(2, null); o_region2 = new RegionOperation(cstxRegions[1]); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Commit didn't put two values in the region"); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for commit on two regions - complete"); ////////////////////////////////// // region test two listener one writer for commit on one region Util.Log(" region test two listener one writer for commit on one region"); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" region test two listener one writer for commit on one region - complete"); ////////////////////////////////// // test two listener one writer for rollback on two regions Util.Log(" test two listener one writer for rollback on two regions"); */ #endregion CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); //two pdx put as well Assert.AreEqual(2 + 2, o_region1.Region.Keys.Count, "Region has incorrect number of objects"); Assert.AreEqual(2 + 2, o_region2.Region.Keys.Count, "Region has incorrect number of objects"); o_region1.DestroyOpWithPdxValue(2, null); o_region2.DestroyOpWithPdxValue(2, null); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* Util.Log(" test two listener one writer for rollback on two regions - complete"); ////////////////////////////////// // test two listener one writer for rollback on on region Util.Log(" test two listener one writer for rollback on on region"); CacheHelper.CSTXManager.Begin(); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Rollback(); Util.Log(" test two listener one writer for rollback on on region - complete"); ////////////////////////////////// // test remove listener Util.Log(" test remove listener"); CacheHelper.CSTXManager.RemoveListener<object, object>(m_listener2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log(" test remove listener - complete" ); ////////////////////////////////// // test GetWriter Util.Log("test GetWriter"); CSTXWriter<object, object> writer = (CSTXWriter<object, object>)CacheHelper.CSTXManager.GetWriter<object, object>(); Assert.AreEqual(writer.InstanceName, m_writer1.InstanceName, "GetWriter is not returning the object set by SetWriter"); Util.Log("test GetWriter - complete"); ////////////////////////////////// // set a different writer Util.Log("set a different writer"); CacheHelper.CSTXManager.SetWriter<object, object>(m_writer2); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(2, null); o_region2.PutOp(2, null); CacheHelper.CSTXManager.Commit(); Util.Log("set a different writer - complete"); ////////////////////////////////// */ #endregion } void runThinClientCSTXTest() { CacheHelper.SetupJavaServers(true, "client_server_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[1], CacheHelper.Locators, false); m_client1.Call(CreateRegion, cstxRegions[2], CacheHelper.Locators, true); m_client1.Call(CallOp); m_client1.Call(SuspendResumeCommit); m_client1.Call(SuspendResumeRollback); m_client1.Call(SuspendResumeInThread); m_client1.Call(ValidateListener); #region CSTX_COMMENTED - transaction listener and writer are disabled for now /* m_client1.Call(ValidateCSTXListenerWriter); */ #endregion m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } void runThinClientPersistentTXTest() { CacheHelper.SetupJavaServers(true, "client_server_persistent_transactions.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, "--J=-Dgemfire.ALLOW_PERSISTENT_TRANSACTIONS=true"); Util.Log("Cacheserver 1 started."); m_client1.Call(CacheHelper.InitClient); Util.Log("Creating two regions in client1"); m_client1.Call(CreateRegion, cstxRegions[0], CacheHelper.Locators, false); m_client1.Call(initializePdxSerializer); m_client1.Call(doPutGetWithPdxSerializer); m_client1.Call(CacheHelper.Close); CacheHelper.StopJavaServer(1); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearLocators(); CacheHelper.ClearEndpoints(); } [TearDown] public override void EndTest() { base.EndTest(); } //Successful [Test] public void ThinClientCSTXTest() { runThinClientCSTXTest(); } [Test] public void ThinClientPersistentTXTest() { runThinClientPersistentTXTest(); } public class SuspendTransactionThread { public SuspendTransactionThread(bool sleep, AutoResetEvent txevent, AutoResetEvent txIdUpdated) { m_sleep = sleep; m_txevent = txevent; m_txIdUpdated = txIdUpdated; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); CacheHelper.CSTXManager.Begin(); o_region1.PutOp(1, null); o_region2.PutOp(1, null); m_tid = CacheHelper.CSTXManager.TransactionId; m_txIdUpdated.Set(); if (m_sleep) { m_txevent.WaitOne(); Thread.Sleep(5000); } m_tid = CacheHelper.CSTXManager.Suspend(); } public TransactionId Tid { get { return m_tid; } } private TransactionId m_tid = null; private bool m_sleep = false; private AutoResetEvent m_txevent = null; AutoResetEvent m_txIdUpdated = null; } public class ResumeTransactionThread { public ResumeTransactionThread(TransactionId tid, bool isCommit, bool tryResumeWithSleep, AutoResetEvent txevent) { m_tryResumeWithSleep = tryResumeWithSleep; m_txevent = txevent; m_tid = tid; m_isCommit = isCommit; } public void ThreadStart() { RegionOperation o_region1 = new RegionOperation(cstxRegions[0]); RegionOperation o_region2 = new RegionOperation(cstxRegions[1]); if (m_tryResumeWithSleep) { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; } else { if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == true, "Transaction should be suspended")) return; } if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after suspend")) return; if (m_tryResumeWithSleep) { m_txevent.Set(); CacheHelper.CSTXManager.TryResume(m_tid, 30000); } else CacheHelper.CSTXManager.Resume(m_tid); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == true, "Transaction should exist")) return; if (AssertCheckFail(o_region1.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; if (AssertCheckFail(o_region2.Region.Keys.Count == 2, "There should be two values in the region after suspend")) return; o_region2.PutOp(2, null); if (m_isCommit) { CacheHelper.CSTXManager.Commit(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, 3000) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(2 == o_region1.Region.Keys.Count, "There should be four values in the region after commit")) return; if (AssertCheckFail(4 == o_region2.Region.Keys.Count, "There should be four values in the region after commit")) return; o_region1.DestroyOpWithPdxValue(1, null); o_region2.DestroyOpWithPdxValue(2, null); } else { CacheHelper.CSTXManager.Rollback(); if (AssertCheckFail(CacheHelper.CSTXManager.IsSuspended(m_tid) == false, "Transaction should not be suspended")) return; if (AssertCheckFail(CacheHelper.CSTXManager.Exists(m_tid) == false, "Transaction should NOT exist")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(CacheHelper.CSTXManager.TryResume(m_tid, 3000) == false, "Transaction should not be resumed")) return; if (AssertCheckFail(0 == o_region1.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; if (AssertCheckFail(0 == o_region2.Region.Keys.Count, "There should be 0 values in the region after rollback")) return; } } public bool AssertCheckFail(bool cond, String error) { if (!cond) { m_isFailed = true; m_error = error; return true; } return false; } public TransactionId Tid { get { return m_tid; } } public bool IsFailed { get { return m_isFailed; } } public String Error { get { return m_error; } } private TransactionId m_tid = null; private bool m_tryResumeWithSleep = false; private bool m_isFailed = false; private String m_error; private bool m_isCommit = false; private AutoResetEvent m_txevent = null; } public void initializePdxSerializer() { Serializable.RegisterPdxSerializer(new PdxSerializer()); } public void doPutGetWithPdxSerializer() { CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 0; i < 10; i++) { o_region1.Region[i] = i + 1; object ret = o_region1.Region[i]; o_region1.Region[i + 10] = i + 10; ret = o_region1.Region[i + 10]; o_region1.Region[i + 20] = i + 20; ret = o_region1.Region[i + 20]; } CacheHelper.CSTXManager.Commit(); Util.Log("Region keys count after commit for non-pdx keys = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(30, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); CacheHelper.CSTXManager.Begin(); o_region1 = new RegionOperation(cstxRegions[0]); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); o_region1.Region[i] = put; put = new SerializePdx2(true); o_region1.Region[i + 10] = put; put = new SerializePdx3(true, i % 2); o_region1.Region[i + 20] = put; } CacheHelper.CSTXManager.Commit(); for (int i = 100; i < 110; i++) { object put = new SerializePdx1(true); object ret = o_region1.Region[i]; Assert.AreEqual(put, ret); put = new SerializePdx2(true); ret = o_region1.Region[i + 10]; Assert.AreEqual(put, ret); put = new SerializePdx3(true, i % 2); ret = o_region1.Region[i + 20]; Assert.AreEqual(put, ret); } Util.Log("Region keys count after pdx-keys commit = {0} ", o_region1.Region.Keys.Count); Assert.AreEqual(60, o_region1.Region.Keys.Count, "Commit didn't put two values in the region"); } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Sax.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Sax { /// <summary> /// <para>Listens for the beginning and ending of text elements. </para> /// </summary> /// <java-name> /// android/sax/TextElementListener /// </java-name> [Dot42.DexImport("android/sax/TextElementListener", AccessFlags = 1537)] public partial interface ITextElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndTextElementListener /* scope: __dot42__ */ { } /// <summary> /// <para>The root XML element. The entry point for this API. Not safe for concurrent use.</para><para>For example, passing this XML:</para><para><pre> /// &lt;feed xmlns='&gt; /// &lt;entry&gt; /// &lt;id&gt;bob&lt;/id&gt; /// &lt;/entry&gt; /// &lt;/feed&gt; /// </pre></para><para>to this code:</para><para><pre> /// static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; /// /// ... /// /// RootElement root = new RootElement(ATOM_NAMESPACE, "feed"); /// Element entry = root.getChild(ATOM_NAMESPACE, "entry"); /// entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener( /// new EndTextElementListener() { /// public void end(String body) { /// System.out.println("Entry ID: " + body); /// } /// }); /// /// XMLReader reader = ...; /// reader.setContentHandler(root.getContentHandler()); /// reader.parse(...); /// </pre></para><para>would output:</para><para><pre> /// Entry ID: bob /// </pre> </para> /// </summary> /// <java-name> /// android/sax/RootElement /// </java-name> [Dot42.DexImport("android/sax/RootElement", AccessFlags = 33)] public partial class RootElement : global::Android.Sax.Element /* scope: __dot42__ */ { /// <summary> /// <para>Constructs a new root element with the given name.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public RootElement(string uri, string localName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Constructs a new root element with the given name. Uses an empty string as the namespace.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public RootElement(string localName) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para> /// </summary> /// <java-name> /// getContentHandler /// </java-name> [Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] public virtual global::Org.Xml.Sax.IContentHandler GetContentHandler() /* MethodBuilder.Create */ { return default(global::Org.Xml.Sax.IContentHandler); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal RootElement() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Gets the SAX <c> ContentHandler </c> . Pass this to your SAX parser. </para> /// </summary> /// <java-name> /// getContentHandler /// </java-name> public global::Org.Xml.Sax.IContentHandler ContentHandler { [Dot42.DexImport("getContentHandler", "()Lorg/xml/sax/ContentHandler;", AccessFlags = 1)] get{ return GetContentHandler(); } } } /// <summary> /// <para>Listens for the beginning and ending of elements. </para> /// </summary> /// <java-name> /// android/sax/ElementListener /// </java-name> [Dot42.DexImport("android/sax/ElementListener", AccessFlags = 1537)] public partial interface IElementListener : global::Android.Sax.IStartElementListener, global::Android.Sax.IEndElementListener /* scope: __dot42__ */ { } /// <summary> /// <para>Listens for the end of elements. </para> /// </summary> /// <java-name> /// android/sax/EndElementListener /// </java-name> [Dot42.DexImport("android/sax/EndElementListener", AccessFlags = 1537)] public partial interface IEndElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the end of an element. </para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "()V", AccessFlags = 1025)] void End() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Listens for the beginning of elements. </para> /// </summary> /// <java-name> /// android/sax/StartElementListener /// </java-name> [Dot42.DexImport("android/sax/StartElementListener", AccessFlags = 1537)] public partial interface IStartElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the beginning of an element.</para><para></para> /// </summary> /// <java-name> /// start /// </java-name> [Dot42.DexImport("start", "(Lorg/xml/sax/Attributes;)V", AccessFlags = 1025)] void Start(global::Org.Xml.Sax.IAttributes attributes) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Listens for the end of text elements. </para> /// </summary> /// <java-name> /// android/sax/EndTextElementListener /// </java-name> [Dot42.DexImport("android/sax/EndTextElementListener", AccessFlags = 1537)] public partial interface IEndTextElementListener /* scope: __dot42__ */ { /// <summary> /// <para>Invoked at the end of a text element with the body of the element.</para><para></para> /// </summary> /// <java-name> /// end /// </java-name> [Dot42.DexImport("end", "(Ljava/lang/String;)V", AccessFlags = 1025)] void End(string body) /* MethodBuilder.Create */ ; } /// <summary> /// <para>An XML element. Provides access to child elements and hooks to listen for events related to this element.</para><para><para>RootElement </para></para> /// </summary> /// <java-name> /// android/sax/Element /// </java-name> [Dot42.DexImport("android/sax/Element", AccessFlags = 33)] public partial class Element /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal Element() /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the child element with the given name. Uses an empty string as the namespace. </para> /// </summary> /// <java-name> /// getChild /// </java-name> [Dot42.DexImport("getChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element GetChild(string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. </para> /// </summary> /// <java-name> /// getChild /// </java-name> [Dot42.DexImport("getChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element GetChild(string uri, string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. Uses an empty string as the namespace. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para> /// </summary> /// <java-name> /// requireChild /// </java-name> [Dot42.DexImport("requireChild", "(Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element RequireChild(string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Gets the child element with the given name. We will throw a org.xml.sax.SAXException at parsing time if the specified child is missing. This helps you ensure that your listeners are called. </para> /// </summary> /// <java-name> /// requireChild /// </java-name> [Dot42.DexImport("requireChild", "(Ljava/lang/String;Ljava/lang/String;)Landroid/sax/Element;", AccessFlags = 1)] public virtual global::Android.Sax.Element RequireChild(string uri, string localName) /* MethodBuilder.Create */ { return default(global::Android.Sax.Element); } /// <summary> /// <para>Sets start and end element listeners at the same time. </para> /// </summary> /// <java-name> /// setElementListener /// </java-name> [Dot42.DexImport("setElementListener", "(Landroid/sax/ElementListener;)V", AccessFlags = 1)] public virtual void SetElementListener(global::Android.Sax.IElementListener elementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets start and end text element listeners at the same time. </para> /// </summary> /// <java-name> /// setTextElementListener /// </java-name> [Dot42.DexImport("setTextElementListener", "(Landroid/sax/TextElementListener;)V", AccessFlags = 1)] public virtual void SetTextElementListener(global::Android.Sax.ITextElementListener elementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the start of this element. </para> /// </summary> /// <java-name> /// setStartElementListener /// </java-name> [Dot42.DexImport("setStartElementListener", "(Landroid/sax/StartElementListener;)V", AccessFlags = 1)] public virtual void SetStartElementListener(global::Android.Sax.IStartElementListener startElementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the end of this element. </para> /// </summary> /// <java-name> /// setEndElementListener /// </java-name> [Dot42.DexImport("setEndElementListener", "(Landroid/sax/EndElementListener;)V", AccessFlags = 1)] public virtual void SetEndElementListener(global::Android.Sax.IEndElementListener endElementListener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets a listener for the end of this text element. </para> /// </summary> /// <java-name> /// setEndTextElementListener /// </java-name> [Dot42.DexImport("setEndTextElementListener", "(Landroid/sax/EndTextElementListener;)V", AccessFlags = 1)] public virtual void SetEndTextElementListener(global::Android.Sax.IEndTextElementListener endTextElementListener) /* MethodBuilder.Create */ { } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } } }
/* * Copyright (c) 2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.InteropServices; using System.Globalization; using ProtoBuf; namespace OpenMetaverse { [Serializable] [StructLayout(LayoutKind.Sequential)] [ProtoContract] public struct Quaternion : IEquatable<Quaternion> { [ProtoMember(1)] /// <summary>X value</summary> public float X; [ProtoMember(2)] /// <summary>Y value</summary> public float Y; [ProtoMember(3)] /// <summary>Z value</summary> public float Z; [ProtoMember(4)] /// <summary>W value</summary> public float W; #region Constructors public Quaternion(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } /// <summary> /// Build a quaternion from normalized float values /// </summary> /// <param name="x">X value from -1.0 to 1.0</param> /// <param name="y">Y value from -1.0 to 1.0</param> /// <param name="z">Z value from -1.0 to 1.0</param> public Quaternion(float x, float y, float z) { X = x; Y = y; Z = z; float xyzsum = 1 - X * X - Y * Y - Z * Z; W = (xyzsum > 0) ? (float)Math.Sqrt(xyzsum) : 0; } /// <summary> /// Constructor, builds a quaternion object from a byte array /// </summary> /// <param name="byteArray">Byte array containing four four-byte floats</param> /// <param name="pos">Offset in the byte array to start reading at</param> /// <param name="normalized">Whether the source data is normalized or /// not. If this is true 12 bytes will be read, otherwise 16 bytes will /// be read.</param> public Quaternion(byte[] byteArray, int pos, bool normalized) { X = Y = Z = W = 0; FromBytes(byteArray, pos, normalized); } public Quaternion(Quaternion q) { X = q.X; Y = q.Y; Z = q.Z; W = q.W; } #endregion Constructors #region Public Methods public bool ApproxEquals(Quaternion quat, float tolerance) { Quaternion diff = this - quat; return (diff.LengthSquared() <= tolerance * tolerance); } public float Length() { return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W); } public float LengthSquared() { return (X * X + Y * Y + Z * Z + W * W); } /// <summary> /// Normalizes the quaternion /// </summary> public void Normalize() { this = Normalize(this); } /// <summary> /// Builds a quaternion object from a byte array /// </summary> /// <param name="byteArray">The source byte array</param> /// <param name="pos">Offset in the byte array to start reading at</param> /// <param name="normalized">Whether the source data is normalized or /// not. If this is true 12 bytes will be read, otherwise 16 bytes will /// be read.</param> public void FromBytes(byte[] byteArray, int pos, bool normalized) { if (!normalized) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); Array.Reverse(conversionBuffer, 12, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); W = BitConverter.ToSingle(conversionBuffer, 12); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); W = BitConverter.ToSingle(byteArray, pos + 12); } } else { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[16]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12); Array.Reverse(conversionBuffer, 0, 4); Array.Reverse(conversionBuffer, 4, 4); Array.Reverse(conversionBuffer, 8, 4); X = BitConverter.ToSingle(conversionBuffer, 0); Y = BitConverter.ToSingle(conversionBuffer, 4); Z = BitConverter.ToSingle(conversionBuffer, 8); } else { // Little endian architecture X = BitConverter.ToSingle(byteArray, pos); Y = BitConverter.ToSingle(byteArray, pos + 4); Z = BitConverter.ToSingle(byteArray, pos + 8); } float xyzsum = 1f - X * X - Y * Y - Z * Z; W = (xyzsum > 0f) ? (float)Math.Sqrt(xyzsum) : 0f; } } /// <summary> /// Normalize this quaternion and serialize it to a byte array /// </summary> /// <returns>A 12 byte array containing normalized X, Y, and Z floating /// point values in order using little endian byte ordering</returns> public byte[] GetBytes() { byte[] bytes = new byte[12]; ToBytes(bytes, 0); return bytes; } /// <summary> /// Writes the raw bytes for this quaternion to a byte array /// </summary> /// <param name="dest">Destination byte array</param> /// <param name="pos">Position in the destination array to start /// writing. Must be at least 12 bytes before the end of the array</param> public void ToBytes(byte[] dest, int pos) { float norm = (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W); if (norm != 0f) { norm = 1f / norm; float x, y, z; if (W >= 0f) { x = X; y = Y; z = Z; } else { x = -X; y = -Y; z = -Z; } Buffer.BlockCopy(BitConverter.GetBytes(norm * x), 0, dest, pos + 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(norm * y), 0, dest, pos + 4, 4); Buffer.BlockCopy(BitConverter.GetBytes(norm * z), 0, dest, pos + 8, 4); if (!BitConverter.IsLittleEndian) { Array.Reverse(dest, pos + 0, 4); Array.Reverse(dest, pos + 4, 4); Array.Reverse(dest, pos + 8, 4); } } else { throw new InvalidOperationException(String.Format( "Quaternion {0} normalized to zero", ToString())); } } /// <summary> /// Convert this quaternion to euler angles /// </summary> /// <param name="roll">X euler angle</param> /// <param name="pitch">Y euler angle</param> /// <param name="yaw">Z euler angle</param> public void GetEulerAngles(out float roll, out float pitch, out float yaw) { roll = 0f; pitch = 0f; yaw = 0f; Quaternion t = new Quaternion(this.X * this.X, this.Y * this.Y, this.Z * this.Z, this.W * this.W); float m = (t.X + t.Y + t.Z + t.W); if (Math.Abs(m) < 0.001d) return; float n = 2 * (this.Y * this.W + this.X * this.Z); float p = m * m - n * n; if (p > 0f) { roll = (float)Math.Atan2(2.0f * (this.X * this.W - this.Y * this.Z), (-t.X - t.Y + t.Z + t.W)); pitch = (float)Math.Atan2(n, Math.Sqrt(p)); yaw = (float)Math.Atan2(2.0f * (this.Z * this.W - this.X * this.Y), t.X - t.Y - t.Z + t.W); } else if (n > 0f) { roll = 0f; pitch = (float)(Math.PI / 2d); yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Y); } else { roll = 0f; pitch = -(float)(Math.PI / 2d); yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Z); } //float sqx = X * X; //float sqy = Y * Y; //float sqz = Z * Z; //float sqw = W * W; //// Unit will be a correction factor if the quaternion is not normalized //float unit = sqx + sqy + sqz + sqw; //double test = X * Y + Z * W; //if (test > 0.499f * unit) //{ // // Singularity at north pole // yaw = 2f * (float)Math.Atan2(X, W); // pitch = (float)Math.PI / 2f; // roll = 0f; //} //else if (test < -0.499f * unit) //{ // // Singularity at south pole // yaw = -2f * (float)Math.Atan2(X, W); // pitch = -(float)Math.PI / 2f; // roll = 0f; //} //else //{ // yaw = (float)Math.Atan2(2f * Y * W - 2f * X * Z, sqx - sqy - sqz + sqw); // pitch = (float)Math.Asin(2f * test / unit); // roll = (float)Math.Atan2(2f * X * W - 2f * Y * Z, -sqx + sqy - sqz + sqw); //} } /// <summary> /// Convert this quaternion to an angle around an axis /// </summary> /// <param name="axis">Unit vector describing the axis</param> /// <param name="angle">Angle around the axis, in radians</param> public void GetAxisAngle(out Vector3 axis, out float angle) { axis = new Vector3(); float scale = (float)Math.Sqrt(X * X + Y * Y + Z * Z); if (scale < Single.Epsilon || W > 1.0f || W < -1.0f) { angle = 0.0f; axis.X = 0.0f; axis.Y = 1.0f; axis.Z = 0.0f; } else { angle = 2.0f * (float)Math.Acos(W); float ooscale = 1f / scale; axis.X = X * ooscale; axis.Y = Y * ooscale; axis.Z = Z * ooscale; } } #endregion Public Methods #region Static Methods public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2) { quaternion1.X += quaternion2.X; quaternion1.Y += quaternion2.Y; quaternion1.Z += quaternion2.Z; quaternion1.W += quaternion2.W; return quaternion1; } /// <summary> /// Returns the conjugate (spatial inverse) of a quaternion /// </summary> public static Quaternion Conjugate(Quaternion quaternion) { quaternion.X = -quaternion.X; quaternion.Y = -quaternion.Y; quaternion.Z = -quaternion.Z; return quaternion; } /// <summary> /// Build a quaternion from an axis and an angle of rotation around /// that axis /// </summary> public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle) { Vector3 axis = new Vector3(axisX, axisY, axisZ); return CreateFromAxisAngle(axis, angle); } /// <summary> /// Build a quaternion from an axis and an angle of rotation around /// that axis /// </summary> /// <param name="axis">Axis of rotation</param> /// <param name="angle">Angle of rotation</param> public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { Quaternion q; axis = Vector3.Normalize(axis); angle *= 0.5f; float c = (float)Math.Cos(angle); float s = (float)Math.Sin(angle); q.X = axis.X * s; q.Y = axis.Y * s; q.Z = axis.Z * s; q.W = c; return Quaternion.Normalize(q); } /// <summary> /// Creates a quaternion from a vector containing roll, pitch, and yaw /// in radians /// </summary> /// <param name="eulers">Vector representation of the euler angles in /// radians</param> /// <returns>Quaternion representation of the euler angles</returns> public static Quaternion CreateFromEulers(Vector3 eulers) { return CreateFromEulers(eulers.X, eulers.Y, eulers.Z); } /// <summary> /// Creates a quaternion from roll, pitch, and yaw euler angles in /// radians /// </summary> /// <param name="roll">X angle in radians</param> /// <param name="pitch">Y angle in radians</param> /// <param name="yaw">Z angle in radians</param> /// <returns>Quaternion representation of the euler angles</returns> public static Quaternion CreateFromEulers(float roll, float pitch, float yaw) { if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI) throw new ArgumentException("Euler angles must be in radians"); double atCos = Math.Cos(roll / 2f); double atSin = Math.Sin(roll / 2f); double leftCos = Math.Cos(pitch / 2f); double leftSin = Math.Sin(pitch / 2f); double upCos = Math.Cos(yaw / 2f); double upSin = Math.Sin(yaw / 2f); double atLeftCos = atCos * leftCos; double atLeftSin = atSin * leftSin; return new Quaternion( (float)(atSin * leftCos * upCos + atCos * leftSin * upSin), (float)(atCos * leftSin * upCos - atSin * leftCos * upSin), (float)(atLeftCos * upSin + atLeftSin * upCos), (float)(atLeftCos * upCos - atLeftSin * upSin) ); } public static Quaternion CreateFromRotationMatrix(Matrix4 m) { Quaternion quat; float trace = m.Trace(); if (trace > Single.Epsilon) { float s = (float)Math.Sqrt(trace + 1f); quat.W = s * 0.5f; s = 0.5f / s; quat.X = (m.M23 - m.M32) * s; quat.Y = (m.M31 - m.M13) * s; quat.Z = (m.M12 - m.M21) * s; } else { if (m.M11 > m.M22 && m.M11 > m.M33) { float s = (float)Math.Sqrt(1f + m.M11 - m.M22 - m.M33); quat.X = 0.5f * s; s = 0.5f / s; quat.Y = (m.M12 + m.M21) * s; quat.Z = (m.M13 + m.M31) * s; quat.W = (m.M23 - m.M32) * s; } else if (m.M22 > m.M33) { float s = (float)Math.Sqrt(1f + m.M22 - m.M11 - m.M33); quat.Y = 0.5f * s; s = 0.5f / s; quat.X = (m.M21 + m.M12) * s; quat.Z = (m.M32 + m.M23) * s; quat.W = (m.M31 - m.M13) * s; } else { float s = (float)Math.Sqrt(1f + m.M33 - m.M11 - m.M22); quat.Z = 0.5f * s; s = 0.5f / s; quat.X = (m.M31 + m.M13) * s; quat.Y = (m.M32 + m.M23) * s; quat.W = (m.M12 - m.M21) * s; } } return quat; } public static Quaternion Divide(Quaternion quaternion1, Quaternion quaternion2) { float x = quaternion1.X; float y = quaternion1.Y; float z = quaternion1.Z; float w = quaternion1.W; float q2lensq = quaternion2.LengthSquared(); float ooq2lensq = 1f / q2lensq; float x2 = -quaternion2.X * ooq2lensq; float y2 = -quaternion2.Y * ooq2lensq; float z2 = -quaternion2.Z * ooq2lensq; float w2 = quaternion2.W * ooq2lensq; return new Quaternion( ((x * w2) + (x2 * w)) + (y * z2) - (z * y2), ((y * w2) + (y2 * w)) + (z * x2) - (x * z2), ((z * w2) + (z2 * w)) + (x * y2) - (y * x2), (w * w2) - ((x * x2) + (y * y2)) + (z * z2)); } public static float Dot(Quaternion q1, Quaternion q2) { return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W); } /// <summary> /// Conjugates and renormalizes a vector /// </summary> public static Quaternion Inverse(Quaternion quaternion) { float norm = quaternion.LengthSquared(); if (norm == 0f) { quaternion.X = quaternion.Y = quaternion.Z = quaternion.W = 0f; } else { float oonorm = 1f / norm; quaternion = Conjugate(quaternion); quaternion.X *= oonorm; quaternion.Y *= oonorm; quaternion.Z *= oonorm; quaternion.W *= oonorm; } return quaternion; } /// <summary> /// Spherical linear interpolation between two quaternions /// </summary> public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount) { float angle = Dot(q1, q2); if (angle < 0f) { q1 *= -1f; angle *= -1f; } float scale; float invscale; if ((angle + 1f) > 0.05f) { if ((1f - angle) >= 0.05f) { // slerp float theta = (float)Math.Acos(angle); float invsintheta = 1f / (float)Math.Sin(theta); scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta; invscale = (float)Math.Sin(theta * amount) * invsintheta; } else { // lerp scale = 1f - amount; invscale = amount; } } else { q2.X = -q1.Y; q2.Y = q1.X; q2.Z = -q1.W; q2.W = q1.Z; scale = (float)Math.Sin(Utils.PI * (0.5f - amount)); invscale = (float)Math.Sin(Utils.PI * amount); } return (q1 * scale) + (q2 * invscale); } public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2) { quaternion1.X -= quaternion2.X; quaternion1.Y -= quaternion2.Y; quaternion1.Z -= quaternion2.Z; quaternion1.W -= quaternion2.W; return quaternion1; } public static Quaternion Multiply(Quaternion a, Quaternion b) { return new Quaternion( a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y, a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z, a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X, a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z ); } public static Quaternion Multiply(Quaternion quaternion, float scaleFactor) { quaternion.X *= scaleFactor; quaternion.Y *= scaleFactor; quaternion.Z *= scaleFactor; quaternion.W *= scaleFactor; return quaternion; } public static Quaternion Negate(Quaternion quaternion) { quaternion.X = -quaternion.X; quaternion.Y = -quaternion.Y; quaternion.Z = -quaternion.Z; quaternion.W = -quaternion.W; return quaternion; } public static Quaternion Normalize(Quaternion q) { const float MAG_THRESHOLD = 0.0000001f; float mag = q.Length(); // Catch very small rounding errors when normalizing if (mag > MAG_THRESHOLD) { float oomag = 1f / mag; q.X *= oomag; q.Y *= oomag; q.Z *= oomag; q.W *= oomag; } else { q.X = 0f; q.Y = 0f; q.Z = 0f; q.W = 1f; } return q; } public static Quaternion Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); if (split.Length == 3) { return new Quaternion( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture)); } else { return new Quaternion( float.Parse(split[0].Trim(), Utils.EnUsCulture), float.Parse(split[1].Trim(), Utils.EnUsCulture), float.Parse(split[2].Trim(), Utils.EnUsCulture), float.Parse(split[3].Trim(), Utils.EnUsCulture)); } } public static bool TryParse(string val, out Quaternion result) { try { result = Parse(val); return true; } catch (Exception) { result = new Quaternion(); return false; } } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Quaternion) ? this == (Quaternion)obj : false; } public bool Equals(Quaternion other) { return W == other.W && X == other.X && Y == other.Y && Z == other.Z; } public override int GetHashCode() { return (X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode()); } public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W); } /// <summary> /// Get a string representation of the quaternion elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the quaternion</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W); } #endregion Overrides #region Operators public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.Equals(quaternion2); } public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2) { return !(quaternion1 == quaternion2); } public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2) { return Add(quaternion1, quaternion2); } public static Quaternion operator -(Quaternion quaternion) { return Negate(quaternion); } public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2) { return Subtract(quaternion1, quaternion2); } public static Quaternion operator *(Quaternion a, Quaternion b) { return Multiply(a, b); } public static Quaternion operator *(Quaternion quaternion, float scaleFactor) { return Multiply(quaternion, scaleFactor); } public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2) { return Divide(quaternion1, quaternion2); } #endregion Operators /// <summary>A quaternion with a value of 0,0,0,1</summary> public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f); } }