context
stringlengths
2.52k
185k
gt
stringclasses
1 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.Diagnostics; using System.Globalization; using System.Net.Sockets; using System.Text; #if SYSTEM_NET_PRIMITIVES_DLL namespace System.Net #else namespace System.Net.Internals #endif { // This class is used when subclassing EndPoint, and provides indication // on how to format the memory buffers that the platform uses for network addresses. #if SYSTEM_NET_PRIMITIVES_DLL public #else internal #endif class SocketAddress { internal static readonly int IPv6AddressSize = SocketAddressPal.IPv6AddressSize; internal static readonly int IPv4AddressSize = SocketAddressPal.IPv4AddressSize; internal int InternalSize; internal byte[] Buffer; private const int MinSize = 2; private const int MaxSize = 32; // IrDA requires 32 bytes private bool _changed = true; private int _hash; public AddressFamily Family { get { return SocketAddressPal.GetAddressFamily(Buffer); } } public int Size { get { return InternalSize; } } // Access to unmanaged serialized data. This doesn't // allow access to the first 2 bytes of unmanaged memory // that are supposed to contain the address family which // is readonly. public byte this[int offset] { get { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } return Buffer[offset]; } set { if (offset < 0 || offset >= Size) { throw new IndexOutOfRangeException(); } if (Buffer[offset] != value) { _changed = true; } Buffer[offset] = value; } } public SocketAddress(AddressFamily family) : this(family, MaxSize) { } public SocketAddress(AddressFamily family, int size) { if (size < MinSize) { throw new ArgumentOutOfRangeException(nameof(size)); } InternalSize = size; Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size]; SocketAddressPal.SetAddressFamily(Buffer, family); } internal SocketAddress(IPAddress ipAddress) : this(ipAddress.AddressFamily, ((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize)) { // No Port. SocketAddressPal.SetPort(Buffer, 0); if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6) { SocketAddressPal.SetIPv6Address(Buffer, ipAddress.GetAddressBytes(), (uint)ipAddress.ScopeId); } else { #pragma warning disable CS0618 // using Obsolete Address API because it's the more efficient option in this case uint address = unchecked((uint)ipAddress.Address); #pragma warning restore CS0618 Debug.Assert(ipAddress.AddressFamily == AddressFamily.InterNetwork); SocketAddressPal.SetIPv4Address(Buffer, address); } } internal SocketAddress(IPAddress ipaddress, int port) : this(ipaddress) { SocketAddressPal.SetPort(Buffer, unchecked((ushort)port)); } internal IPAddress GetIPAddress() { if (Family == AddressFamily.InterNetworkV6) { Debug.Assert(Size >= IPv6AddressSize); byte[] address = new byte[IPAddressParserStatics.IPv6AddressBytes]; uint scope; SocketAddressPal.GetIPv6Address(Buffer, address, out scope); return new IPAddress(address, (long)scope); } else if (Family == AddressFamily.InterNetwork) { Debug.Assert(Size >= IPv4AddressSize); long address = (long)SocketAddressPal.GetIPv4Address(Buffer) & 0x0FFFFFFFF; return new IPAddress(address); } else { #if SYSTEM_NET_PRIMITIVES_DLL throw new SocketException(SocketError.AddressFamilyNotSupported); #else throw new SocketException((int)SocketError.AddressFamilyNotSupported); #endif } } internal IPEndPoint GetIPEndPoint() { IPAddress address = GetIPAddress(); int port = (int)SocketAddressPal.GetPort(Buffer); return new IPEndPoint(address, port); } // For ReceiveFrom we need to pin address size, using reserved Buffer space. internal void CopyAddressSizeIntoBuffer() { Buffer[Buffer.Length - IntPtr.Size] = unchecked((byte)(InternalSize)); Buffer[Buffer.Length - IntPtr.Size + 1] = unchecked((byte)(InternalSize >> 8)); Buffer[Buffer.Length - IntPtr.Size + 2] = unchecked((byte)(InternalSize >> 16)); Buffer[Buffer.Length - IntPtr.Size + 3] = unchecked((byte)(InternalSize >> 24)); } // Can be called after the above method did work. internal int GetAddressSizeOffset() { return Buffer.Length - IntPtr.Size; } public override bool Equals(object comparand) { SocketAddress castedComparand = comparand as SocketAddress; if (castedComparand == null || this.Size != castedComparand.Size) { return false; } for (int i = 0; i < this.Size; i++) { if (this[i] != castedComparand[i]) { return false; } } return true; } public override int GetHashCode() { if (_changed) { _changed = false; _hash = 0; int i; int size = Size & ~3; for (i = 0; i < size; i += 4) { _hash ^= (int)Buffer[i] | ((int)Buffer[i + 1] << 8) | ((int)Buffer[i + 2] << 16) | ((int)Buffer[i + 3] << 24); } if ((Size & 3) != 0) { int remnant = 0; int shift = 0; for (; i < Size; ++i) { remnant |= ((int)Buffer[i]) << shift; shift += 8; } _hash ^= remnant; } } return _hash; } public override string ToString() { StringBuilder bytes = new StringBuilder(); for (int i = SocketAddressPal.DataOffset; i < this.Size; i++) { if (i > SocketAddressPal.DataOffset) { bytes.Append(","); } bytes.Append(this[i].ToString(NumberFormatInfo.InvariantInfo)); } return Family.ToString() + ":" + Size.ToString(NumberFormatInfo.InvariantInfo) + ":{" + bytes.ToString() + "}"; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Xml; using System.Reflection; using gov.va.medora.utils; namespace gov.va.medora.mdo.dao.vista { public class VistaSystemFileHandler : ISystemFileHandler { AbstractConnection myCxn; Hashtable fileDefs; Hashtable files; Hashtable lookupTables; public VistaSystemFileHandler(AbstractConnection cxn) { myCxn = cxn; getFileDefs(); files = new Hashtable(); lookupTables = new Hashtable(); } public Dictionary<string, object> getFile(string fileNum) { if (!files.ContainsKey(fileNum)) { VistaFile theFile = (VistaFile)fileDefs[fileNum]; DdrLister query = buildFileQuery(theFile); string[] response = query.execute(); files.Add(fileNum, toMdo(response, theFile)); } return (Dictionary<string, object>)files[fileNum]; } public StringDictionary getLookupTable(string fileNum) { if (!lookupTables.ContainsKey(fileNum)) { DdrLister query = buildIenNameQuery(fileNum); string[] response = query.execute(); lookupTables.Add(fileNum, VistaUtils.toStringDictionary(response)); } return (StringDictionary)lookupTables[fileNum]; } internal DdrLister buildFileQuery(VistaFile file) { DdrLister query = new DdrLister(myCxn); query.File = file.FileNumber; //query.Fields = file.getFieldString(); query.Flags = "IP"; query.Xref = "#"; return query; } internal void getFileDefs() { VistaFile currentFile = null; VistaField currentFld = null; fileDefs = new Hashtable(); XmlReader reader = new XmlTextReader(VistaConstants.VISTA_FILEDEFS_PATH); while (reader.Read()) { switch ((int)reader.NodeType) { case (int)XmlNodeType.Element: string name = reader.Name; if (name == "File") { currentFile = new VistaFile(); currentFile.FileName = reader.GetAttribute("name"); currentFile.FileNumber = reader.GetAttribute("number"); currentFile.Global = reader.GetAttribute("global"); currentFile.MdoName = reader.GetAttribute("mdo"); } else if (name == "fields") { // currentFile.Fields = new DictionaryHashList(); } else if (name == "field") { currentFld = new VistaField(); currentFld.Pos = Convert.ToInt16(reader.GetAttribute("pos")); } else if (name == "vista") { currentFld.VistaName = reader.GetAttribute("name"); currentFld.VistaNumber = reader.GetAttribute("number"); currentFld.VistaNode = reader.GetAttribute("node"); currentFld.VistaPiece = reader.GetAttribute("piece"); //currentFile.Fields.Add(currentFld.Pos.ToString(), currentFld); } else if (name == "mdo") { currentFld.MdoName = reader.GetAttribute("name"); currentFld.MdoType = reader.GetAttribute("type"); } else if (name == "mapping") { string mappingType = reader.GetAttribute("type"); currentFld.Mapping = new VistaFieldMapping(mappingType); if (currentFld.Mapping.Type == "pointer") { currentFld.Mapping.VistaFileNumber = reader.GetAttribute("file"); } else if (currentFld.Mapping.Type == "decode") { //currentFld.Mapping.DecodeMap = new StringDictionary(); } } else if (name == "map") { //currentFld.Mapping.DecodeMap.Add(reader.GetAttribute("code"), reader.GetAttribute("value")); } break; case (int)XmlNodeType.EndElement: name = reader.Name; if (name == "File") { fileDefs.Add(currentFile.FileNumber, currentFile); } else if (name == "fields") { } else if (name == "field") { } else if (name == "vista") { } else if (name == "mdo") { } else if (name == "mapping") { } else if (name == "map") { } break; } } } internal DdrLister buildIenNameQuery(string fileNum) { DdrLister query = new DdrLister(myCxn); query.File = fileNum; query.Fields = ".01"; query.Flags = "IP"; query.Xref = "#"; return query; } internal Dictionary<string, object> toMdo(string[] response, VistaFile theFile) { if (response == null || response.Length == 0) { return null; } Dictionary<string, object> result = new Dictionary<string, object>(response.Length); for (int lineIdx = 0; lineIdx < response.Length; lineIdx++) { //Need to instantiate the mdo here Object theMdo = Activator.CreateInstance(Type.GetType(theFile.MdoName), new object[] { }); Type theClass = theMdo.GetType(); string[] flds = StringUtils.split(response[lineIdx], StringUtils.CARET); for (int fldIdx = 0; fldIdx < flds.Length; fldIdx++) { VistaField vf = null; // (VistaField)((DictionaryEntry)theFile.Fields[fldIdx]).Value; FieldInfo theField = theClass.GetField(vf.MdoName, BindingFlags.NonPublic | BindingFlags.Instance); if (vf.MdoType == "string") { if (vf.Mapping != null && vf.Mapping.Type == "decode") { // if (vf.Mapping.DecodeMap.ContainsKey(flds[fldIdx])) // { //theField.SetValue(theMdo, vf.Mapping.DecodeMap[flds[fldIdx]]); // } // else // { theField.SetValue(theMdo, flds[fldIdx]); // } } else { theField.SetValue(theMdo, flds[fldIdx]); } } else if (vf.MdoType == "kvp") { string key = flds[fldIdx]; string value = ""; if (vf.Mapping != null && vf.Mapping.Type == "decode") { // value = vf.Mapping.DecodeMap[key]; } else { StringDictionary lookupTbl = getLookupTable(vf.Mapping.VistaFileNumber); if (lookupTbl.ContainsKey(key)) { value = lookupTbl[key]; } } theField.SetValue(theMdo, new KeyValuePair<string, string>(key, value)); //KeyValuePair<string, string> kvp = new KeyValuePair<string, string>(key, value); } } result.Add(flds[0], theMdo); } return result; } public Hashtable LookupTables() { return lookupTables; } public Hashtable Files() { return files; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Timers; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")] public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule { public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private int m_checkTime = 500; private bool m_reusetextures = false; private Dictionary<UUID, long> m_savequeue = new Dictionary<UUID, long>(); private int m_savetime = 5; private Scene m_scene = null; private Dictionary<UUID, long> m_sendqueue = new Dictionary<UUID, long>(); // seconds to wait before saving changed appearance private int m_sendtime = 2; // seconds to wait before sending changed appearance private object m_setAppearanceLock = new object(); // milliseconds to wait between checks for appearance updates private System.Timers.Timer m_updateTimer = new System.Timers.Timer(); #region Region Module interface public bool IsSharedModule { get { return false; } } public string Name { get { return "Default Avatar Factory"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (m_scene == null) m_scene = scene; scene.RegisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient += SubscribeToClientEvents; } public void Close() { } public void Initialise(IConfigSource config) { IConfig appearanceConfig = config.Configs["Appearance"]; if (appearanceConfig != null) { m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave", Convert.ToString(m_savetime))); m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend", Convert.ToString(m_sendtime))); m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures", m_reusetextures); // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime); } } public void RegionLoaded(Scene scene) { m_updateTimer.Enabled = false; m_updateTimer.AutoReset = true; m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer); } public void RemoveRegion(Scene scene) { if (scene == m_scene) { scene.UnregisterModuleInterface<IAvatarFactoryModule>(this); scene.EventManager.OnNewClient -= SubscribeToClientEvents; } m_scene = null; } private void SubscribeToClientEvents(IClientAPI client) { client.OnRequestWearables += Client_OnRequestWearables; client.OnSetAppearance += Client_OnSetAppearance; client.OnAvatarNowWearing += Client_OnAvatarNowWearing; client.OnCachedTextureRequest += Client_OnCachedTextureRequest; } #endregion Region Module interface #region IAvatarFactoryModule public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); return GetBakedTextureFaces(sp); } public WearableCacheItem[] GetCachedItems(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); WearableCacheItem[] items = sp.Appearance.WearableCacheItems; //foreach (WearableCacheItem item in items) //{ //} return items; } public void QueueAppearanceSave(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000); lock (m_savequeue) { m_savequeue[agentid] = timestamp; m_updateTimer.Start(); } } /// <summary> /// Queue up a request to send appearance. /// </summary> /// <remarks> /// Makes it possible to accumulate changes without sending out each one separately. /// </remarks> /// <param name="agentId"></param> public void QueueAppearanceSend(UUID agentid) { // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid); // 10000 ticks per millisecond, 1000 milliseconds per second long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000); lock (m_sendqueue) { m_sendqueue[agentid] = timestamp; m_updateTimer.Start(); } } public int RequestRebake(IScenePresence sp, bool missingTexturesOnly) { int texturesRebaked = 0; // IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // if there is no texture entry, skip it if (face == null) continue; // m_log.DebugFormat( // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}", // face.TextureID, idx, client.Name, client.AgentId); // if the texture is one of the "defaults" then skip it // this should probably be more intelligent (skirt texture doesnt matter // if the avatar isnt wearing a skirt) but if any of the main baked // textures is default then the rest should be as well if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; if (missingTexturesOnly) { if (m_scene.AssetService.Get(face.TextureID.ToString()) != null) { continue; } else { // On inter-simulator teleports, this occurs if baked textures are not being stored by the // grid asset service (which means that they are not available to the new region and so have // to be re-requested from the client). // // The only available core OpenSimulator behaviour right now // is not to store these textures, temporarily or otherwise. m_log.DebugFormat( "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.", face.TextureID, idx, sp.Name); } } else { m_log.DebugFormat( "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.", face.TextureID, idx, sp.Name); } texturesRebaked++; sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID); } return texturesRebaked; } public bool SaveBakedTextures(UUID agentId) { ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) return false; m_log.DebugFormat( "[AV FACTORY]: Permanently saving baked textures for {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp); if (bakedTextures.Count == 0) return false; foreach (BakeType bakeType in bakedTextures.Keys) { Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType]; if (bakedTextureFace == null) { // This can happen legitimately, since some baked textures might not exist //m_log.WarnFormat( // "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently", // bakeType, sp.Name, m_scene.RegionInfo.RegionName); continue; } AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString()); if (asset != null) { // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars asset.ID = asset.FullID.ToString(); asset.Temporary = false; asset.Local = false; m_scene.AssetService.Store(asset); } else { m_log.WarnFormat( "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently", bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName); } } return true; } public bool SendAppearance(UUID agentId) { // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId); ScenePresence sp = m_scene.GetScenePresence(agentId); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId); return false; } SendAppearance(sp); return true; } /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems) { SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems); } public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { float oldoff = sp.Appearance.AvatarFeetOffset; Vector3 oldbox = sp.Appearance.AvatarBoxSize; SetAppearance(sp, textureEntry, visualParams, cacheItems); sp.Appearance.SetSize(avSize); float off = sp.Appearance.AvatarFeetOffset; Vector3 box = sp.Appearance.AvatarBoxSize; if (oldoff != off || oldbox != box) ((ScenePresence)sp).SetSize(box, off); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) /// </summary> /// <param name="sp"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems) { // m_log.DebugFormat( // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}", // sp.Name, textureEntry, visualParams); // TODO: This is probably not necessary any longer, just assume the // textureEntry set implies that the appearance transaction is complete bool changed = false; // Process the texture entry transactionally, this doesn't guarantee that Appearance is // going to be handled correctly but it does serialize the updates to the appearance lock (m_setAppearanceLock) { // Process the visual params, this may change height as well if (visualParams != null) { // string[] visualParamsStrings = new string[visualParams.Length]; // for (int i = 0; i < visualParams.Length; i++) // visualParamsStrings[i] = visualParams[i].ToString(); // m_log.DebugFormat( // "[AVFACTORY]: Setting visual params for {0} to {1}", // client.Name, string.Join(", ", visualParamsStrings)); /* float oldHeight = sp.Appearance.AvatarHeight; changed = sp.Appearance.SetVisualParams(visualParams); if (sp.Appearance.AvatarHeight != oldHeight && sp.Appearance.AvatarHeight > 0) ((ScenePresence)sp).SetHeight(sp.Appearance.AvatarHeight); */ // float oldoff = sp.Appearance.AvatarFeetOffset; // Vector3 oldbox = sp.Appearance.AvatarBoxSize; changed = sp.Appearance.SetVisualParams(visualParams); // float off = sp.Appearance.AvatarFeetOffset; // Vector3 box = sp.Appearance.AvatarBoxSize; // if(oldoff != off || oldbox != box) // ((ScenePresence)sp).SetSize(box,off); } // Process the baked texture array if (textureEntry != null) { m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID); // WriteBakedTexturesReport(sp, m_log.DebugFormat); changed = sp.Appearance.SetTextureEntries(textureEntry) || changed; // WriteBakedTexturesReport(sp, m_log.DebugFormat); // If bake textures are missing and this is not an NPC, request a rebake from client if (!ValidateBakedTextureCache(sp) && (((ScenePresence)sp).PresenceType != PresenceType.Npc)) RequestRebake(sp, true); // This appears to be set only in the final stage of the appearance // update transaction. In theory, we should be able to do an immediate // appearance send and save here. } // NPC should send to clients immediately and skip saving appearance if (((ScenePresence)sp).PresenceType == PresenceType.Npc) { SendAppearance((ScenePresence)sp); return; } // save only if there were changes, send no matter what (doesn't hurt to send twice) if (changed) QueueAppearanceSave(sp.ControllingClient.AgentId); QueueAppearanceSend(sp.ControllingClient.AgentId); } // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString()); } public bool ValidateBakedTextureCache(IScenePresence sp) { bool defonly = true; // are we only using default textures IImprovedAssetCache cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); WearableCacheItem[] wearableCache = null; // Cache wearable data for teleport. // Only makes sense if there's a bake module and a cache module if (bakedModule != null && cache != null) { try { wearableCache = bakedModule.Get(sp.UUID); } catch (Exception) { } if (wearableCache != null) { for (int i = 0; i < wearableCache.Length; i++) { cache.Cache(wearableCache[i].TextureAsset); } } } /* IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>(); if (invService.GetRootFolder(userID) != null) { WearableCacheItem[] wearableCache = null; if (bakedModule != null) { try { wearableCache = bakedModule.Get(userID); appearance.WearableCacheItems = wearableCache; appearance.WearableCacheItemsDirty = false; foreach (WearableCacheItem item in wearableCache) { appearance.Texture.FaceTextures[item.TextureIndex].TextureID = item.TextureID; } } catch (Exception) { } } */ // Process the texture entry for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++) { int idx = AvatarAppearance.BAKE_INDICES[i]; Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx]; // No face, so lets check our baked service cache, teleport or login. if (face == null) { if (wearableCache != null) { // If we find the an appearance item, set it as the textureentry and the face WearableCacheItem searchitem = WearableCacheItem.SearchTextureIndex((uint)idx, wearableCache); if (searchitem != null) { sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint)idx); sp.Appearance.Texture.FaceTextures[idx].TextureID = searchitem.TextureID; face = sp.Appearance.Texture.FaceTextures[idx]; } else { // if there is no texture entry and no baked cache, skip it continue; } } else { //No texture entry face and no cache. Skip this face. continue; } } // m_log.DebugFormat( // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}", // face.TextureID, idx, client.Name, client.AgentId); // if the texture is one of the "defaults" then skip it // this should probably be more intelligent (skirt texture doesnt matter // if the avatar isnt wearing a skirt) but if any of the main baked // textures is default then the rest should be as well if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE) continue; defonly = false; // found a non-default texture reference if (m_scene.AssetService.Get(face.TextureID.ToString()) == null) return false; } // m_log.DebugFormat("[AVFACTORY]: Completed texture check for {0} {1}", sp.Name, sp.UUID); // If we only found default textures, then the appearance is not cached return (defonly ? false : true); } private void SendAppearance(ScenePresence sp) { // Send the appearance to everyone in the scene sp.SendAppearanceToAllOtherAgents(); // Send animations back to the avatar as well sp.Animator.SendAnimPack(); } #endregion IAvatarFactoryModule #region AvatarFactoryModule private methods private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp) { if (sp.IsChildAgent) return new Dictionary<BakeType, Primitive.TextureEntryFace>(); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = new Dictionary<BakeType, Primitive.TextureEntryFace>(); AvatarAppearance appearance = sp.Appearance; Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures; foreach (int i in Enum.GetValues(typeof(BakeType))) { BakeType bakeType = (BakeType)i; if (bakeType == BakeType.Unknown) continue; // m_log.DebugFormat( // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}", // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]); int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType); Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture bakedTextures[bakeType] = texture; } return bakedTextures; } private UUID GetDefaultItem(WearableType wearable) { // These are ruth UUID ret = UUID.Zero; switch (wearable) { case WearableType.Eyes: ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); break; case WearableType.Hair: ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); break; case WearableType.Pants: ret = new UUID("00000000-38f9-1111-024e-222222111120"); break; case WearableType.Shape: ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73"); break; case WearableType.Shirt: ret = new UUID("00000000-38f9-1111-024e-222222111110"); break; case WearableType.Skin: ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb"); break; case WearableType.Undershirt: ret = new UUID("16499ebb-3208-ec27-2def-481881728f47"); break; case WearableType.Underpants: ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d"); break; } return ret; } private void HandleAppearanceUpdateTimer(object sender, EventArgs ea) { long now = DateTime.Now.Ticks; lock (m_sendqueue) { Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue); foreach (KeyValuePair<UUID, long> kvp in sends) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now); if (sendTime < now) { Util.FireAndForget(o => SendAppearance(avatarID)); m_sendqueue.Remove(avatarID); } } } lock (m_savequeue) { Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue); foreach (KeyValuePair<UUID, long> kvp in saves) { // We have to load the key and value into local parameters to avoid a race condition if we loop // around and load kvp with a different value before FireAndForget has launched its thread. UUID avatarID = kvp.Key; long sendTime = kvp.Value; if (sendTime < now) { Util.FireAndForget(o => SaveAppearance(avatarID)); m_savequeue.Remove(avatarID); } } // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread. lock (m_sendqueue) if (m_savequeue.Count == 0 && m_sendqueue.Count == 0) m_updateTimer.Stop(); } } private void SaveAppearance(UUID agentid) { // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved // in a culture where decimal points are commas and then reloaded in a culture which just treats them as // number seperators. Culture.SetCurrentCulture(); ScenePresence sp = m_scene.GetScenePresence(agentid); if (sp == null) { // This is expected if the user has gone away. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid); return; } // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid); // This could take awhile since it needs to pull inventory // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape // assets and item asset id changes to complete. // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids // multiple save requests. SetAppearanceAssets(sp.UUID, sp.Appearance); // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments(); // foreach (AvatarAttachment att in attachments) // { // m_log.DebugFormat( // "[AVFACTORY]: For {0} saving attachment {1} at point {2}", // sp.Name, att.ItemID, att.AttachPoint); // } m_scene.AvatarService.SetAppearance(agentid, sp.Appearance); // Trigger this here because it's the final step in the set/queue/save process for appearance setting. // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes). m_scene.EventManager.TriggerAvatarAppearanceChanged(sp); } /// <summary> /// For a given set of appearance items, check whether the items are valid and add their asset IDs to /// appearance data. /// </summary> /// <param name='userID'></param> /// <param name='appearance'></param> private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance) { IInventoryService invService = m_scene.InventoryService; if (invService.GetRootFolder(userID) != null) { for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) { for (int j = 0; j < appearance.Wearables[i].Count; j++) { if (appearance.Wearables[i][j].ItemID == UUID.Zero) { m_log.WarnFormat( "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.", i, j, userID); continue; } // Ignore ruth's assets if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) continue; InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); baseItem = invService.GetItem(baseItem); if (baseItem != null) { appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); } else { m_log.WarnFormat( "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", appearance.Wearables[i][j].ItemID, (WearableType)i); appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID); } } } } else { m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); } // IInventoryService invService = m_scene.InventoryService; // bool resetwearable = false; // if (invService.GetRootFolder(userID) != null) // { // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++) // { // for (int j = 0; j < appearance.Wearables[i].Count; j++) // { // // Check if the default wearables are not set // if (appearance.Wearables[i][j].ItemID == UUID.Zero) // { // switch ((WearableType) i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values."); // resetwearable = true; // break; // // } // continue; // } // // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1 // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID) // { // switch ((WearableType)i) // { // case WearableType.Eyes: // case WearableType.Hair: // case WearableType.Shape: // case WearableType.Skin: // //case WearableType.Underpants: // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i); // resetwearable = true; // break; // // } // continue; // } // // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID); // baseItem = invService.GetItem(baseItem); // // if (baseItem != null) // { // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID); // int unmodifiedWearableIndexForClosure = i; // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this, // delegate(string x, object y, AssetBase z) // { // if (z == null) // { // TryAndRepairBrokenWearable( // (WearableType)unmodifiedWearableIndexForClosure, invService, // userID, appearance); // } // }); // } // else // { // m_log.ErrorFormat( // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default", // appearance.Wearables[i][j].ItemID, (WearableType)i); // // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance); // resetwearable = true; // // } // } // } // // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int) WearableType.Eyes] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes)); // // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}", // appearance.Wearables[(int) WearableType.Eyes][0].ItemID, // appearance.Wearables[(int) WearableType.Eyes][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Shape] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape)); // // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Shape][0].ItemID, // appearance.Wearables[(int)WearableType.Shape][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Hair] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair)); // // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Hair][0].ItemID, // appearance.Wearables[(int)WearableType.Hair][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance); // resetwearable = true; // // } // // } // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason.... // if (appearance.Wearables[(int)WearableType.Skin] == null) // { // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin)); // // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // } // else // { // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero) // { // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}", // appearance.Wearables[(int)WearableType.Skin][0].ItemID, // appearance.Wearables[(int)WearableType.Skin][0].AssetID); // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance); // resetwearable = true; // // } // // } // if (resetwearable) // { // ScenePresence presence = null; // if (m_scene.TryGetScenePresence(userID, out presence)) // { // presence.ControllingClient.SendWearables(presence.Appearance.Wearables, // presence.Appearance.Serial++); // } // } // // } // else // { // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID); // } } private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID, AvatarAppearance appearance) { UUID defaultwearable = GetDefaultItem(type); if (defaultwearable != UUID.Zero) { UUID newInvItem = UUID.Random(); InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID) { AssetID = defaultwearable, AssetType = (int) AssetType .Bodypart, CreatorId = userID .ToString (), //InvType = (int)InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService .GetFolderForType (userID, AssetType .Bodypart) .ID, Flags = (uint)type, Name = Enum.GetName(typeof(WearableType), type), BasePermissions = (uint)PermissionMask.Copy, CurrentPermissions = (uint)PermissionMask.Copy, EveryOnePermissions = (uint)PermissionMask.Copy, GroupPermissions = (uint)PermissionMask.Copy, NextPermissions = (uint)PermissionMask.Copy }; invService.AddItem(itembase); UUID LinkInvItem = UUID.Random(); itembase = new InventoryItemBase(LinkInvItem, userID) { AssetID = newInvItem, AssetType = (int) AssetType .Link, CreatorId = userID .ToString (), InvType = (int)InventoryType.Wearable, Description = "Failed Wearable Replacement", Folder = invService .GetFolderForType (userID, AssetType .CurrentOutfitFolder) .ID, Flags = (uint)type, Name = Enum.GetName(typeof(WearableType), type), BasePermissions = (uint)PermissionMask.Copy, CurrentPermissions = (uint)PermissionMask.Copy, EveryOnePermissions = (uint)PermissionMask.Copy, GroupPermissions = (uint)PermissionMask.Copy, NextPermissions = (uint)PermissionMask.Copy }; invService.AddItem(itembase); appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type)); ScenePresence presence = null; if (m_scene.TryGetScenePresence(userID, out presence)) { m_scene.SendInventoryUpdate(presence.ControllingClient, invService.GetFolderForType(userID, AssetType .CurrentOutfitFolder), false, true); } } } #endregion AvatarFactoryModule private methods #region Client Event Handlers /// <summary> /// Update what the avatar is wearing using an item from their inventory. /// </summary> /// <param name="client"></param> /// <param name="e"></param> private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e) { // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null) { m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId); return; } // we need to clean out the existing textures sp.Appearance.ResetAppearance(); // operate on a copy of the appearance so we don't have to lock anything yet AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false); foreach (AvatarWearingArgs.Wearable wear in e.NowWearing) { if (wear.Type < AvatarWearable.MAX_WEARABLES) avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero); } avatAppearance.GetAssetsFrom(sp.Appearance); lock (m_setAppearanceLock) { // Update only those fields that we have changed. This is important because the viewer // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing // shouldn't overwrite the changes made in SetAppearance. sp.Appearance.Wearables = avatAppearance.Wearables; sp.Appearance.Texture = avatAppearance.Texture; // We don't need to send the appearance here since the "iswearing" will trigger a new set // of visual param and baked texture changes. When those complete, the new appearance will be sent QueueAppearanceSave(client.AgentId); } } /// <summary> /// Respond to the cached textures request from the client /// </summary> /// <param name="client"></param> /// <param name="serial"></param> /// <param name="cachedTextureRequest"></param> private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest) { // m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>(); foreach (CachedTextureRequestArg request in cachedTextureRequest) { UUID texture = UUID.Zero; int index = request.BakedTextureIndex; if (m_reusetextures) { // this is the most insanely dumb way to do this... however it seems to // actually work. if the appearance has been reset because wearables have // changed then the texture entries are zero'd out until the bakes are // uploaded. on login, if the textures exist in the cache (eg if you logged // into the simulator recently, then the appearance will pull those and send // them back in the packet and you won't have to rebake. if the textures aren't // in the cache then the intial makeroot() call in scenepresence will zero // them out. // // a better solution (though how much better is an open question) is to // store the hashes in the appearance and compare them. Thats's coming. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index]; if (face != null) texture = face.TextureID; // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index); } CachedTextureResponseArg response = new CachedTextureResponseArg(); response.BakedTextureIndex = index; response.BakedTextureID = texture; response.HostName = null; cachedTextureResponse.Add(response); } // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial); // The serial number appears to be used to match requests and responses // in the texture transaction. We just send back the serial number // that was provided in the request. The viewer bumps this for us. client.SendCachedTextureResponse(sp, serial, cachedTextureResponse); } /// <summary> /// Tell the client for this scene presence what items it should be wearing now /// </summary> /// <param name="client"></param> private void Client_OnRequestWearables(IClientAPI client) { Util.FireAndForget(delegate(object x) { Thread.Sleep(4000); // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++); else m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId); }); } /// <summary> /// Set appearance data (texture asset IDs and slider settings) received from a client /// </summary> /// <param name="client"></param> /// <param name="texture"></param> /// <param name="visualParam"></param> private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems) { // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId); ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp != null) SetAppearance(sp, textureEntry, visualParams, avSize, cacheItems); else m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId); } #endregion Client Event Handlers public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction) { outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName); outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID"); Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID); foreach (BakeType bt in bakedTextures.Keys) { string rawTextureID; if (bakedTextures[bt] == null) { rawTextureID = "not set"; } else { rawTextureID = bakedTextures[bt].TextureID.ToString(); if (m_scene.AssetService.Get(rawTextureID) == null) rawTextureID += " (not found)"; else rawTextureID += " (uploaded)"; } outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID); } bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp); outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void AsUInt32() { var test = new VectorAs__AsUInt32(); // Validates basic functionality works test.RunBasicScenario(); // Validates basic functionality works using the generic form, rather than the type-specific form of the method test.RunGenericScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorAs__AsUInt32 { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Vector128<UInt32> value; value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<byte> byteResult = value.AsByte(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<double> doubleResult = value.AsDouble(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<short> shortResult = value.AsInt16(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<int> intResult = value.AsInt32(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<long> longResult = value.AsInt64(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<sbyte> sbyteResult = value.AsSByte(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<float> floatResult = value.AsSingle(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<ushort> ushortResult = value.AsUInt16(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<uint> uintResult = value.AsUInt32(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<ulong> ulongResult = value.AsUInt64(); ValidateResult(ulongResult, value); } public void RunGenericScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario)); Vector128<UInt32> value; value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<byte> byteResult = value.As<UInt32, byte>(); ValidateResult(byteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<double> doubleResult = value.As<UInt32, double>(); ValidateResult(doubleResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<short> shortResult = value.As<UInt32, short>(); ValidateResult(shortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<int> intResult = value.As<UInt32, int>(); ValidateResult(intResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<long> longResult = value.As<UInt32, long>(); ValidateResult(longResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<sbyte> sbyteResult = value.As<UInt32, sbyte>(); ValidateResult(sbyteResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<float> floatResult = value.As<UInt32, float>(); ValidateResult(floatResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<ushort> ushortResult = value.As<UInt32, ushort>(); ValidateResult(ushortResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<uint> uintResult = value.As<UInt32, uint>(); ValidateResult(uintResult, value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); Vector128<ulong> ulongResult = value.As<UInt32, ulong>(); ValidateResult(ulongResult, value); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Vector128<UInt32> value; value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object byteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsByte)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<byte>)(byteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object doubleResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsDouble)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<double>)(doubleResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object shortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt16)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<short>)(shortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object intResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt32)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<int>)(intResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object longResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsInt64)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<long>)(longResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object sbyteResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSByte)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<sbyte>)(sbyteResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object floatResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsSingle)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<float>)(floatResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object ushortResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt16)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ushort>)(ushortResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object uintResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt32)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<uint>)(uintResult), value); value = Vector128.Create(TestLibrary.Generator.GetUInt32()); object ulongResult = typeof(Vector128) .GetMethod(nameof(Vector128.AsUInt64)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value }); ValidateResult((Vector128<ulong>)(ulongResult), value); } private void ValidateResult<T>(Vector128<T> result, Vector128<UInt32> value, [CallerMemberName] string method = "") where T : struct { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); UInt32[] valueElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref valueElements[0]), value); ValidateResult(resultElements, valueElements, typeof(T), method); } private void ValidateResult(UInt32[] resultElements, UInt32[] valueElements, Type targetType, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < ElementCount; i++) { if (resultElements[i] != valueElements[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<UInt32>.As{targetType.Name}: {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Runtime.Augments; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System { public static partial class Environment { internal static readonly bool IsMac = Interop.Sys.GetUnixName() == "OSX"; private static Func<string, IEnumerable<string>> s_fileReadLines; private static Action<string> s_directoryCreateDirectory; private static string CurrentDirectoryCore { get { return Interop.Sys.GetCwd(); } set { Interop.CheckIo(Interop.Sys.ChDir(value), value, isDirectory: true); } } public static int ExitCode { get { return EnvironmentAugments.ExitCode; } set { EnvironmentAugments.ExitCode = value; } } private static string ExpandEnvironmentVariablesCore(string name) { StringBuilder result = StringBuilderCache.Acquire(); int lastPos = 0, pos; while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0) { if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string value = GetEnvironmentVariable(key); if (value != null) { result.Append(value); lastPos = pos + 1; continue; } } result.Append(name.Substring(lastPos, pos - lastPos)); lastPos = pos; } result.Append(name.Substring(lastPos)); return StringBuilderCache.GetStringAndRelease(result); } private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { // Get the path for the SpecialFolder string path = GetFolderPathCoreWithoutValidation(folder); Debug.Assert(path != null); // If we didn't get one, or if we got one but we're not supposed to verify it, // or if we're supposed to verify it and it passes verification, return the path. if (path.Length == 0 || option == SpecialFolderOption.DoNotVerify || Interop.Sys.Access(path, Interop.Sys.AccessMode.R_OK) == 0) { return path; } // Failed verification. If None, then we're supposed to return an empty string. // If Create, we're supposed to create it and then return the path. if (option == SpecialFolderOption.None) { return string.Empty; } else { Debug.Assert(option == SpecialFolderOption.Create); // TODO #11151: Replace with Directory.CreateDirectory once we have access to System.IO.FileSystem here. Action<string> createDirectory = LazyInitializer.EnsureInitialized(ref s_directoryCreateDirectory, () => { Type dirType = Type.GetType("System.IO.Directory, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: true); MethodInfo mi = dirType.GetTypeInfo().GetDeclaredMethod("CreateDirectory"); return (Action<string>)mi.CreateDelegate(typeof(Action<string>)); }); createDirectory(path); return path; } } private static string GetFolderPathCoreWithoutValidation(SpecialFolder folder) { // First handle any paths that involve only static paths, avoiding the overheads of getting user-local paths. // https://www.freedesktop.org/software/systemd/man/file-hierarchy.html switch (folder) { case SpecialFolder.CommonApplicationData: return "/usr/share"; case SpecialFolder.CommonTemplates: return "/usr/share/templates"; } if (IsMac) { switch (folder) { case SpecialFolder.ProgramFiles: return "/Applications"; case SpecialFolder.System: return "/System"; } } // All other paths are based on the XDG Base Directory Specification: // https://specifications.freedesktop.org/basedir-spec/latest/ string home; try { home = PersistedFiles.GetHomeDirectory(); } catch (Exception exc) { Debug.Fail($"Unable to get home directory: {exc}"); home = Path.GetTempPath(); } Debug.Assert(!string.IsNullOrEmpty(home), "Expected non-null or empty HOME"); // TODO: Consider caching (or precomputing and caching) all subsequent results. // This would significantly improve performance for repeated access, at the expense // of not being responsive to changes in the underlying environment variables, // configuration files, etc. switch (folder) { case SpecialFolder.UserProfile: case SpecialFolder.MyDocuments: // same value as Personal return home; case SpecialFolder.ApplicationData: return GetXdgConfig(home); case SpecialFolder.LocalApplicationData: // "$XDG_DATA_HOME defines the base directory relative to which user specific data files should be stored." // "If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used." string data = GetEnvironmentVariable("XDG_DATA_HOME"); if (string.IsNullOrEmpty(data) || data[0] != '/') { data = Path.Combine(home, ".local", "share"); } return data; case SpecialFolder.Desktop: case SpecialFolder.DesktopDirectory: return ReadXdgDirectory(home, "XDG_DESKTOP_DIR", "Desktop"); case SpecialFolder.Templates: return ReadXdgDirectory(home, "XDG_TEMPLATES_DIR", "Templates"); case SpecialFolder.MyVideos: return ReadXdgDirectory(home, "XDG_VIDEOS_DIR", "Videos"); case SpecialFolder.MyMusic: return IsMac ? Path.Combine(home, "Music") : ReadXdgDirectory(home, "XDG_MUSIC_DIR", "Music"); case SpecialFolder.MyPictures: return IsMac ? Path.Combine(home, "Pictures") : ReadXdgDirectory(home, "XDG_PICTURES_DIR", "Pictures"); case SpecialFolder.Fonts: return IsMac ? Path.Combine(home, "Library", "Fonts") : Path.Combine(home, ".fonts"); case SpecialFolder.Favorites: if (IsMac) return Path.Combine(home, "Library", "Favorites"); break; case SpecialFolder.InternetCache: if (IsMac) return Path.Combine(home, "Library", "Caches"); break; } // No known path for the SpecialFolder return string.Empty; } private static string GetXdgConfig(string home) { // "$XDG_CONFIG_HOME defines the base directory relative to which user specific configuration files should be stored." // "If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used." string config = GetEnvironmentVariable("XDG_CONFIG_HOME"); if (string.IsNullOrEmpty(config) || config[0] != '/') { config = Path.Combine(home, ".config"); } return config; } private static string ReadXdgDirectory(string homeDir, string key, string fallback) { Debug.Assert(!string.IsNullOrEmpty(homeDir), $"Expected non-empty homeDir"); Debug.Assert(!string.IsNullOrEmpty(key), $"Expected non-empty key"); Debug.Assert(!string.IsNullOrEmpty(fallback), $"Expected non-empty fallback"); string envPath = GetEnvironmentVariable(key); if (!string.IsNullOrEmpty(envPath) && envPath[0] == '/') { return envPath; } // Use the user-dirs.dirs file to look up the right config. // Note that the docs also highlight a list of directories in which to look for this file: // "$XDG_CONFIG_DIRS defines the preference-ordered set of base directories to search for configuration files in addition // to the $XDG_CONFIG_HOME base directory. The directories in $XDG_CONFIG_DIRS should be separated with a colon ':'. If // $XDG_CONFIG_DIRS is either not set or empty, a value equal to / etc / xdg should be used." // For simplicity, we don't currently do that. We can add it if/when necessary. string userDirsPath = Path.Combine(GetXdgConfig(homeDir), "user-dirs.dirs"); if (Interop.Sys.Access(userDirsPath, Interop.Sys.AccessMode.R_OK) == 0) { try { // TODO #11151: Replace with direct usage of File.ReadLines or equivalent once we have access to System.IO.FileSystem here. Func<string, IEnumerable<string>> readLines = LazyInitializer.EnsureInitialized(ref s_fileReadLines, () => { Type fileType = Type.GetType("System.IO.File, System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (fileType != null) { foreach (MethodInfo mi in fileType.GetTypeInfo().GetDeclaredMethods("ReadLines")) { if (mi.GetParameters().Length == 1) { return (Func<string, IEnumerable<string>>)mi.CreateDelegate(typeof(Func<string, IEnumerable<string>>)); } } } return null; }); IEnumerable<string> lines = readLines?.Invoke(userDirsPath); if (lines != null) { foreach (string line in lines) { // Example lines: // XDG_DESKTOP_DIR="$HOME/Desktop" // XDG_PICTURES_DIR = "/absolute/path" // Skip past whitespace at beginning of line int pos = 0; SkipWhitespace(line, ref pos); if (pos >= line.Length) continue; // Skip past requested key name if (string.CompareOrdinal(line, pos, key, 0, key.Length) != 0) continue; pos += key.Length; // Skip past whitespace and past '=' SkipWhitespace(line, ref pos); if (pos >= line.Length - 4 || line[pos] != '=') continue; // 4 for ="" and at least one char between quotes pos++; // skip past '=' // Skip past whitespace and past first quote SkipWhitespace(line, ref pos); if (pos >= line.Length - 3 || line[pos] != '"') continue; // 3 for "" and at least one char between quotes pos++; // skip past opening '"' // Skip past relative prefix if one exists bool relativeToHome = false; const string RelativeToHomePrefix = "$HOME/"; if (string.CompareOrdinal(line, pos, RelativeToHomePrefix, 0, RelativeToHomePrefix.Length) == 0) { relativeToHome = true; pos += RelativeToHomePrefix.Length; } else if (line[pos] != '/') // if not relative to home, must be absolute path { continue; } // Find end of path int endPos = line.IndexOf('"', pos); if (endPos <= pos) continue; // Got we need. Now extract it. string path = line.Substring(pos, endPos - pos); return relativeToHome ? Path.Combine(homeDir, path) : path; } } } catch (Exception exc) { // assembly not found, file not found, errors reading file, etc. Just eat everything. Debug.Fail($"Failed reading {userDirsPath}: {exc}"); } } return Path.Combine(homeDir, fallback); } private static void SkipWhitespace(string line, ref int pos) { while (pos < line.Length && char.IsWhiteSpace(line[pos])) pos++; } public static string[] GetLogicalDrives() => Interop.Sys.GetAllMountPoints(); private static bool Is64BitOperatingSystemWhen32BitProcess => false; public static string MachineName { get { string hostName = Interop.Sys.GetHostName(); int dotPos = hostName.IndexOf('.'); return dotPos == -1 ? hostName : hostName.Substring(0, dotPos); } } public static string NewLine => "\n"; private static Lazy<OperatingSystem> s_osVersion = new Lazy<OperatingSystem>(() => { int major = 0, minor = 0, build = 0, revision = 0; // Get the uname's utsname.release. Then parse it for the first four numbers found. // This isn't perfect, but Version already doesn't map exactly to all possible release // formats, e.g. string release = Interop.Sys.GetUnixRelease(); if (release != null) { int i = 0; major = FindAndParseNextNumber(release, ref i); minor = FindAndParseNextNumber(release, ref i); build = FindAndParseNextNumber(release, ref i); revision = FindAndParseNextNumber(release, ref i); } return new OperatingSystem(PlatformID.Unix, new Version(major, minor, build, revision)); }); private static int FindAndParseNextNumber(string text, ref int pos) { // Move to the beginning of the number for (; pos < text.Length; pos++) { char c = text[pos]; if ('0' <= c && c <= '9') { break; } } // Parse the number; int num = 0; for (; pos < text.Length; pos++) { char c = text[pos]; if ('0' <= c && c <= '9') { num = (num * 10) + (c - '0'); } else break; } return num; } public static int ProcessorCount => (int)Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_NPROCESSORS_ONLN); public static string SystemDirectory => GetFolderPathCore(SpecialFolder.System, SpecialFolderOption.None); public static int SystemPageSize => (int)Interop.Sys.SysConf(Interop.Sys.SysConfName._SC_PAGESIZE); public static unsafe string UserName { get { // First try with a buffer that should suffice for 99% of cases. string username; const int BufLen = 1024; byte* stackBuf = stackalloc byte[BufLen]; if (TryGetUserNameFromPasswd(stackBuf, BufLen, out username)) { return username; } // Fallback to heap allocations if necessary, growing the buffer until // we succeed. TryGetUserNameFromPasswd will throw if there's an unexpected error. int lastBufLen = BufLen; while (true) { lastBufLen *= 2; byte[] heapBuf = new byte[lastBufLen]; fixed (byte* buf = &heapBuf[0]) { if (TryGetUserNameFromPasswd(buf, heapBuf.Length, out username)) { return username; } } } } } private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string path) { // Call getpwuid_r to get the passwd struct Interop.Sys.Passwd passwd; int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen); // If the call succeeds, give back the user name retrieved if (error == 0) { Debug.Assert(passwd.Name != null); path = Marshal.PtrToStringAnsi((IntPtr)passwd.Name); return true; } // If the current user's entry could not be found, give back null, // but still return true as false indicates the buffer was too small. if (error == -1) { path = null; return true; } var errorInfo = new Interop.ErrorInfo(error); // If the call failed because the buffer was too small, return false to // indicate the caller should try again with a larger buffer. if (errorInfo.Error == Interop.Error.ERANGE) { path = null; return false; } // Otherwise, fail. throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno); } public static string UserDomainName => MachineName; } }
// // Encog(tm) Core v3.3 - .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.Text; using Encog.MathUtil; using Encog.Neural.Networks.Layers; using Encog.Util; namespace Encog.Neural.Networks.Structure { /// <summary> /// Allows the weights and bias values of the neural network to be analyzed. /// </summary> /// public class AnalyzeNetwork { /// <summary> /// All of the values in the neural network. /// </summary> /// private readonly double[] _allValues; /// <summary> /// The ranges of the bias values. /// </summary> /// private readonly NumericRange _bias; /// <summary> /// The bias values in the neural network. /// </summary> /// private readonly double[] _biasValues; /// <summary> /// The number of disabled connections. /// </summary> /// private readonly int _disabledConnections; /// <summary> /// The total number of connections. /// </summary> /// private readonly int _totalConnections; /// <summary> /// The weight values in the neural network. /// </summary> /// private readonly double[] _weightValues; /// <summary> /// The ranges of the weights. /// </summary> /// private readonly NumericRange _weights; /// <summary> /// The ranges of both the weights and biases. /// </summary> /// private readonly NumericRange _weightsAndBias; /// <summary> /// Construct a network analyze class. Analyze the specified network. /// </summary> /// /// <param name="network">The network to analyze.</param> public AnalyzeNetwork(BasicNetwork network) { int assignDisabled = 0; int assignedTotal = 0; IList<Double> biasList = new List<Double>(); IList<Double> weightList = new List<Double>(); IList<Double> allList = new List<Double>(); for (int layerNumber = 0; layerNumber < network.LayerCount - 1; layerNumber++) { int fromCount = network.GetLayerNeuronCount(layerNumber); int fromBiasCount = network .GetLayerTotalNeuronCount(layerNumber); int toCount = network.GetLayerNeuronCount(layerNumber + 1); // weights for (int fromNeuron = 0; fromNeuron < fromCount; fromNeuron++) { for (int toNeuron = 0; toNeuron < toCount; toNeuron++) { double v = network.GetWeight(layerNumber, fromNeuron, toNeuron); if (network.Structure.ConnectionLimited ) { if (Math.Abs(v) < network.Structure.ConnectionLimit ) { assignDisabled++; } } weightList.Add(v); allList.Add(v); assignedTotal++; } } // bias if (fromCount != fromBiasCount) { int biasNeuron = fromCount; for (int toNeuron = 0; toNeuron < toCount; toNeuron++) { double v = network.GetWeight(layerNumber, biasNeuron, toNeuron); if (network.Structure.ConnectionLimited) { if (Math.Abs(v) < network.Structure.ConnectionLimit) { assignDisabled++; } } biasList.Add(v); allList.Add(v); assignedTotal++; } } } _disabledConnections = assignDisabled; _totalConnections = assignedTotal; _weights = new NumericRange(weightList); _bias = new NumericRange(biasList); _weightsAndBias = new NumericRange(allList); _weightValues = EngineArray.ListToDouble(weightList); _allValues = EngineArray.ListToDouble(allList); _biasValues = EngineArray.ListToDouble(biasList); } /// <value>All of the values in the neural network.</value> public double[] AllValues { get { return _allValues; } } /// <value>The numeric range of the bias values.</value> public NumericRange Bias { get { return _bias; } } /// <value>The bias values in the neural network.</value> public double[] BiasValues { get { return _biasValues; } } /// <value>The number of disabled connections in the network.</value> public int DisabledConnections { get { return _disabledConnections; } } /// <value>The total number of connections in the network.</value> public int TotalConnections { get { return _totalConnections; } } /// <value>The numeric range of the weights values.</value> public NumericRange Weights { get { return _weights; } } /// <value>The numeric range of the weights and bias values.</value> public NumericRange WeightsAndBias { get { return _weightsAndBias; } } /// <value>The weight values in the neural network.</value> public double[] WeightValues { get { return _weightValues; } } /// <inheritdoc/> public override sealed String ToString() { var result = new StringBuilder(); result.Append("All Values : "); result.Append((_weightsAndBias.ToString())); result.Append("\n"); result.Append("Bias : "); result.Append((_bias.ToString())); result.Append("\n"); result.Append("Weights : "); result.Append((_weights.ToString())); result.Append("\n"); result.Append("Disabled : "); result.Append(Format.FormatInteger(_disabledConnections)); result.Append("\n"); return result.ToString(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.ComponentModel; using Microsoft.PowerShell; namespace System.Management.Automation { /// <summary> /// Implements Adapter for the COM objects. /// </summary> internal class ComAdapter : Adapter { private readonly ComTypeInfo _comTypeInfo; /// <summary> /// Constructor for the ComAdapter. /// </summary> /// <param name="typeinfo">Typeinfo for the com object we are adapting.</param> internal ComAdapter(ComTypeInfo typeinfo) { Diagnostics.Assert(typeinfo != null, "Caller to verify typeinfo is not null."); _comTypeInfo = typeinfo; } internal static string GetComTypeName(string clsid) { StringBuilder firstType = new StringBuilder("System.__ComObject"); firstType.Append("#{"); firstType.Append(clsid); firstType.Append("}"); return firstType.ToString(); } /// <summary> /// Returns the TypeNameHierarchy out of an object. /// </summary> /// <param name="obj">Object to get the TypeNameHierarchy from.</param> protected override IEnumerable<string> GetTypeNameHierarchy(object obj) { yield return GetComTypeName(_comTypeInfo.Clsid); foreach (string baseType in GetDotNetTypeNameHierarchy(obj)) { yield return baseType; } } /// <summary> /// Returns null if memberName is not a member in the adapter or /// the corresponding PSMemberInfo. /// </summary> /// <param name="obj">Object to retrieve the PSMemberInfo from.</param> /// <param name="memberName">Name of the member to be retrieved.</param> /// <returns>The PSMemberInfo corresponding to memberName from obj.</returns> protected override T GetMember<T>(object obj, string memberName) { ComProperty prop; if (_comTypeInfo.Properties.TryGetValue(memberName, out prop)) { if (prop.IsParameterized) { if (typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty))) { return new PSParameterizedProperty(prop.Name, this, obj, prop) as T; } } else if (typeof(T).IsAssignableFrom(typeof(PSProperty))) { return new PSProperty(prop.Name, this, obj, prop) as T; } } ComMethod method; if (typeof(T).IsAssignableFrom(typeof(PSMethod)) && (_comTypeInfo != null) && (_comTypeInfo.Methods.TryGetValue(memberName, out method))) { PSMethod mshMethod = new PSMethod(method.Name, this, obj, method); return mshMethod as T; } return null; } /// <summary> /// Retrieves all the members available in the object. /// The adapter implementation is encouraged to cache all properties/methods available /// in the first call to GetMember and GetMembers so that subsequent /// calls can use the cache. /// In the case of the .NET adapter that would be a cache from the .NET type to /// the public properties and fields available in that type. /// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass /// to the properties available in it. /// </summary> /// <param name="obj">Object to get all the member information from.</param> /// <returns>All members in obj.</returns> protected override PSMemberInfoInternalCollection<T> GetMembers<T>(object obj) { PSMemberInfoInternalCollection<T> collection = new PSMemberInfoInternalCollection<T>(); bool lookingForProperties = typeof(T).IsAssignableFrom(typeof(PSProperty)); bool lookingForParameterizedProperties = typeof(T).IsAssignableFrom(typeof(PSParameterizedProperty)); if (lookingForProperties || lookingForParameterizedProperties) { foreach (ComProperty prop in _comTypeInfo.Properties.Values) { if (prop.IsParameterized) { if (lookingForParameterizedProperties) { collection.Add(new PSParameterizedProperty(prop.Name, this, obj, prop) as T); } } else if (lookingForProperties) { collection.Add(new PSProperty(prop.Name, this, obj, prop) as T); } } } bool lookingForMethods = typeof(T).IsAssignableFrom(typeof(PSMethod)); if (lookingForMethods) { foreach (ComMethod method in _comTypeInfo.Methods.Values) { if (collection[method.Name] == null) { PSMethod mshmethod = new PSMethod(method.Name, this, obj, method); collection.Add(mshmethod as T); } } } return collection; } /// <summary> /// Returns an array with the property attributes. /// </summary> /// <param name="property">Property we want the attributes from.</param> /// <returns>An array with the property attributes.</returns> protected override AttributeCollection PropertyAttributes(PSProperty property) { return new AttributeCollection(); } /// <summary> /// Returns the value from a property coming from a previous call to DoGetProperty. /// </summary> /// <param name="property">PSProperty coming from a previous call to DoGetProperty.</param> /// <returns>The value of the property.</returns> protected override object PropertyGet(PSProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.GetValue(property.baseObject); } /// <summary> /// Sets the value of a property coming from a previous call to DoGetProperty. /// </summary> /// <param name="property">PSProperty coming from a previous call to DoGetProperty.</param> /// <param name="setValue">Value to set the property with.</param> /// <param name="convertIfPossible">instructs the adapter to convert before setting, if the adapter supports conversion</param> protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { ComProperty prop = (ComProperty)property.adapterData; prop.SetValue(property.baseObject, setValue); } /// <summary> /// Returns true if the property is settable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is settable.</returns> protected override bool PropertyIsSettable(PSProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.IsSettable; } /// <summary> /// Returns true if the property is gettable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is gettable.</returns> protected override bool PropertyIsGettable(PSProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.IsGettable; } /// <summary> /// Returns the name of the type corresponding to the property. /// </summary> /// <param name="property">PSProperty obtained in a previous DoGetProperty.</param> /// <param name="forDisplay">True if the result is for display purposes only.</param> /// <returns>The name of the type corresponding to the property.</returns> protected override string PropertyType(PSProperty property, bool forDisplay) { ComProperty prop = (ComProperty)property.adapterData; return forDisplay ? ToStringCodeMethods.Type(prop.Type) : prop.Type.FullName; } /// <summary> /// Get the property signature. /// </summary> /// <param name="property">Property object whose signature we want.</param> /// <returns>String representing the signature of the property.</returns> protected override string PropertyToString(PSProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.ToString(); } #region Methods /// <summary> /// Called after a non null return from GetMethodData to try to call /// the method with the arguments. /// </summary> /// <param name="method">The non empty return from GetMethods.</param> /// <param name="arguments">The arguments to use.</param> /// <returns>The return value for the method.</returns> protected override object MethodInvoke(PSMethod method, object[] arguments) { ComMethod commethod = (ComMethod)method.adapterData; return commethod.InvokeMethod(method, arguments); } /// <summary> /// Called after a non null return from GetMethodData to return the overloads. /// </summary> /// <param name="method">The return of GetMethodData.</param> /// <returns></returns> protected override Collection<string> MethodDefinitions(PSMethod method) { ComMethod commethod = (ComMethod)method.adapterData; return commethod.MethodDefinitions(); } #endregion #region parameterized property /// <summary> /// Returns the name of the type corresponding to the property's value. /// </summary> /// <param name="property">Property obtained in a previous GetMember.</param> /// <returns>The name of the type corresponding to the member.</returns> protected override string ParameterizedPropertyType(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.Type.FullName; } /// <summary> /// Returns true if the property is settable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is settable.</returns> protected override bool ParameterizedPropertyIsSettable(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.IsSettable; } /// <summary> /// Returns true if the property is gettable. /// </summary> /// <param name="property">Property to check.</param> /// <returns>True if the property is gettable.</returns> protected override bool ParameterizedPropertyIsGettable(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.IsGettable; } /// <summary> /// Called after a non null return from GetMember to get the property value. /// </summary> /// <param name="property">The non empty return from GetMember.</param> /// <param name="arguments">The arguments to use.</param> /// <returns>The return value for the property.</returns> protected override object ParameterizedPropertyGet(PSParameterizedProperty property, object[] arguments) { ComProperty prop = (ComProperty)property.adapterData; return prop.GetValue(property.baseObject, arguments); } /// <summary> /// Called after a non null return from GetMember to set the property value. /// </summary> /// <param name="property">The non empty return from GetMember.</param> /// <param name="setValue">The value to set property with.</param> /// <param name="arguments">The arguments to use.</param> protected override void ParameterizedPropertySet(PSParameterizedProperty property, object setValue, object[] arguments) { ComProperty prop = (ComProperty)property.adapterData; prop.SetValue(property.baseObject, setValue, arguments); } /// <summary> /// Returns the string representation of the property in the object. /// </summary> /// <param name="property">Property obtained in a previous GetMember.</param> /// <returns>The string representation of the property in the object.</returns> protected override string ParameterizedPropertyToString(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; return prop.ToString(); } /// <summary> /// Called after a non null return from GetMember to return the overloads. /// </summary> /// <param name="property">The return of GetMember.</param> protected override Collection<string> ParameterizedPropertyDefinitions(PSParameterizedProperty property) { ComProperty prop = (ComProperty)property.adapterData; Collection<string> returnValue = new Collection<string> { prop.GetDefinition() }; return returnValue; } #endregion parameterized property } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace CppSharp { public enum NewLineKind { Never, Always, BeforeNextBlock, IfNotEmpty } public enum BlockKind { Unknown, Block, BlockComment, InlineComment, Header, Footer, Usings, Namespace, TranslationUnit, Enum, EnumItem, Typedef, Class, InternalsClass, InternalsClassMethod, InternalsClassField, Functions, Function, Method, Event, Variable, Property, Field, VTableDelegate, Region, Interface, Finalizer, Includes, IncludesForwardReferences, ForwardReferences, MethodBody, FunctionsClass, Template, Destructor, AccessSpecifier, Fields, Constructor, ConstructorBody, DestructorBody, FinalizerBody } [DebuggerDisplay("{Kind} | {Object}")] public class Block : ITextGenerator { public TextGenerator Text { get; set; } public BlockKind Kind { get; set; } public NewLineKind NewLineKind { get; set; } public object Object { get; set; } public Block Parent { get; set; } public List<Block> Blocks { get; set; } private bool hasIndentChanged; public Func<bool> CheckGenerate; public Block() : this(BlockKind.Unknown) { } public Block(BlockKind kind) { Kind = kind; Blocks = new List<Block>(); Text = new TextGenerator(); hasIndentChanged = false; } public void AddBlock(Block block) { if (Text.StringBuilder.Length != 0 || hasIndentChanged) { hasIndentChanged = false; var newBlock = new Block { Text = Text.Clone() }; Text.StringBuilder.Clear(); AddBlock(newBlock); } block.Parent = this; Blocks.Add(block); } public IEnumerable<Block> FindBlocks(BlockKind kind) { foreach (var block in Blocks) { if (block.Kind == kind) yield return block; foreach (var childBlock in block.FindBlocks(kind)) yield return childBlock; } } public virtual StringBuilder Generate() { if (CheckGenerate != null && !CheckGenerate()) return new StringBuilder(); if (Blocks.Count == 0) return Text.StringBuilder; var builder = new StringBuilder(); Block previousBlock = null; var previousBlockEmpty = false; foreach (var childBlock in Blocks) { var childText = childBlock.Generate(); if (childText.Length == 0) continue; if (previousBlock != null && (previousBlock.NewLineKind == NewLineKind.BeforeNextBlock || (previousBlock.NewLineKind == NewLineKind.IfNotEmpty && !previousBlockEmpty))) builder.AppendLine(); builder.Append(childText); if (childBlock.NewLineKind == NewLineKind.Always) builder.AppendLine(); previousBlock = childBlock; previousBlockEmpty = childText.Length == 0; } if (Text.StringBuilder.Length != 0) builder.Append(Text.StringBuilder); return builder; } public bool IsEmpty { get { return Blocks.All(block => block.IsEmpty) && string.IsNullOrEmpty(Text.ToString()); } } #region ITextGenerator implementation public void Write(string msg, params object[] args) { Text.Write(msg, args); } public void WriteLine(string msg, params object[] args) { Text.WriteLine(msg, args); } public void WriteLineIndent(string msg, params object[] args) { Text.WriteLineIndent(msg, args); } public void NewLine() { Text.NewLine(); } public void NewLineIfNeeded() { Text.NewLineIfNeeded(); } public void NeedNewLine() { Text.NeedNewLine(); } public bool NeedsNewLine { get => Text.NeedsNewLine; set => Text.NeedsNewLine = value; } public void ResetNewLine() { Text.ResetNewLine(); } public void Indent(uint indentation = 4u) { hasIndentChanged = true; Text.Indent(indentation); } public void Unindent() { hasIndentChanged = true; Text.Unindent(); } public void WriteOpenBraceAndIndent() { Text.WriteOpenBraceAndIndent(); } public void UnindentAndWriteCloseBrace() { Text.UnindentAndWriteCloseBrace(); } #endregion } public abstract class BlockGenerator : ITextGenerator { private static string[] LineBreakSequences = new[] { "\r\n", "\r", "\n" }; public Block RootBlock { get; } public Block ActiveBlock { get; private set; } public uint CurrentIndentation => ActiveBlock.Text.CurrentIndentation; protected BlockGenerator() { RootBlock = new Block(); ActiveBlock = RootBlock; } public virtual string Generate() { return RootBlock.Generate().ToString(); } #region Block helpers public void AddBlock(Block block) { ActiveBlock.AddBlock(block); } public void PushBlock(BlockKind kind = BlockKind.Unknown, object obj = null) { var block = new Block { Kind = kind, Object = obj, Text = { CurrentIndentation = CurrentIndentation, IsStartOfLine = ActiveBlock.Text.IsStartOfLine, NeedsNewLine = ActiveBlock.Text.NeedsNewLine } }; PushBlock(block); } public void PushBlock(Block block) { block.Parent = ActiveBlock; ActiveBlock.AddBlock(block); ActiveBlock = block; } public Block PopBlock(NewLineKind newLineKind = NewLineKind.Never) { var block = ActiveBlock; ActiveBlock.NewLineKind = newLineKind; ActiveBlock = ActiveBlock.Parent; return block; } public IEnumerable<Block> FindBlocks(BlockKind kind) { return RootBlock.FindBlocks(kind); } public Block FindBlock(BlockKind kind) { return FindBlocks(kind).SingleOrDefault(); } #endregion #region ITextGenerator implementation public void Write(string msg, params object[] args) { ActiveBlock.Write(msg, args); } public void WriteLine(string msg, params object[] args) { ActiveBlock.WriteLine(msg, args); } public void WriteLines(string msg, bool trimIndentation = false) { var lines = msg.Split(LineBreakSequences, StringSplitOptions.None); int indentation = int.MaxValue; if (trimIndentation) { foreach(var line in lines) { for (int i = 0; i < line.Length; ++i) { if (char.IsWhiteSpace(line[i])) continue; if (i < indentation) { indentation = i; break; } } } } bool foundNonEmptyLine = false; foreach (var line in lines) { if (!foundNonEmptyLine && string.IsNullOrEmpty(line)) continue; WriteLine(line.Length >= indentation ? line.Substring(indentation) : line); foundNonEmptyLine = true; } } public void WriteLineIndent(string msg, params object[] args) { ActiveBlock.WriteLineIndent(msg, args); } public void NewLine() { ActiveBlock.NewLine(); } public void NewLineIfNeeded() { ActiveBlock.NewLineIfNeeded(); } public void NeedNewLine() { ActiveBlock.NeedNewLine(); } public bool NeedsNewLine { get => ActiveBlock.NeedsNewLine; set => ActiveBlock.NeedsNewLine = value; } public void ResetNewLine() { ActiveBlock.ResetNewLine(); } public void Indent(uint indentation = 4u) { ActiveBlock.Indent(indentation); } public void Unindent() { ActiveBlock.Unindent(); } public void WriteOpenBraceAndIndent() { ActiveBlock.WriteOpenBraceAndIndent(); } public void UnindentAndWriteCloseBrace() { ActiveBlock.UnindentAndWriteCloseBrace(); } #endregion } }
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace ZXing.OneD.RSS { /// <summary> /// /// </summary> internal abstract class AbstractRSSReader : OneDReader { private static readonly int MAX_AVG_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.2f); private static readonly int MAX_INDIVIDUAL_VARIANCE = (int)(PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.45f); private const float MIN_FINDER_PATTERN_RATIO = 9.5f / 12.0f; private const float MAX_FINDER_PATTERN_RATIO = 12.5f / 14.0f; private readonly int[] decodeFinderCounters; private readonly int[] dataCharacterCounters; private readonly float[] oddRoundingErrors; private readonly float[] evenRoundingErrors; private readonly int[] oddCounts; private readonly int[] evenCounts; /// <summary> /// Initializes a new instance of the <see cref="AbstractRSSReader"/> class. /// </summary> protected AbstractRSSReader() { decodeFinderCounters = new int[4]; dataCharacterCounters = new int[8]; oddRoundingErrors = new float[4]; evenRoundingErrors = new float[4]; oddCounts = new int[dataCharacterCounters.Length / 2]; evenCounts = new int[dataCharacterCounters.Length / 2]; } /// <summary> /// Gets the decode finder counters. /// </summary> /// <returns></returns> protected int[] getDecodeFinderCounters() { return decodeFinderCounters; } /// <summary> /// Gets the data character counters. /// </summary> /// <returns></returns> protected int[] getDataCharacterCounters() { return dataCharacterCounters; } /// <summary> /// Gets the odd rounding errors. /// </summary> /// <returns></returns> protected float[] getOddRoundingErrors() { return oddRoundingErrors; } /// <summary> /// Gets the even rounding errors. /// </summary> /// <returns></returns> protected float[] getEvenRoundingErrors() { return evenRoundingErrors; } /// <summary> /// Gets the odd counts. /// </summary> /// <returns></returns> protected int[] getOddCounts() { return oddCounts; } /// <summary> /// Gets the even counts. /// </summary> /// <returns></returns> protected int[] getEvenCounts() { return evenCounts; } /// <summary> /// Parses the finder value. /// </summary> /// <param name="counters">The counters.</param> /// <param name="finderPatterns">The finder patterns.</param> /// <param name="value">The value.</param> /// <returns></returns> protected static bool parseFinderValue(int[] counters, int[][] finderPatterns, out int value) { for (value = 0; value < finderPatterns.Length; value++) { if (patternMatchVariance(counters, finderPatterns[value], MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return true; } } return false; } /// <summary> /// Counts the specified array. /// </summary> /// <param name="array">The array.</param> /// <returns></returns> protected static int count(int[] array) { int count = 0; foreach (int a in array) { count += a; } return count; } /// <summary> /// Increments the specified array. /// </summary> /// <param name="array">The array.</param> /// <param name="errors">The errors.</param> protected static void increment(int[] array, float[] errors) { int index = 0; float biggestError = errors[0]; for (int i = 1; i < array.Length; i++) { if (errors[i] > biggestError) { biggestError = errors[i]; index = i; } } array[index]++; } /// <summary> /// Decrements the specified array. /// </summary> /// <param name="array">The array.</param> /// <param name="errors">The errors.</param> protected static void decrement(int[] array, float[] errors) { int index = 0; float biggestError = errors[0]; for (int i = 1; i < array.Length; i++) { if (errors[i] < biggestError) { biggestError = errors[i]; index = i; } } array[index]--; } /// <summary> /// Determines whether [is finder pattern] [the specified counters]. /// </summary> /// <param name="counters">The counters.</param> /// <returns> /// <c>true</c> if [is finder pattern] [the specified counters]; otherwise, <c>false</c>. /// </returns> protected static bool isFinderPattern(int[] counters) { int firstTwoSum = counters[0] + counters[1]; int sum = firstTwoSum + counters[2] + counters[3]; float ratio = (float)firstTwoSum / (float)sum; if (ratio >= MIN_FINDER_PATTERN_RATIO && ratio <= MAX_FINDER_PATTERN_RATIO) { // passes ratio test in spec, but see if the counts are unreasonable int minCounter = Int32.MaxValue; int maxCounter = Int32.MinValue; foreach (int counter in counters) { if (counter > maxCounter) { maxCounter = counter; } if (counter < minCounter) { minCounter = counter; } } return maxCounter < 10 * minCounter; } return false; } } }
using System; namespace FacebookSharp { using System.Data.SQLite; using System.Web.Security; /// <remarks> /// CREATE TABLE FacebookUsers( /// Username VARCHAR(60), -- membershipUsername, primary key already enforced as unique and not null /// FacebookId VARCHAR(50) NOT NULL UNIQUE, /// AccessToken VARCHAR(256), /// PRIMARY KEY (Username) /// ); /// todo: add support for application name /// </remarks> public class SQLiteFacebookMembershipProvider : IFacebookMembershipProvider { private readonly string _connectionString; private readonly string _tableName; private readonly MembershipProvider _membershipProvider; public SQLiteFacebookMembershipProvider(string connectionString) : this(connectionString, null, null) { } public SQLiteFacebookMembershipProvider(string connectionString, string tableName) : this(connectionString, tableName, null) { } public SQLiteFacebookMembershipProvider(string connectionString, string tableName, MembershipProvider membershipProvider) { _connectionString = connectionString; _tableName = tableName ?? "facebook_users"; _membershipProvider = membershipProvider; // we cound had done _membershipProvider = membershipProvider ?? Membership.Provider // but that wouldn't allow to work under client profile } #region Implementation of IFacebookMembershipProvider /// <summary> /// Name of the application /// </summary> public string ApplicationName { get { return _membershipProvider == null ? string.Empty : _membershipProvider.ApplicationName; } } public bool HasLinkedFacebook(string membershipUsername) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand(string.Format("SELECT COUNT(*) FROM {0} WHERE Username=@Username", _tableName), cn); cmd.Parameters.AddWithValue("@Username", membershipUsername); cn.Open(); return (int)cmd.ExecuteScalar() == 1; } } public bool HasLinkedFacebook(object membershipProviderUserKey) { MembershipUser user = _membershipProvider.GetUser(membershipProviderUserKey, false); if (user == null) throw new FacebookSharpException("User with given membershipProviderUserKey not found."); return HasLinkedFacebook(user.UserName); } public bool IsFacebookUserLinked(string facebookId) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand(string.Format("SELECT COUNT(*) FROM {0} WHERE FacebookId=@FacebookId", _tableName), cn); cmd.Parameters.AddWithValue("@FacebookId", facebookId); cn.Open(); return (int)cmd.ExecuteScalar() == 1; } } public void LinkFacebook(string membershipUsername, string facebookId, string accessToken) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format( "INSERT INTO {0} (Username,FacebookId,AccessToken) VALUES (@Username,@FacebookId,@AccessToken)", _tableName), cn); cmd.Parameters.AddWithValue("@Username", membershipUsername); cmd.Parameters.AddWithValue("@FacebookId", facebookId); cmd.Parameters.AddWithValue("@AccessToken", accessToken); cn.Open(); cmd.ExecuteNonQuery(); } } public void LinkFacebook(string membershipUsername, string facebookId, string accessToken, long expiresIn) { // todo: add expires in LinkFacebook(membershipUsername, facebookId, accessToken); } public void LinkFacebook(object membershipProviderUserKey, string facebookId, string accessToken) { MembershipUser user = _membershipProvider.GetUser(membershipProviderUserKey, false); if (user == null) throw new FacebookSharpException("User with given membershipProviderUserKey not found."); LinkFacebook(user.UserName, facebookId, accessToken); } public void LinkFacebook(object membershipProviderUserKey, string facebookId, string accessToken, long expiresIn) { // todo: add expires in LinkFacebook(membershipProviderUserKey, facebookId, accessToken); } public void UnlinkFacebook(string membershipUsername) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format("DELETE FROM {0} WHERE Username=@Username", _tableName), cn); cmd.Parameters.AddWithValue("@Username", membershipUsername); cn.Open(); cmd.ExecuteNonQuery(); } } public void UnlinkFacebook(object membershipProviderUserKey) { MembershipUser user = _membershipProvider.GetUser(membershipProviderUserKey, false); if (user == null) throw new FacebookSharpException("User with given membershipProviderUserKey not found."); UnlinkFacebook(user.UserName); } public void UnlinkFacebookByFacebookId(string facebookId) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format("DELETE FROM {0} WHERE FacebookId=@FacebookId", _tableName), cn); cmd.Parameters.AddWithValue("@FacebookId", facebookId); cn.Open(); cmd.ExecuteNonQuery(); } } public string GetFacebookAccessToken(string membershipUsername) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format("SELECT AccessToken FROM {0} WHERE Username=@Username", _tableName), cn); cmd.Parameters.AddWithValue("@user_Usernamename", membershipUsername); cn.Open(); var result = cmd.ExecuteScalar(); return result == null ? "" : result.ToString(); } } public string GetFacebookAccessToken(object membershipProviderUserKey) { MembershipUser user = _membershipProvider.GetUser(membershipProviderUserKey, false); if (user == null) throw new FacebookSharpException("User with given membershipProviderUserKey not found."); return GetFacebookAccessToken(user.UserName); } public string GetFacebookAccessTokenByFacebookId(string facebookId) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format("SELECT AccessToken FROM {0} WHERE FacebookId=@FacebookId", _tableName), cn); cmd.Parameters.AddWithValue("@FacebookId", facebookId); cn.Open(); var result = cmd.ExecuteScalar(); return result == null ? "" : result.ToString(); } } public long GetFacebookExpiresIn(string membershipUsername) { throw new NotImplementedException(); } public long GetFacebookExpiresIn(object membershipProviderUserKey) { throw new NotImplementedException(); } public long GetFacebookExpiresInByFacebookId(string facebookId) { throw new NotImplementedException(); } public string GetFacebookId(string membershipUsername) { using (SQLiteConnection cn = new SQLiteConnection(_connectionString)) { SQLiteCommand cmd = new SQLiteCommand( string.Format("SELECT FacebookId FROM {0} WHERE Username=@Username", _tableName), cn); cmd.Parameters.AddWithValue("@Username", membershipUsername); cn.Open(); return cmd.ExecuteScalar().ToString(); } } public string GetFacebookId(object membershipProviderUserKey) { MembershipUser user = _membershipProvider.GetUser(membershipProviderUserKey, false); if (user == null) throw new FacebookSharpException("User with given membershipProviderUserKey not found."); return GetFacebookId(user.UserName); } #endregion } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapSearchConstraints.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap { /// <summary> /// Defines the options controlling search operations. /// /// An LdapSearchConstraints object is always associated with an /// LdapConnection object; its values can be changed with the /// LdapConnection.setConstraints method, or overridden by passing /// an LdapSearchConstraints object to the search operation. /// /// </summary> /// <seealso cref="LdapConstraints"> /// </seealso> /// <seealso cref="LdapConnection.Constraints"> /// </seealso> public class LdapSearchConstraints:LdapConstraints { private void InitBlock() { dereference = DEREF_NEVER; } /// <summary> Returns the number of results to block on during receipt of search /// results. /// /// This should be 0 if intermediate reults are not needed, /// and 1 if results are to be processed as they come in. A value of /// indicates block until all results are received. Default: /// /// </summary> /// <returns> The the number of results to block on. /// /// </returns> /// <seealso cref="BatchSize"> /// </seealso> /// <summary> Specifies the number of results to return in a batch. /// Specifying 0 means to block until all results are received. /// Specifying 1 means to return results one result at a time. Default: 1 /// /// /// This should be 0 if intermediate results are not needed, /// and 1 if results are to be processed as they come in. The /// default is 1. /// /// </summary> /// <param name="batchSize"> The number of results to block on. /// /// </param> /// <seealso cref="BatchSize"> /// </seealso> virtual public int BatchSize { get { return batchSize; } set { this.batchSize = value; return ; } } /// <summary> Specifies when aliases should be dereferenced. /// /// Returns one of the following: /// <ul> /// <li>DEREF_NEVER</li> /// <li>DEREF_FINDING</li> /// <li>DEREF_SEARCHING</li> /// <li>DEREF_ALWAYS</li> /// </ul> /// /// </summary> /// <returns> The setting for dereferencing aliases. /// /// </returns> /// <seealso cref="Dereference"> /// </seealso> /// <summary> Sets a preference indicating whether or not aliases should be /// dereferenced, and if so, when. /// /// /// </summary> /// <param name="dereference"> Specifies how aliases are dereference and can be set /// to one of the following: /// <ul> /// <li>DEREF_NEVER - do not dereference aliases</li> /// <li>DEREF_FINDING - dereference aliases when finding /// the base object to start the search</li> /// <li>DEREF_SEARCHING - dereference aliases when /// searching but not when finding the base /// object to start the search</li> /// <li>DEREF_ALWAYS - dereference aliases when finding /// the base object and when searching</li> /// </ul> /// /// </param> /// <seealso cref="Dereference"> /// </seealso> virtual public int Dereference { get { return dereference; } set { this.dereference = value; return ; } } /// <summary> Returns the maximum number of search results to be returned for /// a search operation. A value of 0 means no limit. Default: 1000 /// The search operation will be terminated with an /// LdapException.SIZE_LIMIT_EXCEEDED if the number of results /// exceed the maximum. /// /// </summary> /// <returns> The value for the maximum number of results to return. /// /// </returns> /// <seealso cref="MaxResults"> /// </seealso> /// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED"> /// </seealso> /// <summary> Sets the maximum number of search results to be returned from a /// search operation. The value 0 means no limit. The default is 1000. /// The search operation will be terminated with an /// LdapException.SIZE_LIMIT_EXCEEDED if the number of results /// exceed the maximum. /// /// </summary> /// <param name="maxResults"> Maximum number of search results to return. /// /// </param> /// <seealso cref="MaxResults"> /// </seealso> /// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED"> /// </seealso> virtual public int MaxResults { get { return maxResults; } set { this.maxResults = value; return ; } } /// <summary> Returns the maximum number of seconds that the server waits when /// returning search results. /// The search operation will be terminated with an /// LdapException.TIME_LIMIT_EXCEEDED if the operation exceeds the time /// limit. /// /// </summary> /// <returns> The maximum number of seconds the server waits for search' /// results. /// /// </returns> /// <seealso cref="ServerTimeLimit"> /// </seealso> /// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED"> /// </seealso> /// <summary> Sets the maximum number of seconds that the server is to wait when /// returning search results. /// The search operation will be terminated with an /// LdapException.TIME_LIMIT_EXCEEDED if the operation exceeds the time /// limit. /// /// The parameter is only recognized on search operations. /// /// </summary> /// <param name="seconds">The number of seconds to wait for search results. /// /// </param> /// <seealso cref="ServerTimeLimit"> /// </seealso> /// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED"> /// </seealso> virtual public int ServerTimeLimit { get { return serverTimeLimit; } set { this.serverTimeLimit = value; return ; } } private int dereference; private int serverTimeLimit = 0; private int maxResults = 1000; private int batchSize = 1; new private static System.Object nameLock; // protect agentNum private static int lSConsNum = 0; // Debug, LdapConnection number new private System.String name; // String name for debug /// <summary> Indicates that aliases are never dereferenced. /// /// DEREF_NEVER = 0 /// /// </summary> /// <seealso cref="Dereference"> /// </seealso> /// <seealso cref="Dereference"> /// </seealso> public const int DEREF_NEVER = 0; /// <summary> Indicates that aliases are are derefrenced when /// searching the entries beneath the starting point of the search, /// but not when finding the starting entry. /// /// DEREF_SEARCHING = 1 /// /// </summary> /// <seealso cref="Dereference"> /// </seealso> /// <seealso cref="Dereference"> /// </seealso> public const int DEREF_SEARCHING = 1; /// <summary> Indicates that aliases are dereferenced when /// finding the starting point for the search, /// but not when searching under that starting entry. /// /// DEREF_FINDING = 2 /// /// </summary> /// <seealso cref="Dereference"> /// </seealso> /// <seealso cref="Dereference"> /// </seealso> public const int DEREF_FINDING = 2; /// <summary> Indicates that aliases are always dereferenced, both when /// finding the starting point for the search, and also when /// searching the entries beneath the starting entry. /// /// DEREF_ALWAYS = 3 /// /// </summary> /// <seealso cref="Dereference"> /// </seealso> /// <seealso cref="Dereference"> /// </seealso> public const int DEREF_ALWAYS = 3; /// <summary> Constructs an LdapSearchConstraints object with a default set /// of search constraints. /// </summary> public LdapSearchConstraints():base() { InitBlock(); // Get a unique connection name for debug } /// <summary> Constructs an LdapSearchConstraints object initialized with values /// from an existing constraints object (LdapConstraints /// or LdapSearchConstraints). /// </summary> public LdapSearchConstraints(LdapConstraints cons):base(cons.TimeLimit, cons.ReferralFollowing, cons.getReferralHandler(), cons.HopLimit) { InitBlock(); LdapControl[] lsc = cons.getControls(); if (lsc != null) { LdapControl[] generated_var = new LdapControl[lsc.Length]; lsc.CopyTo(generated_var, 0); base.setControls(generated_var); } System.Collections.Hashtable lp = cons.Properties; if (lp != null) { base.Properties = (System.Collections.Hashtable) lp.Clone(); } if (cons is LdapSearchConstraints) { LdapSearchConstraints scons = (LdapSearchConstraints) cons; this.serverTimeLimit = scons.ServerTimeLimit; this.dereference = scons.Dereference; this.maxResults = scons.MaxResults; this.batchSize = scons.BatchSize; } // Get a unique connection name for debug return ; } /// <summary> Constructs a new LdapSearchConstraints object and allows the /// specification operational constraints in that object. /// /// </summary> /// <param name="msLimit"> The maximum time in milliseconds to wait for results. /// The default is 0, which means that there is no /// maximum time limit. This limit is enforced for an /// operation by the API, not by the server. /// The operation will be abandoned and terminated by the /// API with an LdapException.Ldap_TIMEOUT if the /// operation exceeds the time limit. /// /// </param> /// <param name="serverTimeLimit">The maximum time in seconds that the server /// should spend returning search results. This is a /// server-enforced limit. The default of 0 means /// no time limit. /// The operation will be terminated by the server with an /// LdapException.TIME_LIMIT_EXCEEDED if the search /// operation exceeds the time limit. /// /// </param> /// <param name="dereference">Specifies when aliases should be dereferenced. /// Must be either DEREF_NEVER, DEREF_FINDING, /// DEREF_SEARCHING, or DEREF_ALWAYS from this class. /// Default: DEREF_NEVER /// /// </param> /// <param name="maxResults">The maximum number of search results to return /// for a search request. /// The search operation will be terminated by the server /// with an LdapException.SIZE_LIMIT_EXCEEDED if the /// number of results exceed the maximum. /// Default: 1000 /// /// </param> /// <param name="doReferrals">Determines whether to automatically follow /// referrals or not. Specify true to follow /// referrals automatically, and false to throw /// an LdapException.REFERRAL if the server responds /// with a referral. /// It is ignored for asynchronous operations. /// Default: false /// /// </param> /// <param name="batchSize">The number of results to return in a batch. Specifying /// 0 means to block until all results are received. /// Specifying 1 means to return results one result at a /// time. Default: 1 /// /// /// </param> /// <param name="handler"> The custom authentication handler called when /// LdapConnection needs to authenticate, typically on /// following a referral. A null may be specified to /// indicate default authentication processing, i.e. /// referrals are followed with anonymous authentication. /// ThE object may be an implemention of either the /// the LdapBindHandler or LdapAuthHandler interface. /// It is ignored for asynchronous operations. /// /// </param> /// <param name="hop_limit">The maximum number of referrals to follow in a /// sequence during automatic referral following. /// The default value is 10. A value of 0 means no limit. /// It is ignored for asynchronous operations. /// The operation will be abandoned and terminated by the /// API with an LdapException.REFERRAL_LIMIT_EXCEEDED if the /// number of referrals in a sequence exceeds the limit. /// /// </param> /// <seealso cref="LdapException.Ldap_TIMEOUT"> /// </seealso> /// <seealso cref="LdapException.REFERRAL"> /// </seealso> /// <seealso cref="LdapException.SIZE_LIMIT_EXCEEDED"> /// </seealso> /// <seealso cref="LdapException.TIME_LIMIT_EXCEEDED"> /// </seealso> public LdapSearchConstraints(int msLimit, int serverTimeLimit, int dereference, int maxResults, bool doReferrals, int batchSize, LdapReferralHandler handler, int hop_limit):base(msLimit, doReferrals, handler, hop_limit) { InitBlock(); this.serverTimeLimit = serverTimeLimit; this.dereference = dereference; this.maxResults = maxResults; this.batchSize = batchSize; // Get a unique connection name for debug return ; } static LdapSearchConstraints() { nameLock = new System.Object(); } } }
using System; using NUnit.Framework; using System.Text.RegularExpressions; using System.Drawing; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium.Interactions { [TestFixture] public class BasicMouseInterfaceTest : DriverTestFixture { [SetUp] public void SetupTest() { IActionExecutor actionExecutor = driver as IActionExecutor; if (actionExecutor != null) { actionExecutor.ResetInputState(); } } [Test] public void ShouldAllowDraggingElementWithMouseMovesItToAnotherList() { PerformDragAndDropWithMouse(); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); Assert.AreEqual(6, dragInto.FindElements(By.TagName("li")).Count); } // This test is very similar to DraggingElementWithMouse. The only // difference is that this test also verifies the correct events were fired. [Test] public void DraggingElementWithMouseFiresEvents() { PerformDragAndDropWithMouse(); IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); // This is failing under HtmlUnit. A bug was filed. Assert.That(dragReporter.Text, Does.Match("Nothing happened\\. (?:DragOut *)+DropIn RightItem 3")); } [Test] public void ShouldAllowDoubleClickThenNavigate() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); driver.Url = droppableItems; } [Test] public void ShouldAllowDragAndDrop() { driver.Url = droppableItems; DateTime waitEndTime = DateTime.Now.Add(TimeSpan.FromSeconds(15)); while (!IsElementAvailable(driver, By.Id("draggable")) && (DateTime.Now < waitEndTime)) { System.Threading.Thread.Sleep(200); } if (!IsElementAvailable(driver, By.Id("draggable"))) { throw new Exception("Could not find draggable element after 15 seconds."); } IWebElement toDrag = driver.FindElement(By.Id("draggable")); IWebElement dropInto = driver.FindElement(By.Id("droppable")); Actions actionProvider = new Actions(driver); IAction holdDrag = actionProvider.ClickAndHold(toDrag).Build(); IAction move = actionProvider.MoveToElement(dropInto).Build(); IAction drop = actionProvider.Release(dropInto).Build(); holdDrag.Perform(); move.Perform(); drop.Perform(); dropInto = driver.FindElement(By.Id("droppable")); string text = dropInto.FindElement(By.TagName("p")).Text; Assert.AreEqual("Dropped!", text); } [Test] public void ShouldAllowDoubleClick() { driver.Url = javascriptPage; IWebElement toDoubleClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction dblClick = actionProvider.DoubleClick(toDoubleClick).Build(); dblClick.Perform(); Assert.AreEqual("DoubleClicked", toDoubleClick.GetAttribute("value")); } [Test] public void ShouldAllowContextClick() { driver.Url = javascriptPage; IWebElement toContextClick = driver.FindElement(By.Id("doubleClickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.ContextClick(toContextClick).Build(); contextClick.Perform(); Assert.AreEqual("ContextClicked", toContextClick.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.Remote, "API not implemented in driver")] public void ShouldAllowMoveAndClick() { driver.Url = javascriptPage; IWebElement toClick = driver.FindElement(By.Id("clickField")); Actions actionProvider = new Actions(driver); IAction contextClick = actionProvider.MoveToElement(toClick).Click().Build(); contextClick.Perform(); Assert.AreEqual("Clicked", toClick.GetAttribute("value"), "Value should change to Clicked."); } [Test] public void ShouldNotMoveToANullLocator() { driver.Url = javascriptPage; Assert.That(() => new Actions(driver).MoveToElement(null).Perform(), Throws.InstanceOf<ArgumentException>()); } [Test] [IgnoreBrowser(Browser.Chrome, "Drivers correctly click at current mouse position without another move, preserving mouse position.")] [IgnoreBrowser(Browser.Edge, "Drivers correctly click at current mouse position without another move, preserving mouse position.")] [IgnoreBrowser(Browser.Firefox, "Drivers correctly click at current mouse position without another move, preserving mouse position.")] [IgnoreBrowser(Browser.IE, "Drivers correctly click at current mouse position without another move, preserving mouse position.")] [IgnoreBrowser(Browser.Safari, "Drivers correctly click at current mouse position without another move, preserving mouse position.")] public void MousePositionIsNotPreservedInActionsChain() { driver.Url = javascriptPage; IWebElement toMoveTo = driver.FindElement(By.Id("clickField")); new Actions(driver).MoveToElement(toMoveTo).Perform(); Assert.That(() => new Actions(driver).Click().Perform(), Throws.InstanceOf<WebDriverException>()); } [Test] [IgnoreBrowser(Browser.All, "Behaviour not finalized yet regarding linked images.")] public void MovingIntoAnImageEnclosedInALink() { driver.Url = linkedImage; // Note: For some reason, the Accessibility API in Firefox will not be available before we // click on something. As a work-around, click on a different element just to get going. driver.FindElement(By.Id("linkToAnchorOnThisPage")).Click(); IWebElement linkElement = driver.FindElement(By.Id("linkWithEnclosedImage")); // Image is 644 x 41 - move towards the end. // Note: The width of the link element itself is correct - 644 pixels. However, // the height is 17 pixels and the rectangle containing it is *underneath* the image. // For this reason, this action will fail. new Actions(driver).MoveToElement(linkElement, 500, 30).Click().Perform(); WaitFor(TitleToBe("We Arrive Here"), "Title was not expected value"); } [Test] [IgnoreBrowser(Browser.Chrome)] [IgnoreBrowser(Browser.Edge)] [IgnoreBrowser(Browser.Firefox, "Moving outside of view port throws exception in spec-compliant driver")] [IgnoreBrowser(Browser.IE, "Moving outside of view port throws exception in spec-compliant driver")] [IgnoreBrowser(Browser.Safari)] public void MovingMouseBackAndForthPastViewPort() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("veryLargeCanvas.html"); IWebElement firstTarget = driver.FindElement(By.Id("r1")); new Actions(driver).MoveToElement(firstTarget).Click().Perform(); IWebElement resultArea = driver.FindElement(By.Id("result")); String expectedEvents = "First"; WaitFor(ElementTextToEqual(resultArea, expectedEvents), "Element text did not equal " + expectedEvents); // Move to element with id 'r2', at (2500, 50) to (2580, 100) new Actions(driver).MoveByOffset(2540 - 150, 75 - 125).Click().Perform(); expectedEvents += " Second"; WaitFor(ElementTextToEqual(resultArea, expectedEvents), "Element text did not equal " + expectedEvents); // Move to element with id 'r3' at (60, 1500) to (140, 1550) new Actions(driver).MoveByOffset(100 - 2540, 1525 - 75).Click().Perform(); expectedEvents += " Third"; WaitFor(ElementTextToEqual(resultArea, expectedEvents), "Element text did not equal " + expectedEvents); // Move to element with id 'r4' at (220,180) to (320, 230) new Actions(driver).MoveByOffset(270 - 100, 205 - 1525).Click().Perform(); expectedEvents += " Fourth"; WaitFor(ElementTextToEqual(resultArea, expectedEvents), "Element text did not equal " + expectedEvents); } [Test] [IgnoreBrowser(Browser.Opera, "API not implemented in driver")] public void ShouldClickElementInIFrame() { driver.Url = clicksPage; try { driver.SwitchTo().Frame("source"); IWebElement element = driver.FindElement(By.Id("otherframe")); new Actions(driver).MoveToElement(element).Click().Perform(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); WaitFor(() => { return driver.FindElement(By.Id("span")).Text == "An inline element"; }, "Could not find element with text 'An inline element'"); } finally { driver.SwitchTo().DefaultContent(); } } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldAllowUsersToHoverOverElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("menu1")); if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { Assert.Ignore("Skipping test: Simulating hover needs native events"); } IWebElement item = driver.FindElement(By.Id("item1")); Assert.AreEqual("", item.Text); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element); Actions actionBuilder = new Actions(driver); actionBuilder.MoveToElement(element).Perform(); item = driver.FindElement(By.Id("item1")); Assert.AreEqual("Item 1", item.Text); } [Test] public void HoverPersists() { driver.Url = javascriptPage; // Move to a different element to make sure the mouse is not over the // element with id 'item1' (from a previous test). new Actions(driver).MoveToElement(driver.FindElement(By.Id("dynamo"))).Perform(); IWebElement element = driver.FindElement(By.Id("menu1")); IWebElement item = driver.FindElement(By.Id("item1")); Assert.AreEqual(string.Empty, item.Text); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element); new Actions(driver).MoveToElement(element).Perform(); // Intentionally wait to make sure hover persists. System.Threading.Thread.Sleep(2000); WaitFor(ElementTextToNotEqual(item, ""), "Element text was empty after timeout"); Assert.AreEqual("Item 1", item.Text); } [Test] public void MovingMouseByRelativeOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 50, 200), "Coordinate matching was not within tolerance"); new Actions(driver).MoveByOffset(10, 20).Build().Perform(); WaitFor(FuzzyMatchingOfCoordinates(reporter, 60, 220), "Coordinate matching was not within tolerance"); } [Test] public void MovingMouseToRelativeElementOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv, 95, 195).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 95, 195), "Coordinate matching was not within tolerance"); } [Test] public void MovingMouseToRelativeZeroElementOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv, 0, 0).Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 0, 0), "Coordinate matching was not within tolerance"); } [Test] [NeedsFreshDriver(IsCreatedBeforeTest = true)] public void MoveRelativeToBody() { driver.Url = mouseTrackerPage; new Actions(driver).MoveByOffset(50, 100).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 40, 20), "Coordinate matching was not within tolerance"); } [Test] public void MoveMouseByOffsetOverAndOutOfAnElement() { driver.Url = mouseOverPage; IWebElement greenbox = driver.FindElement(By.Id("greenbox")); IWebElement redbox = driver.FindElement(By.Id("redbox")); Point greenboxPosition = greenbox.Location; Point redboxPosition = redbox.Location; int shiftX = redboxPosition.X - greenboxPosition.X; int shiftY = redboxPosition.Y - greenboxPosition.Y; new Actions(driver).MoveToElement(greenbox, 2, 2).Perform(); WaitFor(ElementColorToBe(redbox, Color.Green), "element color was not green"); new Actions(driver).MoveToElement(greenbox, 2, 2).MoveByOffset(shiftX, shiftY).Perform(); WaitFor(ElementColorToBe(redbox, Color.Red), "element color was not red"); new Actions(driver).MoveToElement(greenbox, 2, 2).MoveByOffset(shiftX, shiftY).MoveByOffset(-shiftX, -shiftY).Perform(); WaitFor(ElementColorToBe(redbox, Color.Green), "element color was not red"); } [Test] public void CanMouseOverAndOutOfAnElement() { driver.Url = mouseOverPage; IWebElement greenbox = driver.FindElement(By.Id("greenbox")); IWebElement redbox = driver.FindElement(By.Id("redbox")); Size size = redbox.Size; new Actions(driver).MoveToElement(greenbox, 1, 1).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); new Actions(driver).MoveToElement(redbox).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(255, 0, 0, 1)").Or.EqualTo("rgb(255, 0, 0)")); new Actions(driver).MoveToElement(redbox, size.Width + 2, size.Height + 2).Perform(); Assert.That(redbox.GetCssValue("background-color"), Is.EqualTo("rgba(0, 128, 0, 1)").Or.EqualTo("rgb(0, 128, 0)")); } private Func<bool> FuzzyMatchingOfCoordinates(IWebElement element, int x, int y) { return () => { return FuzzyPositionMatching(x, y, element.Text); }; } private bool FuzzyPositionMatching(int expectedX, int expectedY, String locationTuple) { string[] splitString = locationTuple.Split(','); int gotX = int.Parse(splitString[0].Trim()); int gotY = int.Parse(splitString[1].Trim()); // Everything within 5 pixels range is OK const int ALLOWED_DEVIATION = 5; return Math.Abs(expectedX - gotX) < ALLOWED_DEVIATION && Math.Abs(expectedY - gotY) < ALLOWED_DEVIATION; } private void PerformDragAndDropWithMouse() { driver.Url = draggableLists; IWebElement dragReporter = driver.FindElement(By.Id("dragging_reports")); IWebElement toDrag = driver.FindElement(By.Id("rightitem-3")); IWebElement dragInto = driver.FindElement(By.Id("sortable1")); IAction holdItem = new Actions(driver).ClickAndHold(toDrag).Build(); IAction moveToSpecificItem = new Actions(driver).MoveToElement(driver.FindElement(By.Id("leftitem-4"))).Build(); IAction moveToOtherList = new Actions(driver).MoveToElement(dragInto).Build(); IAction drop = new Actions(driver).Release(dragInto).Build(); Assert.AreEqual("Nothing happened.", dragReporter.Text); holdItem.Perform(); moveToSpecificItem.Perform(); moveToOtherList.Perform(); Assert.That(dragReporter.Text, Does.Match("Nothing happened\\. (?:DragOut *)+")); drop.Perform(); } private bool IsElementAvailable(IWebDriver driver, By locator) { try { driver.FindElement(locator); return true; } catch (NoSuchElementException) { return false; } } private Func<bool> TitleToBe(string desiredTitle) { return () => driver.Title == desiredTitle; } private Func<bool> ElementTextToEqual(IWebElement element, string text) { return () => element.Text == text; } private Func<bool> ElementTextToNotEqual(IWebElement element, string text) { return () => element.Text != text; } private Func<bool> ElementColorToBe(IWebElement element, Color color) { return () => { string rgb = string.Format("rgb({0}, {1}, {2})", color.R, color.G, color.B); string rgba = string.Format("rgba({0}, {1}, {2}, 1)", color.R, color.G, color.B); string value = element.GetCssValue("background-color"); return value == rgb || value == rgba; }; } } }
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // $Id: Util.java,v 1.13 2004/07/28 08:14:14 belaban Exp $ using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using Event = Alachisoft.NGroups.Event; using Alachisoft.NGroups.Blocks; using Message = Alachisoft.NGroups.Message; using Alachisoft.NCache.Common; using System.Text; using Alachisoft.NCache.Serialization.Formatters; namespace Alachisoft.NGroups.Util { /// <summary> Collection of various utility routines that can not be assigned to other classes.</summary> internal class Util { // constants public const int MAX_PORT = 65535; // highest port allocatable /// <summary>Finds first available port starting at start_port and returns server socket </summary> public static System.Net.Sockets.TcpListener createServerSocket(int start_port) { System.Net.Sockets.TcpListener ret = null; while (true) { try { System.Net.Sockets.TcpListener temp_tcpListener; temp_tcpListener = new System.Net.Sockets.TcpListener(start_port); temp_tcpListener.Start(); ret = temp_tcpListener; } catch (System.Net.Sockets.SocketException bind_ex) { //Trace.error("util.createServerSocket()",bind_ex.Message); start_port++; continue; } catch (System.IO.IOException io_ex) { //Trace.error("Util.createServerSocket():2" + io_ex.Message); } break; } return ret; } /// <summary> Returns all members that left between 2 views. All members that are element of old_mbrs but not element of /// new_mbrs are returned. /// </summary> public static System.Collections.ArrayList determineLeftMembers(System.Collections.ArrayList old_mbrs, System.Collections.ArrayList new_mbrs) { System.Collections.ArrayList retval = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); object mbr; if (old_mbrs == null || new_mbrs == null) return retval; for (int i = 0; i < old_mbrs.Count; i++) { mbr = old_mbrs[i]; if (!new_mbrs.Contains(mbr)) retval.Add(mbr); } return retval; } /// <summary>Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted </summary> public static void sleep(long timeout) { System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(timeout)); } internal static byte[] serializeMessage(Message msg) { int len = 0; byte[] buffie; FlagsByte flags = new FlagsByte(); msg.Dest = null; msg.Dests = null; RequestCorrelator.HDR rqHeader = (RequestCorrelator.HDR)msg.getHeader(HeaderType.REQUEST_COORELATOR); if (rqHeader != null) { rqHeader.serializeFlag = false; } Stream stmOut = new MemoryStream(); stmOut.Write(Util.WriteInt32(len), 0, 4); stmOut.Write(Util.WriteInt32(len), 0, 4); if (msg.IsUserMsg) { BinaryWriter msgWriter = new BinaryWriter(stmOut, new UTF8Encoding(true)); flags.SetOn(FlagsByte.Flag.TRANS); msgWriter.Write(flags.DataByte); msg.SerializeLocal(msgWriter); } else { flags.SetOff(FlagsByte.Flag.TRANS); stmOut.WriteByte(flags.DataByte); CompactBinaryFormatter.Serialize(stmOut, msg, null, false); } len = (int)stmOut.Position - 4; int payloadLength = 0; // the user payload size. payload is passed on untill finally send on the socket. if (msg.Payload != null) { for (int i = 0; i < msg.Payload.Length; i++) { payloadLength += ((byte[])msg.Payload.GetValue(i)).Length; } len += payloadLength; } stmOut.Position = 0; stmOut.Write(Util.WriteInt32(len), 0, 4); stmOut.Write(Util.WriteInt32(len - 4 - payloadLength), 0, 4); stmOut.Position = 0; buffie = new byte[len + 4 - payloadLength]; stmOut.Read(buffie, 0, len + 4 - payloadLength); stmOut.Position = 0; return buffie; } /// <summary> On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will /// sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the /// thread never relinquishes control and therefore the sleep(x) is exactly x ms long. /// </summary> public static void sleep(long msecs, bool busy_sleep) { if (!busy_sleep) { sleep(msecs); return ; } long start = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; long stop = start + msecs; while (stop > start) { start = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; } } /// <summary>Returns a random value in the range [1 - range] </summary> public static long random(long range) { return (long) ((Global.Random.NextDouble() * 100000) % range) + 1; } /// <summary>E.g. 2000,4000,8000</summary> public static long[] parseCommaDelimitedLongs(string s) { if (s == null) return null; string[] v = s.Split(','); if (v.Length == 0) return null; long[] retval = new long[v.Length]; for (int i = 0; i < v.Length; i++) retval[i] = Convert.ToInt64(v[i].Trim()); return retval; } /// <summary> Selects a random subset of members according to subset_percentage and returns them. /// Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. /// </summary> public static System.Collections.ArrayList pickSubset(System.Collections.ArrayList members, double subset_percentage) { System.Collections.ArrayList ret = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)), tmp_mbrs; int num_mbrs = members.Count, subset_size, index; if (num_mbrs == 0) return ret; subset_size = (int) System.Math.Ceiling(num_mbrs * subset_percentage); tmp_mbrs = (System.Collections.ArrayList) members.Clone(); for (int i = subset_size; i > 0 && tmp_mbrs.Count > 0; i--) { index = (int) ((Global.Random.NextDouble() * num_mbrs) % tmp_mbrs.Count); ret.Add(tmp_mbrs[index]); tmp_mbrs.RemoveAt(index); } return ret; } /// <summary>Tries to read an object from the message's buffer and prints it </summary> public static string printMessage(Message msg) { if (msg == null) return ""; if (msg.Length == 0) return null; try { return msg.getObject().ToString(); } catch (System.Exception ex) { return ""; } } public static string printEvent(Event evt) { Message msg; if (evt.Type == Event.MSG) { msg = (Message) evt.Arg; if (msg != null) { if (msg.Length > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.ToString(); } /// <summary>Fragments a byte buffer into smaller fragments of (max.) frag_size. /// Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments /// of 248 bytes each and 1 fragment of 32 bytes. /// </summary> /// <returns> An array of byte buffers (<code>byte[]</code>). /// </returns> public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { byte[][] retval; long total_size = buf.Length; int accumulated_size = 0; byte[] fragment; int tmp_size = 0; int num_frags; int index = 0; num_frags = buf.Length % frag_size == 0?buf.Length / frag_size:buf.Length / frag_size + 1; retval = new byte[num_frags][]; while (accumulated_size < total_size) { if (accumulated_size + frag_size <= total_size) tmp_size = frag_size; else tmp_size = (int) (total_size - accumulated_size); fragment = new byte[tmp_size]; Array.Copy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++] = fragment; accumulated_size += tmp_size; } return retval; } /// <summary> Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and /// return them in a list. Example:<br/> /// Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). /// This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment /// starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length /// of 2 bytes. /// </summary> /// <param name="">frag_size /// </param> /// <returns> List. A List<Range> of offset/length pairs /// </returns> public static System.Collections.IList computeFragOffsets(int offset, int length, int frag_size) { System.Collections.IList retval = new System.Collections.ArrayList(); long total_size = length + offset; int index = offset; int tmp_size = 0; Range r; while (index < total_size) { if (index + frag_size <= total_size) tmp_size = frag_size; else tmp_size = (int) (total_size - index); r = new Range(index, tmp_size); retval.Add(r); index += tmp_size; } return retval; } public static System.Collections.IList computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.Length, frag_size); } /// <summary>Concatenates smaller fragments into entire buffers.</summary> /// <param name="fragments">An array of byte buffers (<code>byte[]</code>) /// </param> /// <returns> A byte buffer /// </returns> public static byte[] defragmentBuffer(byte[][] fragments) { int total_length = 0; byte[] ret; int index = 0; if (fragments == null) return null; for (int i = 0; i < fragments.Length; i++) { if (fragments[i] == null) continue; total_length += fragments[i].Length; } ret = new byte[total_length]; for (int i = 0; i < fragments.Length; i++) { if (fragments[i] == null) continue; Array.Copy(fragments[i], 0, ret, index, fragments[i].Length); index += fragments[i].Length; } return ret; } public static void printFragments(byte[][] frags) { for (int i = 0; i < frags.Length; i++) System.Console.Out.WriteLine('\'' + new string(Global.ToCharArray(frags[i])) + '\''); } public static string shortName(string hostname) { int index; System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (hostname == null) return null; index = hostname.IndexOf((System.Char) '.'); if (index > 0 && !System.Char.IsDigit(hostname[0])) sb.Append(hostname.Substring(0, (index) - (0))); else sb.Append(hostname); return sb.ToString(); } /// <summary>Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.</summary> /// <param name="sourceStream">The source Stream to read from.</param> /// <param name="target">Contains the array of characteres read from the source Stream.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source Stream.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; int bytesRead,totalBytesRead = 0,buffStart = start; while(true) { try { if (!sock.Connected) throw new ExtSocketException("socket closed"); bytesRead = sock.Receive(target, start, count, SocketFlags.None); if (bytesRead == 0) throw new ExtSocketException("socket closed"); totalBytesRead += bytesRead; if (bytesRead == count) break; else count = count - bytesRead; start = start + bytesRead; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } } // Returns -1 if EOF if (totalBytesRead == 0) return -1; return totalBytesRead; } public static System.Int32 ReadInput(System.Net.Sockets.Socket sock, byte[] target, int start, int count,int min) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; int bytesRead, totalBytesRead = 0, buffStart = start; while (true) { try { if (!sock.Connected) throw new ExtSocketException("socket closed"); bytesRead = sock.Receive(target, start, count, SocketFlags.None); if (bytesRead == 0) throw new ExtSocketException("socket closed"); totalBytesRead += bytesRead; if (bytesRead == count) break; else count = count - bytesRead; start = start + bytesRead; if (totalBytesRead >min && sock.Available <= 0) break; } catch (SocketException e) { if (e.SocketErrorCode == SocketError.NoBufferSpaceAvailable) continue; else throw; } } // Returns -1 if EOF if (totalBytesRead == 0) return -1; return totalBytesRead; } /// <summary> /// Compares the two IP Addresses. Returns 0 if both are equal, 1 if ip1 is greateer than ip2 otherwise -1. /// </summary> /// <param name="ip1"></param> /// <param name="ip1"></param> /// <returns></returns> public static int CompareIP(IPAddress ip1,IPAddress ip2) { uint ipval1,ipval2; ipval1 = IPAddressToLong(ip1); ipval2 = IPAddressToLong(ip2); if(ipval1 == ipval2) return 0; if(ipval1 > ipval2) return 1; else return -1; } static private uint IPAddressToLong(IPAddress IPAddr) { byte[] byteIP=IPAddr.GetAddressBytes(); uint ip=(uint)byteIP[0]<<24; ip+=(uint)byteIP[1]<<16; ip+=(uint)byteIP[2]<<8; ip+=(uint)byteIP[3]; return ip; } /// <summary>Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.</summary> /// <param name="sourceTextReader">The source TextReader to read from</param> /// <param name="target">Contains the array of characteres read from the source TextReader.</param> /// <param name="start">The starting index of the target array.</param> /// <param name="count">The maximum number of characters to read from the source TextReader.</param> /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached.</returns> public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int index=start; index<start+bytesRead; index++) target[index] = (byte)charArray[index]; return bytesRead; } /// <summary> /// Creates a byte buffer representation of a <c>int32</c> /// </summary> /// <param name="value"><c>int</c> to be converted</param> /// <returns>Byte Buffer representation of a <c>Int32</c></returns> public static byte[] WriteInt32(int value) { byte[] _byteBuffer = new byte[4]; _byteBuffer[0] = (byte)value; _byteBuffer[1] = (byte)(value >> 8); _byteBuffer[2] = (byte)(value >> 16); _byteBuffer[3] = (byte)(value >> 24); return _byteBuffer; } // WriteInt32 /// <summary> /// Creates a <c>Int32</c> from a byte buffer representation /// </summary> /// <param name="_byteBuffer">Byte Buffer representation of a <c>Int32</c></param> /// <returns></returns> public static int convertToInt32(byte[] _byteBuffer) { return (int)((_byteBuffer[0] & 0xFF) | _byteBuffer[1] << 8 | _byteBuffer[2] << 16 | _byteBuffer[3] << 24); } // ReadInt32 /// <summary> /// Creates a <c>Int32</c> from a byte buffer representation /// </summary> /// <param name="_byteBuffer">Byte Buffer representation of a <c>Int32</c></param> /// <returns></returns> public static int convertToInt32(byte[] _byteBuffer, int offset) { byte[] temp = new byte[4]; System.Buffer.BlockCopy(_byteBuffer, offset, temp, 0, 4); return convertToInt32(temp); } // ReadInt32 } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using CALI.Database.Contracts; using CALI.Database.Contracts.Auth; /////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend.// /////////////////////////////////////////////////////////// // This file contains static implementations of the UserLogic // Add your own static methods by making a new partial class. // You cannot override static methods, instead override the methods // located in UserLogicBase by making a partial class of UserLogic // and overriding the base methods. namespace CALI.Database.Logic.Auth { public partial class UserLogic { //Put your code in a separate file. This is auto generated. /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> public static int? InsertNow(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { return (new UserLogic()).Insert(fldUserName , fldPassword , fldDisplayName , fldEmail , fldAuthToken , fldUserToken , fldFailedLogins , fldIsActive , fldWINSID ); } /// <summary> /// Run User_Insert. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> public static int? InsertNow(string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Insert(fldUserName , fldPassword , fldDisplayName , fldEmail , fldAuthToken , fldUserToken , fldFailedLogins , fldIsActive , fldWINSID , connection, transaction); } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(UserContract row) { return (new UserLogic()).Insert(row); } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertNow(UserContract row, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Insert(row, connection, transaction); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<UserContract> rows) { return (new UserLogic()).InsertAll(rows); } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int InsertAllNow(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).InsertAll(rows, connection, transaction); } /// <summary> /// Run User_Update. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID ) { return (new UserLogic()).Update(fldUserId , fldUserName , fldPassword , fldDisplayName , fldEmail , fldAuthToken , fldUserToken , fldFailedLogins , fldIsActive , fldWINSID ); } /// <summary> /// Run User_Update. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldPassword">Value for Password</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldAuthToken">Value for AuthToken</param> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="fldFailedLogins">Value for FailedLogins</param> /// <param name="fldIsActive">Value for IsActive</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(int fldUserId , string fldUserName , byte[] fldPassword , string fldDisplayName , string fldEmail , Guid fldAuthToken , Guid fldUserToken , int fldFailedLogins , bool fldIsActive , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Update(fldUserId , fldUserName , fldPassword , fldDisplayName , fldEmail , fldAuthToken , fldUserToken , fldFailedLogins , fldIsActive , fldWINSID , connection, transaction); } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(UserContract row) { return (new UserLogic()).Update(row); } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateNow(UserContract row, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Update(row, connection, transaction); } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<UserContract> rows) { return (new UserLogic()).UpdateAll(rows); } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int UpdateAllNow(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).UpdateAll(rows, connection, transaction); } /// <summary> /// Run User_Delete. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldUserId ) { return (new UserLogic()).Delete(fldUserId ); } /// <summary> /// Run User_Delete. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(int fldUserId , SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Delete(fldUserId , connection, transaction); } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(UserContract row) { return (new UserLogic()).Delete(row); } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteNow(UserContract row, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Delete(row, connection, transaction); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<UserContract> rows) { return (new UserLogic()).DeleteAll(rows); } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int DeleteAllNow(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).DeleteAll(rows, connection, transaction); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldUserId ) { return (new UserLogic()).Exists(fldUserId ); } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public static bool ExistsNow(int fldUserId , SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).Exists(fldUserId , connection, transaction); } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SearchNow(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID ) { var driver = new UserLogic(); driver.Search(fldUserName , fldDisplayName , fldEmail , fldWINSID ); return driver.Results; } /// <summary> /// Run User_Search, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="fldDisplayName">Value for DisplayName</param> /// <param name="fldEmail">Value for Email</param> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SearchNow(string fldUserName , string fldDisplayName , string fldEmail , string fldWINSID , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.Search(fldUserName , fldDisplayName , fldEmail , fldWINSID , connection, transaction); return driver.Results; } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectAllNow() { var driver = new UserLogic(); driver.SelectAll(); return driver.Results; } /// <summary> /// Run User_SelectAll, and return results as a list of UserRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectAllNow(SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectAll(connection, transaction); return driver.Results; } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldUserName ) { return (new UserLogic()).List(fldUserName ); } /// <summary> /// Run User_List, and return results as a list. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of __ListItemRow.</returns> public static List<ListItemContract> ListNow(string fldUserName , SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).List(fldUserName , connection, transaction); } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserIdNow(int fldUserId ) { var driver = new UserLogic(); driver.SelectBy_UserId(fldUserId ); return driver.Results; } /// <summary> /// Run User_SelectBy_UserId, and return results as a list of UserRow. /// </summary> /// <param name="fldUserId">Value for UserId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserIdNow(int fldUserId , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectBy_UserId(fldUserId , connection, transaction); return driver.Results; } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserNameNow(string fldUserName ) { var driver = new UserLogic(); driver.SelectBy_UserName(fldUserName ); return driver.Results; } /// <summary> /// Run User_SelectBy_UserName, and return results as a list of UserRow. /// </summary> /// <param name="fldUserName">Value for UserName</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserNameNow(string fldUserName , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectBy_UserName(fldUserName , connection, transaction); return driver.Results; } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_EmailNow(string fldEmail ) { var driver = new UserLogic(); driver.SelectBy_Email(fldEmail ); return driver.Results; } /// <summary> /// Run User_SelectBy_Email, and return results as a list of UserRow. /// </summary> /// <param name="fldEmail">Value for Email</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_EmailNow(string fldEmail , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectBy_Email(fldEmail , connection, transaction); return driver.Results; } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserTokenNow(Guid fldUserToken ) { var driver = new UserLogic(); driver.SelectBy_UserToken(fldUserToken ); return driver.Results; } /// <summary> /// Run User_SelectBy_UserToken, and return results as a list of UserRow. /// </summary> /// <param name="fldUserToken">Value for UserToken</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_UserTokenNow(Guid fldUserToken , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectBy_UserToken(fldUserToken , connection, transaction); return driver.Results; } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_WINSIDNow(string fldWINSID ) { var driver = new UserLogic(); driver.SelectBy_WINSID(fldWINSID ); return driver.Results; } /// <summary> /// Run User_SelectBy_WINSID, and return results as a list of UserRow. /// </summary> /// <param name="fldWINSID">Value for WINSID</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of UserRow.</returns> public static List<UserContract> SelectBy_WINSIDNow(string fldWINSID , SqlConnection connection, SqlTransaction transaction) { var driver = new UserLogic(); driver.SelectBy_WINSID(fldWINSID , connection, transaction); return driver.Results; } /// <summary> /// Read all User rows from the provided reader into the list structure of UserRows /// </summary> /// <param name="reader">The result of running a sql command.</param> /// <returns>A populated UserRows or an empty UserRows if there are no results.</returns> public static List<UserContract> ReadAllNow(SqlDataReader reader) { var driver = new UserLogic(); driver.ReadAll(reader); return driver.Results; } /// <summary>"); /// Advance one, and read values into a User /// </summary> /// <param name="reader">The result of running a sql command.</param>"); /// <returns>A User or null if there are no results.</returns> public static UserContract ReadOneNow(SqlDataReader reader) { var driver = new UserLogic(); return driver.ReadOne(reader) ? driver.Results[0] : null; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(UserContract row) { if(row.UserId == null) { return InsertNow(row); } else { return UpdateNow(row); } } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveNow(UserContract row, SqlConnection connection, SqlTransaction transaction) { if(row.UserId == null) { return InsertNow(row, connection, transaction); } else { return UpdateNow(row, connection, transaction); } } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<UserContract> rows) { return (new UserLogic()).SaveAll(rows); } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public static int SaveAllNow(List<UserContract> rows, SqlConnection connection, SqlTransaction transaction) { return (new UserLogic()).SaveAll(rows, connection, transaction); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal.CRM { public partial class CRMUsers { /// <summary> /// asyncTasks control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks; /// <summary> /// Image1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Image Image1; /// <summary> /// locTitle control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTitle; /// <summary> /// messageBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox; /// <summary> /// btnCreateUser control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnCreateUser; /// <summary> /// SearchPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel SearchPanel; /// <summary> /// ddlPageSize control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlPageSize; /// <summary> /// ddlSearchColumn control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlSearchColumn; /// <summary> /// txtSearchValue control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtSearchValue; /// <summary> /// cmdSearch control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ImageButton cmdSearch; /// <summary> /// gvUsers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.GridView gvUsers; /// <summary> /// odsAccountsPaged control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ObjectDataSource odsAccountsPaged; /// <summary> /// CRM2011Panel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel CRM2011Panel; /// <summary> /// locQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locQuota; /// <summary> /// usersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer usersQuota; /// <summary> /// locLimitedQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locLimitedQuota; /// <summary> /// limitedusersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer limitedusersQuota; /// <summary> /// locESSQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locESSQuota; /// <summary> /// essusersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer essusersQuota; /// <summary> /// CRM2013Panel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel CRM2013Panel; /// <summary> /// Localize1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize Localize1; /// <summary> /// professionalusersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer professionalusersQuota; /// <summary> /// locBasicQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locBasicQuota; /// <summary> /// basicusersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer basicusersQuota; /// <summary> /// locEssentialQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locEssentialQuota; /// <summary> /// essentialusersQuota control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.QuotaViewer essentialusersQuota; } }
using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using Microsoft.Reactive.Testing; using Avalonia.Data; using Avalonia.Data.Core; using Avalonia.UnitTests; using Xunit; using System.Threading.Tasks; using Avalonia.Markup.Parsers; namespace Avalonia.Base.UnitTests.Data.Core { public class ExpressionObserverTests_Property { [Fact] public async Task Should_Get_Simple_Property_Value() { var data = new { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Equal("foo", result); GC.KeepAlive(data); } [Fact] public void Should_Get_Simple_Property_Value_Type() { var data = new { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); target.Subscribe(_ => { }); Assert.Equal(typeof(string), target.ResultType); GC.KeepAlive(data); } [Fact] public async Task Should_Get_Simple_Property_Value_Null() { var data = new { Foo = (string)null }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Null(result); GC.KeepAlive(data); } [Fact] public async Task Should_Get_Simple_Property_From_Base_Class() { var data = new Class3 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = await target.Take(1); Assert.Equal("foo", result); GC.KeepAlive(data); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Root_Null() { var target = ExpressionObserver.Create(default(Class3), o => o.Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Root_UnsetValue() { var target = ExpressionObserver.Create(AvaloniaProperty.UnsetValue, o => (o as Class3).Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => (o As Class3).Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Return_BindingNotification_Error_For_Observable_Root_Null() { var target = ExpressionObserver.Create(Observable.Return(default(Class3)), o => o.Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async void Should_Return_BindingNotification_Error_For_Observable_Root_UnsetValue() { var target = ExpressionObserver.Create<object, string>(Observable.Return(AvaloniaProperty.UnsetValue), o => (o as Class3).Foo); var result = await target.Take(1); Assert.Equal( new BindingNotification( new MarkupBindingChainException("Null value", "o => (o As Class3).Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue), result); } [Fact] public async Task Should_Get_Simple_Property_Chain() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = ExpressionObserver.Create(data, o => o.Foo.Bar.Baz); var result = await target.Take(1); Assert.Equal("baz", result); GC.KeepAlive(data); } [Fact] public void Should_Get_Simple_Property_Chain_Type() { var data = new { Foo = new { Bar = new { Baz = "baz" } } }; var target = ExpressionObserver.Create(data, o => o.Foo.Bar.Baz); target.Subscribe(_ => { }); Assert.Equal(typeof(string), target.ResultType); GC.KeepAlive(data); } [Fact] public void Should_Return_BindingNotification_Error_For_Chain_With_Null_Value() { var data = new { Foo = default(Class1) }; var target = ExpressionObserver.Create(data, o => o.Foo.Foo.Length); var result = new List<object>(); target.Subscribe(x => result.Add(x)); Assert.Equal( new[] { new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo.Foo.Length", "Foo"), BindingErrorType.Error, AvaloniaProperty.UnsetValue), }, result); GC.KeepAlive(data); } [Fact] public void Should_Track_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); data.Foo = "bar"; Assert.Equal(new[] { "foo", "bar" }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Trigger_PropertyChanged_On_Null_Or_Empty_String() { var data = new Class1 { Bar = "foo" }; var target = ExpressionObserver.Create(data, o => o.Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); Assert.Equal(new[] { "foo" }, result); data.Bar = "bar"; Assert.Equal(new[] { "foo" }, result); data.RaisePropertyChanged(string.Empty); Assert.Equal(new[] { "foo", "bar" }, result); data.RaisePropertyChanged(null); Assert.Equal(new[] { "foo", "bar", "bar" }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_End_Of_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); ((Class2)data.Next).Bar = "baz"; ((Class2)data.Next).Bar = null; Assert.Equal(new[] { "bar", "baz", null }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Changing() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = new Class2 { Bar = "baz" }; data.Next = new Class2 { Bar = null }; Assert.Equal(new[] { "bar", "baz", null }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Null_Then_Mending() { var data = new Class1 { Next = new Class2 { Next = new Class2 { Bar = "bar" } } }; var target = ExpressionObserver.Create(data, o => ((o.Next as Class2).Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; data.Next = new Class2 { Bar = "baz" }; data.Next = old; Assert.Equal( new object[] { "bar", new BindingNotification( new MarkupBindingChainException("Null value", "o => ((o.Next As Class2).Next As Class2).Bar", "Next.Next"), BindingErrorType.Error, AvaloniaProperty.UnsetValue), "bar" }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Chain_Breaking_With_Missing_Member_Then_Mending() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); var old = data.Next; var breaking = new WithoutBar(); data.Next = breaking; data.Next = new Class2 { Bar = "baz" }; Assert.Equal( new object[] { "bar", new BindingNotification( new MissingMemberException("Could not find a matching property accessor for 'Bar' on 'Avalonia.Base.UnitTests.Data.Core.ExpressionObserverTests_Property+WithoutBar'"), BindingErrorType.Error), "baz", }, result); sub.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); Assert.Equal(0, data.Next.PropertyChangedSubscriptionCount); Assert.Equal(0, breaking.PropertyChangedSubscriptionCount); Assert.Equal(0, old.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void Empty_Expression_Should_Track_Root() { var data = new Class1 { Foo = "foo" }; var update = new Subject<Unit>(); var target = ExpressionObserver.Create(() => data.Foo, o => o, update); var result = new List<object>(); target.Subscribe(x => result.Add(x)); data.Foo = "bar"; update.OnNext(Unit.Default); Assert.Equal(new[] { "foo", "bar" }, result); GC.KeepAlive(data); } [Fact] public void Should_Track_Property_Value_From_Observable_Root() { var scheduler = new TestScheduler(); var source = scheduler.CreateColdObservable( OnNext(1, new Class1 { Foo = "foo" }), OnNext(2, new Class1 { Foo = "bar" })); var target = ExpressionObserver.Create(source, o => o.Foo); var result = new List<object>(); using (target.Subscribe(x => result.Add(x))) { scheduler.Start(); } Assert.Equal(new[] { "foo", "bar" }, result); Assert.All(source.Subscriptions, x => Assert.NotEqual(Subscription.Infinite, x.Unsubscribe)); } [Fact] public void Subscribing_Multiple_Times_Should_Return_Values_To_All() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var result1 = new List<object>(); var result2 = new List<object>(); var result3 = new List<object>(); target.Subscribe(x => result1.Add(x)); target.Subscribe(x => result2.Add(x)); data.Foo = "bar"; target.Subscribe(x => result3.Add(x)); Assert.Equal(new[] { "foo", "bar" }, result1); Assert.Equal(new[] { "foo", "bar" }, result2); Assert.Equal(new[] { "bar" }, result3); GC.KeepAlive(data); } [Fact] public void Subscribing_Multiple_Times_Should_Only_Add_PropertyChanged_Handlers_Once() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); var sub1 = target.Subscribe(x => { }); var sub2 = target.Subscribe(x => { }); Assert.Equal(1, data.PropertyChangedSubscriptionCount); sub1.Dispose(); sub2.Dispose(); Assert.Equal(0, data.PropertyChangedSubscriptionCount); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Set_Simple_Property_Value() { var data = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(data, o => o.Foo); using (target.Subscribe(_ => { })) { Assert.True(target.SetValue("bar")); } Assert.Equal("bar", data.Foo); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Set_Property_At_The_End_Of_Chain() { var data = new Class1 { Next = new Class2 { Bar = "bar" } }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.True(target.SetValue("baz")); } Assert.Equal("baz", ((Class2)data.Next).Bar); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Return_False_For_Missing_Property() { var data = new Class1 { Next = new WithoutBar() }; var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.False(target.SetValue("baz")); } GC.KeepAlive(data); } [Fact] public void SetValue_Should_Notify_New_Value_With_Inpc() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => o.Foo); var result = new List<object>(); target.Subscribe(x => result.Add(x)); target.SetValue("bar"); Assert.Equal(new[] { null, "bar" }, result); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Notify_New_Value_Without_Inpc() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => o.Bar); var result = new List<object>(); target.Subscribe(x => result.Add(x)); target.SetValue("bar"); Assert.Equal(new[] { null, "bar" }, result); GC.KeepAlive(data); } [Fact] public void SetValue_Should_Return_False_For_Missing_Object() { var data = new Class1(); var target = ExpressionObserver.Create(data, o => (o.Next as Class2).Bar); using (target.Subscribe(_ => { })) { Assert.False(target.SetValue("baz")); } GC.KeepAlive(data); } [Fact] public void Can_Replace_Root() { var first = new Class1 { Foo = "foo" }; var second = new Class1 { Foo = "bar" }; var root = first; var update = new Subject<Unit>(); var target = ExpressionObserver.Create(() => root, o => o.Foo, update); var result = new List<object>(); var sub = target.Subscribe(x => result.Add(x)); root = second; update.OnNext(Unit.Default); root = null; update.OnNext(Unit.Default); Assert.Equal( new object[] { "foo", "bar", new BindingNotification( new MarkupBindingChainException("Null value", "o => o.Foo", string.Empty), BindingErrorType.Error, AvaloniaProperty.UnsetValue) }, result); Assert.Equal(0, first.PropertyChangedSubscriptionCount); Assert.Equal(0, second.PropertyChangedSubscriptionCount); GC.KeepAlive(first); GC.KeepAlive(second); } [Fact] public void Should_Not_Keep_Source_Alive() { Func<Tuple<ExpressionObserver, WeakReference>> run = () => { var source = new Class1 { Foo = "foo" }; var target = ExpressionObserver.Create(source, o => o.Foo); return Tuple.Create(target, new WeakReference(source)); }; var result = run(); result.Item1.Subscribe(x => { }); // Mono trickery GC.Collect(2); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); GC.Collect(2); Assert.Null(result.Item2.Target); } [Fact] public void Should_Not_Throw_Exception_On_Unsubscribe_When_Already_Unsubscribed() { var source = new Class1 { Foo = "foo" }; var target = new PropertyAccessorNode("Foo", false); Assert.NotNull(target); target.Target = new WeakReference<object>(source); target.Subscribe(_ => { }); target.Unsubscribe(); target.Unsubscribe(); Assert.True(true); } [Fact] public void Should_Not_Throw_Exception_When_Enabling_Data_Validation_On_Missing_Member() { var source = new Class1(); var target = new PropertyAccessorNode("NotFound", true); target.Target = new WeakReference<object>(source); var result = new List<object>(); target.Subscribe(x => result.Add(x)); Assert.Equal( new object[] { new BindingNotification( new MissingMemberException("Could not find a matching property accessor for 'NotFound' on 'Avalonia.Base.UnitTests.Data.Core.ExpressionObserverTests_Property+Class1'"), BindingErrorType.Error), }, result); } [Fact] public void Should_Not_Throw_Exception_On_Duplicate_Properties() { // Repro of https://github.com/AvaloniaUI/Avalonia/issues/4733. var source = new MyViewModel(); var target = new PropertyAccessorNode("Name", false); target.Target = new WeakReference<object>(source); var result = new List<object>(); target.Subscribe(x => result.Add(x)); } public class MyViewModelBase { public object Name => "Name"; } public class MyViewModel : MyViewModelBase { public new string Name => "NewName"; } private interface INext { int PropertyChangedSubscriptionCount { get; } } private class Class1 : NotifyingBase { private string _foo; private INext _next; public string Foo { get { return _foo; } set { _foo = value; RaisePropertyChanged(nameof(Foo)); } } private string _bar; public string Bar { get { return _bar; } set { _bar = value; } } public INext Next { get { return _next; } set { _next = value; RaisePropertyChanged(nameof(Next)); } } } private class Class2 : NotifyingBase, INext { private string _bar; private INext _next; public string Bar { get { return _bar; } set { _bar = value; RaisePropertyChanged(nameof(Bar)); } } public INext Next { get { return _next; } set { _next = value; RaisePropertyChanged(nameof(Next)); } } } private class Class3 : Class1 { } private class WithoutBar : NotifyingBase, INext { } private Recorded<Notification<T>> OnNext<T>(long time, T value) { return new Recorded<Notification<T>>(time, Notification.CreateOnNext<T>(value)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; 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> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestLongRunningOperationTestService : ServiceClient<AutoRestLongRunningOperationTestService>, IAutoRestLongRunningOperationTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// The management credentials for Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// The retry timeout for Long Running Operations. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } public virtual ILROsOperations LROs { get; private set; } public virtual ILRORetrysOperations LRORetrys { get; private set; } public virtual ILROSADsOperations LROSADs { get; private set; } public virtual ILROsCustomHeaderOperations LROsCustomHeader { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> public AutoRestLongRunningOperationTestService() : base() { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestLongRunningOperationTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestLongRunningOperationTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestLongRunningOperationTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestLongRunningOperationTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. The management credentials for Azure. /// </param> /// <param name='handlers'> /// Optional. The set of delegating handlers to insert in the http /// client pipeline. /// </param> public AutoRestLongRunningOperationTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.LROs = new LROsOperations(this); this.LRORetrys = new LRORetrysOperations(this); this.LROSADs = new LROSADsOperations(this); this.LROsCustomHeader = new LROsCustomHeaderOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings = new JsonSerializerSettings{ DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new ResourceJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Interfaces.Claims; using JoinRpg.Data.Write.Interfaces; using JoinRpg.DataModel; using JoinRpg.Domain; using JoinRpg.Helpers; using JoinRpg.Interfaces; using JoinRpg.Services.Interfaces; using JoinRpg.Services.Interfaces.Projects; namespace JoinRpg.Services.Impl { [UsedImplicitly] internal class ProjectService : DbServiceImplBase, IProjectService { public ProjectService(IUnitOfWork unitOfWork, ICurrentUserAccessor currentUserAccessor) : base(unitOfWork, currentUserAccessor) { } public async Task<Project> AddProject(ProjectName projectName, string rootCharacterGroupName) { var rootGroup = new CharacterGroup() { IsPublic = true, IsRoot = true, CharacterGroupName = rootCharacterGroupName, IsActive = true, ResponsibleMasterUserId = CurrentUserId, HaveDirectSlots = true, AvaiableDirectSlots = -1, }; MarkCreatedNow(rootGroup); var project = new Project() { Active = true, IsAcceptingClaims = false, CreatedDate = Now, ProjectName = projectName, CharacterGroups = new List<CharacterGroup>() { rootGroup, }, ProjectAcls = new List<ProjectAcl>() { ProjectAcl.CreateRootAcl(CurrentUserId, isOwner: true), }, Details = new ProjectDetails() { CharacterNameLegacyMode = false, }, ProjectFields = new List<ProjectField>(), }; MarkTreeModified(project); _ = UnitOfWork.GetDbSet<Project>().Add(project); await UnitOfWork.SaveChangesAsync(); return project; } public async Task AddCharacterGroup(int projectId, string name, bool isPublic, IReadOnlyCollection<int> parentCharacterGroupIds, string description, bool haveDirectSlotsForSave, int directSlotsForSave, int? responsibleMasterId) { var project = await ProjectRepository.GetProjectAsync(projectId); if (responsibleMasterId != null && project.ProjectAcls.All(acl => acl.UserId != responsibleMasterId)) { //TODO: Move this check into ChGroup validation throw new Exception("No such master"); } _ = project.RequestMasterAccess(CurrentUserId, acl => acl.CanEditRoles); _ = project.EnsureProjectActive(); Create(new CharacterGroup() { AvaiableDirectSlots = directSlotsForSave, HaveDirectSlots = haveDirectSlotsForSave, CharacterGroupName = Required(name), ParentCharacterGroupIds = await ValidateCharacterGroupList(projectId, Required(() => parentCharacterGroupIds)), ProjectId = projectId, IsRoot = false, IsSpecial = false, IsPublic = isPublic, IsActive = true, Description = new MarkdownString(description), ResponsibleMasterUserId = responsibleMasterId, }); MarkTreeModified(project); await UnitOfWork.SaveChangesAsync(); } public async Task MoveCharacterGroup(int currentUserId, int projectId, int charactergroupId, int parentCharacterGroupId, short direction) { var parentCharacterGroup = await ProjectRepository.LoadGroupWithChildsAsync(projectId, parentCharacterGroupId); _ = parentCharacterGroup.RequestMasterAccess(currentUserId, acl => acl.CanEditRoles); _ = parentCharacterGroup.EnsureProjectActive(); var thisCharacterGroup = parentCharacterGroup.ChildGroups.Single(i => i.CharacterGroupId == charactergroupId); parentCharacterGroup.ChildGroupsOrdering = parentCharacterGroup .GetCharacterGroupsContainer().Move(thisCharacterGroup, direction).GetStoredOrder(); await UnitOfWork.SaveChangesAsync(); } public async Task CloseProject(int projectId, int currentUserId, bool publishPlot) { var project = await ProjectRepository.GetProjectAsync(projectId); var user = await UserRepository.GetById(currentUserId); RequestProjectAdminAccess(project, user); project.Active = false; project.IsAcceptingClaims = false; project.Details.PublishPlot = publishPlot; await UnitOfWork.SaveChangesAsync(); } public async Task SetCheckInOptions(int projectId, bool checkInProgress, bool enableCheckInModule, bool modelAllowSecondRoles) { var project = await ProjectRepository.GetProjectAsync(projectId); _ = project.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeProjectProperties); project.Details.CheckInProgress = checkInProgress && enableCheckInModule; project.Details.EnableCheckInModule = enableCheckInModule; project.Details.AllowSecondRoles = modelAllowSecondRoles && enableCheckInModule; await UnitOfWork.SaveChangesAsync(); } public async Task GrantAccessAsAdmin(int projectId) { var project = await ProjectRepository.GetProjectAsync(projectId); if (!IsCurrentUserAdmin) { throw new NoAccessToProjectException(project, CurrentUserId); } var acl = project.ProjectAcls.SingleOrDefault(a => a.UserId == CurrentUserId); if (acl == null) { project.ProjectAcls.Add(ProjectAcl.CreateRootAcl(CurrentUserId)); } await UnitOfWork.SaveChangesAsync(); } private static void RequestProjectAdminAccess(Project project, User user) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (!project.HasMasterAccess(user.UserId, acl => acl.CanChangeProjectProperties) && !user.Auth.IsAdmin) { throw new NoAccessToProjectException(project, user.UserId, acl => acl.CanChangeProjectProperties); } } public async Task EditCharacterGroup(int projectId, int currentUserId, int characterGroupId, string name, bool isPublic, IReadOnlyCollection<int> parentCharacterGroupIds, string description, bool haveDirectSlots, int directSlots, int? responsibleMasterId) { var characterGroup = (await ProjectRepository.GetGroupAsync(projectId, characterGroupId)) .RequestMasterAccess(currentUserId, acl => acl.CanEditRoles) .EnsureProjectActive(); if (!characterGroup.IsRoot ) //We shoud not edit root group, except of possibility of direct claims here { characterGroup.CharacterGroupName = Required(name); characterGroup.IsPublic = isPublic; characterGroup.ParentCharacterGroupIds = await ValidateCharacterGroupList(projectId, Required(parentCharacterGroupIds), ensureNotSpecial: true); characterGroup.Description = new MarkdownString(description); } if (responsibleMasterId != null && characterGroup.Project.ProjectAcls.All(acl => acl.UserId != responsibleMasterId)) { throw new Exception("No such master"); } characterGroup.ResponsibleMasterUserId = responsibleMasterId; characterGroup.AvaiableDirectSlots = directSlots; characterGroup.HaveDirectSlots = haveDirectSlots; MarkTreeModified(characterGroup.Project); // Can be smarted than this MarkChanged(characterGroup); await UnitOfWork.SaveChangesAsync(); } public async Task DeleteCharacterGroup(int projectId, int characterGroupId) { var characterGroup = await ProjectRepository.GetGroupAsync(projectId, characterGroupId); if (characterGroup == null) { throw new DbEntityValidationException(); } if (characterGroup.HasActiveClaims()) { throw new DbEntityValidationException(); } _ = characterGroup.RequestMasterAccess(CurrentUserId, acl => acl.CanEditRoles); _ = characterGroup.EnsureProjectActive(); foreach (var character in characterGroup.Characters.Where(ch => ch.IsActive)) { if (character.ParentCharacterGroupIds.Except(new[] { characterGroupId }).Any()) { continue; } character.ParentCharacterGroupIds = character.ParentCharacterGroupIds .Union(characterGroup.ParentCharacterGroupIds).ToArray(); } foreach (var character in characterGroup.ChildGroups.Where(ch => ch.IsActive)) { if (character.ParentCharacterGroupIds.Except(new[] { characterGroupId }).Any()) { continue; } character.ParentCharacterGroupIds = character.ParentCharacterGroupIds .Union(characterGroup.ParentCharacterGroupIds).ToArray(); } MarkTreeModified(characterGroup.Project); MarkChanged(characterGroup); if (characterGroup.CanBePermanentlyDeleted) { characterGroup.DirectlyRelatedPlotFolders.CleanLinksList(); characterGroup.DirectlyRelatedPlotElements.CleanLinksList(); } _ = SmartDelete(characterGroup); await UnitOfWork.SaveChangesAsync(); } public async Task EditProject(EditProjectRequest request) { var project = await ProjectRepository.GetProjectAsync(request.ProjectId); _ = project.RequestMasterAccess(CurrentUserId, acl => acl.CanChangeProjectProperties); project.Details.ClaimApplyRules = new MarkdownString(request.ClaimApplyRules); project.Details.ProjectAnnounce = new MarkdownString(request.ProjectAnnounce); project.Details.EnableManyCharacters = request.MultipleCharacters; project.Details.PublishPlot = request.PublishPlot && !project.Active; project.ProjectName = Required(request.ProjectName); project.IsAcceptingClaims = request.IsAcceptingClaims && project.Active; project.Details.AutoAcceptClaims = request.AutoAcceptClaims; project.Details.EnableAccommodation = request.IsAccommodationEnabled; await UnitOfWork.SaveChangesAsync(); } public async Task GrantAccess(GrantAccessRequest grantAccessRequest) { var project = await ProjectRepository.GetProjectAsync(grantAccessRequest.ProjectId); if (!project.HasMasterAccess(CurrentUserId, a => a.CanGrantRights)) { var user = await UserRepository.GetById(CurrentUserId); if (!user.Auth.IsAdmin) { _ = project.RequestMasterAccess(CurrentUserId, a => a.CanGrantRights); } } _ = project.EnsureProjectActive(); var acl = project.ProjectAcls.SingleOrDefault(a => a.UserId == grantAccessRequest.UserId); if (acl == null) { acl = new ProjectAcl { ProjectId = project.ProjectId, UserId = grantAccessRequest.UserId, }; project.ProjectAcls.Add(acl); } SetRightsFromRequest(grantAccessRequest, acl); await UnitOfWork.SaveChangesAsync(); } private static void SetRightsFromRequest(AccessRequestBase grantAccessRequest, ProjectAcl acl) { acl.CanGrantRights = grantAccessRequest.CanGrantRights; acl.CanChangeFields = grantAccessRequest.CanChangeFields; acl.CanChangeProjectProperties = grantAccessRequest.CanChangeProjectProperties; acl.CanManageClaims = grantAccessRequest.CanManageClaims; acl.CanEditRoles = grantAccessRequest.CanEditRoles; acl.CanManageMoney = grantAccessRequest.CanManageMoney; acl.CanSendMassMails = grantAccessRequest.CanSendMassMails; acl.CanManagePlots = grantAccessRequest.CanManagePlots; acl.CanManageAccommodation = grantAccessRequest.CanManageAccommodation && acl.Project.Details.EnableAccommodation; acl.CanSetPlayersAccommodations = grantAccessRequest.CanSetPlayersAccommodations && acl.Project.Details.EnableAccommodation; } public async Task RemoveAccess(int projectId, int userId, int? newResponsibleMasterIdOrDefault) { var project = await ProjectRepository.GetProjectAsync(projectId); if (userId != CurrentUserId) { _ = project.RequestMasterAccess(CurrentUserId, a => a.CanGrantRights); } if (!project.ProjectAcls.Any(a => a.CanGrantRights && a.UserId != userId)) { throw new DbEntityValidationException(); } var acl = project.ProjectAcls.Single( a => a.ProjectId == projectId && a.UserId == userId); var respFor = await ProjectRepository.GetGroupsWithResponsible(projectId); if (respFor.Any(item => item.ResponsibleMasterUserId == userId)) { throw new MasterHasResponsibleException(acl); } var claims = await ClaimsRepository.GetClaimsForMaster(projectId, acl.UserId, ClaimStatusSpec.Any); if (claims.Any()) { if (newResponsibleMasterIdOrDefault is int newResponsible) { _ = project.RequestMasterAccess(newResponsible); foreach (var claim in claims) { claim.ResponsibleMasterUserId = newResponsible; } } else { throw new MasterHasResponsibleException(acl); } } if (acl.IsOwner) { if (acl.UserId == CurrentUserId) { // if owner removing himself, assign "random" owner project.ProjectAcls.OrderBy(a => a.UserId).First().IsOwner = true; } else { //who kills the king, becomes one project.ProjectAcls.Single(a => a.UserId == CurrentUserId).IsOwner = true; } } _ = UnitOfWork.GetDbSet<ProjectAcl>().Remove(acl); _ = UnitOfWork.GetDbSet<UserSubscription>() .RemoveRange(UnitOfWork.GetDbSet<UserSubscription>() .Where(x => x.UserId == userId && x.ProjectId == projectId)); await UnitOfWork.SaveChangesAsync(); } public async Task ChangeAccess(ChangeAccessRequest changeAccessRequest) { var project = await ProjectRepository.GetProjectAsync(changeAccessRequest.ProjectId); _ = project.RequestMasterAccess(CurrentUserId, a => a.CanGrantRights); var acl = project.ProjectAcls.Single( a => a.ProjectId == changeAccessRequest.ProjectId && a.UserId == changeAccessRequest.UserId); SetRightsFromRequest(changeAccessRequest, acl); await UnitOfWork.SaveChangesAsync(); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2016 FUJIWARA, Yusuke // // 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 -- License Terms -- using System; using System.Collections.Generic; #if NETSTANDARD1_1 using Contract = MsgPack.MPContract; #else using System.Diagnostics.Contracts; #endif // NETSTANDARD1_1 using System.Globalization; using System.Linq; using System.Reflection; using System.Reflection.Emit; #if FEATURE_TAP using System.Threading; using System.Threading.Tasks; #endif // FEATURE_TAP using MsgPack.Serialization.AbstractSerializers; namespace MsgPack.Serialization.EmittingSerializers { /// <summary> /// An implementation of <see cref="SerializerBuilder{AssemblyBuilderEmittingContext,TConstruct}"/> with <see cref="AssemblyBuilder"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Constracts" )] internal sealed class AssemblyBuilderSerializerBuilder : SerializerBuilder<AssemblyBuilderEmittingContext, ILConstruct> { /// <summary> /// Initializes a new instance of the <see cref="AssemblyBuilderSerializerBuilder"/> class for instance creation. /// </summary> /// <param name="targetType">The type of serialization target.</param> /// <param name="collectionTraits">The collection traits of the serialization target.</param> public AssemblyBuilderSerializerBuilder( Type targetType, CollectionTraits collectionTraits ) : base( targetType, collectionTraits ) { } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitSequentialStatements( AssemblyBuilderEmittingContext context, TypeDefinition contextType, IEnumerable<ILConstruct> statements ) { return ILConstruct.Sequence( contextType.ResolveRuntimeType(), statements ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeNullLiteral( AssemblyBuilderEmittingContext context, TypeDefinition contextType ) { return ILConstruct.Literal( contextType.ResolveRuntimeType(), default( object ), il => il.EmitLdnull() ); } protected override ILConstruct MakeByteLiteral( AssemblyBuilderEmittingContext context, byte constant ) { return MakeIntegerLiteral( TypeDefinition.ByteType, constant ); } protected override ILConstruct MakeSByteLiteral( AssemblyBuilderEmittingContext context, sbyte constant ) { return MakeIntegerLiteral( TypeDefinition.SByteType, constant ); } protected override ILConstruct MakeInt16Literal( AssemblyBuilderEmittingContext context, short constant ) { return MakeIntegerLiteral( TypeDefinition.Int16Type, constant ); } protected override ILConstruct MakeUInt16Literal( AssemblyBuilderEmittingContext context, ushort constant ) { return MakeIntegerLiteral( TypeDefinition.UInt16Type, constant ); } protected override ILConstruct MakeInt32Literal( AssemblyBuilderEmittingContext context, int constant ) { return MakeIntegerLiteral( TypeDefinition.Int32Type, constant ); } protected override ILConstruct MakeUInt32Literal( AssemblyBuilderEmittingContext context, uint constant ) { return MakeIntegerLiteral( TypeDefinition.UInt32Type, unchecked( ( int )constant ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Many case switch" )] private static ILConstruct MakeIntegerLiteral( TypeDefinition contextType, int constant ) { switch ( constant ) { case 0: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_0() ); } case 1: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_1() ); } case 2: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_2() ); } case 3: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_3() ); } case 4: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_4() ); } case 5: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_5() ); } case 6: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_6() ); } case 7: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_7() ); } case 8: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_8() ); } case -1: { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_M1() ); } default: { if ( SByte.MinValue <= constant && constant <= SByte.MaxValue ) { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4_S( unchecked( ( byte )constant ) ) ); } else { return ILConstruct.Literal( contextType, constant, il => il.EmitLdc_I4( constant ) ); } } } } protected override ILConstruct MakeInt64Literal( AssemblyBuilderEmittingContext context, long constant ) { return ILConstruct.Literal( TypeDefinition.Int64Type, constant, il => il.EmitLdc_I8( constant ) ); } protected override ILConstruct MakeUInt64Literal( AssemblyBuilderEmittingContext context, ulong constant ) { return ILConstruct.Literal( TypeDefinition.UInt64Type, constant, il => il.EmitLdc_I8( unchecked( ( long )constant ) ) ); } protected override ILConstruct MakeReal32Literal( AssemblyBuilderEmittingContext context, float constant ) { return ILConstruct.Literal( TypeDefinition.SingleType, constant, il => il.EmitLdc_R4( constant ) ); } protected override ILConstruct MakeReal64Literal( AssemblyBuilderEmittingContext context, double constant ) { return ILConstruct.Literal( TypeDefinition.DoubleType, constant, il => il.EmitLdc_R8( constant ) ); } protected override ILConstruct MakeBooleanLiteral( AssemblyBuilderEmittingContext context, bool constant ) { return MakeIntegerLiteral( TypeDefinition.BooleanType, constant ? 1 : 0 ); } protected override ILConstruct MakeCharLiteral( AssemblyBuilderEmittingContext context, char constant ) { return MakeIntegerLiteral( TypeDefinition.CharType, constant ); } protected override ILConstruct MakeStringLiteral( AssemblyBuilderEmittingContext context, string constant ) { return ILConstruct.Literal( TypeDefinition.StringType, constant, il => il.EmitLdstr( constant ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeEnumLiteral( AssemblyBuilderEmittingContext context, TypeDefinition type, object constant ) { var underyingType = Enum.GetUnderlyingType( type.ResolveRuntimeType() ); #if !NETSTANDARD1_1 && !NETSTANDARD1_3 switch ( Type.GetTypeCode( underyingType ) ) #else switch ( NetStandardCompatibility.GetTypeCode( underyingType ) ) #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 { case TypeCode.Byte: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( byte )constant ); } case TypeCode.SByte: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( sbyte )constant ); } case TypeCode.Int16: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( short )constant ); } case TypeCode.UInt16: { // tiny integrals are represented as int32 in IL operands. return this.MakeInt32Literal( context, ( ushort )constant ); } case TypeCode.Int32: { return this.MakeInt32Literal( context, ( int )constant ); } case TypeCode.UInt32: { // signeds and unsigneds are identical in IL operands. return this.MakeInt32Literal( context, unchecked( ( int )( uint )constant ) ); } case TypeCode.Int64: { return this.MakeInt64Literal( context, ( long )constant ); } case TypeCode.UInt64: { // signeds and unsigneds are identical in IL operands. return this.MakeInt64Literal( context, unchecked( ( long )( ulong )constant ) ); } default: { // bool and char are not supported. // Of course these are very rare, and bool is not supported in ExpressionTree (it hurts portability), // and char is not supported by MsgPack protocol itself. throw new NotSupportedException( String.Format( CultureInfo.CurrentCulture, "Underying type '{0}' is not supported.", underyingType ) ); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct MakeDefaultLiteral( AssemblyBuilderEmittingContext context, TypeDefinition type ) { return ILConstruct.Literal( type.ResolveRuntimeType(), "default(" + type + ")", il => { var temp = il.DeclareLocal( type.ResolveRuntimeType(), context.GetUniqueVariableName( "tmp" ) ); il.EmitAnyLdloca( temp ); il.EmitInitobj( type.ResolveRuntimeType() ); il.EmitAnyLdloc( temp ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitThisReferenceExpression( AssemblyBuilderEmittingContext context ) { return ILConstruct.Literal( context.GetSerializerType( this.TargetType ), "(this)", il => il.EmitLdarg_0() ); } protected override ILConstruct EmitBoxExpression( AssemblyBuilderEmittingContext context, TypeDefinition valueType, ILConstruct value ) { return ILConstruct.UnaryOperator( "box", value, ( il, val ) => { val.LoadValue( il, false ); il.EmitBox( valueType.ResolveRuntimeType() ); } ); } protected override ILConstruct EmitUnboxAnyExpression( AssemblyBuilderEmittingContext context, TypeDefinition targetType, ILConstruct value ) { return ILConstruct.UnaryOperator( "unbox.any", value, ( il, val ) => { val.LoadValue( il, false ); il.EmitUnbox_Any( targetType.ResolveRuntimeType() ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitNotExpression( AssemblyBuilderEmittingContext context, ILConstruct booleanExpression ) { if ( booleanExpression.ContextType.ResolveRuntimeType() != typeof( bool ) ) { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Not expression must be Boolean elementType, but actual is '{0}'.", booleanExpression.ContextType ), "booleanExpression" ); } return ILConstruct.UnaryOperator( "!", booleanExpression, ( il, val ) => { val.LoadValue( il, false ); il.EmitLdc_I4_0(); il.EmitCeq(); }, ( il, val, @else ) => { val.LoadValue( il, false ); il.EmitBrtrue( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitEqualsExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { var equality = left.ContextType.ResolveRuntimeType().GetMethod( "op_Equality" ); return ILConstruct.BinaryOperator( "==", TypeDefinition.BooleanType, left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( equality == null ) { il.EmitCeq(); } else { il.EmitAnyCall( equality ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( equality == null ) { il.EmitCeq(); } else { il.EmitAnyCall( equality ); } il.EmitBrfalse( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitGreaterThanExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { #if DEBUG && !CORE_CLR Contract.Assert( left.ContextType.ResolveRuntimeType().GetIsPrimitive() && left.ContextType.ResolveRuntimeType() != typeof( string ) ); #endif // DEBUG && !CORE_CLR var greaterThan = left.ContextType.ResolveRuntimeType().GetMethod( "op_GreaterThan" ); return ILConstruct.BinaryOperator( ">", TypeDefinition.BooleanType, left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( greaterThan == null ) { il.EmitCgt(); } else { il.EmitAnyCall( greaterThan ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( greaterThan == null ) { il.EmitCgt(); } else { il.EmitAnyCall( greaterThan ); } il.EmitBrfalse( @else ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitLessThanExpression( AssemblyBuilderEmittingContext context, ILConstruct left, ILConstruct right ) { #if DEBUG && !CORE_CLR Contract.Assert( left.ContextType.ResolveRuntimeType().GetIsPrimitive() && left.ContextType.ResolveRuntimeType() != typeof( string ) ); #endif // DEBUG && !CORE_CLR var lessThan = left.ContextType.ResolveRuntimeType().GetMethod( "op_LessThan" ); return ILConstruct.BinaryOperator( "<", TypeDefinition.BooleanType, left, right, ( il, l, r ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( lessThan == null ) { il.EmitClt(); } else { il.EmitAnyCall( lessThan ); } }, ( il, l, r, @else ) => { l.LoadValue( il, false ); r.LoadValue( il, false ); if ( lessThan == null ) { il.EmitClt(); } else { il.EmitAnyCall( lessThan ); } il.EmitBrfalse( @else ); } ); } protected override ILConstruct EmitIncrement( AssemblyBuilderEmittingContext context, ILConstruct int32Value ) { return ILConstruct.UnaryOperator( "++", int32Value, ( il, variable ) => { variable.LoadValue( il, false ); il.EmitLdc_I4_1(); il.EmitAdd(); variable.StoreValue( il ); } ); } protected override ILConstruct EmitTypeOfExpression( AssemblyBuilderEmittingContext context, TypeDefinition type ) { return ILConstruct.Literal( TypeDefinition.TypeType, type, il => il.EmitTypeOf( type.ResolveRuntimeType() ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitMethodOfExpression( AssemblyBuilderEmittingContext context, MethodBase method ) { var instructions = context.Emitter.RegisterMethodCache( method ); return ILConstruct.Instruction( "getsetter", TypeDefinition.MethodBaseType, false, // Both of this pointer for FieldBasedSerializerEmitter and context argument of methods for ContextBasedSerializerEmitter are 0. il => instructions( il, 0 ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitFieldOfExpression( AssemblyBuilderEmittingContext context, FieldInfo field ) { var instructions = context.Emitter.RegisterFieldCache( field ); return ILConstruct.Instruction( "getfield", TypeDefinition.FieldInfoType, false, // Both of this pointer for FieldBasedSerializerEmitter and context argument of methods for ContextBasedSerializerEmitter are 0. il => instructions( il, 0 ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitThrowStatement( AssemblyBuilderEmittingContext context, ILConstruct exception ) { return ILConstruct.Instruction( "throw", TypeDefinition.VoidType, true, il => { exception.LoadValue( il, false ); il.EmitThrow(); } ); } protected override ILConstruct DeclareLocal( AssemblyBuilderEmittingContext context, TypeDefinition nestedType, string name ) { return ILConstruct.Variable( nestedType, name ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct ReferArgument( AssemblyBuilderEmittingContext context, TypeDefinition type, string name, int index ) { return ILConstruct.Argument( index, type.ResolveRuntimeType(), name ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitInvokeVoidMethod( AssemblyBuilderEmittingContext context, ILConstruct instance, MethodDefinition method, params ILConstruct[] arguments ) { return method.ResolveRuntimeMethod().ReturnType == typeof( void ) ? ILConstruct.Invoke( instance, method, arguments ) : ILConstruct.Sequence( TypeDefinition.VoidType, new[] { ILConstruct.Invoke( instance, method, arguments ), ILConstruct.Instruction( "pop", TypeDefinition.VoidType, false, il => il.EmitPop() ) } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewObjectExpression( AssemblyBuilderEmittingContext context, ILConstruct variable, ConstructorDefinition constructor, params ILConstruct[] arguments ) { #if DEBUG Contract.Assert( constructor?.ResolveRuntimeConstructor() != null ); #endif // DEBUG return ILConstruct.NewObject( variable, constructor.ResolveRuntimeConstructor(), arguments ); } protected override ILConstruct EmitMakeRef( AssemblyBuilderEmittingContext context, ILConstruct target ) { return ILConstruct.MakeRef( target ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmittingContext context, TypeDefinition elementType, int length ) { var array = ILConstruct.Variable( elementType.ResolveRuntimeType().MakeArrayType(), "array" ); return ILConstruct.Composite( ILConstruct.Sequence( array.ContextType, new[] { array, ILConstruct.Instruction( "NewArray", array.ContextType, false, il => { il.EmitNewarr( elementType.ResolveRuntimeType(), length ); array.StoreValue( il ); } ) } ), array ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "3", Justification = "Validated internally" )] protected override ILConstruct EmitCreateNewArrayExpression( AssemblyBuilderEmittingContext context, TypeDefinition elementType, int length, IEnumerable<ILConstruct> initialElements ) { var array = ILConstruct.Variable( elementType.ResolveRuntimeType().MakeArrayType(), "array" ); return ILConstruct.Composite( ILConstruct.Sequence( array.ContextType, new[] { array, ILConstruct.Instruction( "CreateArray", array.ContextType, false, il => { il.EmitNewarr( elementType.ResolveRuntimeType(), length ); array.StoreValue( il ); var index = 0; foreach ( var initialElement in initialElements ) { array.LoadValue( il, false ); this.MakeInt32Literal( context, index ).LoadValue( il, false ); initialElement.LoadValue( il, false ); il.EmitStelem( elementType.ResolveRuntimeType() ); index++; } } ) } ), array ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitGetArrayElementExpression( AssemblyBuilderEmittingContext context, ILConstruct array, ILConstruct index ) { return ILConstruct.Instruction( "SetArrayElement", array.ContextType, false, il => { il.EmitAnyLdelem( array.ContextType.ResolveRuntimeType().GetElementType(), il0 => array.LoadValue( il0, false ), il0 => index.LoadValue( il0, false ) ); } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitSetArrayElementStatement( AssemblyBuilderEmittingContext context, ILConstruct array, ILConstruct index, ILConstruct value ) { return ILConstruct.Instruction( "SetArrayElement", array.ContextType, false, il => { il.EmitAnyStelem( value.ContextType.ResolveRuntimeType(), il0 => array.LoadValue( il0, false ), il0 => index.LoadValue( il0, false ), il0 => value.LoadValue( il0, true ) ); } ); } protected override ILConstruct EmitInvokeMethodExpression( AssemblyBuilderEmittingContext context, ILConstruct instance, MethodDefinition method, IEnumerable<ILConstruct> arguments ) { return ILConstruct.Invoke( instance, method, arguments ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitInvokeDelegateExpression( AssemblyBuilderEmittingContext context, TypeDefinition delegateReturnType, ILConstruct @delegate, params ILConstruct[] arguments ) { return ILConstruct.Invoke( @delegate, @delegate.ContextType.ResolveRuntimeType().GetMethod( "Invoke" ), arguments ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitGetPropertyExpression( AssemblyBuilderEmittingContext context, ILConstruct instance, PropertyInfo property ) { return ILConstruct.Invoke( instance, property.GetGetMethod( true ), ILConstruct.NoArguments ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitGetFieldExpression( AssemblyBuilderEmittingContext context, ILConstruct instance, FieldDefinition field ) { return ILConstruct.LoadField( instance, field.ResolveRuntimeField() ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetProperty( AssemblyBuilderEmittingContext context, ILConstruct instance, PropertyInfo property, ILConstruct value ) { #if DEBUG // ReSharper disable PossibleNullReferenceException Contract.Assert( property.GetSetMethod( true ) != null, property.DeclaringType.FullName + "::" + property.Name + ".set != null" ); // ReSharper restore PossibleNullReferenceException #endif return ILConstruct.Invoke( instance, property.GetSetMethod( true ), new[] { value } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "4", Justification = "Validated by caller in base class" )] protected override ILConstruct EmitSetIndexedProperty( AssemblyBuilderEmittingContext context, ILConstruct instance, TypeDefinition declaringType, string proeprtyName, ILConstruct key, ILConstruct value ) { #if DEBUG Contract.Assert( declaringType.HasRuntimeTypeFully() ); Contract.Assert( key.ContextType.HasRuntimeTypeFully() ); #endif var indexer = declaringType.ResolveRuntimeType().GetProperty( proeprtyName, new[] { key.ContextType.ResolveRuntimeType() } ); return ILConstruct.Invoke( instance, indexer.GetSetMethod( true ), new[] { key, value } ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetField( AssemblyBuilderEmittingContext context, ILConstruct instance, FieldDefinition field, ILConstruct value ) { return ILConstruct.StoreField( instance, field.ResolveRuntimeField(), value ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitSetField( AssemblyBuilderEmittingContext context, ILConstruct instance, TypeDefinition nestedType, string fieldName, ILConstruct value ) { return ILConstruct.StoreField( instance, nestedType.ResolveRuntimeType().GetField( fieldName ), value ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitLoadVariableExpression( AssemblyBuilderEmittingContext context, ILConstruct variable ) { return ILConstruct.Instruction( "load", variable.ContextType, false, il => variable.LoadValue( il, false ) ); } protected override ILConstruct EmitStoreVariableStatement( AssemblyBuilderEmittingContext context, ILConstruct variable, ILConstruct value ) { return ILConstruct.StoreLocal( variable, value ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitTryFinally( AssemblyBuilderEmittingContext context, ILConstruct tryStatement, ILConstruct finallyStatement ) { return ILConstruct.Instruction( "try-finally", tryStatement.ContextType, false, il => { il.BeginExceptionBlock(); tryStatement.Evaluate( il ); il.BeginFinallyBlock(); finallyStatement.Evaluate( il ); il.EndExceptionBlock(); } ); } protected override ILConstruct EmitConditionalExpression( AssemblyBuilderEmittingContext context, ILConstruct conditionExpression, ILConstruct thenExpression, ILConstruct elseExpression ) { return ILConstruct.IfThenElse( conditionExpression, thenExpression, elseExpression ); } protected override ILConstruct EmitAndConditionalExpression( AssemblyBuilderEmittingContext context, IList<ILConstruct> conditionExpressions, ILConstruct thenExpression, ILConstruct elseExpression ) { return ILConstruct.IfThenElse( ILConstruct.AndCondition( conditionExpressions ), thenExpression, elseExpression ); } protected override ILConstruct EmitForEachLoop( AssemblyBuilderEmittingContext context, CollectionTraits traits, ILConstruct collection, Func<ILConstruct, ILConstruct> loopBodyEmitter ) { return ILConstruct.Instruction( "foreach", TypeDefinition.VoidType, false, il => { var enumerator = il.DeclareLocal( traits.GetEnumeratorMethod.ReturnType, "enumerator" ); var currentItem = this.DeclareLocal( context, traits.ElementType, "item" ); // gets enumerator collection.LoadValue( il, true ); il.EmitAnyCall( traits.GetEnumeratorMethod ); il.EmitAnyStloc( enumerator ); if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) ) { il.BeginExceptionBlock(); } var startLoop = il.DefineLabel( "START_LOOP" ); il.MarkLabel( startLoop ); currentItem.Evaluate( il ); var endLoop = il.DefineLabel( "END_LOOP" ); var enumeratorType = traits.GetEnumeratorMethod.ReturnType; var moveNextMethod = Metadata._IEnumerator.FindEnumeratorMoveNextMethod( enumeratorType ); var currentProperty = Metadata._IEnumerator.FindEnumeratorCurrentProperty( enumeratorType, traits ); Contract.Assert( currentProperty != null, enumeratorType.ToString() ); // iterates if ( traits.GetEnumeratorMethod.ReturnType.GetIsValueType() ) { il.EmitAnyLdloca( enumerator ); } else { il.EmitAnyLdloc( enumerator ); } il.EmitAnyCall( moveNextMethod ); il.EmitBrfalse( endLoop ); // get current item if ( traits.GetEnumeratorMethod.ReturnType.GetIsValueType() ) { il.EmitAnyLdloca( enumerator ); } else { il.EmitAnyLdloc( enumerator ); } il.EmitGetProperty( currentProperty ); currentItem.StoreValue( il ); // body loopBodyEmitter( currentItem ).Evaluate( il ); // end loop il.EmitBr( startLoop ); il.MarkLabel( endLoop ); // Dispose if ( typeof( IDisposable ).IsAssignableFrom( traits.GetEnumeratorMethod.ReturnType ) ) { il.BeginFinallyBlock(); if ( traits.GetEnumeratorMethod.ReturnType.GetIsValueType() ) { var disposeMethod = traits.GetEnumeratorMethod.ReturnType.GetMethod( "Dispose" ); if ( disposeMethod != null && disposeMethod.GetParameters().Length == 0 && disposeMethod.ReturnType == typeof( void ) ) { il.EmitAnyLdloca( enumerator ); il.EmitAnyCall( disposeMethod ); } else { il.EmitAnyLdloc( enumerator ); il.EmitBox( traits.GetEnumeratorMethod.ReturnType ); il.EmitAnyCall( Metadata._IDisposable.Dispose ); } } else { il.EmitAnyLdloc( enumerator ); il.EmitAnyCall( Metadata._IDisposable.Dispose ); } il.EndExceptionBlock(); } } ); } protected override ILConstruct EmitEnumFromUnderlyingCastExpression( AssemblyBuilderEmittingContext context, Type enumType, ILConstruct underlyingValue ) { // No operations are needed in IL level. return underlyingValue; } protected override ILConstruct EmitEnumToUnderlyingCastExpression( AssemblyBuilderEmittingContext context, Type underlyingType, ILConstruct enumValue ) { // No operations are needed in IL level. return enumValue; } protected override Func<SerializationContext, MessagePackSerializer> CreateSerializerConstructor( AssemblyBuilderEmittingContext codeGenerationContext, SerializationTarget targetInfo, PolymorphismSchema schema, SerializerCapabilities? capabilities ) { return context => codeGenerationContext.Emitter.CreateObjectInstance( codeGenerationContext, this, targetInfo, schema, capabilities ); } protected override Func<SerializationContext, MessagePackSerializer> CreateEnumSerializerConstructor( AssemblyBuilderEmittingContext codeGenerationContext ) { return context => codeGenerationContext.Emitter.CreateEnumInstance( context, EnumMessagePackSerializerHelpers.DetermineEnumSerializationMethod( context, this.TargetType, EnumMemberSerializationMethod.Default ) ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetSerializerExpression( AssemblyBuilderEmittingContext context, Type targetType, SerializingMember? memberInfo, PolymorphismSchema itemsSchema ) { var realSchema = itemsSchema ?? PolymorphismSchema.Create( targetType, memberInfo ); var field = context.Emitter.RegisterSerializer( targetType, memberInfo == null ? EnumMemberSerializationMethod.Default : memberInfo.Value.GetEnumMemberSerializationMethod(), memberInfo == null ? DateTimeMemberConversionMethod.Default : memberInfo.Value.GetDateTimeMemberConversionMethod(), realSchema, () => this.EmitConstructPolymorphismSchema( context, realSchema ) ); return this.EmitGetFieldExpression( context, this.EmitThisReferenceExpression( context ), field ); } private IEnumerable<ILConstruct> EmitConstructPolymorphismSchema( AssemblyBuilderEmittingContext context, PolymorphismSchema currentSchema ) { var schema = this.DeclareLocal( context, TypeDefinition.PolymorphismSchemaType, "schema" ); yield return schema; foreach ( var construct in this.EmitConstructPolymorphismSchema( context, schema, currentSchema ) ) { yield return construct; } yield return this.EmitLoadVariableExpression( context, schema ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetActionsExpression( AssemblyBuilderEmittingContext context, ActionType actionType, bool isAsync ) { Type type; string name; switch ( actionType ) { case ActionType.PackToArray: { type = #if FEATURE_TAP isAsync ? typeof( IList<> ).MakeGenericType( typeof( Func<,,,> ).MakeGenericType( typeof( Packer ), this.TargetType, typeof( CancellationToken ), typeof( Task ) ) ) : #endif // FEATURE_TAP typeof( IList<> ).MakeGenericType( typeof( Action<,> ).MakeGenericType( typeof( Packer ), this.TargetType ) ); name = FieldName.PackOperationList; break; } case ActionType.PackToMap: { type = #if FEATURE_TAP isAsync ? typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,,,> ).MakeGenericType( typeof( Packer ), this.TargetType, typeof( CancellationToken ), typeof( Task ) ) ) : #endif // FEATURE_TAP typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Action<,> ).MakeGenericType( typeof( Packer ), this.TargetType ) ); name = FieldName.PackOperationTable; break; } case ActionType.IsNull: { type = typeof( IDictionary<,> ).MakeGenericType( typeof( string ), typeof( Func<,> ).MakeGenericType( this.TargetType, typeof( bool ) ) ); name = FieldName.NullCheckersTable; break; } case ActionType.UnpackFromArray: { type = typeof( IList<> ).MakeGenericType( #if FEATURE_TAP isAsync ? typeof( Func<,,,,,> ).MakeGenericType( typeof( Unpacker ), context.UnpackingContextType == null ? this.TargetType : context.UnpackingContextType.ResolveRuntimeType(), typeof( int ), typeof( int ), typeof( CancellationToken ), typeof( Task ) ) : #endif // FEATURE_TAP typeof( Action<,,,> ).MakeGenericType( typeof( Unpacker ), context.UnpackingContextType == null ? this.TargetType : context.UnpackingContextType.ResolveRuntimeType(), typeof( int ), typeof( int ) ) ); name = FieldName.UnpackOperationList; break; } case ActionType.UnpackFromMap: { type = typeof( IDictionary<,> ).MakeGenericType( typeof( string ), #if FEATURE_TAP isAsync ? typeof( Func<,,,,,> ).MakeGenericType( typeof( Unpacker ), context.UnpackingContextType == null ? this.TargetType : context.UnpackingContextType.ResolveRuntimeType(), typeof( int ), typeof( int ), typeof( CancellationToken ), typeof( Task ) ) : #endif // FEATURE_TAP typeof( Action<,,,> ).MakeGenericType( typeof( Unpacker ), context.UnpackingContextType == null ? this.TargetType : context.UnpackingContextType.ResolveRuntimeType(), typeof( int ), typeof( int ) ) ); name = FieldName.UnpackOperationTable; break; } case ActionType.UnpackTo: { type = #if FEATURE_TAP isAsync ? typeof( Func<,,,,> ).MakeGenericType( typeof( Packer ), this.TargetType, typeof( int ), typeof( CancellationToken ), typeof( Task ) ) : #endif // FEATURE_TAP typeof( Action<,,> ).MakeGenericType( typeof( Unpacker ), this.TargetType, typeof( int ) ); name = FieldName.UnpackTo; break; } default: // UnpackFromMap { throw new ArgumentOutOfRangeException( "actionType" ); } } if ( isAsync ) { name += "Async"; } var field = context.DeclarePrivateField( name, type ); return this.EmitGetFieldExpression( context, this.EmitThisReferenceExpression( context ), field ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] protected override ILConstruct EmitGetMemberNamesExpression( AssemblyBuilderEmittingContext context ) { var field = context.DeclarePrivateField( FieldName.MemberNames, TypeDefinition.IListOfStringType ); return this.EmitGetFieldExpression( context, this.EmitThisReferenceExpression( context ), field ); } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated internally" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "2", Justification = "Validated internally" )] protected override ILConstruct EmitFinishFieldInitializationStatement( AssemblyBuilderEmittingContext context, string name, ILConstruct value ) { var field = context.DeclarePrivateField( name, value.ContextType.ResolveRuntimeType() ); return this.EmitSetField( context, this.EmitThisReferenceExpression( context ), field, value ); } protected override AssemblyBuilderEmittingContext CreateCodeGenerationContextForSerializerCreation( SerializationContext context ) { string serializerTypeName, serializerTypeNamespace; DefaultSerializerNameResolver.ResolveTypeName( true, this.TargetType, this.GetType().Namespace + ".Generated", out serializerTypeName, out serializerTypeNamespace ); var spec = new SerializerSpecification( this.TargetType, this.CollectionTraits, serializerTypeName, serializerTypeNamespace ); return new AssemblyBuilderEmittingContext( context, this.TargetType, this.TargetType.GetIsEnum() ? new Func<SerializerEmitter>( () => SerializationMethodGeneratorManager.Get().CreateEnumEmitter( context, spec ) ) : () => SerializationMethodGeneratorManager.Get().CreateObjectEmitter( spec, this.BaseClass ) ); } #if FEATURE_ASMGEN protected override void BuildSerializerCodeCore( ISerializerCodeGenerationContext context, Type concreteType, PolymorphismSchema itemSchema ) { var asAssemblyBuilderCodeGenerationContext = context as AssemblyBuilderCodeGenerationContext; if ( asAssemblyBuilderCodeGenerationContext == null ) { throw new ArgumentException( "'context' was not created with CreateGenerationContextForCodeGeneration method.", "context" ); } var emittingContext = asAssemblyBuilderCodeGenerationContext.CreateEmittingContext( this.TargetType, this.CollectionTraits, this.BaseClass ); if ( !this.TargetType.GetIsEnum() ) { SerializationTarget targetInfo; this.BuildSerializer( emittingContext, concreteType, itemSchema, out targetInfo ); // Finish type creation, and discard returned ctor. emittingContext.Emitter.CreateObjectConstructor( emittingContext, this, targetInfo, targetInfo.GetCapabilitiesForObject() ); } else { this.BuildEnumSerializer( emittingContext ); // Finish type creation, and discard returned ctor. emittingContext.Emitter.CreateEnumConstructor(); } } #endif // FEATURE_ASMGEN [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )] protected override ILConstruct EmitNewPrivateMethodDelegateExpression( AssemblyBuilderEmittingContext context, MethodDefinition method ) { var delegateType = SerializerBuilderHelper.GetResolvedDelegateType( method.ReturnType, method.ParameterTypes ); return ILConstruct.Instruction( "CreateDelegate", delegateType, false, il => { if ( method.IsStatic ) { il.EmitLdnull(); } else { il.EmitLdargThis(); } // OK this should not be ldvirtftn because target is private. il.EmitLdftn( method.ResolveRuntimeMethod() ); // call extern .ctor(Object, void*) il.EmitNewobj( delegateType.GetConstructors().Single() ); } ); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprPercentilesPesoEstatura class. /// </summary> [Serializable] public partial class AprPercentilesPesoEstaturaCollection : ActiveList<AprPercentilesPesoEstatura, AprPercentilesPesoEstaturaCollection> { public AprPercentilesPesoEstaturaCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprPercentilesPesoEstaturaCollection</returns> public AprPercentilesPesoEstaturaCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprPercentilesPesoEstatura o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the APR_PercentilesPesoEstatura table. /// </summary> [Serializable] public partial class AprPercentilesPesoEstatura : ActiveRecord<AprPercentilesPesoEstatura>, IActiveRecord { #region .ctors and Default Settings public AprPercentilesPesoEstatura() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprPercentilesPesoEstatura(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprPercentilesPesoEstatura(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprPercentilesPesoEstatura(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("APR_PercentilesPesoEstatura", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "Sexo"; colvarSexo.DataType = DbType.Int32; colvarSexo.MaxLength = 0; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = false; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; colvarSexo.DefaultSetting = @""; colvarSexo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarEstatura = new TableSchema.TableColumn(schema); colvarEstatura.ColumnName = "Estatura"; colvarEstatura.DataType = DbType.Decimal; colvarEstatura.MaxLength = 0; colvarEstatura.AutoIncrement = false; colvarEstatura.IsNullable = false; colvarEstatura.IsPrimaryKey = false; colvarEstatura.IsForeignKey = false; colvarEstatura.IsReadOnly = false; colvarEstatura.DefaultSetting = @""; colvarEstatura.ForeignKeyTableName = ""; schema.Columns.Add(colvarEstatura); TableSchema.TableColumn colvarP1 = new TableSchema.TableColumn(schema); colvarP1.ColumnName = "P1"; colvarP1.DataType = DbType.Decimal; colvarP1.MaxLength = 0; colvarP1.AutoIncrement = false; colvarP1.IsNullable = false; colvarP1.IsPrimaryKey = false; colvarP1.IsForeignKey = false; colvarP1.IsReadOnly = false; colvarP1.DefaultSetting = @""; colvarP1.ForeignKeyTableName = ""; schema.Columns.Add(colvarP1); TableSchema.TableColumn colvarP3 = new TableSchema.TableColumn(schema); colvarP3.ColumnName = "P3"; colvarP3.DataType = DbType.Decimal; colvarP3.MaxLength = 0; colvarP3.AutoIncrement = false; colvarP3.IsNullable = false; colvarP3.IsPrimaryKey = false; colvarP3.IsForeignKey = false; colvarP3.IsReadOnly = false; colvarP3.DefaultSetting = @""; colvarP3.ForeignKeyTableName = ""; schema.Columns.Add(colvarP3); TableSchema.TableColumn colvarP15 = new TableSchema.TableColumn(schema); colvarP15.ColumnName = "P15"; colvarP15.DataType = DbType.Decimal; colvarP15.MaxLength = 0; colvarP15.AutoIncrement = false; colvarP15.IsNullable = false; colvarP15.IsPrimaryKey = false; colvarP15.IsForeignKey = false; colvarP15.IsReadOnly = false; colvarP15.DefaultSetting = @""; colvarP15.ForeignKeyTableName = ""; schema.Columns.Add(colvarP15); TableSchema.TableColumn colvarP50 = new TableSchema.TableColumn(schema); colvarP50.ColumnName = "P50"; colvarP50.DataType = DbType.Decimal; colvarP50.MaxLength = 0; colvarP50.AutoIncrement = false; colvarP50.IsNullable = false; colvarP50.IsPrimaryKey = false; colvarP50.IsForeignKey = false; colvarP50.IsReadOnly = false; colvarP50.DefaultSetting = @""; colvarP50.ForeignKeyTableName = ""; schema.Columns.Add(colvarP50); TableSchema.TableColumn colvarP85 = new TableSchema.TableColumn(schema); colvarP85.ColumnName = "P85"; colvarP85.DataType = DbType.Decimal; colvarP85.MaxLength = 0; colvarP85.AutoIncrement = false; colvarP85.IsNullable = false; colvarP85.IsPrimaryKey = false; colvarP85.IsForeignKey = false; colvarP85.IsReadOnly = false; colvarP85.DefaultSetting = @""; colvarP85.ForeignKeyTableName = ""; schema.Columns.Add(colvarP85); TableSchema.TableColumn colvarP97 = new TableSchema.TableColumn(schema); colvarP97.ColumnName = "P97"; colvarP97.DataType = DbType.Decimal; colvarP97.MaxLength = 0; colvarP97.AutoIncrement = false; colvarP97.IsNullable = false; colvarP97.IsPrimaryKey = false; colvarP97.IsForeignKey = false; colvarP97.IsReadOnly = false; colvarP97.DefaultSetting = @""; colvarP97.ForeignKeyTableName = ""; schema.Columns.Add(colvarP97); TableSchema.TableColumn colvarP99 = new TableSchema.TableColumn(schema); colvarP99.ColumnName = "P99"; colvarP99.DataType = DbType.Decimal; colvarP99.MaxLength = 0; colvarP99.AutoIncrement = false; colvarP99.IsNullable = false; colvarP99.IsPrimaryKey = false; colvarP99.IsForeignKey = false; colvarP99.IsReadOnly = false; colvarP99.DefaultSetting = @""; colvarP99.ForeignKeyTableName = ""; schema.Columns.Add(colvarP99); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_PercentilesPesoEstatura",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Sexo")] [Bindable(true)] public int Sexo { get { return GetColumnValue<int>(Columns.Sexo); } set { SetColumnValue(Columns.Sexo, value); } } [XmlAttribute("Estatura")] [Bindable(true)] public decimal Estatura { get { return GetColumnValue<decimal>(Columns.Estatura); } set { SetColumnValue(Columns.Estatura, value); } } [XmlAttribute("P1")] [Bindable(true)] public decimal P1 { get { return GetColumnValue<decimal>(Columns.P1); } set { SetColumnValue(Columns.P1, value); } } [XmlAttribute("P3")] [Bindable(true)] public decimal P3 { get { return GetColumnValue<decimal>(Columns.P3); } set { SetColumnValue(Columns.P3, value); } } [XmlAttribute("P15")] [Bindable(true)] public decimal P15 { get { return GetColumnValue<decimal>(Columns.P15); } set { SetColumnValue(Columns.P15, value); } } [XmlAttribute("P50")] [Bindable(true)] public decimal P50 { get { return GetColumnValue<decimal>(Columns.P50); } set { SetColumnValue(Columns.P50, value); } } [XmlAttribute("P85")] [Bindable(true)] public decimal P85 { get { return GetColumnValue<decimal>(Columns.P85); } set { SetColumnValue(Columns.P85, value); } } [XmlAttribute("P97")] [Bindable(true)] public decimal P97 { get { return GetColumnValue<decimal>(Columns.P97); } set { SetColumnValue(Columns.P97, value); } } [XmlAttribute("P99")] [Bindable(true)] public decimal P99 { get { return GetColumnValue<decimal>(Columns.P99); } set { SetColumnValue(Columns.P99, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varSexo,decimal varEstatura,decimal varP1,decimal varP3,decimal varP15,decimal varP50,decimal varP85,decimal varP97,decimal varP99) { AprPercentilesPesoEstatura item = new AprPercentilesPesoEstatura(); item.Sexo = varSexo; item.Estatura = varEstatura; item.P1 = varP1; item.P3 = varP3; item.P15 = varP15; item.P50 = varP50; item.P85 = varP85; item.P97 = varP97; item.P99 = varP99; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,int varSexo,decimal varEstatura,decimal varP1,decimal varP3,decimal varP15,decimal varP50,decimal varP85,decimal varP97,decimal varP99) { AprPercentilesPesoEstatura item = new AprPercentilesPesoEstatura(); item.Id = varId; item.Sexo = varSexo; item.Estatura = varEstatura; item.P1 = varP1; item.P3 = varP3; item.P15 = varP15; item.P50 = varP50; item.P85 = varP85; item.P97 = varP97; item.P99 = varP99; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn SexoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn EstaturaColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn P1Column { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn P3Column { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn P15Column { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn P50Column { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn P85Column { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn P97Column { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn P99Column { get { return Schema.Columns[9]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string Sexo = @"Sexo"; public static string Estatura = @"Estatura"; public static string P1 = @"P1"; public static string P3 = @"P3"; public static string P15 = @"P15"; public static string P50 = @"P50"; public static string P85 = @"P85"; public static string P97 = @"P97"; public static string P99 = @"P99"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework.Skinning; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Layout; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.ApplicationFramework.Preferences; using OpenLiveWriter.PostEditor.WordCount; using System.IO; using OpenLiveWriter.PostEditor.JumpList; namespace OpenLiveWriter.PostEditor { public class PostEditorPreferencesPanel : PreferencesPanel { /// <summary> /// Required designer variable. /// </summary> private Container components = null; private GroupBox groupBoxPublishing; private CheckBox checkBoxViewWeblog; private PostEditorPreferences _postEditorPreferences; private System.Windows.Forms.CheckBox checkBoxCloseWindow; private System.Windows.Forms.GroupBox groupBoxPostWindows; private System.Windows.Forms.RadioButton radioButtonOpenNewWindowIfDirty; private System.Windows.Forms.RadioButton radioButtonUseSameWindow; private System.Windows.Forms.RadioButton radioButtonOpenNewWindow; private System.Windows.Forms.CheckBox checkBoxCategoryReminder; private System.Windows.Forms.CheckBox checkBoxTagReminder; private System.Windows.Forms.CheckBox checkBoxTitleReminder; private System.Windows.Forms.CheckBox checkBoxAutoSaveDrafts; private System.Windows.Forms.GroupBox groupBoxGeneral; private System.Windows.Forms.CheckBox checkBoxWordCount; private System.Windows.Forms.GroupBox groupBoxWeblogPostsFolder; private System.Windows.Forms.TextBox textBoxWeblogPostsFolder; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.Button buttonBrowserDialog; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel; private WordCountPreferences _wordCountPreferences; private string _originalFolder = string.Empty; public PostEditorPreferencesPanel() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); if (!DesignMode) { this.groupBoxPostWindows.Text = Res.Get(StringId.PostEditorPrefPostWindows); this.groupBoxPublishing.Text = Res.Get(StringId.PostEditorPrefPublishing); checkBoxTagReminder.Text = Res.Get(StringId.PostEditorPrefRemind); checkBoxCategoryReminder.Text = Res.Get(StringId.PostEditorPrefRemindCat); checkBoxCloseWindow.Text = Res.Get(StringId.PostEditorPrefClose); checkBoxViewWeblog.Text = Res.Get(StringId.PostEditorPrefView); radioButtonOpenNewWindowIfDirty.Text = Res.Get(StringId.PostEditorPrefUnsave); radioButtonUseSameWindow.Text = Res.Get(StringId.PostEditorPrefSingle); radioButtonOpenNewWindow.Text = Res.Get(StringId.PostEditorPrefNew); checkBoxTitleReminder.Text = Res.Get(StringId.PostEditorPrefTitle); groupBoxGeneral.Text = Res.Get(StringId.PostEditorPrefGeneral); checkBoxAutoSaveDrafts.Text = Res.Get(StringId.PostEditorPrefAuto); checkBoxWordCount.Text = Res.Get(StringId.ShowRealTimeWordCount); PanelName = Res.Get(StringId.PostEditorPrefName); this.groupBoxWeblogPostsFolder.Text = Res.Get(StringId.PostEditorPrefPostLocation); } PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.PreferencesOther.png"); _postEditorPreferences = PostEditorPreferences.Instance; _postEditorPreferences.PreferencesModified += _writerPreferences_PreferencesModified; switch (_postEditorPreferences.PostWindowBehavior) { case PostWindowBehavior.UseSameWindow: radioButtonUseSameWindow.Checked = true; break; case PostWindowBehavior.OpenNewWindow: radioButtonOpenNewWindow.Checked = true; break; case PostWindowBehavior.OpenNewWindowIfDirty: this.radioButtonOpenNewWindowIfDirty.Checked = true; break; } checkBoxViewWeblog.Checked = _postEditorPreferences.ViewPostAfterPublish; checkBoxCloseWindow.Checked = _postEditorPreferences.CloseWindowOnPublish; checkBoxTitleReminder.Checked = _postEditorPreferences.TitleReminder; checkBoxCategoryReminder.Checked = _postEditorPreferences.CategoryReminder; checkBoxTagReminder.Checked = _postEditorPreferences.TagReminder; textBoxWeblogPostsFolder.Text = _postEditorPreferences.WeblogPostsFolder; _originalFolder = _postEditorPreferences.WeblogPostsFolder; textBoxWeblogPostsFolder.TextChanged += TextBoxWeblogPostsFolder_TextChanged; buttonBrowserDialog.MouseClick += ButtonBrowserDialog_MouseClick; checkBoxAutoSaveDrafts.Checked = _postEditorPreferences.AutoSaveDrafts; checkBoxAutoSaveDrafts.CheckedChanged += new EventHandler(checkBoxAutoSaveDrafts_CheckedChanged); _wordCountPreferences = new WordCountPreferences(); _wordCountPreferences.PreferencesModified += _wordCountPreferences_PreferencesModified; checkBoxWordCount.Checked = _wordCountPreferences.EnableRealTimeWordCount; checkBoxWordCount.CheckedChanged += new EventHandler(checkBoxWordCount_CheckedChanged); radioButtonUseSameWindow.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged); radioButtonOpenNewWindow.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged); radioButtonOpenNewWindowIfDirty.CheckedChanged += new EventHandler(radioButtonPostWindowBehavior_CheckedChanged); checkBoxViewWeblog.CheckedChanged += new EventHandler(checkBoxViewWeblog_CheckedChanged); checkBoxCloseWindow.CheckedChanged += new EventHandler(checkBoxCloseWindow_CheckedChanged); checkBoxTitleReminder.CheckedChanged += new EventHandler(checkBoxTitleReminder_CheckedChanged); checkBoxCategoryReminder.CheckedChanged += new EventHandler(checkBoxCategoryReminder_CheckedChanged); checkBoxTagReminder.CheckedChanged += new EventHandler(checkBoxTagReminder_CheckedChanged); } private void ButtonBrowserDialog_MouseClick(object sender, MouseEventArgs e) { folderBrowserDialog.SelectedPath = textBoxWeblogPostsFolder.Text; DialogResult result = folderBrowserDialog.ShowDialog(); if (result == DialogResult.OK) { textBoxWeblogPostsFolder.Text = folderBrowserDialog.SelectedPath; } } private bool _layedOut = false; protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (!DesignMode && !_layedOut) { LayoutHelper.FixupGroupBox(this.groupBoxPostWindows); LayoutHelper.FixupGroupBox(this.groupBoxPublishing); LayoutHelper.FixupGroupBox(this.groupBoxGeneral); LayoutHelper.FixupGroupBox(this.groupBoxWeblogPostsFolder); LayoutHelper.NaturalizeHeightAndDistribute(8, groupBoxPostWindows, groupBoxPublishing, groupBoxGeneral, groupBoxWeblogPostsFolder); _layedOut = true; } } public override void Save() { string destinationRecentPosts = Path.Combine(_postEditorPreferences.WeblogPostsFolder + "\\Recent Posts"); string destinationDrafts = Path.Combine(_postEditorPreferences.WeblogPostsFolder + "\\Drafts"); Directory.CreateDirectory(destinationRecentPosts); Directory.CreateDirectory(destinationDrafts); _postEditorPreferences.SaveWebLogPostFolder(); if (string.Compare(_originalFolder, _postEditorPreferences.WeblogPostsFolder, true, CultureInfo.CurrentUICulture) != 0) { string message = "You have updated the default location for your blog posts, would you like to move any existing posts?"; string caption = "Move existing posts"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; result = MessageBox.Show(message, caption, buttons); if (result == DialogResult.Yes) { MovePosts(Path.Combine(_originalFolder + @"\\Recent Posts\\"), destinationRecentPosts); MovePosts(Path.Combine(_originalFolder + @"\\Drafts\\"), destinationDrafts); PostEditorForm frm = Application.OpenForms?[0] as PostEditorForm; if (frm != null) { PostEditorMainControl ctrl = frm.Controls?[0] as PostEditorMainControl; if (ctrl != null) { ctrl.FirePostListChangedEvent(); } } } } if (_postEditorPreferences.IsModified()) _postEditorPreferences.Save(); if (_wordCountPreferences.IsModified()) _wordCountPreferences.Save(); _originalFolder = _postEditorPreferences.WeblogPostsFolder; } private void checkBoxViewWeblog_CheckedChanged(object sender, EventArgs e) { _postEditorPreferences.ViewPostAfterPublish = checkBoxViewWeblog.Checked; } private void radioButtonPostWindowBehavior_CheckedChanged(object sender, EventArgs e) { if (radioButtonUseSameWindow.Checked) _postEditorPreferences.PostWindowBehavior = PostWindowBehavior.UseSameWindow; else if (radioButtonOpenNewWindow.Checked) _postEditorPreferences.PostWindowBehavior = PostWindowBehavior.OpenNewWindow; else if (radioButtonOpenNewWindowIfDirty.Checked) _postEditorPreferences.PostWindowBehavior = PostWindowBehavior.OpenNewWindowIfDirty; } private void checkBoxCloseWindow_CheckedChanged(object sender, EventArgs e) { UpdateClosePreferences(); } private void UpdateClosePreferences() { _postEditorPreferences.CloseWindowOnPublish = checkBoxCloseWindow.Checked; } private void _writerPreferences_PreferencesModified(object sender, EventArgs e) { OnModified(EventArgs.Empty); } private void checkBoxTitleReminder_CheckedChanged(object sender, EventArgs e) { _postEditorPreferences.TitleReminder = checkBoxTitleReminder.Checked; } private void checkBoxCategoryReminder_CheckedChanged(object sender, EventArgs e) { _postEditorPreferences.CategoryReminder = checkBoxCategoryReminder.Checked; } private void checkBoxTagReminder_CheckedChanged(object sender, EventArgs e) { _postEditorPreferences.TagReminder = checkBoxTagReminder.Checked; } private void checkBoxAutoSaveDrafts_CheckedChanged(object sender, EventArgs e) { _postEditorPreferences.AutoSaveDrafts = checkBoxAutoSaveDrafts.Checked; } void _wordCountPreferences_PreferencesModified(object sender, EventArgs e) { OnModified(EventArgs.Empty); } void checkBoxWordCount_CheckedChanged(object sender, EventArgs e) { _wordCountPreferences.EnableRealTimeWordCount = checkBoxWordCount.Checked; } private void TextBoxWeblogPostsFolder_TextChanged(object sender, EventArgs e) { _postEditorPreferences.WeblogPostsFolder = textBoxWeblogPostsFolder.Text; } private void MovePosts(string sourceFolder, string destinationFolder) { string[] files = System.IO.Directory.GetFiles(sourceFolder); foreach (string s in files) { string fileName = Path.GetFileName(s); string destFile = Path.Combine(destinationFolder, fileName); MoveFile(s, destFile); } } private void MoveFile(string sourcefile, string destinationfile) { if (File.Exists(destinationfile)) { string newdestfilename = Path.GetDirectoryName(destinationfile) + @"\" + Path.GetFileNameWithoutExtension(destinationfile) + "_Copy" + Path.GetExtension(destinationfile); MoveFile(sourcefile, newdestfilename); } else { File.Move(sourcefile, destinationfile); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { _postEditorPreferences.PreferencesModified -= new EventHandler(_writerPreferences_PreferencesModified); if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBoxPublishing = new System.Windows.Forms.GroupBox(); this.checkBoxTitleReminder = new System.Windows.Forms.CheckBox(); this.checkBoxTagReminder = new System.Windows.Forms.CheckBox(); this.checkBoxCategoryReminder = new System.Windows.Forms.CheckBox(); this.checkBoxCloseWindow = new System.Windows.Forms.CheckBox(); this.checkBoxViewWeblog = new System.Windows.Forms.CheckBox(); this.groupBoxPostWindows = new System.Windows.Forms.GroupBox(); this.radioButtonOpenNewWindowIfDirty = new System.Windows.Forms.RadioButton(); this.radioButtonUseSameWindow = new System.Windows.Forms.RadioButton(); this.radioButtonOpenNewWindow = new System.Windows.Forms.RadioButton(); this.groupBoxGeneral = new System.Windows.Forms.GroupBox(); this.checkBoxAutoSaveDrafts = new System.Windows.Forms.CheckBox(); this.checkBoxWordCount = new System.Windows.Forms.CheckBox(); this.groupBoxWeblogPostsFolder = new System.Windows.Forms.GroupBox(); this.textBoxWeblogPostsFolder = new TextBox(); this.folderBrowserDialog = new FolderBrowserDialog(); this.buttonBrowserDialog = new Button(); this.flowLayoutPanel = new FlowLayoutPanel(); this.flowLayoutPanel.SuspendLayout(); this.groupBoxPublishing.SuspendLayout(); this.groupBoxPostWindows.SuspendLayout(); this.groupBoxGeneral.SuspendLayout(); this.groupBoxWeblogPostsFolder.SuspendLayout(); this.SuspendLayout(); // // groupBoxPublishing // this.groupBoxPublishing.Controls.Add(this.checkBoxTitleReminder); this.groupBoxPublishing.Controls.Add(this.checkBoxTagReminder); this.groupBoxPublishing.Controls.Add(this.checkBoxCategoryReminder); this.groupBoxPublishing.Controls.Add(this.checkBoxCloseWindow); this.groupBoxPublishing.Controls.Add(this.checkBoxViewWeblog); this.groupBoxPublishing.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxPublishing.Location = new System.Drawing.Point(8, 154); this.groupBoxPublishing.Name = "groupBoxPublishing"; this.groupBoxPublishing.Size = new System.Drawing.Size(345, 174); this.groupBoxPublishing.TabIndex = 2; this.groupBoxPublishing.TabStop = false; this.groupBoxPublishing.Text = "Publishing"; // // checkBoxTitleReminder // this.checkBoxTitleReminder.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxTitleReminder.Location = new System.Drawing.Point(16, 93); this.checkBoxTitleReminder.Name = "checkBoxTitleReminder"; this.checkBoxTitleReminder.Size = new System.Drawing.Size(312, 21); this.checkBoxTitleReminder.TabIndex = 3; this.checkBoxTitleReminder.Text = "&Remind me to specify a title before publishing"; this.checkBoxTitleReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // checkBoxTagReminder // this.checkBoxTagReminder.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxTagReminder.Location = new System.Drawing.Point(16, 135); this.checkBoxTagReminder.Name = "checkBoxTagReminder"; this.checkBoxTagReminder.Size = new System.Drawing.Size(312, 21); this.checkBoxTagReminder.TabIndex = 5; this.checkBoxTagReminder.Text = "Remind me to add &tags before publishing"; this.checkBoxTagReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // checkBoxCategoryReminder // this.checkBoxCategoryReminder.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxCategoryReminder.Location = new System.Drawing.Point(16, 114); this.checkBoxCategoryReminder.Name = "checkBoxCategoryReminder"; this.checkBoxCategoryReminder.Size = new System.Drawing.Size(312, 21); this.checkBoxCategoryReminder.TabIndex = 4; this.checkBoxCategoryReminder.Text = "Remind me to add &categories before publishing"; this.checkBoxCategoryReminder.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // checkBoxCloseWindow // this.checkBoxCloseWindow.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxCloseWindow.Location = new System.Drawing.Point(16, 42); this.checkBoxCloseWindow.Name = "checkBoxCloseWindow"; this.checkBoxCloseWindow.Size = new System.Drawing.Size(312, 24); this.checkBoxCloseWindow.TabIndex = 1; this.checkBoxCloseWindow.Text = "Close &window after publishing: "; this.checkBoxCloseWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // checkBoxViewWeblog // this.checkBoxViewWeblog.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxViewWeblog.Location = new System.Drawing.Point(16, 21); this.checkBoxViewWeblog.Name = "checkBoxViewWeblog"; this.checkBoxViewWeblog.Size = new System.Drawing.Size(312, 21); this.checkBoxViewWeblog.TabIndex = 0; // Modified on 2/19/2016 by @kathweaver to resolve Issue #377 this.checkBoxViewWeblog.Text = "&View blog after publishing"; this.checkBoxViewWeblog.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // groupBoxPostWindows // this.groupBoxPostWindows.Controls.Add(this.radioButtonOpenNewWindowIfDirty); this.groupBoxPostWindows.Controls.Add(this.radioButtonUseSameWindow); this.groupBoxPostWindows.Controls.Add(this.radioButtonOpenNewWindow); this.groupBoxPostWindows.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxPostWindows.Location = new System.Drawing.Point(8, 32); this.groupBoxPostWindows.Name = "groupBoxPostWindows"; this.groupBoxPostWindows.Size = new System.Drawing.Size(345, 116); this.groupBoxPostWindows.TabIndex = 1; this.groupBoxPostWindows.TabStop = false; this.groupBoxPostWindows.Text = "Post Windows"; // // radioButtonOpenNewWindowIfDirty // this.radioButtonOpenNewWindowIfDirty.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonOpenNewWindowIfDirty.Location = new System.Drawing.Point(16, 69); this.radioButtonOpenNewWindowIfDirty.Name = "radioButtonOpenNewWindowIfDirty"; this.radioButtonOpenNewWindowIfDirty.Size = new System.Drawing.Size(312, 30); this.radioButtonOpenNewWindowIfDirty.TabIndex = 2; this.radioButtonOpenNewWindowIfDirty.Text = "Open a new window &only when there are unsaved changes to the current post"; this.radioButtonOpenNewWindowIfDirty.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // radioButtonUseSameWindow // this.radioButtonUseSameWindow.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonUseSameWindow.Location = new System.Drawing.Point(16, 21); this.radioButtonUseSameWindow.Name = "radioButtonUseSameWindow"; this.radioButtonUseSameWindow.Size = new System.Drawing.Size(312, 24); this.radioButtonUseSameWindow.TabIndex = 0; this.radioButtonUseSameWindow.Text = "Use a &single window for editing all posts"; this.radioButtonUseSameWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // radioButtonOpenNewWindow // this.radioButtonOpenNewWindow.FlatStyle = System.Windows.Forms.FlatStyle.System; this.radioButtonOpenNewWindow.Location = new System.Drawing.Point(16, 44); this.radioButtonOpenNewWindow.Name = "radioButtonOpenNewWindow"; this.radioButtonOpenNewWindow.Size = new System.Drawing.Size(312, 24); this.radioButtonOpenNewWindow.TabIndex = 1; this.radioButtonOpenNewWindow.Text = "Open a new window for &each post"; this.radioButtonOpenNewWindow.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // groupBoxGeneral // this.groupBoxGeneral.Controls.Add(this.checkBoxAutoSaveDrafts); this.groupBoxGeneral.Controls.Add(this.checkBoxWordCount); this.groupBoxGeneral.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxGeneral.Location = new System.Drawing.Point(8, 154); this.groupBoxGeneral.Name = "groupBoxGeneral"; this.groupBoxGeneral.Size = new System.Drawing.Size(345, 174); this.groupBoxGeneral.TabIndex = 3; this.groupBoxGeneral.TabStop = false; this.groupBoxGeneral.Text = "General"; // // checkBoxAutoSaveDrafts // this.checkBoxAutoSaveDrafts.CheckAlign = System.Drawing.ContentAlignment.TopLeft; this.checkBoxAutoSaveDrafts.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxAutoSaveDrafts.Location = new System.Drawing.Point(16, 21); this.checkBoxAutoSaveDrafts.Name = "checkBoxAutoSaveDrafts"; this.checkBoxAutoSaveDrafts.Size = new System.Drawing.Size(312, 18); this.checkBoxAutoSaveDrafts.TabIndex = 0; this.checkBoxAutoSaveDrafts.Text = "Automatically save &drafts every:"; this.checkBoxAutoSaveDrafts.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // checkBoxWordCount // this.checkBoxWordCount.CheckAlign = System.Drawing.ContentAlignment.TopLeft; this.checkBoxWordCount.FlatStyle = System.Windows.Forms.FlatStyle.System; this.checkBoxWordCount.Location = new System.Drawing.Point(16, 156); this.checkBoxWordCount.Name = "checkBoxWordCount"; this.checkBoxWordCount.Size = new System.Drawing.Size(312, 18); this.checkBoxWordCount.TabIndex = 1; this.checkBoxWordCount.Text = "Show real time &word count in status bar"; this.checkBoxWordCount.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.checkBoxWordCount.UseVisualStyleBackColor = true; // // textBoxWeblogPostsFolder // this.textBoxWeblogPostsFolder.Name = "textBoxWeblogPostsFolder"; this.textBoxWeblogPostsFolder.Size = new System.Drawing.Size(314, 22); this.textBoxWeblogPostsFolder.AutoSize = false; this.textBoxWeblogPostsFolder.TabIndex = 1; this.textBoxWeblogPostsFolder.Text = "Show default post save location"; this.textBoxWeblogPostsFolder.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.textBoxWeblogPostsFolder.Location = new System.Drawing.Point(16, 21); this.textBoxWeblogPostsFolder.BorderStyle = BorderStyle.FixedSingle; this.textBoxWeblogPostsFolder.Font = Res.DefaultFont; // // buttonBrowserDialog // this.buttonBrowserDialog.Name = "buttonBrowserDialog"; this.buttonBrowserDialog.Text = Res.Get(StringId.PostEditorPrefBrowseFolder); this.buttonBrowserDialog.TabIndex = 2; this.buttonBrowserDialog.Location = new System.Drawing.Point(16, 32); this.buttonBrowserDialog.Size = new System.Drawing.Size(70, 22); this.buttonBrowserDialog.Font = Res.DefaultFont; this.buttonBrowserDialog.AutoSize = false; // // FolderBrowserDialog // this.folderBrowserDialog.Description = "Select the directory that you want to use as the default"; this.folderBrowserDialog.ShowNewFolderButton = true; this.folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer; // // groupBoxWeblogPostsFolder // this.groupBoxWeblogPostsFolder.Controls.Add(this.textBoxWeblogPostsFolder); this.groupBoxWeblogPostsFolder.Controls.Add(this.buttonBrowserDialog); this.groupBoxWeblogPostsFolder.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxWeblogPostsFolder.Location = new System.Drawing.Point(8, 154); this.groupBoxWeblogPostsFolder.Name = "groupBoxWeblogPostsFolder"; this.groupBoxWeblogPostsFolder.Size = new System.Drawing.Size(345, 45); this.groupBoxWeblogPostsFolder.TabIndex = 4; this.groupBoxWeblogPostsFolder.TabStop = false; this.groupBoxWeblogPostsFolder.Text = "Post Folder Location"; // // PostEditorPreferencesPanel // this.AccessibleName = "Preferences"; this.Controls.Add(this.groupBoxPostWindows); this.Controls.Add(this.groupBoxPublishing); this.Controls.Add(this.groupBoxGeneral); this.Controls.Add(this.groupBoxWeblogPostsFolder); this.Name = "PostEditorPreferencesPanel"; this.PanelName = "Preferences"; this.Size = new System.Drawing.Size(370, 521); this.Controls.SetChildIndex(this.groupBoxPublishing, 0); this.Controls.SetChildIndex(this.groupBoxPostWindows, 0); this.Controls.SetChildIndex(this.groupBoxGeneral, 0); this.Controls.SetChildIndex(this.groupBoxWeblogPostsFolder, 0); this.groupBoxPublishing.ResumeLayout(false); this.groupBoxPostWindows.ResumeLayout(false); this.groupBoxGeneral.ResumeLayout(false); this.flowLayoutPanel.ResumeLayout(false); this.groupBoxWeblogPostsFolder.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="_OverlappedAsyncResult.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.Sockets { using System; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32; // // BaseOverlappedAsyncResult - used to enable async Socket operation // such as the BeginSend, BeginSendTo, BeginReceive, BeginReceiveFrom, BeginSendFile, // BeginAccept, calls. // internal class BaseOverlappedAsyncResult : ContextAwareResult { // // internal class members // private SafeOverlappedFree m_UnmanagedBlob; // Handle for global memory. private AutoResetEvent m_OverlappedEvent; private int m_CleanupCount; private bool m_DisableOverlapped; private bool m_UseOverlappedIO; private GCHandle [] m_GCHandles; private OverlappedCache m_Cache; // // The WinNT Completion Port callback. // #if SOCKETTHREADPOOL internal #else private #endif unsafe static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(CompletionPortCallback); // // Constructor. We take in the socket that's creating us, the caller's // state object, and callback. We save the socket and state, and allocate // an event for the WaitHandle. // internal BaseOverlappedAsyncResult(Socket socket, Object asyncState, AsyncCallback asyncCallback) : base(socket, asyncState, asyncCallback) { // // BeginAccept() allocates and returns an AcceptOverlappedAsyncResult that will call // this constructor. // m_UseOverlappedIO = Socket.UseOverlappedIO || socket.UseOnlyOverlappedIO; if (m_UseOverlappedIO) { // // since the binding between the event handle and the callback // happens after the IO was queued to the OS, there is no ---- // condition and the Cleanup code can be called at most once. // m_CleanupCount = 1; } else { // // since the binding between the event handle and the callback // has already happened there is a race condition and so the // Cleanup code can be called more than once and at most twice. // m_CleanupCount = 2; } } // // Constructor. We take in the socket that's creating us, and turn off Async // We save the socket and state. internal BaseOverlappedAsyncResult(Socket socket) : base(socket, null, null) { m_CleanupCount = 1; m_DisableOverlapped = true; } //PostCompletion returns the result object to be set before the user's callback is invoked. internal virtual object PostCompletion(int numBytes) { return numBytes; } // // SetUnmanagedStructures - // // This needs to be called for overlapped IO to function properly. // // Fills in Overlapped Structures used in an Async Overlapped Winsock call // these calls are outside the runtime and are unmanaged code, so we need // to prepare specific structures and ints that lie in unmanaged memory // since the Overlapped calls can be Async // internal void SetUnmanagedStructures(object objectsToPin) { if (!m_DisableOverlapped) { // Casting to object[] is very expensive. Only do it once. object[] objectsToPinArray = null; bool triedCastingToArray = false; bool useCache = false; if (m_Cache != null) { if (objectsToPin == null && m_Cache.PinnedObjects == null) { useCache = true; } else if (m_Cache.PinnedObjects != null) { if (m_Cache.PinnedObjectsArray == null) { if (objectsToPin == m_Cache.PinnedObjects) { useCache = true; } } else if (objectsToPin != null) { triedCastingToArray = true; objectsToPinArray = objectsToPin as object[]; if (objectsToPinArray != null && objectsToPinArray.Length == 0) { objectsToPinArray = null; } if (objectsToPinArray != null && objectsToPinArray.Length == m_Cache.PinnedObjectsArray.Length) { useCache = true; for (int i = 0; i < objectsToPinArray.Length; i++) { if (objectsToPinArray[i] != m_Cache.PinnedObjectsArray[i]) { useCache = false; break; } } } } } } if (!useCache && m_Cache != null) { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::SetUnmanagedStructures() Cache miss - freeing cache."); m_Cache.Free(); m_Cache = null; } Socket s = (Socket) AsyncObject; if (m_UseOverlappedIO) { // // we're using overlapped IO, allocate an overlapped structure // consider using a static growing pool of allocated unmanaged memory. // GlobalLog.Assert(m_UnmanagedBlob == null, "BaseOverlappedAsyncResult#{0}::SetUnmanagedStructures()|Unmanaged blob already allocated. (Called twice?)", ValidationHelper.HashString(this)); m_UnmanagedBlob = SafeOverlappedFree.Alloc(s.SafeHandle); PinUnmanagedObjects(objectsToPin); // // create the event handle // m_OverlappedEvent = new AutoResetEvent(false); // // fill in the overlapped structure with the event handle. // Marshal.WriteIntPtr( m_UnmanagedBlob.DangerousGetHandle(), Win32.OverlappedhEventOffset, m_OverlappedEvent.SafeWaitHandle.DangerousGetHandle() ); } else { // // Bind the Win32 Socket Handle to the ThreadPool // s.BindToCompletionPort(); if (m_Cache == null) { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() Creating new overlapped cache."); if (objectsToPinArray != null) { m_Cache = new OverlappedCache(new Overlapped(), objectsToPinArray, s_IOCallback); } else { m_Cache = new OverlappedCache(new Overlapped(), objectsToPin, s_IOCallback, triedCastingToArray); } } else { GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() Using cached overlapped."); } m_Cache.Overlapped.AsyncResult = this; #if DEBUG m_InitialNativeOverlapped = m_Cache.NativeOverlapped; #endif GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(this) + "::EnableCompletionPort() overlapped:" + ValidationHelper.HashString(m_Cache.Overlapped) + " NativeOverlapped = " + m_Cache.NativeOverlapped.DangerousGetHandle().ToString("x")); } } } /* // Consider removing. internal void SetUnmanagedStructures(object objectsToPin, ref OverlappedCache overlappedCache) { SetupCache(ref overlappedCache); SetUnmanagedStructures(objectsToPin); } */ protected void SetupCache(ref OverlappedCache overlappedCache) { #if !NO_OVERLAPPED_CACHE GlobalLog.Assert(m_Cache == null, "BaseOverlappedAsyncResult#{0}::SetUnmanagedStructures()|Cache already set up. (Called twice?)", ValidationHelper.HashString(this)); if (!m_UseOverlappedIO && !m_DisableOverlapped) { m_Cache = overlappedCache == null ? null : Interlocked.Exchange<OverlappedCache>(ref overlappedCache, null); // Need to hold on to the unmanaged structures until the cache is extracted. m_CleanupCount++; } #endif } // // This method pins unmanaged objects for Win9x and systems where completion ports are not found // protected void PinUnmanagedObjects(object objectsToPin) { if (m_Cache != null) { m_Cache.Free(); m_Cache = null; } if (objectsToPin != null) { if (objectsToPin.GetType() == typeof(object[])) { object [] objectsArray = (object []) objectsToPin; m_GCHandles = new GCHandle[objectsArray.Length]; for (int i=0; i<objectsArray.Length; i++) { if (objectsArray[i] != null) { m_GCHandles[i] = GCHandle.Alloc(objectsArray[i], GCHandleType.Pinned); } } } else { m_GCHandles = new GCHandle[1]; m_GCHandles[0] = GCHandle.Alloc(objectsToPin, GCHandleType.Pinned); } } } internal void ExtractCache(ref OverlappedCache overlappedCache) { #if !NO_OVERLAPPED_CACHE if (!m_UseOverlappedIO && !m_DisableOverlapped) { // Have to be super careful. Socket isn't synchronized, so if a user calls End() twice, we don't want to // copy out this cache twice which could result in posting an IO with a deleted NativeOverlapped. OverlappedCache cache = m_Cache == null ? null : Interlocked.Exchange<OverlappedCache>(ref m_Cache, null); if (cache != null) { // If overlappedCache is null, just slap it in there. There's a chance for a conflict, // resulting in a OverlappedCache getting finalized, but it's better than // the interlocked. This won't be an issue in most 'correct' cases. if (overlappedCache == null) { overlappedCache = cache; } else { OverlappedCache oldCache = Interlocked.Exchange<OverlappedCache>(ref overlappedCache, cache); if (oldCache != null) { oldCache.Free(); } } } ReleaseUnmanagedStructures(); } #endif } private unsafe static void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.CompletionPort); using (GlobalLog.SetThreadKind(ThreadKinds.System)) { #if TRAVE try { #endif #endif // // Create an Overlapped object out of the native pointer we're provided with. // (this will NOT free the unmanaged memory in the native overlapped structure) // Overlapped callbackOverlapped = Overlapped.Unpack(nativeOverlapped); BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)callbackOverlapped.AsyncResult; Debug.Assert((IntPtr)nativeOverlapped == asyncResult.m_Cache.NativeOverlapped.DangerousGetHandle(), "Handle mismatch"); // The AsyncResult must be cleared before the callback is called (i.e. before ExtractCache is called). // Not doing so leads to a leak where the pinned cached OverlappedData continues to point to the async result object, // which points to the Socket (as well as user data), which points to the OverlappedCache, preventing the OverlappedCache // finalizer from freeing the pinned OverlappedData. callbackOverlapped.AsyncResult = null; object returnObject = null; GlobalLog.Assert(!asyncResult.InternalPeekCompleted, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|asyncResult.IsCompleted", ValidationHelper.HashString(asyncResult)); GlobalLog.Print("BaseOverlappedAsyncResult#" + ValidationHelper.HashString(asyncResult) + "::CompletionPortCallback" + " errorCode:" + errorCode.ToString() + " numBytes:" + numBytes.ToString() + " pOverlapped:" + ((int)nativeOverlapped).ToString()); // // complete the IO and invoke the user's callback // SocketError socketError = (SocketError)errorCode; if (socketError != SocketError.Success && socketError != SocketError.OperationAborted) { // There are cases where passed errorCode does not reflect the details of the underlined socket error. // "So as of today, the key is the difference between WSAECONNRESET and ConnectionAborted, // .e.g remote party or network causing the connection reset or something on the local host (e.g. closesocket // or receiving data after shutdown (SD_RECV)). With Winsock/TCP stack rewrite in longhorn, there may // be other differences as well." Socket socket = asyncResult.AsyncObject as Socket; if (socket == null) { socketError = SocketError.NotSocket; } else if (socket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // // The Async IO completed with a failure. // here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error. // SocketFlags ignore; bool success = UnsafeNclNativeMethods.OSSOCK.WSAGetOverlappedResult( socket.SafeHandle, asyncResult.m_Cache.NativeOverlapped, out numBytes, false, out ignore); if (!success) { socketError = (SocketError)Marshal.GetLastWin32Error(); GlobalLog.Assert(socketError != 0, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|socketError:0 numBytes:{1}", ValidationHelper.HashString(asyncResult), numBytes); } GlobalLog.Assert(!success, "BaseOverlappedAsyncResult#{0}::CompletionPortCallback()|Unexpectedly succeeded. errorCode:{1} numBytes:{2}", ValidationHelper.HashString(asyncResult), errorCode, numBytes); } // CleanedUp check above does not always work since this code is subject to race conditions catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } } } asyncResult.ErrorCode = (int)socketError; returnObject = asyncResult.PostCompletion((int)numBytes); asyncResult.ReleaseUnmanagedStructures(); asyncResult.InvokeCallback(returnObject); #if DEBUG #if TRAVE } catch(Exception exception) { if (!NclUtilities.IsFatal(exception)){ GlobalLog.Assert("BaseOverlappedAsyncResult::CompletionPortCallback", "Exception in completion callback type:" + exception.GetType().ToString() + " message:" + exception.Message); } throw; } #endif } #endif } // // The overlapped function called (either by the thread pool or the socket) // when IO completes. (only called on Win9x) // private void OverlappedCallback(object stateObject, bool Signaled) { #if DEBUG // GlobalLog.SetThreadSource(ThreadKinds.Worker); Because of change 1077887, need logic to determine thread type here. using (GlobalLog.SetThreadKind(ThreadKinds.System)) { #endif BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)stateObject; GlobalLog.Assert(!asyncResult.InternalPeekCompleted, "AcceptOverlappedAsyncResult#{0}::OverlappedCallback()|asyncResult.IsCompleted", ValidationHelper.HashString(asyncResult)); // // the IO completed asynchronously, see if there was a failure the Internal // field in the Overlapped structure will be non zero. to optimize the non // error case, we look at it without calling WSAGetOverlappedResult(). // uint errorCode = (uint)Marshal.ReadInt32(IntPtrHelper.Add(asyncResult.m_UnmanagedBlob.DangerousGetHandle(), Win32.OverlappedInternalOffset)); uint numBytes = errorCode!=0 ? unchecked((uint)-1) : (uint)Marshal.ReadInt32(IntPtrHelper.Add(asyncResult.m_UnmanagedBlob.DangerousGetHandle(), Win32.OverlappedInternalHighOffset)); // // this will release the unmanaged pin handles and unmanaged overlapped ptr // asyncResult.ErrorCode = (int)errorCode; object returnObject = asyncResult.PostCompletion((int)numBytes); asyncResult.ReleaseUnmanagedStructures(); asyncResult.InvokeCallback(returnObject); #if DEBUG } #endif } #if DEBUG private SocketError m_SavedErrorCode = unchecked((SocketError) 0xDEADBEEF); private SafeNativeOverlapped m_InitialNativeOverlapped; private SafeNativeOverlapped m_IntermediateNativeOverlapped; #endif // // This method is called after an asynchronous call is made for the user, // it checks and acts accordingly if the IO: // 1) completed synchronously. // 2) was pended. // 3) failed. // internal unsafe SocketError CheckAsyncCallOverlappedResult(SocketError errorCode) { #if DEBUG m_SavedErrorCode = errorCode; #endif // // Check if the Async IO call: // 1) was pended. // 2) completed synchronously. // 3) failed. // if (m_UseOverlappedIO) { // // we're using overlapped IO under Win9x (or NT with registry setting overriding // completion port usage) // switch (errorCode) { case 0: case SocketError.IOPending: // // the Async IO call was pended: // Queue our event to the thread pool. // GlobalLog.Assert(m_UnmanagedBlob != null, "BaseOverlappedAsyncResult#{0}::CheckAsyncCallOverlappedResult()|Unmanaged blob isn't allocated.", ValidationHelper.HashString(this)); ThreadPool.UnsafeRegisterWaitForSingleObject( m_OverlappedEvent, new WaitOrTimerCallback(OverlappedCallback), this, -1, true ); // // we're done, completion will be asynchronous // in the callback. return // return SocketError.Success; default: // // the Async IO call failed: // set the number of bytes transferred to -1 (error) // ErrorCode = (int)errorCode; Result = -1; ReleaseUnmanagedStructures(); break; } } else { #if DEBUG OverlappedCache cache = m_Cache; if (cache != null) { SafeNativeOverlapped nativeOverlappedPtr = cache.NativeOverlapped; if (nativeOverlappedPtr != null) m_IntermediateNativeOverlapped = nativeOverlappedPtr; } #endif // // We're using completion ports under WinNT. Release one reference on the structures for // the main thread. // ReleaseUnmanagedStructures(); switch (errorCode) { // // ignore cases in which a completion packet will be queued: // we'll deal with this IO in the callback // case 0: case SocketError.IOPending: // // ignore, do nothing // return SocketError.Success; // // in the remaining cases a completion packet will NOT be queued: // we'll have to call the callback explicitly signaling an error // default: // // call the callback with error code // ErrorCode = (int)errorCode; Result = -1; // The AsyncResult must be cleared since the callback isn't going to be called. // Not doing so leads to a leak where the pinned cached OverlappedData continues to point to the async result object, // which points to the Socket (as well as user data) and to the OverlappedCache, preventing the OverlappedCache // finalizer from freeing the pinned OverlappedData. if (m_Cache != null) { // Could be null only if SetUnmanagedStructures weren't called. m_Cache.Overlapped.AsyncResult = null; } ReleaseUnmanagedStructures(); // Additional release for the completion that won't happen. break; } } return errorCode; } // // The following property returns the Win32 unsafe pointer to // whichever Overlapped structure we're using for IO. // internal SafeHandle OverlappedHandle { get { if (m_UseOverlappedIO) { // // on Win9x we allocate our own overlapped structure // and we use a win32 event for IO completion // return the native pointer to unmanaged memory // return (m_UnmanagedBlob == null || m_UnmanagedBlob.IsInvalid)? SafeOverlappedFree.Zero : m_UnmanagedBlob; } else { // // on WinNT we need to use (due to the current implementation) // an Overlapped object in order to bind the socket to the // ThreadPool's completion port, so return the native handle // return m_Cache == null ? SafeNativeOverlapped.Zero : m_Cache.NativeOverlapped; } } } // OverlappedHandle private void ReleaseUnmanagedStructures() { if (Interlocked.Decrement(ref m_CleanupCount) == 0) { ForceReleaseUnmanagedStructures(); } } protected override void Cleanup() { base.Cleanup(); // If we get all the way to here and it's still not cleaned up... if (m_CleanupCount > 0 && Interlocked.Exchange(ref m_CleanupCount, 0) > 0) { ForceReleaseUnmanagedStructures(); } } // Utility cleanup routine. Frees the overlapped structure. // This should be overriden to free pinned and unmanaged memory in the subclass. // It needs to also be invoked from the subclass. protected virtual void ForceReleaseUnmanagedStructures() { // // free the unmanaged memory if allocated. // ReleaseGCHandles(); GC.SuppressFinalize(this); if (m_UnmanagedBlob != null && !m_UnmanagedBlob.IsInvalid) { m_UnmanagedBlob.Close(true); m_UnmanagedBlob = null; } // This is interlocked because Cleanup() can be called simultaneously with ExtractCache(). OverlappedCache.InterlockedFree(ref m_Cache); if (m_OverlappedEvent != null) { m_OverlappedEvent.Close(); m_OverlappedEvent = null; } } ~BaseOverlappedAsyncResult() { ReleaseGCHandles(); } private void ReleaseGCHandles() { GCHandle[] gcHandles = m_GCHandles; if (gcHandles != null) { for (int i = 0; i < gcHandles.Length; i++) { if (gcHandles[i].IsAllocated) { gcHandles[i].Free(); } } } } } internal class OverlappedCache { internal Overlapped m_Overlapped; internal SafeNativeOverlapped m_NativeOverlapped; internal object m_PinnedObjects; internal object[] m_PinnedObjectsArray; internal OverlappedCache(Overlapped overlapped, object[] pinnedObjectsArray, IOCompletionCallback callback) { m_Overlapped = overlapped; m_PinnedObjects = pinnedObjectsArray; m_PinnedObjectsArray = pinnedObjectsArray; unsafe { m_NativeOverlapped = new SafeNativeOverlapped(overlapped.UnsafePack(callback, pinnedObjectsArray)); } } internal OverlappedCache(Overlapped overlapped, object pinnedObjects, IOCompletionCallback callback, bool alreadyTriedCast) { m_Overlapped = overlapped; m_PinnedObjects = pinnedObjects; m_PinnedObjectsArray = alreadyTriedCast ? null : NclConstants.EmptyObjectArray; unsafe { m_NativeOverlapped = new SafeNativeOverlapped(overlapped.UnsafePack(callback, pinnedObjects)); } } internal Overlapped Overlapped { get { return m_Overlapped; } } internal SafeNativeOverlapped NativeOverlapped { get { return m_NativeOverlapped; } } internal object PinnedObjects { get { return m_PinnedObjects; } } internal object[] PinnedObjectsArray { get { object[] pinnedObjectsArray = m_PinnedObjectsArray; if (pinnedObjectsArray != null && pinnedObjectsArray.Length == 0) { pinnedObjectsArray = m_PinnedObjects as object[]; if (pinnedObjectsArray != null && pinnedObjectsArray.Length == 0) { m_PinnedObjectsArray = null; } else { m_PinnedObjectsArray = pinnedObjectsArray; } } return m_PinnedObjectsArray; } } // This must only be called once. internal void Free() { InternalFree(); GC.SuppressFinalize(this); } private void InternalFree() { m_Overlapped = null; m_PinnedObjects = null; if (m_NativeOverlapped != null) { if (!m_NativeOverlapped.IsInvalid) { m_NativeOverlapped.Dispose(); } m_NativeOverlapped = null; } } internal static void InterlockedFree(ref OverlappedCache overlappedCache) { OverlappedCache cache = overlappedCache == null ? null : Interlocked.Exchange<OverlappedCache>(ref overlappedCache, null); if (cache != null) { cache.Free(); } } ~OverlappedCache() { if (!NclUtilities.HasShutdownStarted) { InternalFree(); } } } }
// 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.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxFactsService : ISyntaxFactsService { public bool IsAwaitKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.AwaitKeyword); } public bool IsIdentifier(SyntaxToken token) { return token.IsKind(SyntaxKind.IdentifierToken); } public bool IsGlobalNamespaceKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.GlobalKeyword); } public bool IsVerbatimIdentifier(SyntaxToken token) { return token.IsVerbatimIdentifier(); } public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords } public bool IsContextualKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsContextualKeyword(kind); } public bool IsPreprocessorKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsPreprocessorKeyword(kind); } public bool IsHashToken(SyntaxToken token) { return (SyntaxKind)token.RawKind == SyntaxKind.HashToken; } public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInNonUserCode(position, cancellationToken); } public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective(SyntaxNode node) { return node is DirectiveTriviaSyntax; } public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info) { var lineDirective = node as LineDirectiveTriviaSyntax; if (lineDirective != null) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default(ExternalSourceInfo); return false; } public bool IsRightSideOfQualifiedName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsMemberAccessExpressionName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsMemberAccessExpressionName(); } public bool IsObjectCreationExpressionType(SyntaxNode node) { return node.IsParentKind(SyntaxKind.ObjectCreationExpression) && ((ObjectCreationExpressionSyntax)node.Parent).Type == node; } public bool IsAttributeName(SyntaxNode node) { return SyntaxFacts.IsAttributeName(node); } public bool IsInvocationExpression(SyntaxNode node) { return node is InvocationExpressionSyntax; } public bool IsAnonymousFunction(SyntaxNode node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsGenericName(SyntaxNode node) { return node is GenericNameSyntax; } public bool IsNamedParameter(SyntaxNode node) { return node.CheckParent<NameColonSyntax>(p => p.Name == node); } public bool IsSkippedTokensTrivia(SyntaxNode node) { return node is SkippedTokensTriviaSyntax; } public bool HasIncompleteParentMember(SyntaxNode node) { return node.IsParentKind(SyntaxKind.IncompleteMember); } public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName) { var csharpGenericName = genericName as GenericNameSyntax; return csharpGenericName != null ? csharpGenericName.Identifier : default(SyntaxToken); } public bool IsCaseSensitive { get { return true; } } public bool IsUsingDirectiveName(SyntaxNode node) { return node.IsParentKind(SyntaxKind.UsingDirective) && ((UsingDirectiveSyntax)node.Parent).Name == node; } public bool IsForEachStatement(SyntaxNode node) { return node is ForEachStatementSyntax; } public bool IsLockStatement(SyntaxNode node) { return node is LockStatementSyntax; } public bool IsUsingStatement(SyntaxNode node) { return node is UsingStatementSyntax; } public bool IsThisConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsBaseConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsQueryExpression(SyntaxNode node) { return node is QueryExpressionSyntax; } public bool IsPredefinedType(SyntaxToken token) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None; } public bool IsPredefinedType(SyntaxToken token, PredefinedType type) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType == type; } public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private PredefinedType GetPredefinedType(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.BoolKeyword: return PredefinedType.Boolean; case SyntaxKind.ByteKeyword: return PredefinedType.Byte; case SyntaxKind.SByteKeyword: return PredefinedType.SByte; case SyntaxKind.IntKeyword: return PredefinedType.Int32; case SyntaxKind.UIntKeyword: return PredefinedType.UInt32; case SyntaxKind.ShortKeyword: return PredefinedType.Int16; case SyntaxKind.UShortKeyword: return PredefinedType.UInt16; case SyntaxKind.LongKeyword: return PredefinedType.Int64; case SyntaxKind.ULongKeyword: return PredefinedType.UInt64; case SyntaxKind.FloatKeyword: return PredefinedType.Single; case SyntaxKind.DoubleKeyword: return PredefinedType.Double; case SyntaxKind.DecimalKeyword: return PredefinedType.Decimal; case SyntaxKind.StringKeyword: return PredefinedType.String; case SyntaxKind.CharKeyword: return PredefinedType.Char; case SyntaxKind.ObjectKeyword: return PredefinedType.Object; case SyntaxKind.VoidKeyword: return PredefinedType.Void; default: return PredefinedType.None; } } public bool IsPredefinedOperator(SyntaxToken token) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None; } public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op; } public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) { return SyntaxFacts.GetText((SyntaxKind)kind); } public bool IsIdentifierStartCharacter(char c) { return SyntaxFacts.IsIdentifierStartCharacter(c); } public bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } public bool IsIdentifierEscapeCharacter(char c) { return c == '@'; } public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) { return false; } public bool IsStartOfUnicodeEscapeSequence(char c) { return c == '\\'; } public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; } return false; } public bool IsStringLiteral(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); } public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration)) { declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration)) { declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent) { var typedParent = parent as ExpressionSyntax; if (typedParent != null) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } return false; } public bool IsMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression; } public bool IsConditionalMemberAccessExpression(SyntaxNode node) { return node is ConditionalAccessExpressionSyntax; } public bool IsPointerMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression; } public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { name = null; arity = 0; var simpleName = node as SimpleNameSyntax; if (simpleName != null) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node) { if (node.IsKind(SyntaxKind.MemberBindingExpression)) { if (node.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent); } if (node.IsParentKind(SyntaxKind.InvocationExpression) && node.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent.Parent); } } return (node as MemberAccessExpressionSyntax)?.Expression; } public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node) { return (node as ConditionalAccessExpressionSyntax)?.Expression; } public bool IsInStaticContext(SyntaxNode node) { return node.IsInStaticContext(); } public bool IsInNamespaceOrTypeContext(SyntaxNode node) { return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); } public SyntaxNode GetExpressionOfArgument(SyntaxNode node) { return ((ArgumentSyntax)node).Expression; } public RefKind GetRefKindOfArgument(SyntaxNode node) { return (node as ArgumentSyntax).GetRefKind(); } public bool IsInConstantContext(SyntaxNode node) { return (node as ExpressionSyntax).IsInConstantContext(); } public bool IsInConstructor(SyntaxNode node) { return node.GetAncestor<ConstructorDeclarationSyntax>() != null; } public bool IsUnsafeContext(SyntaxNode node) { return node.IsUnsafeContext(); } public SyntaxNode GetNameOfAttribute(SyntaxNode node) { return ((AttributeSyntax)node).Name; } public bool IsAttribute(SyntaxNode node) { return node is AttributeSyntax; } public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsParentKind(SyntaxKind.NameEquals) && identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument); } public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node) { throw ExceptionUtilities.Unreachable; } public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsObjectCreationExpression(SyntaxNode node) { return node is ObjectCreationExpressionSyntax; } public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsLeftSideOfAssignExpression() && identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression); } public bool IsElementAccessExpression(SyntaxNode node) { return node.Kind() == SyntaxKind.ElementAccessExpression; } public SyntaxNode ConvertToSingleLine(SyntaxNode node) { return node.ConvertToSingleLine(); } public SyntaxToken ToIdentifierToken(string name) { return name.ToIdentifierToken(); } public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia) { return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia); } public bool IsIndexerMemberCRef(SyntaxNode node) { return node.Kind() == SyntaxKind.IndexerMemberCref; } public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { if ((node.Kind() != SyntaxKind.GlobalStatement) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember(SyntaxNode node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers(SyntaxNode node) { return node is NamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span); return true; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ctorDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, ctorDecl.Identifier.Span, parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span); return true; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span); return true; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span); return true; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span); return true; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span); return true; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span); return true; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, method.Identifier.Span, parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0), typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Property, property.Identifier.Span); return true; case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span); return true; case SyntaxKind.VariableDeclarator: // could either be part of a field declaration or an event field declaration var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText, GetContainerDisplayName(fieldDeclaration.Parent), GetFullyQualifiedContainerName(fieldDeclaration.Parent), kind, variableDeclarator.Identifier.Span); return true; } break; } declaredSymbolInfo = default(DeclaredSymbolInfo); return false; } private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier) { if (explicitInterfaceSpecifier == null) { return identifier; } else { var builder = new StringBuilder(); ExpandTypeName(explicitInterfaceSpecifier.Name, builder); builder.Append('.'); builder.Append(identifier); return builder.ToString(); } } private static void ExpandTypeName(TypeSyntax type, StringBuilder builder) { switch (type.Kind()) { case SyntaxKind.AliasQualifiedName: var alias = (AliasQualifiedNameSyntax)type; builder.Append(alias.Alias.Identifier.ValueText); break; case SyntaxKind.ArrayType: var array = (ArrayTypeSyntax)type; ExpandTypeName(array.ElementType, builder); for (int i = 0; i < array.RankSpecifiers.Count; i++) { var rankSpecifier = array.RankSpecifiers[i]; builder.Append(rankSpecifier.OpenBracketToken.Text); for (int j = 1; j < rankSpecifier.Sizes.Count; j++) { builder.Append(','); } builder.Append(rankSpecifier.CloseBracketToken.Text); } break; case SyntaxKind.GenericName: var generic = (GenericNameSyntax)type; builder.Append(generic.Identifier.ValueText); if (generic.TypeArgumentList != null) { var arguments = generic.TypeArgumentList.Arguments; builder.Append(generic.TypeArgumentList.LessThanToken.Text); for (int i = 0; i < arguments.Count; i++) { if (i != 0) { builder.Append(','); } ExpandTypeName(arguments[i], builder); } builder.Append(generic.TypeArgumentList.GreaterThanToken.Text); } break; case SyntaxKind.IdentifierName: var identifierName = (IdentifierNameSyntax)type; builder.Append(identifierName.Identifier.ValueText); break; case SyntaxKind.NullableType: var nullable = (NullableTypeSyntax)type; ExpandTypeName(nullable.ElementType, builder); builder.Append(nullable.QuestionToken.Text); break; case SyntaxKind.OmittedTypeArgument: // do nothing since it was omitted, but don't reach the default block break; case SyntaxKind.PointerType: var pointer = (PointerTypeSyntax)type; ExpandTypeName(pointer.ElementType, builder); builder.Append(pointer.AsteriskToken.Text); break; case SyntaxKind.PredefinedType: var predefined = (PredefinedTypeSyntax)type; builder.Append(predefined.Keyword.Text); break; case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)type; ExpandTypeName(qualified.Left, builder); builder.Append(qualified.DotToken.Text); ExpandTypeName(qualified.Right, builder); break; default: Debug.Assert(false, "Unexpected type syntax " + type.Kind()); break; } } private string GetContainerDisplayName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters); } private string GetFullyQualifiedContainerName(SyntaxNode node) { return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces); } private const string dotToken = "."; public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string>.GetInstance(); // containing type(s) var parent = (SyntaxNode)node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.NamespaceDeclaration: return GetName(((NamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string name = null; var memberDeclaration = node as MemberDeclarationSyntax; if (memberDeclaration != null) { var nameToken = memberDeclaration.GetNameToken(); if (nameToken == default(SyntaxToken)) { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration); name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } } else { var fieldDeclarator = node as VariableDeclaratorSyntax; if (fieldDeclarator != null) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default(SyntaxToken)) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (int i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root) { var list = new List<SyntaxNode>(); AppendMethodLevelMembers(root, list); return list; } private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { AppendMethodLevelMembers(member, list); continue; } if (IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default(TextSpan); } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default(TextSpan); } // TODO: currently we only support method for now var method = member as BaseMethodDeclarationSyntax; if (method != null) { if (method.Body == null) { return default(TextSpan); } return GetBlockBodySpan(method.Body); } return default(TextSpan); } public bool ContainsInMemberBody(SyntaxNode node, TextSpan span) { var constructor = node as ConstructorDeclarationSyntax; if (constructor != null) { return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); } var method = node as BaseMethodDeclarationSyntax; if (method != null) { return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); } var property = node as BasePropertyDeclarationSyntax; if (property != null) { return property.AccessorList != null && property.AccessorList.Span.Contains(span); } var @enum = node as EnumMemberDeclarationSyntax; if (@enum != null) { return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); } var field = node as BaseFieldDeclarationSyntax; if (field != null) { return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private TextSpan GetBlockBodySpan(BlockSyntax body) { return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); } public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node) { Contract.Requires(root.SyntaxTree == node.SyntaxTree); int currentId = 0; SyntaxNode currentNode; Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode)); Contract.ThrowIfFalse(currentId >= 0); CheckMemberId(root, node, currentId); return currentId; } public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId) { int currentId = 0; SyntaxNode currentNode; if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode)) { return null; } Contract.ThrowIfNull(currentNode); CheckMemberId(root, currentNode, memberId); return currentNode; } private bool TryGetMethodLevelMember( SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode)) { return true; } continue; } if (IsMethodLevelMember(member)) { if (predicate(member, currentId)) { currentNode = member; return true; } currentId++; } } currentNode = null; return false; } [Conditional("DEBUG")] private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId) { var list = GetMethodLevelMembers(root); var index = list.IndexOf(node); Contract.ThrowIfFalse(index == memberId); } public SyntaxNode GetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. var qualifiedName = parent as QualifiedNameSyntax; if (qualifiedName != null) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. var aliasQualifiedName = parent as AliasQualifiedNameSyntax; if (aliasQualifiedName != null) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. var objectCreation = parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. var name = parent as NameSyntax; if (name == null) { break; } node = parent; } return node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken) { var compilationUnit = root as CompilationUnitSyntax; if (compilationUnit == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); var constructor = member as ConstructorDeclarationSyntax; if (constructor != null) { constructors.Add(constructor); continue; } var @namespace = member as NamespaceDeclarationSyntax; if (@namespace != null) { AppendConstructors(@namespace.Members, constructors, cancellationToken); } var @class = member as ClassDeclarationSyntax; if (@class != null) { AppendConstructors(@class.Members, constructors, cancellationToken); } var @struct = member as StructDeclarationSyntax; if (@struct != null) { AppendConstructors(@struct.Members, constructors, cancellationToken); } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.Item1; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default(SyntaxToken); return false; } } }
using UnityEngine; using XInputDotNetPure; namespace XboxCtrlrInput { // ================= Enumerations ==================== // /// <summary> /// List of enumerated identifiers for Xbox controllers. /// </summary> public enum XboxController { All = 0, First = 1, Second = 2, Third = 3, Fourth = 4 } /// <summary> /// List of enumerated identifiers for Xbox buttons. /// </summary> public enum XboxButton { A, B, X, Y, Start, Back, LeftStick, RightStick, LeftBumper, RightBumper, DPadUp, DPadDown, DPadLeft, DPadRight } /// <summary> /// List of enumerated identifiers for Xbox D-Pad directions. /// </summary> public enum XboxDPad { Up, Down, Left, Right } /// <summary> /// List of enumerated identifiers for Xbox axis. /// </summary> public enum XboxAxis { LeftStickX, LeftStickY, RightStickX, RightStickY, LeftTrigger, RightTrigger } // ================ Classes =================== // public static class XCI { // ------------ Public Methods --------------- // // >>> For Buttons <<< // /// <summary> /// Returns <c>true</c> if the specified button is held down by any controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> public static bool GetButton(XboxButton button) { if (button.IsDPad()) return GetDPad(button.ToDPad()); if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); if( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) { return true; } } else { string btnCode = DetermineButtonCode(button, 0); if(Input.GetKey(btnCode)) { return true; } } return false; } /// <summary> /// Returns <c>true</c> if the specified button is held down by a specified controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the button. /// </param> public static bool GetButton(XboxButton button, XboxController controller) { if (button.IsDPad()) return GetDPad(button.ToDPad(), controller); if (controller == XboxController.All) return GetButton(button); int controllerNumber = (int)controller; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); if( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) { return true; } } else { string btnCode = DetermineButtonCode(button, controllerNumber); if(Input.GetKey(btnCode)) { return true; } } return false; } /// <summary> /// Returns <c>true</c> at the frame the specified button starts to press down (not held down) by any controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> public static bool GetButtonDown(XboxButton button) { if (button.IsDPad()) return GetDPadDown(button.ToDPad()); if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); GamePadState ctrlrStatePrev = XInputGetSingleStatePrev(); if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) && ( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Released ) ) { return true; } } else { string btnCode = DetermineButtonCode(button, 0); if(Input.GetKeyDown(btnCode)) { return true; } } return false; } /// <summary> /// Returns <c>true</c> at the frame the specified button starts to press down (not held down) by a specified controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the button. /// </param> public static bool GetButtonDown(XboxButton button, XboxController controller) { if (button.IsDPad()) return GetDPadDown(button.ToDPad(), controller); if (controller == XboxController.All) return GetButtonDown(button); int controllerNumber = (int)controller; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber); if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) && ( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Released ) ) { return true; } } else { string btnCode = DetermineButtonCode(button, controllerNumber); if(Input.GetKeyDown(btnCode)) { return true; } } return false; } /// <summary> /// Returns <c>true</c> at the frame the specified button is released by any controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> public static bool GetButtonUp(XboxButton button) { if (button.IsDPad()) return GetDPadUp(button.ToDPad()); if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); GamePadState ctrlrStatePrev = XInputGetSingleStatePrev(); if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Released ) && ( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Pressed ) ) { return true; } } else { string btnCode = DetermineButtonCode(button, 0); if(Input.GetKeyUp(btnCode)) { return true; } } return false; } /// <summary> /// Returns <c>true</c> at the frame the specified button is released by a specified controller. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the button. /// </param> public static bool GetButtonUp(XboxButton button, XboxController controller) { if (button.IsDPad()) return GetDPadUp(button.ToDPad(), controller); if (controller == XboxController.All) return GetButtonUp(button); int controllerNumber = (int)controller; if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber); if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Released ) && ( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Pressed ) ) { return true; } } else { string btnCode = DetermineButtonCode(button, controllerNumber); if(Input.GetKeyUp(btnCode)) { return true; } } return false; } // >>> For D-Pad <<< // /// <summary> /// Returns <c>true</c> if the specified D-Pad direction is pressed down by any controller. /// </summary> /// <param name='padDirection'> /// An identifier for the specified D-Pad direction to be tested. /// </param> public static bool GetDPad(XboxDPad padDirection) { bool r = false; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); if( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, 0); r = Input.GetKey(inputCode); } else if(OnLinux() && IsControllerWireless()) { inputCode = DetermineDPadWirelessLinux(padDirection, 0); r = Input.GetKey(inputCode); } else // Windows Web Player and Linux Wired Controller { inputCode = DetermineDPad(padDirection, 0); switch(padDirection) { case XboxDPad.Up: r = Input.GetAxis(inputCode) > 0; break; case XboxDPad.Down: r = Input.GetAxis(inputCode) < 0; break; case XboxDPad.Left: r = Input.GetAxis(inputCode) < 0; break; case XboxDPad.Right: r = Input.GetAxis(inputCode) > 0; break; default: r = false; break; } } } return r; } /// <summary> /// Returns <c>true</c> if the specified D-Pad direction is pressed down by a specified controller. /// </summary> /// <param name='padDirection'> /// An identifier for the specified D-Pad direction to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the D-Pad. /// </param> public static bool GetDPad(XboxDPad padDirection, XboxController controller) { if (controller == XboxController.All) return GetDPad(padDirection); int controllerNumber = (int)controller; bool r = false; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); if( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, controllerNumber); r = Input.GetKey(inputCode); } else if(OnLinux() && IsControllerWireless(controllerNumber)) { inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber); r = Input.GetKey(inputCode); } else // Windows Web Player and Linux Wired Controller { inputCode = DetermineDPad(padDirection, controllerNumber); switch(padDirection) { case XboxDPad.Up: r = Input.GetAxis(inputCode) > 0; break; case XboxDPad.Down: r = Input.GetAxis(inputCode) < 0; break; case XboxDPad.Left: r = Input.GetAxis(inputCode) < 0; break; case XboxDPad.Right: r = Input.GetAxis(inputCode) > 0; break; default: r = false; break; } } } return r; } // From @ProjectEnder /// <summary> /// Returns <c>true</c> at the frame the specified button is released. /// Does NOT work on Linux with Wired Controllers. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> public static bool GetDPadUp(XboxDPad padDirection) { bool r = false; if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); GamePadState ctrlrStatePrev = XInputGetSingleStatePrev(); if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Released ) && ( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Pressed ) ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, 0); r = Input.GetKeyUp(inputCode); } else if(OnLinux() && IsControllerWireless()) { inputCode = DetermineDPadWirelessLinux(padDirection, 0); r = Input.GetKeyUp(inputCode); } else { //Place Holder for Wired Linux r = false; } } return r; } // From @ProjectEnder /// <summary> /// Returns <c>true</c> at the frame the specified button is released by a specified controller. /// Does NOT work on Linux with Wired Controllers. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the button. /// </param> public static bool GetDPadUp(XboxDPad padDirection, XboxController controller) { if (controller == XboxController.All) return GetDPadUp(padDirection); int controllerNumber = (int)controller; bool r = false; if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber); if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Released ) && ( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Pressed ) ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, controllerNumber); r = Input.GetKeyUp(inputCode); } else if(OnLinux() && IsControllerWireless(controllerNumber)) { inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber); r = Input.GetKeyUp(inputCode); } else { //Place Holder for Wired Linux r = false; } } return r; } // From @ProjectEnder /// <summary> /// Returns <c>true</c> at the frame the specified button is Pressed. /// Does NOT work on Linux with Wired Controllers. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> public static bool GetDPadDown(XboxDPad padDirection) { bool r = false; if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); GamePadState ctrlrStatePrev = XInputGetSingleStatePrev(); if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) && ( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Released ) ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, 0); r = Input.GetKeyDown(inputCode); } else if(OnLinux() && IsControllerWireless()) { inputCode = DetermineDPadWirelessLinux(padDirection, 0); r = Input.GetKeyDown(inputCode); } else { //Place Holder for Wired Linux r = false; } } return r; } // From @ProjectEnder /// <summary> /// Returns <c>true</c> at the frame the specified button is Pressed by a specified controller. /// Does NOT work on Linux with Wired Controllers. /// </summary> /// <param name='button'> /// Identifier for the Xbox button to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the button. /// </param> public static bool GetDPadDown(XboxDPad padDirection, XboxController controller) { if (controller == XboxController.All) return GetDPadDown(padDirection); int controllerNumber = (int)controller; bool r = false; if(OnWindowsNative()) { if(Time.frameCount < 2) { return false; } if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber); if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) && ( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Released ) ) { return true; } } else { string inputCode = ""; if(OnMac()) { inputCode = DetermineDPadMac(padDirection, controllerNumber); r = Input.GetKeyDown(inputCode); } else if(OnLinux() && IsControllerWireless(controllerNumber)) { inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber); r = Input.GetKeyDown(inputCode); } else { //Place Holder for Wired Linux r = false; } } return r; } // >>> For Axis <<< // /// <summary> /// Returns the analog number of the specified axis from any controller. /// </summary> /// <param name='axis'> /// An identifier for the specified Xbox axis to be tested. /// </param> public static float GetAxis(XboxAxis axis) { float r = 0.0f; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger) { r = XInputGetAxisState(ctrlrState.Triggers, axis); } else { r = XInputGetAxisState(ctrlrState.ThumbSticks, axis); } } else { string axisCode = DetermineAxisCode(axis, 0); r = Input.GetAxis(axisCode); r = AdjustAxisValues(r, axis, 0); } return r; } /// <summary> /// Returns the float number of the specified axis from a specified controller. /// </summary> /// <param name='axis'> /// An identifier for the specified Xbox axis to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the axis. /// </param> public static float GetAxis(XboxAxis axis, XboxController controller) { if (controller == XboxController.All) return GetAxis(axis); int controllerNumber = (int)controller; float r = 0.0f; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger) { r = XInputGetAxisState(ctrlrState.Triggers, axis); } else { r = XInputGetAxisState(ctrlrState.ThumbSticks, axis); } } else { string axisCode = DetermineAxisCode(axis, controllerNumber); r = Input.GetAxis(axisCode); r = AdjustAxisValues(r, axis, controllerNumber); } return r; } /// <summary> /// Returns the float number of the specified axis from any controller without Unity's smoothing filter. /// </summary> /// <param name='axis'> /// An identifier for the specified Xbox axis to be tested. /// </param> public static float GetAxisRaw(XboxAxis axis) { float r = 0.0f; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetSingleState(); if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger) { r = XInputGetAxisState(ctrlrState.Triggers, axis); } else { r = XInputGetAxisState(ctrlrState.ThumbSticks, axis); } } else { string axisCode = DetermineAxisCode(axis, 0); r = Input.GetAxisRaw(axisCode); r = AdjustAxisValues(r, axis, 0); } return r; } /// <summary> /// Returns the float number of the specified axis from a specified controller without Unity's smoothing filter. /// </summary> /// <param name='axis'> /// An identifier for the specified Xbox axis to be tested. /// </param> /// <param name='controller'> /// An identifier for the specific controller on which to test the axis. /// </param> public static float GetAxisRaw(XboxAxis axis, XboxController controller) { if (controller == XboxController.All) return GetAxisRaw(axis); int controllerNumber = (int)controller; float r = 0.0f; if(OnWindowsNative()) { if(!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger) { r = XInputGetAxisState(ctrlrState.Triggers, axis); } else { r = XInputGetAxisState(ctrlrState.ThumbSticks, axis); } } else { string axisCode = DetermineAxisCode(axis, controllerNumber); r = Input.GetAxisRaw(axisCode); r = AdjustAxisValues(r, axis, controllerNumber); } return r; } // >>> Other important functions <<< // /// <summary> /// Returns the number of Xbox controllers plugged to the computer. /// </summary> public static int GetNumPluggedCtrlrs() { int r = 0; if(OnWindowsNative()) { if(!xiNumOfCtrlrsQueried || !XInputStillInCurrFrame()) { xiNumOfCtrlrsQueried = true; XInputUpdateAllStates(); } for(int i = 0; i < 4; i++) { if(xInputCtrlrs[i].IsConnected) { r++; } } } else { string[] ctrlrNames = Input.GetJoystickNames(); for(int i = 0; i < ctrlrNames.Length; i++) { if(ctrlrNames[i].Contains("Xbox") || ctrlrNames[i].Contains("XBOX") || ctrlrNames[i].Contains("Microsoft")) { r++; } } } return r; } /// <summary> /// DEBUG function. Log all controller names to Unity's console. /// </summary> public static void DEBUG_LogControllerNames() { string[] cNames = Input.GetJoystickNames(); for(int i = 0; i < cNames.Length; i++) { Debug.Log("Ctrlr " + i.ToString() + ": " + cNames[i]); } } // From @xoorath /// <summary> /// Determines if the controller is plugged in the specified controllerNumber. /// CAUTION: Only works on Windows Native (Desktop and Editor, not Web)! /// </summary> /// <param name="controllerNumber"> /// An identifier for the specific controller on which to test the axis. An int between 1 and 4. /// </param> public static bool IsPluggedIn(int controllerNumber) { if(OnWindowsNative()) { if (!XInputStillInCurrFrame()) { XInputUpdateAllStates(); } GamePadState ctrlrState = XInputGetPaticularState(controllerNumber); return ctrlrState.IsConnected; } // NOT IMPLEMENTED for other platforms return false; } //// // ------------- Private -------------- // //// // ------------ Members --------------- // private static GamePadState[] xInputCtrlrs = new GamePadState[4]; private static GamePadState[] xInputCtrlrsPrev = new GamePadState[4]; private static int xiPrevFrameCount = -1; private static bool xiUpdateAlreadyCalled = false; private static bool xiNumOfCtrlrsQueried = false; // ------------ Methods --------------- // private static bool OnMac() { // All Mac mappings are based off TattieBogle Xbox Controller drivers // http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/OsxDriver // http://wiki.unity3d.com/index.php?title=Xbox360Controller return (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXWebPlayer); } private static bool OnWindows() { return (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer); } private static bool OnWindowsWebPlayer() { return (Application.platform == RuntimePlatform.WindowsWebPlayer); } private static bool OnWindowsNative() { return (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer); } private static bool OnLinux() { // Linux mapping based on observation of mapping from default drivers on Ubuntu 13.04 return Application.platform == RuntimePlatform.LinuxPlayer; } private static bool IsControllerWireless() { // 0 means for any controller return IsControllerWireless(0); } private static bool IsControllerWireless(int ctrlNum) { if (ctrlNum < 0 || ctrlNum > 4) return false; // If 0 is passed in, that assumes that only 1 controller is plugged in. if(ctrlNum == 0) { return ( (string) Input.GetJoystickNames()[0]).Contains("Wireless"); } return ( (string) Input.GetJoystickNames()[ctrlNum-1]).Contains("Wireless"); } private static bool IsControllerNumberValid(int ctrlrNum) { if(ctrlrNum > 0 && ctrlrNum <= 4) { return true; } else { Debug.LogError("XCI.IsControllerNumberValid(): " + "Invalid contoller number! Should be between 1 and 4."); } return false; } private static float RefactorRange(float oldRangeValue, int ctrlrNum, XboxAxis axis) { // HACK: On OS X, Left and right trigger under OSX return 0.5 until touched // Issue #16 on Github: https://github.com/JISyed/Unity-XboxCtrlrInput/issues/16 if(XCI.OnMac()) { if(axis == XboxAxis.LeftTrigger) { switch(ctrlrNum) { case 0: { if(!XCI.XciHandler.Instance.u3dTrigger0LeftIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger0LeftIsTouched = true; } else { return 0.0f; } } break; } case 1: { if(!XCI.XciHandler.Instance.u3dTrigger1LeftIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger1LeftIsTouched = true; } else { return 0.0f; } } break; } case 2: { if(!XCI.XciHandler.Instance.u3dTrigger2LeftIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger2LeftIsTouched = true; } else { return 0.0f; } } break; } case 3: { if(!XCI.XciHandler.Instance.u3dTrigger3LeftIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger3LeftIsTouched = true; } else { return 0.0f; } } break; } case 4: { if(!XCI.XciHandler.Instance.u3dTrigger4LeftIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger4LeftIsTouched = true; } else { return 0.0f; } } break; } default: break; } } else if(axis == XboxAxis.RightTrigger) { switch(ctrlrNum) { case 0: { if(!XCI.XciHandler.Instance.u3dTrigger0RightIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger0RightIsTouched = true; } else { return 0.0f; } } break; } case 1: { if(!XCI.XciHandler.Instance.u3dTrigger1RightIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger1RightIsTouched = true; } else { return 0.0f; } } break; } case 2: { if(!XCI.XciHandler.Instance.u3dTrigger2RightIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger2RightIsTouched = true; } else { return 0.0f; } } break; } case 3: { if(!XCI.XciHandler.Instance.u3dTrigger3RightIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger3RightIsTouched = true; } else { return 0.0f; } } break; } case 4: { if(!XCI.XciHandler.Instance.u3dTrigger4RightIsTouched) { if(oldRangeValue != 0.0f) { XCI.XciHandler.Instance.u3dTrigger4RightIsTouched = true; } else { return 0.0f; } } break; } default: break; } } } // Assumes you want to take a number from -1 to 1 range // And turn it into a number from a 0 to 1 range return ((oldRangeValue + 1.0f) / 2.0f ); } private static string DetermineButtonCode(XboxButton btn, int ctrlrNum) { string r = ""; string sJoyCode = ""; string sKeyCode = ""; bool invalidCode = false; if(ctrlrNum == 0) { sJoyCode = ""; } else { sJoyCode = " " + ctrlrNum.ToString(); } if(OnMac()) { switch(btn) { case XboxButton.A: sKeyCode = "16"; break; case XboxButton.B: sKeyCode = "17"; break; case XboxButton.X: sKeyCode = "18"; break; case XboxButton.Y: sKeyCode = "19"; break; case XboxButton.Start: sKeyCode = "9"; break; case XboxButton.Back: sKeyCode = "10"; break; case XboxButton.LeftStick: sKeyCode = "11"; break; case XboxButton.RightStick: sKeyCode = "12"; break; case XboxButton.LeftBumper: sKeyCode = "13"; break; case XboxButton.RightBumper: sKeyCode = "14"; break; default: invalidCode = true; break; } } else if (OnLinux()) { switch(btn) { case XboxButton.A: sKeyCode = "0"; break; case XboxButton.B: sKeyCode = "1"; break; case XboxButton.X: sKeyCode = "2"; break; case XboxButton.Y: sKeyCode = "3"; break; case XboxButton.Start: sKeyCode = "7"; break; case XboxButton.Back: sKeyCode = "6"; break; case XboxButton.LeftStick: sKeyCode = "9"; break; case XboxButton.RightStick: sKeyCode = "10"; break; case XboxButton.LeftBumper: sKeyCode = "4"; break; case XboxButton.RightBumper: sKeyCode = "5"; break; default: invalidCode = true; break; } } else // Windows Web Player { switch(btn) { case XboxButton.A: sKeyCode = "0"; break; case XboxButton.B: sKeyCode = "1"; break; case XboxButton.X: sKeyCode = "2"; break; case XboxButton.Y: sKeyCode = "3"; break; case XboxButton.Start: sKeyCode = "7"; break; case XboxButton.Back: sKeyCode = "6"; break; case XboxButton.LeftStick: sKeyCode = "8"; break; case XboxButton.RightStick: sKeyCode = "9"; break; case XboxButton.LeftBumper: sKeyCode = "4"; break; case XboxButton.RightBumper: sKeyCode = "5"; break; default: invalidCode = true; break; } } r = "joystick" + sJoyCode + " button " + sKeyCode; if(invalidCode) { r = ""; } return r; } private static string DetermineAxisCode(XboxAxis axs, int ctrlrNum) { string r = ""; string sJoyCode = ctrlrNum.ToString(); string sAxisCode = ""; bool invalidCode = false; if(OnMac()) { switch(axs) { case XboxAxis.LeftStickX: sAxisCode = "X"; break; case XboxAxis.LeftStickY: sAxisCode = "Y"; break; case XboxAxis.RightStickX: sAxisCode = "3"; break; case XboxAxis.RightStickY: sAxisCode = "4"; break; case XboxAxis.LeftTrigger: sAxisCode = "5"; break; case XboxAxis.RightTrigger: sAxisCode = "6"; break; default: invalidCode = true; break; } } else if(OnLinux()) { switch(axs) { case XboxAxis.LeftStickX: sAxisCode = "X"; break; case XboxAxis.LeftStickY: sAxisCode = "Y"; break; case XboxAxis.RightStickX: sAxisCode = "4"; break; case XboxAxis.RightStickY: sAxisCode = "5"; break; case XboxAxis.LeftTrigger: sAxisCode = "3"; break; case XboxAxis.RightTrigger: sAxisCode = "6"; break; default: invalidCode = true; break; } } else // Windows Web Player { switch(axs) { case XboxAxis.LeftStickX: sAxisCode = "X"; break; case XboxAxis.LeftStickY: sAxisCode = "Y"; break; case XboxAxis.RightStickX: sAxisCode = "4"; break; case XboxAxis.RightStickY: sAxisCode = "5"; break; case XboxAxis.LeftTrigger: sAxisCode = "9"; break; case XboxAxis.RightTrigger: sAxisCode = "10"; break; default: invalidCode = true; break; } } r = "XboxAxis" + sAxisCode + "Joy" + sJoyCode; if(invalidCode) { r = ""; } return r; } private static float AdjustAxisValues(float axisValue, XboxAxis axis, int ctrlrNum) { float newAxisValue = axisValue; if(OnMac()) { if(axis == XboxAxis.LeftTrigger) { newAxisValue = -newAxisValue; newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis); } else if(axis == XboxAxis.RightTrigger) { newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis); } else if(axis == XboxAxis.RightStickY) { newAxisValue = -newAxisValue; } } else if(OnLinux()) { if(axis == XboxAxis.RightTrigger) { newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis); } else if(axis == XboxAxis.LeftTrigger) { newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis); } } return newAxisValue; } private static string DetermineDPad(XboxDPad padDir, int ctrlrNum) { string r = ""; string sJoyCode = ctrlrNum.ToString(); string sPadCode = ""; bool invalidCode = false; if(OnLinux()) { switch(padDir) { case XboxDPad.Up: sPadCode = "8"; break; case XboxDPad.Down: sPadCode = "8"; break; case XboxDPad.Left: sPadCode = "7"; break; case XboxDPad.Right: sPadCode = "7"; break; default: invalidCode = true; break; } } else // Windows Web Player { switch(padDir) { case XboxDPad.Up: sPadCode = "7"; break; case XboxDPad.Down: sPadCode = "7"; break; case XboxDPad.Left: sPadCode = "6"; break; case XboxDPad.Right: sPadCode = "6"; break; default: invalidCode = true; break; } } r = "XboxAxis" + sPadCode + "Joy" + sJoyCode; if(invalidCode) { r = ""; } return r; } private static string DetermineDPadMac(XboxDPad padDir, int ctrlrNum) { string r = ""; string sJoyCode = ""; string sPadCode = ""; bool invalidCode = false; if(ctrlrNum == 0) { sJoyCode = ""; } else { sJoyCode = " " + ctrlrNum.ToString(); } switch(padDir) { case XboxDPad.Up: sPadCode = "5"; break; case XboxDPad.Down: sPadCode = "6"; break; case XboxDPad.Left: sPadCode = "7"; break; case XboxDPad.Right: sPadCode = "8"; break; default: invalidCode = true; break; } r = "joystick" + sJoyCode + " button " + sPadCode; if(invalidCode) { r = ""; } return r; } private static string DetermineDPadWirelessLinux(XboxDPad padDir, int ctrlrNum) { string r = ""; string sJoyCode = ""; string sPadCode = ""; bool invalidCode = false; if(ctrlrNum == 0) { sJoyCode = ""; } else { sJoyCode = " " + ctrlrNum.ToString(); } switch(padDir) { case XboxDPad.Up: sPadCode = "13"; break; case XboxDPad.Down: sPadCode = "14"; break; case XboxDPad.Left: sPadCode = "11"; break; case XboxDPad.Right: sPadCode = "12"; break; default: invalidCode = true; break; } r = "joystick" + sJoyCode + " button " + sPadCode; if(invalidCode) { r = ""; } return r; } // ------------- Private XInput Wrappers (for Windows Native player and editor only) -------------- // //>> For updating states << private static void XInputUpdateAllStates() { if(xiUpdateAlreadyCalled) return; for(int i = 0; i < 4; i++) { PlayerIndex plyNum = (PlayerIndex) i; xInputCtrlrsPrev[i] = xInputCtrlrs[i]; xInputCtrlrs[i] = GamePad.GetState(plyNum, GamePadDeadZone.IndependentAxes); } xiUpdateAlreadyCalled = true; } //>> For getting states << private static GamePadState XInputGetSingleState() { return xInputCtrlrs[0]; } private static GamePadState XInputGetPaticularState(int ctrlNum) { if (!IsControllerNumberValid(ctrlNum)) return xInputCtrlrs[0]; return xInputCtrlrs[ctrlNum-1]; } private static GamePadState XInputGetSingleStatePrev() { return xInputCtrlrsPrev[0]; } private static GamePadState XInputGetPaticularStatePrev(int ctrlNum) { if (!IsControllerNumberValid(ctrlNum)) return xInputCtrlrsPrev[0]; return xInputCtrlrsPrev[ctrlNum-1]; } //>> For getting input << private static ButtonState XInputGetButtonState(GamePadButtons xiButtons, XboxButton xciBtn) { ButtonState stateToReturn = ButtonState.Pressed; switch(xciBtn) { case XboxButton.A: stateToReturn = xiButtons.A; break; case XboxButton.B: stateToReturn = xiButtons.B; break; case XboxButton.X: stateToReturn = xiButtons.X; break; case XboxButton.Y: stateToReturn = xiButtons.Y; break; case XboxButton.Start: stateToReturn = xiButtons.Start; break; case XboxButton.Back: stateToReturn = xiButtons.Back; break; case XboxButton.LeftBumper: stateToReturn = xiButtons.LeftShoulder; break; case XboxButton.RightBumper: stateToReturn = xiButtons.RightShoulder; break; case XboxButton.LeftStick: stateToReturn = xiButtons.LeftStick; break; case XboxButton.RightStick: stateToReturn = xiButtons.RightStick; break; } return stateToReturn; } private static ButtonState XInputGetDPadState(GamePadDPad xiDPad, XboxDPad xciDPad) { ButtonState stateToReturn = ButtonState.Released; switch(xciDPad) { case XboxDPad.Up: stateToReturn = xiDPad.Up; break; case XboxDPad.Down: stateToReturn = xiDPad.Down; break; case XboxDPad.Left: stateToReturn = xiDPad.Left; break; case XboxDPad.Right: stateToReturn = xiDPad.Right; break; } return stateToReturn; } private static float XInputGetAxisState(GamePadTriggers xiTriggers, XboxAxis xciAxis) { float stateToReturn = 0.0f; switch(xciAxis) { case XboxAxis.LeftTrigger: stateToReturn = xiTriggers.Left; break; case XboxAxis.RightTrigger: stateToReturn = xiTriggers.Right; break; default: stateToReturn = 0.0f; break; } return stateToReturn; } private static float XInputGetAxisState(GamePadThumbSticks xiThumbSticks, XboxAxis xciAxis) { float stateToReturn = 0.0f; switch(xciAxis) { case XboxAxis.LeftStickX: stateToReturn = xiThumbSticks.Left.X; break; case XboxAxis.LeftStickY: stateToReturn = xiThumbSticks.Left.Y; break; case XboxAxis.RightStickX: stateToReturn = xiThumbSticks.Right.X; break; case XboxAxis.RightStickY: stateToReturn = xiThumbSticks.Right.Y; break; default: stateToReturn = 0.0f; break; } return stateToReturn; } private static bool XInputStillInCurrFrame() { bool r = false; // Get the current frame int currFrame = Time.frameCount; // Are we still in the current frame? if(xiPrevFrameCount == currFrame) { r = true; } else { r = false; xiUpdateAlreadyCalled = false; } // Assign the previous frame count regardless of whether it's the same or not. xiPrevFrameCount = currFrame; return r; } // -------------------------- Handler Script ------------------- // Secret Private Script that does some maintainace work for XCI states. User should not use this script at all. private class XciHandler : MonoBehaviour { private static XciHandler instance = null; public bool u3dTrigger0LeftIsTouched = false; public bool u3dTrigger0RightIsTouched = false; public bool u3dTrigger1LeftIsTouched = false; public bool u3dTrigger1RightIsTouched = false; public bool u3dTrigger2LeftIsTouched = false; public bool u3dTrigger2RightIsTouched = false; public bool u3dTrigger3LeftIsTouched = false; public bool u3dTrigger3RightIsTouched = false; public bool u3dTrigger4LeftIsTouched = false; public bool u3dTrigger4RightIsTouched = false; void Awake() { if(XciHandler.instance != null) { GameObject.Destroy(this.gameObject); } XciHandler.instance = this; // Lives for the life of the game DontDestroyOnLoad(this.gameObject); } void OnLevelWasLoaded(int level) { this.ResetTriggerTouches(); } private void ResetTriggerTouches() { this.u3dTrigger0LeftIsTouched = false; this.u3dTrigger0RightIsTouched = false; this.u3dTrigger1LeftIsTouched = false; this.u3dTrigger1RightIsTouched = false; this.u3dTrigger2LeftIsTouched = false; this.u3dTrigger2RightIsTouched = false; this.u3dTrigger3LeftIsTouched = false; this.u3dTrigger3RightIsTouched = false; this.u3dTrigger4LeftIsTouched = false; this.u3dTrigger4RightIsTouched = false; } public static XciHandler Instance { get { if(XciHandler.instance == null) { GameObject xciHandleObj = new GameObject("XboxCtrlrInput Handler Script"); xciHandleObj.AddComponent<XciHandler>(); } return XciHandler.instance; } } } // end of XciHandler } // end of XCI public static class XboxButtonExtensions { public static bool IsDPad(this XboxButton button) { return (button == XboxButton.DPadUp || button == XboxButton.DPadDown || button == XboxButton.DPadLeft || button == XboxButton.DPadRight); } public static XboxDPad ToDPad(this XboxButton button) { if (button == XboxButton.DPadUp) return XboxDPad.Up; if (button == XboxButton.DPadDown) return XboxDPad.Down; if (button == XboxButton.DPadLeft) return XboxDPad.Left; if (button == XboxButton.DPadRight) return XboxDPad.Right; return default(XboxDPad); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Xml.Schema; using System.Xml; using System.Text; using System.ComponentModel; using System.Globalization; using System.Security.Cryptography; using System.Diagnostics; using System.Linq; using System.Xml.Extensions; using System.Xml.Serialization; // These classes provide a higher level view on reflection specific to // Xml serialization, for example: // - allowing one to talk about types w/o having them compiled yet // - abstracting collections & arrays // - abstracting classes, structs, interfaces // - knowing about XSD primitives // - dealing with Serializable and xmlelement // and lots of other little details internal enum TypeKind { Root, Primitive, Enum, Struct, Class, Array, Collection, Enumerable, Void, Node, Attribute, Serializable } internal enum TypeFlags { None = 0x0, Abstract = 0x1, Reference = 0x2, Special = 0x4, CanBeAttributeValue = 0x8, CanBeTextValue = 0x10, CanBeElementValue = 0x20, HasCustomFormatter = 0x40, AmbiguousDataType = 0x80, IgnoreDefault = 0x200, HasIsEmpty = 0x400, HasDefaultConstructor = 0x800, XmlEncodingNotRequired = 0x1000, UseReflection = 0x4000, CollapseWhitespace = 0x8000, OptionalValue = 0x10000, CtorInaccessible = 0x20000, UsePrivateImplementation = 0x40000, GenericInterface = 0x80000, Unsupported = 0x100000, } internal class TypeDesc { private string _name; private string _fullName; private string _cSharpName; private TypeDesc _arrayElementTypeDesc; private TypeDesc _arrayTypeDesc; private TypeDesc _nullableTypeDesc; private TypeKind _kind; private XmlSchemaType _dataType; private Type _type; private TypeDesc _baseTypeDesc; private TypeFlags _flags; private string _formatterName; private bool _isXsdType; private bool _isMixed; private int _weight; private Exception _exception; internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName) { _name = name.Replace('+', '.'); _fullName = fullName.Replace('+', '.'); _kind = kind; _baseTypeDesc = baseTypeDesc; _flags = flags; _isXsdType = kind == TypeKind.Primitive; if (_isXsdType) _weight = 1; else if (kind == TypeKind.Enum) _weight = 2; else if (_kind == TypeKind.Root) _weight = -1; else _weight = baseTypeDesc == null ? 0 : baseTypeDesc.Weight + 1; _dataType = dataType; _formatterName = formatterName; } internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags) : this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null) { } internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags) : this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName) { _isXsdType = isXsdType; _type = type; } internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc) : this(name, fullName, null, kind, baseTypeDesc, flags, null) { _arrayElementTypeDesc = arrayElementTypeDesc; _type = type; } public override string ToString() { return _fullName; } internal TypeFlags Flags { get { return _flags; } } internal bool IsXsdType { get { return _isXsdType; } } internal bool IsMappedType { get { return false; } } internal string Name { get { return _name; } } internal string FullName { get { return _fullName; } } internal string CSharpName { get { if (_cSharpName == null) { _cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type); } return _cSharpName; } } internal XmlSchemaType DataType { get { return _dataType; } } internal Type Type { get { return _type; } } internal string FormatterName { get { return _formatterName; } } internal TypeKind Kind { get { return _kind; } } internal bool IsValueType { get { return (_flags & TypeFlags.Reference) == 0; } } internal bool CanBeAttributeValue { get { return (_flags & TypeFlags.CanBeAttributeValue) != 0; } } internal bool XmlEncodingNotRequired { get { return (_flags & TypeFlags.XmlEncodingNotRequired) != 0; } } internal bool CanBeElementValue { get { return (_flags & TypeFlags.CanBeElementValue) != 0; } } internal bool CanBeTextValue { get { return (_flags & TypeFlags.CanBeTextValue) != 0; } } internal bool IsMixed { get { return _isMixed || CanBeTextValue; } set { _isMixed = value; } } internal bool IsSpecial { get { return (_flags & TypeFlags.Special) != 0; } } internal bool IsAmbiguousDataType { get { return (_flags & TypeFlags.AmbiguousDataType) != 0; } } internal bool HasCustomFormatter { get { return (_flags & TypeFlags.HasCustomFormatter) != 0; } } internal bool HasDefaultSupport { get { return (_flags & TypeFlags.IgnoreDefault) == 0; } } internal bool HasIsEmpty { get { return (_flags & TypeFlags.HasIsEmpty) != 0; } } internal bool CollapseWhitespace { get { return (_flags & TypeFlags.CollapseWhitespace) != 0; } } internal bool HasDefaultConstructor { get { return (_flags & TypeFlags.HasDefaultConstructor) != 0; } } internal bool IsUnsupported { get { return (_flags & TypeFlags.Unsupported) != 0; } } internal bool IsGenericInterface { get { return (_flags & TypeFlags.GenericInterface) != 0; } } internal bool IsPrivateImplementation { get { return (_flags & TypeFlags.UsePrivateImplementation) != 0; } } internal bool CannotNew { get { return !HasDefaultConstructor || ConstructorInaccessible; } } internal bool IsAbstract { get { return (_flags & TypeFlags.Abstract) != 0; } } internal bool IsOptionalValue { get { return (_flags & TypeFlags.OptionalValue) != 0; } } internal bool UseReflection { get { return (_flags & TypeFlags.UseReflection) != 0; } } internal bool IsVoid { get { return _kind == TypeKind.Void; } } internal bool IsClass { get { return _kind == TypeKind.Class; } } internal bool IsStructLike { get { return _kind == TypeKind.Struct || _kind == TypeKind.Class; } } internal bool IsArrayLike { get { return _kind == TypeKind.Array || _kind == TypeKind.Collection || _kind == TypeKind.Enumerable; } } internal bool IsCollection { get { return _kind == TypeKind.Collection; } } internal bool IsEnumerable { get { return _kind == TypeKind.Enumerable; } } internal bool IsArray { get { return _kind == TypeKind.Array; } } internal bool IsPrimitive { get { return _kind == TypeKind.Primitive; } } internal bool IsEnum { get { return _kind == TypeKind.Enum; } } internal bool IsNullable { get { return !IsValueType; } } internal bool IsRoot { get { return _kind == TypeKind.Root; } } internal bool ConstructorInaccessible { get { return (_flags & TypeFlags.CtorInaccessible) != 0; } } internal Exception Exception { get { return _exception; } set { _exception = value; } } internal TypeDesc GetNullableTypeDesc(Type type) { if (IsOptionalValue) return this; if (_nullableTypeDesc == null) { _nullableTypeDesc = new TypeDesc("NullableOf" + _name, "System.Nullable`1[" + _fullName + "]", null, TypeKind.Struct, this, _flags | TypeFlags.OptionalValue, _formatterName); _nullableTypeDesc._type = type; } return _nullableTypeDesc; } internal void CheckSupported() { if (IsUnsupported) { if (Exception != null) { throw Exception; } else { throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName)); } } if (_baseTypeDesc != null) _baseTypeDesc.CheckSupported(); if (_arrayElementTypeDesc != null) _arrayElementTypeDesc.CheckSupported(); } internal void CheckNeedConstructor() { if (!IsValueType && !IsAbstract && !HasDefaultConstructor) { _flags |= TypeFlags.Unsupported; _exception = new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, FullName)); } } internal TypeDesc ArrayElementTypeDesc { get { return _arrayElementTypeDesc; } set { _arrayElementTypeDesc = value; } } internal int Weight { get { return _weight; } } internal TypeDesc CreateArrayTypeDesc() { if (_arrayTypeDesc == null) _arrayTypeDesc = new TypeDesc(null, _name + "[]", _fullName + "[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this); return _arrayTypeDesc; } internal TypeDesc BaseTypeDesc { get { return _baseTypeDesc; } set { _baseTypeDesc = value; _weight = _baseTypeDesc == null ? 0 : _baseTypeDesc.Weight + 1; } } internal bool IsDerivedFrom(TypeDesc baseTypeDesc) { TypeDesc typeDesc = this; while (typeDesc != null) { if (typeDesc == baseTypeDesc) return true; typeDesc = typeDesc.BaseTypeDesc; } return baseTypeDesc.IsRoot; } internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs) { if (typeDescs.Length == 0) return null; TypeDesc leastDerivedTypeDesc = null; int leastDerivedLevel = int.MaxValue; for (int i = 0; i < typeDescs.Length; i++) { int derivationLevel = typeDescs[i].Weight; if (derivationLevel < leastDerivedLevel) { leastDerivedLevel = derivationLevel; leastDerivedTypeDesc = typeDescs[i]; } } while (leastDerivedTypeDesc != null) { int i; for (i = 0; i < typeDescs.Length; i++) { if (!typeDescs[i].IsDerivedFrom(leastDerivedTypeDesc)) break; } if (i == typeDescs.Length) break; leastDerivedTypeDesc = leastDerivedTypeDesc.BaseTypeDesc; } return leastDerivedTypeDesc; } } internal class TypeScope { private Hashtable _typeDescs = new Hashtable(); private Hashtable _arrayTypeDescs = new Hashtable(); private ArrayList _typeMappings = new ArrayList(); private static Hashtable s_primitiveTypes = new Hashtable(); private static Hashtable s_primitiveDataTypes = new Hashtable(); private static NameTable s_primitiveNames = new NameTable(); private static string[] s_unsupportedTypes = new string[] { "anyURI", "duration", "ENTITY", "ENTITIES", "gDay", "gMonth", "gMonthDay", "gYear", "gYearMonth", "ID", "IDREF", "IDREFS", "integer", "language", "negativeInteger", "nonNegativeInteger", "nonPositiveInteger", //"normalizedString", "NOTATION", "positiveInteger", "token" }; static TypeScope() { AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor); AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference); AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(SByte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt16), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt32), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(UInt64), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); // Types without direct mapping (ambiguous) AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor); AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor); // NOTE, Micorosft: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we // can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or // [XmlArrayItem]. XmlSchemaPatternFacet guidPattern = new XmlSchemaPatternFacet(); guidPattern.Value = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), new XmlSchemaFacet[] { guidPattern }, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault); AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.IgnoreDefault); AddNonXsdPrimitive(typeof(TimeSpan), "TimeSpan", UrtTypes.Namespace, "TimeSpan", new XmlQualifiedName("duration", XmlSchema.Namespace), new XmlSchemaFacet[0], TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedTypes(Soap.Encoding); // Unsuppoted types that we map to string, if in the future we decide // to add support for them we would need to create custom formatters for them // normalizedString is the only one unsupported type that suppose to preserve whitesapce AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor); for (int i = 0; i < s_unsupportedTypes.Length; i++) { AddPrimitive(typeof(string), s_unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace); } } internal static bool IsKnownType(Type type) { if (type == typeof(object)) return true; if (type.IsEnum) return false; switch (type.GetTypeCode()) { case TypeCode.String: return true; case TypeCode.Int32: return true; case TypeCode.Boolean: return true; case TypeCode.Int16: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; case TypeCode.Decimal: return true; case TypeCode.DateTime: return true; case TypeCode.Byte: return true; case TypeCode.SByte: return true; case TypeCode.UInt16: return true; case TypeCode.UInt32: return true; case TypeCode.UInt64: return true; case TypeCode.Char: return true; default: if (type == typeof(XmlQualifiedName)) return true; else if (type == typeof(byte[])) return true; else if (type == typeof(Guid)) return true; else if (type == typeof(TimeSpan)) return true; else if (type == typeof(XmlNode[])) return true; break; } return false; } private static void AddSoapEncodedTypes(string ns) { AddSoapEncodedPrimitive(typeof(string), "normalizedString", ns, "String", new XmlQualifiedName("normalizedString", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor); for (int i = 0; i < s_unsupportedTypes.Length; i++) { AddSoapEncodedPrimitive(typeof(string), s_unsupportedTypes[i], ns, "String", new XmlQualifiedName(s_unsupportedTypes[i], XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace); } AddSoapEncodedPrimitive(typeof(string), "string", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(int), "int", ns, "Int32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(bool), "boolean", ns, "Boolean", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(short), "short", ns, "Int16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(long), "long", ns, "Int64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(float), "float", ns, "Single", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(double), "double", ns, "Double", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(decimal), "decimal", ns, "Decimal", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(DateTime), "dateTime", ns, "DateTime", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(XmlQualifiedName), "QName", ns, "XmlQualifiedName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(byte), "unsignedByte", ns, "Byte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(SByte), "byte", ns, "SByte", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(UInt16), "unsignedShort", ns, "UInt16", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(UInt32), "unsignedInt", ns, "UInt32", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(UInt64), "unsignedLong", ns, "UInt64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired); // Types without direct mapping (ambigous) AddSoapEncodedPrimitive(typeof(DateTime), "date", ns, "Date", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(DateTime), "time", ns, "Time", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(string), "Name", ns, "XmlName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(string), "NCName", ns, "XmlNCName", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(string), "NMTOKEN", ns, "XmlNmToken", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(string), "NMTOKENS", ns, "XmlNmTokens", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference); AddSoapEncodedPrimitive(typeof(byte[]), "base64Binary", ns, "ByteArrayBase64", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(byte[]), "hexBinary", ns, "ByteArrayHex", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired); AddSoapEncodedPrimitive(typeof(string), "arrayCoordinate", ns, "String", new XmlQualifiedName("string", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue); AddSoapEncodedPrimitive(typeof(byte[]), "base64", ns, "ByteArrayBase64", new XmlQualifiedName("base64Binary", XmlSchema.Namespace), TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.IgnoreDefault | TypeFlags.Reference); } private static void AddPrimitive(Type type, string dataTypeName, string formatterName, TypeFlags flags) { XmlSchemaSimpleType dataType = new XmlSchemaSimpleType(); dataType.Name = dataTypeName; TypeDesc typeDesc = new TypeDesc(type, true, dataType, formatterName, flags); if (s_primitiveTypes[type] == null) s_primitiveTypes.Add(type, typeDesc); s_primitiveDataTypes.Add(dataType, typeDesc); s_primitiveNames.Add(dataTypeName, XmlSchema.Namespace, typeDesc); } private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags) { XmlSchemaSimpleType dataType = new XmlSchemaSimpleType(); dataType.Name = dataTypeName; XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = baseTypeName; foreach (XmlSchemaFacet facet in facets) { restriction.Facets.Add(facet); } dataType.Content = restriction; TypeDesc typeDesc = new TypeDesc(type, false, dataType, formatterName, flags); if (s_primitiveTypes[type] == null) s_primitiveTypes.Add(type, typeDesc); s_primitiveDataTypes.Add(dataType, typeDesc); s_primitiveNames.Add(dataTypeName, ns, typeDesc); } private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, TypeFlags flags) { AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, new XmlSchemaFacet[0], flags); } internal TypeDesc GetTypeDesc(string name, string ns) { return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue); } internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags) { TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns]; if (typeDesc != null) { if ((typeDesc.Flags & flags) != 0) { return typeDesc; } } return null; } internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType) { return (TypeDesc)s_primitiveDataTypes[dataType]; } internal TypeDesc GetTypeDesc(Type type) { return GetTypeDesc(type, null, true, true); } internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference) { return GetTypeDesc(type, source, directReference, true); } internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError) { if (type.ContainsGenericParameters) { throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type.ToString())); } TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type]; if (typeDesc == null) { typeDesc = (TypeDesc)_typeDescs[type]; if (typeDesc == null) { typeDesc = ImportTypeDesc(type, source, directReference); } } if (throwOnError) typeDesc.CheckSupported(); return typeDesc; } internal TypeDesc GetArrayTypeDesc(Type type) { TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type]; if (typeDesc == null) { typeDesc = GetTypeDesc(type); if (!typeDesc.IsArrayLike) typeDesc = ImportTypeDesc(type, null, false); typeDesc.CheckSupported(); _arrayTypeDescs.Add(type, typeDesc); } return typeDesc; } #if !FEATURE_SERIALIZATION_UAPAOT internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc) { foreach (TypeMapping typeMapping in TypeMappings) { if (typeMapping.TypeDesc == typeDesc) return typeMapping; } return null; } internal Type GetTypeFromTypeDesc(TypeDesc typeDesc) { if (typeDesc.Type != null) return typeDesc.Type; foreach (DictionaryEntry de in _typeDescs) { if (de.Value == typeDesc) return de.Key as Type; } return null; } #endif private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference) { TypeDesc typeDesc = null; TypeKind kind; Type arrayElementType = null; Type baseType = null; TypeFlags flags = 0; Exception exception = null; if (!type.IsVisible) { flags |= TypeFlags.Unsupported; exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName)); } else if (directReference && (type.IsAbstract && type.IsSealed)) { flags |= TypeFlags.Unsupported; exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName)); } if (DynamicAssemblies.IsTypeDynamic(type)) { flags |= TypeFlags.UseReflection; } if (!type.IsValueType) flags |= TypeFlags.Reference; if (type == typeof(object)) { kind = TypeKind.Root; flags |= TypeFlags.HasDefaultConstructor; } else if (type == typeof(ValueType)) { kind = TypeKind.Enum; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } else if (type == typeof(void)) { kind = TypeKind.Void; } else if (typeof(IXmlSerializable).IsAssignableFrom(type)) { kind = TypeKind.Serializable; flags |= TypeFlags.Special | TypeFlags.CanBeElementValue; flags |= GetConstructorFlags(type, ref exception); } else if (type.IsArray) { kind = TypeKind.Array; if (type.GetArrayRank() > 1) { flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName)); } } arrayElementType = type.GetElementType(); flags |= TypeFlags.HasDefaultConstructor; } else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type)) { kind = TypeKind.Collection; arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name); flags |= GetConstructorFlags(type, ref exception); } else if (type == typeof(XmlQualifiedName)) { kind = TypeKind.Primitive; } else if (type.IsPrimitive) { kind = TypeKind.Primitive; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } else if (type.IsEnum) { kind = TypeKind.Enum; } else if (type.IsValueType) { kind = TypeKind.Struct; if (IsOptionalValue(type)) { baseType = type.GetGenericArguments()[0]; flags |= TypeFlags.OptionalValue; } else { baseType = type.BaseType; } if (type.IsAbstract) flags |= TypeFlags.Abstract; } else if (type.IsClass) { if (type == typeof(XmlAttribute)) { kind = TypeKind.Attribute; flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue; } else if (typeof(XmlNode).IsAssignableFrom(type)) { kind = TypeKind.Node; baseType = type.BaseType; flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue; if (typeof(XmlText).IsAssignableFrom(type)) flags &= ~TypeFlags.CanBeElementValue; else if (typeof(XmlElement).IsAssignableFrom(type)) flags &= ~TypeFlags.CanBeTextValue; else if (type.IsAssignableFrom(typeof(XmlAttribute))) flags |= TypeFlags.CanBeAttributeValue; } else { kind = TypeKind.Class; baseType = type.BaseType; if (type.IsAbstract) flags |= TypeFlags.Abstract; } } else if (type.IsInterface) { kind = TypeKind.Void; flags |= TypeFlags.Unsupported; if (exception == null) { if (memberInfo == null) { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName)); } else { exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName)); } } } else { kind = TypeKind.Void; flags |= TypeFlags.Unsupported; if (exception == null) { exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName)); } } // check to see if the type has public default constructor for classes if (kind == TypeKind.Class && !type.IsAbstract) { flags |= GetConstructorFlags(type, ref exception); } // check if a struct-like type is enumerable if (kind == TypeKind.Struct || kind == TypeKind.Class) { if (typeof(IEnumerable).IsAssignableFrom(type) && !IsArraySegment(type)) { arrayElementType = GetEnumeratorElementType(type, ref flags); kind = TypeKind.Enumerable; // GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property, // we need to check the MoveNext() and ctor methods for the security attribues flags |= GetConstructorFlags(type, ref exception); } } typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null); typeDesc.Exception = exception; if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable)) typeDesc.CheckNeedConstructor(); if (typeDesc.IsUnsupported) { // return right away, do not check anything else return typeDesc; } _typeDescs.Add(type, typeDesc); if (arrayElementType != null) { TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false); // explicitly disallow read-only elements, even if they are collections if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive) { td.CheckNeedConstructor(); } typeDesc.ArrayElementTypeDesc = td; } if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType)) { typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false); } if (type.IsNestedPublic) { for (Type t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType) GetTypeDesc(t, null, false); } return typeDesc; } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } internal static bool IsOptionalValue(Type type) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition()) return true; } return false; } /* static string GetHash(string str) { MD5 md5 = MD5.Create(); string hash = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0, 6).Replace("+", "_P").Replace("/", "_S"); return hash; } */ internal static string TypeName(Type t) { if (t.IsArray) { return "ArrayOf" + TypeName(t.GetElementType()); } else if (t.IsGenericType) { StringBuilder typeName = new StringBuilder(); StringBuilder ns = new StringBuilder(); string name = t.Name; int arity = name.IndexOf("`", StringComparison.Ordinal); if (arity >= 0) { name = name.Substring(0, arity); } typeName.Append(name); typeName.Append("Of"); Type[] arguments = t.GetGenericArguments(); for (int i = 0; i < arguments.Length; i++) { typeName.Append(TypeName(arguments[i])); ns.Append(arguments[i].Namespace); } /* if (ns.Length > 0) { typeName.Append("_"); typeName.Append(GetHash(ns.ToString())); } */ return typeName.ToString(); } return t.Name; } internal static Type GetArrayElementType(Type type, string memberInfo) { if (type.IsArray) return type.GetElementType(); else if (IsArraySegment(type)) return null; else if (typeof(ICollection).IsAssignableFrom(type)) return GetCollectionElementType(type, memberInfo); else if (typeof(IEnumerable).IsAssignableFrom(type)) { TypeFlags flags = TypeFlags.None; return GetEnumeratorElementType(type, ref flags); } else return null; } internal static MemberMapping[] GetAllMembers(StructMapping mapping) { if (mapping.BaseMapping == null) return mapping.Members; ArrayList list = new ArrayList(); GetAllMembers(mapping, list); return (MemberMapping[])list.ToArray(typeof(MemberMapping)); } internal static void GetAllMembers(StructMapping mapping, ArrayList list) { if (mapping.BaseMapping != null) { GetAllMembers(mapping.BaseMapping, list); } for (int i = 0; i < mapping.Members.Length; i++) { list.Add(mapping.Members[i]); } } internal static MemberMapping[] GetAllMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos) { MemberMapping[] mappings = GetAllMembers(mapping); PopulateMemberInfos(mapping, mappings, memberInfos); return mappings; } internal static MemberMapping[] GetSettableMembers(StructMapping structMapping) { ArrayList list = new ArrayList(); GetSettableMembers(structMapping, list); return (MemberMapping[])list.ToArray(typeof(MemberMapping)); } private static void GetSettableMembers(StructMapping mapping, ArrayList list) { if (mapping.BaseMapping != null) { GetSettableMembers(mapping.BaseMapping, list); } if (mapping.Members != null) { foreach (MemberMapping memberMapping in mapping.Members) { MemberInfo memberInfo = memberMapping.MemberInfo; PropertyInfo propertyInfo = memberInfo as PropertyInfo; if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc)) { throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name)); } list.Add(memberMapping); } } } private static bool CanWriteProperty(PropertyInfo propertyInfo, TypeDesc typeDesc) { Debug.Assert(propertyInfo != null); Debug.Assert(typeDesc != null); // If the property is a collection, we don't need a setter. if (typeDesc.Kind == TypeKind.Collection || typeDesc.Kind == TypeKind.Enumerable) { return true; } // Else the property needs a public setter. return propertyInfo.SetMethod != null && propertyInfo.SetMethod.IsPublic; } internal static MemberMapping[] GetSettableMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos) { MemberMapping[] mappings = GetSettableMembers(mapping); PopulateMemberInfos(mapping, mappings, memberInfos); return mappings; } private static void PopulateMemberInfos(StructMapping structMapping, MemberMapping[] mappings, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos) { memberInfos.Clear(); for (int i = 0; i < mappings.Length; ++i) { memberInfos[mappings[i].Name] = mappings[i].MemberInfo; if (mappings[i].ChoiceIdentifier != null) memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo; if (mappings[i].CheckSpecifiedMemberInfo != null) memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo; } // The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B. // There's one virtual property defined in A and overridden by B. Without the replacing logic below, the code generated will always // try to access the property defined in A, rather than B. // The logic here is to: // 1) Check current members inside memberInfos dictionary and figure out whether there's any override or new properties defined in the derived class. // If so, replace the one on the base class with the one on the derived class. // 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced // by the StructMapping of the baseclass, so updating it directly could lead to other issues. Dictionary<string, MemberInfo> replaceList = null; MemberInfo replacedInfo = null; foreach (KeyValuePair<string, MemberInfo> pair in memberInfos) { if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo)) { if (replaceList == null) { replaceList = new Dictionary<string, MemberInfo>(); } replaceList.Add(pair.Key, replacedInfo); } } if (replaceList != null) { foreach (KeyValuePair<string, MemberInfo> pair in replaceList) { memberInfos[pair.Key] = pair.Value; } for (int i = 0; i < mappings.Length; i++) { MemberInfo mi; if (replaceList.TryGetValue(mappings[i].Name, out mi)) { MemberMapping newMapping = mappings[i].Clone(); newMapping.MemberInfo = mi; mappings[i] = newMapping; } } } } private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type derivedType, out MemberInfo replacedInfo) { replacedInfo = memberInfoToBeReplaced; Type currentType = derivedType; Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType; if (typeToBeReplaced.IsAssignableFrom(currentType)) { while (currentType != typeToBeReplaced) { TypeInfo currentInfo = currentType.GetTypeInfo(); foreach (PropertyInfo info in currentInfo.DeclaredProperties) { if (info.Name == memberInfoToBeReplaced.Name) { // we have a new modifier situation: property names are the same but the declaring types are different replacedInfo = info; if (replacedInfo != memberInfoToBeReplaced) { if (!info.GetMethod.IsPublic && memberInfoToBeReplaced is PropertyInfo && ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic ) { break; } return true; } } } foreach (FieldInfo info in currentInfo.DeclaredFields) { if (info.Name == memberInfoToBeReplaced.Name) { // we have a new modifier situation: field names are the same but the declaring types are different replacedInfo = info; if (replacedInfo != memberInfoToBeReplaced) { return true; } } } // we go one level down and try again currentType = currentType.BaseType; } } return false; } private static TypeFlags GetConstructorFlags(Type type, ref Exception exception) { ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>()); if (ctor != null) { TypeFlags flags = TypeFlags.HasDefaultConstructor; if (!ctor.IsPublic) flags |= TypeFlags.CtorInaccessible; else { object[] attrs = ctor.GetCustomAttributes(typeof(ObsoleteAttribute), false); if (attrs != null && attrs.Length > 0) { ObsoleteAttribute obsolete = (ObsoleteAttribute)attrs[0]; if (obsolete.IsError) { flags |= TypeFlags.CtorInaccessible; } } } return flags; } return 0; } private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) { if (typeof(IEnumerable).IsAssignableFrom(type)) { MethodInfo enumerator = type.GetMethod("GetEnumerator", new Type[0]); if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType)) { // try generic implementation enumerator = null; foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic)) { enumerator = member as MethodInfo; if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType)) { // use the first one we find flags |= TypeFlags.GenericInterface; break; } else { enumerator = null; } } if (enumerator == null) { // and finally private interface implementation flags |= TypeFlags.UsePrivateImplementation; enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>()); } } if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType)) { return null; } XmlAttributes methodAttrs = new XmlAttributes(enumerator); if (methodAttrs.XmlIgnore) return null; PropertyInfo p = enumerator.ReturnType.GetProperty("Current"); Type currentType = (p == null ? typeof(object) : p.PropertyType); MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType }); if (addMethod == null && currentType != typeof(object)) { currentType = typeof(object); addMethod = type.GetMethod("Add", new Type[] { currentType }); } if (addMethod == null) { throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable")); } return currentType; } else { return null; } } internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) { if (typeof(IDictionary).IsAssignableFrom(type)) { if (memberInfo == null) { throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionary, type.FullName)); } else { throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionaryDetails, memberInfo, type.FullName)); } } MemberInfo[] defaultMembers = type.GetDefaultMembers(); PropertyInfo indexer = null; if (defaultMembers != null && defaultMembers.Length > 0) { for (Type t = type; t != null; t = t.BaseType) { for (int i = 0; i < defaultMembers.Length; i++) { if (defaultMembers[i] is PropertyInfo) { PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i]; if (defaultProp.DeclaringType != t) continue; if (!defaultProp.CanRead) continue; MethodInfo getMethod = defaultProp.GetMethod; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int)) { indexer = defaultProp; break; } } } if (indexer != null) break; } } if (indexer == null) { throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName)); } MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType }); if (addMethod == null) { throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection")); } return indexer; } private static Type GetCollectionElementType(Type type, string memberInfo) { return GetDefaultIndexer(type, memberInfo).PropertyType; } internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent) { string ns; string name; int nsLen = type.LastIndexOf(':'); if (nsLen <= 0) { ns = ""; } else { ns = type.Substring(0, nsLen); } int nameLen = type.IndexOf('[', nsLen + 1); if (nameLen <= nsLen) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayTypeSyntax, type)); } name = type.Substring(nsLen + 1, nameLen - nsLen - 1); dims = type.Substring(nameLen); // parent is not null only in the case when we used XmlSchema.Read(), // in which case we need to fixup the wsdl:arayType attribute value while (parent != null) { if (parent.Namespaces != null) { string wsdlNs; if (parent.Namespaces.Namespaces.TryGetValue(ns, out wsdlNs) && wsdlNs != null) { ns = wsdlNs; break; } } parent = parent.Parent; } return new XmlQualifiedName(name, ns); } internal ICollection Types { get { return _typeDescs.Keys; } } internal void AddTypeMapping(TypeMapping typeMapping) { _typeMappings.Add(typeMapping); } internal ICollection TypeMappings { get { return _typeMappings; } } internal static Hashtable PrimtiveTypes { get { return s_primitiveTypes; } } } internal class Soap { private Soap() { } internal const string Encoding = "http://schemas.xmlsoap.org/soap/encoding/"; internal const string UrType = "anyType"; internal const string Array = "Array"; internal const string ArrayType = "arrayType"; } internal class Soap12 { private Soap12() { } internal const string Encoding = "http://www.w3.org/2003/05/soap-encoding"; internal const string RpcNamespace = "http://www.w3.org/2003/05/soap-rpc"; internal const string RpcResult = "result"; } internal class Wsdl { private Wsdl() { } internal const string Namespace = "http://schemas.xmlsoap.org/wsdl/"; internal const string ArrayType = "arrayType"; } internal class UrtTypes { private UrtTypes() { } internal const string Namespace = "http://microsoft.com/wsdl/types/"; } }
// // <copyright file="SecUtil.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // using System; using System.Globalization; using System.Web.Hosting; using System.Collections; using System.Collections.Specialized; using System.Data; using System.Data.Services; using System.Data.Services.Client; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Configuration.Provider; using System.Configuration; using System.Text.RegularExpressions; using System.Xml; using System.Net; using System.Diagnostics; using System.Security; using System.Text; using Microsoft.WindowsAzure.StorageClient; using System.Threading; using Microsoft.WindowsAzure; namespace Microsoft.Samples.ServiceHosting.AspProviders { internal static class SecUtility { internal const int Infinite = Int32.MaxValue; internal static bool ValidateParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize) { if (param == null) { return !checkForNull; } param = param.Trim(); if ((checkIfEmpty && param.Length < 1) || (maxSize > 0 && param.Length > maxSize) || (checkForCommas && param.Contains(","))) { return false; } return true; } internal static void CheckParameter(ref string param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName) { if (param == null) { if (checkForNull) { throw new ArgumentNullException(paramName); } return; } param = param.Trim(); if (checkIfEmpty && param.Length < 1) { throw new ArgumentException(string.Format(CultureInfo.InstalledUICulture, "The parameter '{0}' must not be empty.", paramName), paramName); } if (maxSize > 0 && param.Length > maxSize) { throw new ArgumentException(string.Format(CultureInfo.InstalledUICulture, "The parameter '{0}' is too long: it must not exceed {1} chars in length.", paramName, maxSize.ToString(CultureInfo.InvariantCulture)), paramName); } if (checkForCommas && param.Contains(",")) { throw new ArgumentException(string.Format(CultureInfo.InstalledUICulture, "The parameter '{0}' must not contain commas.", paramName), paramName); } } internal static void CheckArrayParameter(ref string[] param, bool checkForNull, bool checkIfEmpty, bool checkForCommas, int maxSize, string paramName) { if (param == null) { throw new ArgumentNullException(paramName); } if (param.Length < 1) { throw new ArgumentException(string.Format(CultureInfo.InstalledUICulture, "The array parameter '{0}' should not be empty.", paramName), paramName); } Hashtable values = new Hashtable(param.Length); for (int i = param.Length - 1; i >= 0; i--) { SecUtility.CheckParameter(ref param[i], checkForNull, checkIfEmpty, checkForCommas, maxSize, paramName + "[ " + i.ToString(CultureInfo.InvariantCulture) + " ]"); if (values.Contains(param[i])) { throw new ArgumentException(string.Format(CultureInfo.InstalledUICulture, "The array '{0}' should not contain duplicate values.", paramName), paramName); } else { values.Add(param[i], param[i]); } } } internal static void SetUtcTime(DateTime value, out DateTime res) { res = Configuration.MinSupportedDateTime; if ((value.Kind == DateTimeKind.Local && value.ToUniversalTime() < Configuration.MinSupportedDateTime) || value < Configuration.MinSupportedDateTime) { throw new ArgumentException("Invalid time value!"); } if (value.Kind == DateTimeKind.Local) { res = value.ToUniversalTime(); } else { res = value; } } internal const string ValidTableNameRegex = @"^([a-z]|[A-Z]){1}([a-z]|[A-Z]|\d){2,62}$"; internal static bool IsValidTableName(string name) { if (string.IsNullOrEmpty(name)) { return false; } Regex reg = new Regex(ValidTableNameRegex); if (reg.IsMatch(name)) { return true; } else { return false; } } internal const string ValidContainerNameRegex = @"^([a-z]|\d){1}([a-z]|-|\d){1,61}([a-z]|\d){1}$"; internal static bool IsValidContainerName(string name) { if (string.IsNullOrEmpty(name)) { return false; } Regex reg = new Regex(ValidContainerNameRegex); if (reg.IsMatch(name)) { return true; } else { return false; } } // the table storage system currently does not support the StartsWith() operation in // queries. As a result we transform s.StartsWith(substring) into s.CompareTo(substring) > 0 && // s.CompareTo(NextComparisonString(substring)) < 0 // we assume that comparison on the service side is as ordinal comparison internal static string NextComparisonString(string s) { if (string.IsNullOrEmpty(s)) { throw new ArgumentException("The string argument must not be null or empty!"); } string ret; char last = s[s.Length - 1]; if ((int)last + 1 > (int)char.MaxValue) { throw new ArgumentException("Cannot convert the string."); } // don't use "as" because we want to have an explicit exception here if something goes wrong last = (char)((int)last + 1); ret = s.Substring(0, s.Length - 1) + last; return ret; } // we use a normal character as the separator because of string comparison operations // these have to be valid characters internal const char KeySeparator = 'a'; internal static readonly string KeySeparatorString = new string(KeySeparator, 1); internal const char EscapeCharacter = 'b'; internal static readonly string EscapeCharacterString = new string(EscapeCharacter, 1); // Some characters can cause problems when they are contained in columns // that are included in queries. We are very defensive here and escape a wide range // of characters for key columns (as the key columns are present in most queries) internal static bool IsInvalidKeyCharacter(char c) { return ((c < 32) || (c >= 127 && c < 160) || (c == '#') || (c == '&') || (c == '+') || (c == '/') || (c == '?') || (c == ':') || (c == '%') || (c == '\\') ); } internal static string CharToEscapeSequence(char c) { string ret; ret = EscapeCharacterString + string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)c); return ret; } internal static string Escape(string s) { if (string.IsNullOrEmpty(s)) { return s; } StringBuilder ret = new StringBuilder(); foreach (char c in s) { if (c == EscapeCharacter || c == KeySeparator || IsInvalidKeyCharacter(c)) { ret.Append(CharToEscapeSequence(c)); } else { ret.Append(c); } } return ret.ToString(); } internal static string UnEscape(string s) { if (string.IsNullOrEmpty(s)) { return s; } StringBuilder ret = new StringBuilder(); char c; for (int i = 0; i < s.Length; i++) { c = s[i]; if (c == EscapeCharacter) { if (i + 2 >= s.Length) { throw new FormatException("The string " + s + " is not correctly escaped!"); } int ascii = Convert.ToInt32(s.Substring(i + 1, 2), 16); ret.Append((char)ascii); i += 2; } else { ret.Append(c); } } return ret.ToString(); } internal static string CombineToKey(string s1, string s2) { return Escape(s1) + KeySeparator + Escape(s2); } internal static string EscapedFirst(string s) { return Escape(s) + KeySeparator; } internal static string GetFirstFromKey(string key) { Debug.Assert(key.IndexOf(KeySeparator) != -1); string first = key.Substring(0, key.IndexOf(KeySeparator)); return UnEscape(first); } internal static string GetSecondFromKey(string key) { Debug.Assert(key.IndexOf(KeySeparator) != -1); string second = key.Substring(key.IndexOf(KeySeparator) + 1); return UnEscape(second); } internal static void CheckAllowInsecureEndpoints(bool allowInsecureRemoteEndpoints, StorageCredentials info, Uri baseUri) { if (info == null) { throw new ArgumentNullException("info"); } if (allowInsecureRemoteEndpoints) { return; } if (baseUri == null || string.IsNullOrEmpty(baseUri.Scheme)) { throw new SecurityException("allowInsecureRemoteEndpoints is set to false (default setting) but the endpoint URL seems to be empty or there is no URL scheme." + "Please configure the provider to use an https enpoint for the storage endpoint or " + "explicitly set the configuration option allowInsecureRemoteEndpoints to true."); } if (baseUri.Scheme.ToUpper(CultureInfo.InvariantCulture) == Uri.UriSchemeHttps.ToUpper(CultureInfo.InvariantCulture)) { return; } if (baseUri.IsLoopback) { return; } throw new SecurityException("The provider is configured with allowInsecureRemoteEndpoints set to false (default setting) but the endpoint for " + "the storage system does not seem to be an https or local endpoint. " + "Please configure the provider to use an https enpoint for the storage endpoint or " + "explicitly set the configuration option allowInsecureRemoteEndpoints to true."); } } internal static class Constants { internal const int MaxTableUsernameLength = 256; internal const int MaxTableApplicationNameLength = 256; } /// <summary> /// This delegate defines the shape of a provider retry policy. /// Provider retry policies are only used to retry when a row retrieved from a table /// was changed by another entity before it could be saved to the data store.A retry policy will invoke the given /// <paramref name="action"/> as many times as it wants to in the face of /// retriable InvalidOperationExceptions. /// </summary> /// <param name="action">The action to retry</param> /// <returns></returns> public delegate void ProviderRetryPolicy(Action action); /// <summary> /// We are using this retry policies for only one purpose: the ASP providers often read data from the server, process it /// locally and then write the result back to the server. The problem is that the row that has been read might have changed /// between the read and write operation. This retry policy is used to retry the whole process in this case. /// </summary> /// <summary> /// Provides definitions for some standard retry policies. /// </summary> public static class ProviderRetryPolicies { public static readonly TimeSpan StandardMinBackoff = TimeSpan.FromMilliseconds(100); public static readonly TimeSpan StandardMaxBackoff = TimeSpan.FromSeconds(30); private static readonly Random Random = new Random(); /// <summary> /// Policy that does no retries i.e., it just invokes <paramref name="action"/> exactly once /// </summary> /// <param name="action">The action to retry</param> /// <returns>The return value of <paramref name="action"/></returns> internal static void NoRetry(Action action) { action(); } /// <summary> /// Policy that retries a specified number of times with an exponential backoff scheme /// </summary> /// <param name="numberOfRetries">The number of times to retry. Should be a non-negative number.</param> /// <param name="deltaBackoff">The multiplier in the exponential backoff scheme</param> /// <returns></returns> /// <remarks>For this retry policy, the minimum amount of milliseconds between retries is given by the /// StandardMinBackoff constant, and the maximum backoff is predefined by the StandardMaxBackoff constant. /// Otherwise, the backoff is calculated as random(2^currentRetry) * deltaBackoff.</remarks> public static ProviderRetryPolicy RetryN(int numberOfRetries, TimeSpan deltaBackoff) { return new ProviderRetryPolicy((Action action) => { RetryNImpl(action, numberOfRetries, StandardMinBackoff, StandardMaxBackoff, deltaBackoff); } ); } /// <summary> /// Policy that retries a specified number of times with an exponential backoff scheme /// </summary> /// <param name="numberOfRetries">The number of times to retry. Should be a non-negative number</param> /// <param name="deltaBackoff">The multiplier in the exponential backoff scheme</param> /// <param name="minBackoff">The minimum backoff interval</param> /// <param name="minBackoff">The minimum backoff interval</param> /// <returns></returns> /// <remarks>For this retry policy, the minimum amount of milliseconds between retries is given by the /// minBackoff parameter, and the maximum backoff is predefined by the maxBackoff parameter. /// Otherwise, the backoff is calculated as random(2^currentRetry) * deltaBackoff.</remarks> public static ProviderRetryPolicy RetryN(int numberOfRetries, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff) { return new ProviderRetryPolicy((Action action) => { RetryNImpl(action, numberOfRetries, minBackoff, maxBackoff, deltaBackoff); } ); } private static void RetryNImpl(Action action, int numberOfRetries, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff) { int totalNumberOfRetries = numberOfRetries; int backoff; if (minBackoff > maxBackoff) { throw new ArgumentException("The minimum backoff must not be larger than the maximum backoff period."); } if (minBackoff.TotalMilliseconds < 0) { throw new ArgumentException("The minimum backoff period must not be negative."); } do { try { action(); break; } catch (InvalidOperationException e) { HttpStatusCode status; var dsce = e.InnerException as DataServiceClientException; // precondition failed is the status code returned by the server to indicate that the etag is wrong if (dsce != null) { status = (HttpStatusCode)dsce.StatusCode; if (status == HttpStatusCode.PreconditionFailed) { if (numberOfRetries == 0) { throw; } backoff = CalculateCurrentBackoff(minBackoff, maxBackoff, deltaBackoff, totalNumberOfRetries - numberOfRetries); Debug.Assert(backoff >= minBackoff.TotalMilliseconds); Debug.Assert(backoff <= maxBackoff.TotalMilliseconds); if (backoff > 0) { Thread.Sleep(backoff); } } else { throw; } } else { throw; } } } while (numberOfRetries-- > 0); } private static int CalculateCurrentBackoff(TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff, int curRetry) { int backoff; if (curRetry > 31) { backoff = (int)maxBackoff.TotalMilliseconds; } try { backoff = Random.Next((1 << curRetry) + 1); // Console.WriteLine("backoff:" + backoff); // Console.WriteLine("index:" + ((1 << curRetry) + 1)); backoff *= (int)deltaBackoff.TotalMilliseconds; backoff += (int)minBackoff.TotalMilliseconds; } catch (OverflowException) { backoff = (int)maxBackoff.TotalMilliseconds; } if (backoff > (int)maxBackoff.TotalMilliseconds) { backoff = (int)maxBackoff.TotalMilliseconds; } Debug.Assert(backoff >= (int)minBackoff.TotalMilliseconds); // Console.WriteLine("real backoff:" + backoff); return backoff; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Azure.Core.TestFramework; using Microsoft.Identity.Client; using Microsoft.Identity.Client.Extensions.Msal; using Moq; using NUnit.Framework; namespace Azure.Identity.Tests { public class TokenCacheTests : ClientTestBase { public TokenCacheTests(bool isAsync) : base(isAsync) { } internal TokenCache cache; public Mock<ITokenCacheSerializer> mockSerializer; public Mock<ITokenCacheSerializer> mockSerializer2; public Mock<ITokenCache> mockMSALCache; internal Mock<MsalCacheHelperWrapper> mockWrapper; public static Random random = new(); public byte[] bytes = { 1, 0 }; public byte[] updatedBytes = { 0, 2 }; public byte[] mergedBytes = { 1, 2 }; public Func<TokenCacheNotificationArgs, Task> main_OnBeforeCacheAccessAsync = null; public Func<TokenCacheNotificationArgs, Task> main_OnAfterCacheAccessAsync = null; public TokenCacheCallback merge_OnBeforeCacheAccessAsync = null; public TokenCacheCallback merge_OnAfterCacheAccessAsync = null; private const int TestBufferSize = 512; private static Random rand = new(); [SetUp] public void Setup() { mockSerializer = new Mock<ITokenCacheSerializer>(); mockSerializer2 = new Mock<ITokenCacheSerializer>(); mockMSALCache = new Mock<ITokenCache>(); mockWrapper = new Mock<MsalCacheHelperWrapper>(); mockWrapper.Setup(m => m.InitializeAsync(It.IsAny<StorageCreationProperties>(), null)) .Returns(Task.CompletedTask); cache = new TokenCache(new TokenCachePersistenceOptions(), mockWrapper.Object); } [TearDown] public void Cleanup() { TokenCache.ResetWrapperCache(); } public static IEnumerable<object[]> PersistentCacheOptions() { yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true, Name = "foo" }, true, "foo" }; yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = false, Name = "bar" }, false, "bar" }; yield return new object[] { new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = false }, false, Constants.DefaultMsalTokenCacheName }; yield return new object[] { new TokenCachePersistenceOptions { Name = "fizz" }, false, "fizz" }; yield return new object[] { new TokenCachePersistenceOptions(), false, Constants.DefaultMsalTokenCacheName }; } [Test] [TestCaseSource(nameof(PersistentCacheOptions))] public void CtorAllowsAllPermutations(TokenCachePersistenceOptions options, bool expectedAllowUnencryptedStorage, string expectedName) { cache = new TokenCache(options); } [Test] public async Task NoPersistance_RegisterCacheInitializesEvents() { cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); } [Test] public async Task NoPersistance_RegisterCacheInitializesEventsOnlyOnce() { cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); } [Test] [NonParallelizable] public async Task RegisterCacheInitializesCacheWithName() { string cacheName = Guid.NewGuid().ToString(); cache = new TokenCache(new TokenCachePersistenceOptions() { Name = cacheName }, mockWrapper.Object); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockWrapper.Verify(m => m.InitializeAsync( It.Is<StorageCreationProperties>(p => p.CacheFileName == cacheName && p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService && p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection), null)); mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce); } [Test] [NonParallelizable] public async Task RegisterCacheInitializesCache() { await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockWrapper.Verify(m => m.InitializeAsync( It.Is<StorageCreationProperties>(p => p.CacheFileName == Constants.DefaultMsalTokenCacheName && p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService && p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection), null)); mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce); } [Test] [NonParallelizable] public async Task RegisterCacheInitializesCacheOnlyOnce() { await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockWrapper.Verify(m => m.InitializeAsync( It.Is<StorageCreationProperties>(p => p.CacheFileName == Constants.DefaultMsalTokenCacheName && p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService && p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection), null), Times.Once); mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.Exactly(2)); } [Test] [NonParallelizable] public void RegisterCacheInitializesCacheAndIsThreadSafe() { ManualResetEventSlim resetEvent2 = new(); ManualResetEventSlim resetEvent1 = new(); //The fist call to InitializeAsync will block. The second one will complete immediately. mockWrapper.SetupSequence(m => m.InitializeAsync(It.IsAny<StorageCreationProperties>(), null)) .Returns(() => { resetEvent1.Wait(1); resetEvent1.Set(); resetEvent2.Wait(); return Task.CompletedTask; }) .Returns(Task.CompletedTask); var cache2 = new TokenCache(new TokenCachePersistenceOptions(), mockWrapper.Object); var task1 = Task.Run(() => cache.RegisterCache(IsAsync, mockMSALCache.Object, default)); var task2 = Task.Run(() => cache2.RegisterCache(IsAsync, mockMSALCache.Object, default)); //Ensure the two tasks are running before we release the first call to InitializeAsync. resetEvent1.Wait(); resetEvent2.Set(); Task.WaitAll(task1, task2); mockWrapper.Verify(m => m.InitializeAsync( It.Is<StorageCreationProperties>(p => p.CacheFileName == Constants.DefaultMsalTokenCacheName && p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService && p.KeyringCollection == Constants.DefaultMsalTokenCacheKeyringCollection), null)); mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.Exactly(2)); } [Test] [NonParallelizable] public void RegisterCacheThrowsIfEncryptionIsUnavailableAndAllowUnencryptedStorageIsFalse() { mockWrapper.Setup(m => m.VerifyPersistence()).Throws<MsalCachePersistenceException>(); Assert.ThrowsAsync<MsalCachePersistenceException>(() => cache.RegisterCache(IsAsync, mockMSALCache.Object, default)); } [Test] [NonParallelizable] public async Task RegisterCacheInitializesCacheIfEncryptionIsUnavailableAndAllowUnencryptedStorageIsTrue() { mockWrapper.SetupSequence(m => m.VerifyPersistence()) .Throws<MsalCachePersistenceException>() .Pass(); cache = new TokenCache(new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true }, mockWrapper.Object); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockWrapper.Verify(m => m.InitializeAsync( It.Is<StorageCreationProperties>(p => p.CacheFileName == Constants.DefaultMsalTokenCacheName && p.MacKeyChainServiceName == Constants.DefaultMsalTokenCacheKeychainService && p.UseLinuxUnencryptedFallback), null)); mockWrapper.Verify(m => m.RegisterCache(It.IsAny<ITokenCache>()), Times.AtLeastOnce); } [Test] public async Task Persistance_RegisterCacheDoesNotInitializesEvents() { var options = Environment.OSVersion.Platform switch { // Linux tests will fail without UnsafeAllowUnencryptedStorage = true. PlatformID.Unix => new TokenCachePersistenceOptions { UnsafeAllowUnencryptedStorage = true }, _ => new TokenCachePersistenceOptions() }; cache = new TokenCache(options); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Never); mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Never); } [Test] public async Task InMemory_RegisterCacheInitializesEvents() { cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); } [Test] public async Task InMemory_RegisterCacheInitializesEventsOnlyOnce() { cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); mockMSALCache.Verify(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); mockMSALCache.Verify(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>()), Times.Once); } [Test] public async Task RegisteredEventsAreCalledOnFirstUpdate() { cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes)); TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true); bool updatedCalled = false; mockMSALCache .Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess); mockMSALCache .Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess); mockSerializer.Setup(m => m.SerializeMsalV3()).Returns(bytes); cache.TokenCacheUpdatedAsync += (args) => { updatedCalled = true; return Task.CompletedTask; }; await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await main_OnBeforeCacheAccessAsync.Invoke(mockArgs); await main_OnAfterCacheAccessAsync.Invoke(mockArgs); mockSerializer.Verify(m => m.DeserializeMsalV3(cache.Data, true), Times.Once); mockSerializer.Verify(m => m.SerializeMsalV3(), Times.Once); Assert.That(updatedCalled); Assert.That(cache.Data, Is.EqualTo(bytes)); } [Test] public async Task MergeOccursOnSecondUpdate() { var mockPublicClient = new Mock<IPublicClientApplication>(); var mergeMSALCache = new Mock<ITokenCache>(); TokenCacheNotificationArgs mockArgs1 = GetMockArgs(mockSerializer, true); TokenCacheNotificationArgs mockArgs2 = GetMockArgs(mockSerializer2, true); mockMSALCache .Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess); mockMSALCache .Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess); mergeMSALCache .Setup(m => m.SetBeforeAccess(It.IsAny<TokenCacheCallback>())) .Callback<TokenCacheCallback>(beforeAccess => { merge_OnBeforeCacheAccessAsync = beforeAccess; }); mergeMSALCache .Setup(m => m.SetAfterAccess(It.IsAny<TokenCacheCallback>())) .Callback<TokenCacheCallback>(afterAccess => merge_OnAfterCacheAccessAsync = afterAccess); mockSerializer .SetupSequence(m => m.SerializeMsalV3()) .Returns(bytes) .Returns(mergedBytes); mockSerializer2 .SetupSequence(m => m.SerializeMsalV3()) .Returns(updatedBytes); mockPublicClient .SetupGet(m => m.UserTokenCache).Returns(mergeMSALCache.Object); mockPublicClient .Setup(m => m.GetAccountsAsync()) .ReturnsAsync(() => new List<IAccount>()) .Callback(() => { merge_OnBeforeCacheAccessAsync(mockArgs1); var list = merge_OnBeforeCacheAccessAsync.GetInvocationList(); if (merge_OnAfterCacheAccessAsync != null) merge_OnAfterCacheAccessAsync(mockArgs1); }); cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes), default, publicApplicationFactory: new Func<IPublicClientApplication>(() => mockPublicClient.Object)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await cache.RegisterCache(IsAsync, mergeMSALCache.Object, default); // Read the cache from consumer 1. await main_OnBeforeCacheAccessAsync.Invoke(mockArgs1); // Read and write the cache from consumer 2. await main_OnBeforeCacheAccessAsync.Invoke(mockArgs2); // Dealy to ensure that the timestamps are different between last read and last updated. await Task.Delay(100); await main_OnAfterCacheAccessAsync.Invoke(mockArgs2); // Consumer 1 now writes, and must update its cache first. await main_OnAfterCacheAccessAsync.Invoke(mockArgs1); mockSerializer.Verify(m => m.DeserializeMsalV3(bytes, true), Times.Exactly(1)); mockSerializer.Verify(m => m.SerializeMsalV3(), Times.Exactly(2)); mockSerializer.Verify(m => m.DeserializeMsalV3(bytes, false), Times.Exactly(1)); mockSerializer.Verify(m => m.DeserializeMsalV3(updatedBytes, false), Times.Exactly(1)); mockSerializer2.Verify(m => m.DeserializeMsalV3(bytes, true), Times.Exactly(1)); mockSerializer2.Verify(m => m.SerializeMsalV3(), Times.Exactly(1)); // validate that we ended up with the merged cache. Assert.That(cache.Data, Is.EqualTo(mergedBytes)); } [Test] public async Task Serialize() { var evt = new ManualResetEventSlim(); var mockPublicClient = new Mock<IPublicClientApplication>(); TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true); mockSerializer .SetupSequence(m => m.SerializeMsalV3()) .Returns(updatedBytes); mockMSALCache .Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess); mockMSALCache .Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess); var cache = new TokenCache(new TestInMemoryTokenCacheOptions(bytes, updateHandler), default, publicApplicationFactory: new Func<IPublicClientApplication>(() => mockPublicClient.Object)); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await main_OnBeforeCacheAccessAsync.Invoke(mockArgs); await main_OnAfterCacheAccessAsync.Invoke(mockArgs); Task updateHandler(TokenCacheUpdatedArgs args) { Assert.That(args.UnsafeCacheData.ToArray(), Is.EqualTo(updatedBytes)); evt.Set(); return Task.CompletedTask; }; evt.Wait(); } [Test] public async Task UnsafeOptions() { var bytes1 = new ReadOnlyMemory<byte>(new byte[] { 1 }); var bytes2 = new ReadOnlyMemory<byte>(new byte[] { 2 }); var bytes3 = new ReadOnlyMemory<byte>(new byte[] { 3 }); var evt = new ManualResetEventSlim(); var mockPublicClient = new Mock<IPublicClientApplication>(); TokenCacheNotificationArgs mockArgs = GetMockArgs(mockSerializer, true); mockSerializer .SetupSequence(m => m.SerializeMsalV3()) .Returns(updatedBytes); mockMSALCache .Setup(m => m.SetBeforeAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(beforeAccess => main_OnBeforeCacheAccessAsync = beforeAccess); mockMSALCache .Setup(m => m.SetAfterAccessAsync(It.IsAny<Func<TokenCacheNotificationArgs, Task>>())) .Callback<Func<TokenCacheNotificationArgs, Task>>(afterAccess => main_OnAfterCacheAccessAsync = afterAccess); var mockUnsafeOptions = new MockInMemoryTokenCacheOptions( new[]{bytes1, bytes2, bytes3}); var cache = new TokenCache(mockUnsafeOptions, default, () => mockPublicClient.Object); await cache.RegisterCache(IsAsync, mockMSALCache.Object, default); await main_OnBeforeCacheAccessAsync.Invoke(mockArgs); await main_OnBeforeCacheAccessAsync.Invoke(mockArgs); await main_OnBeforeCacheAccessAsync.Invoke(mockArgs); mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes1.ToArray())), true)); mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes2.ToArray())), true)); mockSerializer.Verify(m => m.DeserializeMsalV3(It.Is<byte[]>(b => b.SequenceEqual(bytes3.ToArray())), true)); } private static TokenCacheNotificationArgs GetMockArgs(Mock<ITokenCacheSerializer> mockSerializer, bool hasStateChanged) { var mockArgs = new TokenCacheNotificationArgs(mockSerializer.Object, "foo", null, hasStateChanged, true, "key", true, null, default ); return mockArgs; } public class MockInMemoryTokenCacheOptions : UnsafeTokenCacheOptions { private readonly ReadOnlyMemory<byte>[] _bytes; private int callIndex; public MockInMemoryTokenCacheOptions(ReadOnlyMemory<byte>[] bytes) { _bytes = bytes; } protected internal override Task<ReadOnlyMemory<byte>> RefreshCacheAsync() { return Task.FromResult(_bytes[callIndex++]); } protected internal override Task TokenCacheUpdatedAsync(TokenCacheUpdatedArgs tokenCacheUpdatedArgs) { return Task.CompletedTask; } } public class TestInMemoryTokenCacheOptions : UnsafeTokenCacheOptions { private readonly ReadOnlyMemory<byte> _bytes; private readonly Func<TokenCacheUpdatedArgs, Task> _updated; public TestInMemoryTokenCacheOptions(byte[] bytes, Func<TokenCacheUpdatedArgs, Task> updated = null) { _bytes = bytes; _updated = updated; } protected internal override Task<ReadOnlyMemory<byte>> RefreshCacheAsync() { return Task.FromResult(_bytes); } protected internal override Task TokenCacheUpdatedAsync(TokenCacheUpdatedArgs tokenCacheUpdatedArgs) { return _updated == null ? Task.CompletedTask : _updated(tokenCacheUpdatedArgs); } } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Diagnostics; using System.Security.AccessControl; using System.Windows.Controls; using NLog; using NLog.Targets; #if !NET_CF && !MONO && !SILVERLIGHT namespace GPK_RePack.Core.Helper { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; using System.Text.RegularExpressions; using System.Windows.Forms; using NLog.Config; using NLog.Internal; using System.Windows.Documents; using System.Windows.Media; using System.Linq; [Target("RichTextBox")] public sealed class WpfRichTextBoxTarget : TargetWithLayout { private int lineCount; private int _width = 500; private int _height = 500; private static readonly TypeConverter colorConverter = new ColorConverter(); static WpfRichTextBoxTarget() { var rules = new List<WpfRichTextBoxRowColoringRule>() { new WpfRichTextBoxRowColoringRule("level == LogLevel.Fatal", "White", "Red", FontStyles.Normal, FontWeights.Bold), new WpfRichTextBoxRowColoringRule("level == LogLevel.Error", "Red", "Empty", FontStyles.Italic, FontWeights.Bold), new WpfRichTextBoxRowColoringRule("level == LogLevel.Warn", "Orange", "Empty"), new WpfRichTextBoxRowColoringRule("level == LogLevel.Info", "Black", "Empty"), new WpfRichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Empty"), new WpfRichTextBoxRowColoringRule("level == LogLevel.Trace", "DarkGray", "Empty", FontStyles.Italic, FontWeights.Normal), }; DefaultRowColoringRules = rules.AsReadOnly(); } public WpfRichTextBoxTarget() { this.WordColoringRules = new List<WpfRichTextBoxWordColoringRule>(); this.RowColoringRules = new List<WpfRichTextBoxRowColoringRule>(); this.ToolWindow = true; } private delegate void DelSendTheMessageToRichTextBox(string logMessage, WpfRichTextBoxRowColoringRule rule); private delegate void FormCloseDelegate(); public static ReadOnlyCollection<WpfRichTextBoxRowColoringRule> DefaultRowColoringRules { get; private set; } public string ControlName { get; set; } public string FormName { get; set; } [DefaultValue(false)] public bool UseDefaultRowColoringRules { get; set; } [ArrayParameter(typeof(WpfRichTextBoxRowColoringRule), "row-coloring")] public IList<WpfRichTextBoxRowColoringRule> RowColoringRules { get; private set; } [ArrayParameter(typeof(WpfRichTextBoxWordColoringRule), "word-coloring")] public IList<WpfRichTextBoxWordColoringRule> WordColoringRules { get; private set; } [DefaultValue(true)] public bool ToolWindow { get; set; } public bool ShowMinimized { get; set; } public int Width { get { return _width; } set { _width = value; } } public int Height { get { return _height; } set { _height = value; } } public bool AutoScroll { get; set; } public int MaxLines { get; set; } internal Window TargetForm { get; set; } internal System.Windows.Controls.RichTextBox TargetRichTextBox { get; set; } internal bool CreatedForm { get; set; } protected override void InitializeTarget() { TargetRichTextBox = System.Windows.Application.Current.MainWindow.FindName(ControlName) as System.Windows.Controls.RichTextBox; if (TargetRichTextBox != null) return; //this.TargetForm = FormHelper.CreateForm(this.FormName, this.Width, this.Height, false, this.ShowMinimized, this.ToolWindow); //this.CreatedForm = true; var openFormByName = System.Windows.Application.Current.Windows.Cast<Window>().FirstOrDefault(x => x.GetType().Name == FormName); if (openFormByName != null) { TargetForm = openFormByName; if (string.IsNullOrEmpty(this.ControlName)) { // throw new NLogConfigurationException("Rich text box control name must be specified for " + GetType().Name + "."); Trace.WriteLine("Rich text box control name must be specified for " + GetType().Name + "."); } CreatedForm = false; TargetRichTextBox = TargetForm.FindName(ControlName) as System.Windows.Controls.RichTextBox ; if (this.TargetRichTextBox == null) { // throw new NLogConfigurationException("Rich text box control '" + ControlName + "' cannot be found on form '" + FormName + "'."); Trace.WriteLine("Rich text box control '" + ControlName + "' cannot be found on form '" + FormName + "'."); } } if(TargetRichTextBox == null) { TargetForm = new Window { Name = FormName, Width = Width, Height = Height, WindowStyle = ToolWindow ? WindowStyle.ToolWindow : WindowStyle.None, WindowState = ShowMinimized ? WindowState.Minimized : WindowState.Normal, Title = "NLog Messages" }; TargetForm.Show(); TargetRichTextBox = new System.Windows.Controls.RichTextBox { Name = ControlName }; var style = new Style(typeof(Paragraph)); TargetRichTextBox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; style.Setters.Add(new Setter(Block.MarginProperty, new Thickness(0,0,0,0))); TargetRichTextBox.Resources.Add(typeof(Paragraph), style); TargetForm.Content = TargetRichTextBox; CreatedForm = true; } } protected override void CloseTarget() { if (CreatedForm) { try { TargetForm.Dispatcher.Invoke(() => { TargetForm.Close(); TargetForm = null; }); } catch { } } } protected override void Write(LogEventInfo logEvent) { WpfRichTextBoxRowColoringRule matchingRule = RowColoringRules.FirstOrDefault(rr => rr.CheckCondition(logEvent)); if (UseDefaultRowColoringRules && matchingRule == null) { foreach (var rr in DefaultRowColoringRules.Where(rr => rr.CheckCondition(logEvent))) { matchingRule = rr; break; } } if (matchingRule == null) { matchingRule = WpfRichTextBoxRowColoringRule.Default; } var logMessage = Layout.Render(logEvent); if (System.Windows.Application.Current == null) return; try { if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) { System.Windows.Application.Current.Dispatcher.Invoke(() => SendTheMessageToRichTextBox(logMessage, matchingRule)); } else { SendTheMessageToRichTextBox(logMessage, matchingRule); } } catch(Exception ex) { Debug.WriteLine(ex); } } private static Color GetColorFromString(string color, Brush defaultColor) { if (color == "Empty") { color = "White"; } return (Color)colorConverter.ConvertFromString(color); } private void SendTheMessageToRichTextBox(string logMessage, WpfRichTextBoxRowColoringRule rule) { System.Windows.Controls.RichTextBox rtbx = TargetRichTextBox; var tr = new TextRange(rtbx.Document.ContentEnd, rtbx.Document.ContentEnd); tr.Text = logMessage + "\n"; tr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(GetColorFromString(rule.FontColor, (Brush)tr.GetPropertyValue(TextElement.ForegroundProperty))) ); tr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(GetColorFromString(rule.BackgroundColor, (Brush)tr.GetPropertyValue(TextElement.BackgroundProperty))) ); tr.ApplyPropertyValue(TextElement.FontStyleProperty, rule.Style); tr.ApplyPropertyValue(TextElement.FontWeightProperty, rule.Weight); if (this.MaxLines > 0) { this.lineCount++; if (this.lineCount > MaxLines) { tr = new TextRange(rtbx.Document.ContentStart, rtbx.Document.ContentEnd); tr.Text.Remove(0, tr.Text.IndexOf('\n')); this.lineCount--; } } if (this.AutoScroll) { rtbx.ScrollToEnd(); } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing.Internal { using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; internal class GPStream : UnsafeNativeMethods.IStream { protected Stream dataStream; // to support seeking ahead of the stream length... private long _virtualPosition = -1; internal GPStream(Stream stream) { if (!stream.CanSeek) { const int ReadBlock = 256; byte[] bytes = new byte[ReadBlock]; int readLen; int current = 0; do { if (bytes.Length < current + ReadBlock) { byte[] newData = new byte[bytes.Length * 2]; Array.Copy(bytes, newData, bytes.Length); bytes = newData; } readLen = stream.Read(bytes, current, ReadBlock); current += readLen; } while (readLen != 0); dataStream = new MemoryStream(bytes); } else { dataStream = stream; } } private void ActualizeVirtualPosition() { if (_virtualPosition == -1) return; if (_virtualPosition > dataStream.Length) dataStream.SetLength(_virtualPosition); dataStream.Position = _virtualPosition; _virtualPosition = -1; } public virtual UnsafeNativeMethods.IStream Clone() { NotImplemented(); return null; } public virtual void Commit(int grfCommitFlags) { dataStream.Flush(); // Extend the length of the file if needed. ActualizeVirtualPosition(); } [ UIPermission(SecurityAction.Demand, Window = UIPermissionWindow.AllWindows), SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode) ] public virtual long CopyTo(UnsafeNativeMethods.IStream pstm, long cb, long[] pcbRead) { int bufsize = 4096; // one page IntPtr buffer = Marshal.AllocHGlobal(bufsize); if (buffer == IntPtr.Zero) throw new OutOfMemoryException(); long written = 0; try { while (written < cb) { int toRead = bufsize; if (written + toRead > cb) toRead = (int)(cb - written); int read = Read(buffer, toRead); if (read == 0) break; if (pstm.Write(buffer, read) != read) { throw EFail("Wrote an incorrect number of bytes"); } written += read; } } finally { Marshal.FreeHGlobal(buffer); } if (pcbRead != null && pcbRead.Length > 0) { pcbRead[0] = written; } return written; } public virtual Stream GetDataStream() { return dataStream; } public virtual void LockRegion(long libOffset, long cb, int dwLockType) { } protected static ExternalException EFail(string msg) { throw new ExternalException(msg, SafeNativeMethods.E_FAIL); } protected static void NotImplemented() { throw new ExternalException(SR.Format(SR.NotImplemented), SafeNativeMethods.E_NOTIMPL); } public virtual int Read(IntPtr buf, /* cpr: int offset,*/ int length) { // System.Text.Out.WriteLine("IStream::Read(" + length + ")"); byte[] buffer = new byte[length]; int count = Read(buffer, length); Marshal.Copy(buffer, 0, buf, length); return count; } public virtual int Read(byte[] buffer, /* cpr: int offset,*/ int length) { ActualizeVirtualPosition(); return dataStream.Read(buffer, 0, length); } public virtual void Revert() { NotImplemented(); } public virtual long Seek(long offset, int origin) { // Console.WriteLine("IStream::Seek("+ offset + ", " + origin + ")"); long pos = _virtualPosition; if (_virtualPosition == -1) { pos = dataStream.Position; } long len = dataStream.Length; switch (origin) { case SafeNativeMethods.StreamConsts.STREAM_SEEK_SET: if (offset <= len) { dataStream.Position = offset; _virtualPosition = -1; } else { _virtualPosition = offset; } break; case SafeNativeMethods.StreamConsts.STREAM_SEEK_END: if (offset <= 0) { dataStream.Position = len + offset; _virtualPosition = -1; } else { _virtualPosition = len + offset; } break; case SafeNativeMethods.StreamConsts.STREAM_SEEK_CUR: if (offset + pos <= len) { dataStream.Position = pos + offset; _virtualPosition = -1; } else { _virtualPosition = offset + pos; } break; } if (_virtualPosition != -1) { return _virtualPosition; } else { return dataStream.Position; } } public virtual void SetSize(long value) { dataStream.SetLength(value); } public void Stat(IntPtr pstatstg, int grfStatFlag) { STATSTG stats = new STATSTG(); stats.cbSize = dataStream.Length; Marshal.StructureToPtr(stats, pstatstg, true); } public virtual void UnlockRegion(long libOffset, long cb, int dwLockType) { } public virtual int Write(IntPtr buf, /* cpr: int offset,*/ int length) { byte[] buffer = new byte[length]; Marshal.Copy(buf, buffer, 0, length); return Write(buffer, length); } public virtual int Write(byte[] buffer, /* cpr: int offset,*/ int length) { ActualizeVirtualPosition(); dataStream.Write(buffer, 0, length); return length; } [StructLayout(LayoutKind.Sequential)] public class STATSTG { public IntPtr pwcsName = IntPtr.Zero; public int type; [MarshalAs(UnmanagedType.I8)] public long cbSize; [MarshalAs(UnmanagedType.I8)] public long mtime; [MarshalAs(UnmanagedType.I8)] public long ctime; [MarshalAs(UnmanagedType.I8)] public long atime; [MarshalAs(UnmanagedType.I4)] public int grfMode; [MarshalAs(UnmanagedType.I4)] public int grfLocksSupported; public int clsid_data1; [MarshalAs(UnmanagedType.I2)] public short clsid_data2; [MarshalAs(UnmanagedType.I2)] public short clsid_data3; [MarshalAs(UnmanagedType.U1)] public byte clsid_b0; [MarshalAs(UnmanagedType.U1)] public byte clsid_b1; [MarshalAs(UnmanagedType.U1)] public byte clsid_b2; [MarshalAs(UnmanagedType.U1)] public byte clsid_b3; [MarshalAs(UnmanagedType.U1)] public byte clsid_b4; [MarshalAs(UnmanagedType.U1)] public byte clsid_b5; [MarshalAs(UnmanagedType.U1)] public byte clsid_b6; [MarshalAs(UnmanagedType.U1)] public byte clsid_b7; [MarshalAs(UnmanagedType.I4)] public int grfStateBits; [MarshalAs(UnmanagedType.I4)] public int reserved; } } }
#pragma warning disable 1587 #region Header /// /// JsonWriter.cs /// Stream-like facility to output JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace Json.LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ("\r\n"); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { char c = str[i]; switch (c) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (c); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) c >= 32 && (int) c <= 126) { writer.Write (c); continue; } if (c < ' ' || (c >= '\u0080' && c < '\u00a0')) { // Turn into a \uXXXX sequence IntToHex((int)c, hex_seq); writer.Write("\\u"); writer.Write(hex_seq); } else { writer.Write(c); } } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write(DateTime date) { DoValidation(Condition.Value); PutNewline(); Put(ServiceClientGenerator.GeneratorHelpers.ConvertToUnixEpochMilliSeconds(date).ToString(CultureInfo.InvariantCulture)); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 4:35:25 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// GaussKrugerBeijing1954 /// </summary> public class GaussKrugerBeijing1954 : CoordinateSystemCategory { #region Fields public readonly ProjectionInfo Beijing19543DegreeGKCM102E; public readonly ProjectionInfo Beijing19543DegreeGKCM105E; public readonly ProjectionInfo Beijing19543DegreeGKCM108E; public readonly ProjectionInfo Beijing19543DegreeGKCM111E; public readonly ProjectionInfo Beijing19543DegreeGKCM114E; public readonly ProjectionInfo Beijing19543DegreeGKCM117E; public readonly ProjectionInfo Beijing19543DegreeGKCM120E; public readonly ProjectionInfo Beijing19543DegreeGKCM123E; public readonly ProjectionInfo Beijing19543DegreeGKCM126E; public readonly ProjectionInfo Beijing19543DegreeGKCM129E; public readonly ProjectionInfo Beijing19543DegreeGKCM132E; public readonly ProjectionInfo Beijing19543DegreeGKCM135E; public readonly ProjectionInfo Beijing19543DegreeGKCM75E; public readonly ProjectionInfo Beijing19543DegreeGKCM78E; public readonly ProjectionInfo Beijing19543DegreeGKCM81E; public readonly ProjectionInfo Beijing19543DegreeGKCM84E; public readonly ProjectionInfo Beijing19543DegreeGKCM87E; public readonly ProjectionInfo Beijing19543DegreeGKCM90E; public readonly ProjectionInfo Beijing19543DegreeGKCM93E; public readonly ProjectionInfo Beijing19543DegreeGKCM96E; public readonly ProjectionInfo Beijing19543DegreeGKCM99E; public readonly ProjectionInfo Beijing19543DegreeGKZone25; public readonly ProjectionInfo Beijing19543DegreeGKZone26; public readonly ProjectionInfo Beijing19543DegreeGKZone27; public readonly ProjectionInfo Beijing19543DegreeGKZone28; public readonly ProjectionInfo Beijing19543DegreeGKZone29; public readonly ProjectionInfo Beijing19543DegreeGKZone30; public readonly ProjectionInfo Beijing19543DegreeGKZone31; public readonly ProjectionInfo Beijing19543DegreeGKZone32; public readonly ProjectionInfo Beijing19543DegreeGKZone33; public readonly ProjectionInfo Beijing19543DegreeGKZone34; public readonly ProjectionInfo Beijing19543DegreeGKZone35; public readonly ProjectionInfo Beijing19543DegreeGKZone36; public readonly ProjectionInfo Beijing19543DegreeGKZone37; public readonly ProjectionInfo Beijing19543DegreeGKZone38; public readonly ProjectionInfo Beijing19543DegreeGKZone39; public readonly ProjectionInfo Beijing19543DegreeGKZone40; public readonly ProjectionInfo Beijing19543DegreeGKZone41; public readonly ProjectionInfo Beijing19543DegreeGKZone42; public readonly ProjectionInfo Beijing19543DegreeGKZone43; public readonly ProjectionInfo Beijing19543DegreeGKZone44; public readonly ProjectionInfo Beijing19543DegreeGKZone45; public readonly ProjectionInfo Beijing1954GKZone13; public readonly ProjectionInfo Beijing1954GKZone13N; public readonly ProjectionInfo Beijing1954GKZone14; public readonly ProjectionInfo Beijing1954GKZone14N; public readonly ProjectionInfo Beijing1954GKZone15; public readonly ProjectionInfo Beijing1954GKZone15N; public readonly ProjectionInfo Beijing1954GKZone16; public readonly ProjectionInfo Beijing1954GKZone16N; public readonly ProjectionInfo Beijing1954GKZone17; public readonly ProjectionInfo Beijing1954GKZone17N; public readonly ProjectionInfo Beijing1954GKZone18; public readonly ProjectionInfo Beijing1954GKZone18N; public readonly ProjectionInfo Beijing1954GKZone19; public readonly ProjectionInfo Beijing1954GKZone19N; public readonly ProjectionInfo Beijing1954GKZone20; public readonly ProjectionInfo Beijing1954GKZone20N; public readonly ProjectionInfo Beijing1954GKZone21; public readonly ProjectionInfo Beijing1954GKZone21N; public readonly ProjectionInfo Beijing1954GKZone22; public readonly ProjectionInfo Beijing1954GKZone22N; public readonly ProjectionInfo Beijing1954GKZone23; public readonly ProjectionInfo Beijing1954GKZone23N; #endregion #region Constructors /// <summary> /// Creates a new instance of GaussKrugerBeijing1954 /// </summary> public GaussKrugerBeijing1954() { Beijing19543DegreeGKCM102E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM105E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM108E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM111E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM114E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM117E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM120E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM123E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM126E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM129E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM132E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM135E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM75E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM78E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM81E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM84E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM87E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM90E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM93E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM96E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM99E = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone25 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=25500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone26 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=78 +k=1.000000 +x_0=26500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone27 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=27500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone28 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=84 +k=1.000000 +x_0=28500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone29 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=29500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone30 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=90 +k=1.000000 +x_0=30500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone31 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=31500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone32 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=96 +k=1.000000 +x_0=32500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone33 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=33500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone34 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=102 +k=1.000000 +x_0=34500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone35 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=35500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone36 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=108 +k=1.000000 +x_0=36500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone37 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=37500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone38 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=114 +k=1.000000 +x_0=38500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone39 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=39500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone40 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=120 +k=1.000000 +x_0=40500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone41 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=41500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone42 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=126 +k=1.000000 +x_0=42500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone43 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=43500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone44 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=132 +k=1.000000 +x_0=44500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKZone45 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=45500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone13 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=13500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone13N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=75 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone14 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=14500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone14N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=81 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone15 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=15500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone15N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=87 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone16 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=16500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone16N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=93 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone17 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=17500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone17N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=99 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone18 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=18500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone18N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=105 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone19 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=19500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone19N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=111 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone20 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=20500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone20N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=117 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone21 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=21500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone21N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=123 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone22 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=22500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone22N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=129 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone23 = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=23500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing1954GKZone23N = ProjectionInfo.FromProj4String("+proj=tmerc +lat_0=0 +lon_0=135 +k=1.000000 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs "); Beijing19543DegreeGKCM102E.Name = "Beijing_1954_3_Degree_GK_CM_102E"; Beijing19543DegreeGKCM105E.Name = "Beijing_1954_3_Degree_GK_CM_105E"; Beijing19543DegreeGKCM108E.Name = "Beijing_1954_3_Degree_GK_CM_108E"; Beijing19543DegreeGKCM111E.Name = "Beijing_1954_3_Degree_GK_CM_111E"; Beijing19543DegreeGKCM114E.Name = "Beijing_1954_3_Degree_GK_CM_114E"; Beijing19543DegreeGKCM117E.Name = "Beijing_1954_3_Degree_GK_CM_117E"; Beijing19543DegreeGKCM120E.Name = "Beijing_1954_3_Degree_GK_CM_120E"; Beijing19543DegreeGKCM123E.Name = "Beijing_1954_3_Degree_GK_CM_123E"; Beijing19543DegreeGKCM126E.Name = "Beijing_1954_3_Degree_GK_CM_126E"; Beijing19543DegreeGKCM129E.Name = "Beijing_1954_3_Degree_GK_CM_129E"; Beijing19543DegreeGKCM132E.Name = "Beijing_1954_3_Degree_GK_CM_132E"; Beijing19543DegreeGKCM135E.Name = "Beijing_1954_3_Degree_GK_CM_135E"; Beijing19543DegreeGKCM75E.Name = "Beijing_1954_3_Degree_GK_CM_75E"; Beijing19543DegreeGKCM78E.Name = "Beijing_1954_3_Degree_GK_CM_78E"; Beijing19543DegreeGKCM81E.Name = "Beijing_1954_3_Degree_GK_CM_81E"; Beijing19543DegreeGKCM84E.Name = "Beijing_1954_3_Degree_GK_CM_84E"; Beijing19543DegreeGKCM87E.Name = "Beijing_1954_3_Degree_GK_CM_87E"; Beijing19543DegreeGKCM90E.Name = "Beijing_1954_3_Degree_GK_CM_90E"; Beijing19543DegreeGKCM93E.Name = "Beijing_1954_3_Degree_GK_CM_93E"; Beijing19543DegreeGKCM96E.Name = "Beijing_1954_3_Degree_GK_CM_96E"; Beijing19543DegreeGKCM99E.Name = "Beijing_1954_3_Degree_GK_CM_99E"; Beijing19543DegreeGKZone25.Name = "Beijing_1954_3_Degree_GK_Zone_25"; Beijing19543DegreeGKZone26.Name = "Beijing_1954_3_Degree_GK_Zone_26"; Beijing19543DegreeGKZone27.Name = "Beijing_1954_3_Degree_GK_Zone_27"; Beijing19543DegreeGKZone28.Name = "Beijing_1954_3_Degree_GK_Zone_28"; Beijing19543DegreeGKZone29.Name = "Beijing_1954_3_Degree_GK_Zone_29"; Beijing19543DegreeGKZone30.Name = "Beijing_1954_3_Degree_GK_Zone_30"; Beijing19543DegreeGKZone31.Name = "Beijing_1954_3_Degree_GK_Zone_31"; Beijing19543DegreeGKZone32.Name = "Beijing_1954_3_Degree_GK_Zone_32"; Beijing19543DegreeGKZone33.Name = "Beijing_1954_3_Degree_GK_Zone_33"; Beijing19543DegreeGKZone34.Name = "Beijing_1954_3_Degree_GK_Zone_34"; Beijing19543DegreeGKZone35.Name = "Beijing_1954_3_Degree_GK_Zone_35"; Beijing19543DegreeGKZone36.Name = "Beijing_1954_3_Degree_GK_Zone_36"; Beijing19543DegreeGKZone37.Name = "Beijing_1954_3_Degree_GK_Zone_37"; Beijing19543DegreeGKZone38.Name = "Beijing_1954_3_Degree_GK_Zone_38"; Beijing19543DegreeGKZone39.Name = "Beijing_1954_3_Degree_GK_Zone_39"; Beijing19543DegreeGKZone40.Name = "Beijing_1954_3_Degree_GK_Zone_40"; Beijing19543DegreeGKZone41.Name = "Beijing_1954_3_Degree_GK_Zone_41"; Beijing19543DegreeGKZone42.Name = "Beijing_1954_3_Degree_GK_Zone_42"; Beijing19543DegreeGKZone43.Name = "Beijing_1954_3_Degree_GK_Zone_43"; Beijing19543DegreeGKZone44.Name = "Beijing_1954_3_Degree_GK_Zone_44"; Beijing19543DegreeGKZone45.Name = "Beijing_1954_3_Degree_GK_Zone_45"; Beijing1954GKZone13.Name = "Beijing_1954_GK_Zone_13"; Beijing1954GKZone13N.Name = "Beijing_1954_GK_Zone_13N"; Beijing1954GKZone14.Name = "Beijing_1954_GK_Zone_14"; Beijing1954GKZone14N.Name = "Beijing_1954_GK_Zone_14N"; Beijing1954GKZone15.Name = "Beijing_1954_GK_Zone_15"; Beijing1954GKZone15N.Name = "Beijing_1954_GK_Zone_15N"; Beijing1954GKZone16.Name = "Beijing_1954_GK_Zone_16"; Beijing1954GKZone16N.Name = "Beijing_1954_GK_Zone_16N"; Beijing1954GKZone17.Name = "Beijing_1954_GK_Zone_17"; Beijing1954GKZone17N.Name = "Beijing_1954_GK_Zone_17N"; Beijing1954GKZone18.Name = "Beijing_1954_GK_Zone_18"; Beijing1954GKZone18N.Name = "Beijing_1954_GK_Zone_18N"; Beijing1954GKZone19.Name = "Beijing_1954_GK_Zone_19"; Beijing1954GKZone19N.Name = "Beijing_1954_GK_Zone_19N"; Beijing1954GKZone20.Name = "Beijing_1954_GK_Zone_20"; Beijing1954GKZone20N.Name = "Beijing_1954_GK_Zone_20N"; Beijing1954GKZone21.Name = "Beijing_1954_GK_Zone_21"; Beijing1954GKZone21N.Name = "Beijing_1954_GK_Zone_21N"; Beijing1954GKZone22.Name = "Beijing_1954_GK_Zone_22"; Beijing1954GKZone22N.Name = "Beijing_1954_GK_Zone_22N"; Beijing1954GKZone23.Name = "Beijing_1954_GK_Zone_23"; Beijing1954GKZone23N.Name = "Beijing_1954_GK_Zone_23N"; Beijing19543DegreeGKZone28.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone29.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone30.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone31.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone32.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone33.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone34.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone35.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone36.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone37.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone38.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone39.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone40.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone41.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone42.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone43.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone44.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone45.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone13.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone13N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone14.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone14N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone15.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone15N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone16.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone16N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone17.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone17N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone18.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone18N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone19.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone19N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone20.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone20N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone21.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone21N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone22.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone22N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone23.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing1954GKZone23N.GeographicInfo.Name = "GCS_Beijing_1954"; Beijing19543DegreeGKZone28.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone29.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone30.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone31.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone32.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone33.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone34.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone35.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone36.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone37.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone38.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone39.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone40.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone41.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone42.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone43.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone44.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing19543DegreeGKZone45.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone13.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone13N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone14.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone14N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone15.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone15N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone16.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone16N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone17.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone17N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone18.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone18N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone19.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone19N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone20.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone20N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone21.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone21N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone22.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone22N.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone23.GeographicInfo.Datum.Name = "D_Beijing_1954"; Beijing1954GKZone23N.GeographicInfo.Datum.Name = "D_Beijing_1954"; } #endregion } } #pragma warning restore 1591
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider { internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return text[characterPosition] == '<'; } protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync( Document document, int position, TextSpan span, CompletionTrigger trigger, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken); var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>(); if (parentTrivia == null) { return null; } var items = new List<CompletionItem>(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var attachedToken = parentTrivia.ParentTrivia.Token; if (attachedToken.Kind() == SyntaxKind.None) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false); ISymbol declaredSymbol = null; var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken); } else { var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>(); if (typeDeclaration != null) { declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); } } if (declaredSymbol != null) { items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token)); } if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText || (token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) || (token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement))) { // The user is typing inside an XmlElement if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement) { items.AddRange(GetNestedTags(declaredSymbol)); } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement)) { var element = (XmlElementSyntax)token.Parent.Parent.Parent; if (element.StartTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } } if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems()); } if (token.Parent.Parent is DocumentationCommentTriviaSyntax) { items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span)); items.AddRange(GetTopLevelRepeatableItems()); } } if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag) { var startTag = (XmlElementStartTagSyntax)token.Parent; if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListTagName) { items.AddRange(GetListItems(span)); } if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == ListHeaderTagName) { items.AddRange(GetListHeaderItems()); } } items.AddRange(GetAlwaysVisibleItems()); return items; } private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span) { var names = new HashSet<string>(new[] { SummaryTagName, RemarksTagName, ExampleTagName, CompletionListTagName }); RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText); return names.Select(GetItem); } private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector) { if (parentTrivia != null) { foreach (var node in parentTrivia.Content) { var element = node as XmlElementSyntax; if (element != null) { names.Remove(selector(element)); } } } } private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan itemSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { if (symbol is IMethodSymbol) { return GetTagsForMethod((IMethodSymbol)symbol, trivia, token); } if (symbol is IPropertySymbol) { return GetTagsForProperty((IPropertySymbol)symbol, trivia, token); } if (symbol is INamedTypeSymbol) { return GetTagsForType((INamedTypeSymbol)symbol, trivia); } return SpecializedCollections.EmptyEnumerable<CompletionItem>(); } private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, DocumentationCommentTriviaSyntax trivia) { var items = new List<CompletionItem>(); var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet(); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t)))); return items; } private string AttributeSelector(XmlElementSyntax element, string attribute) { if (!element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == NameAttributeName); if (nameAttribute != null) { if (startTag.Name.LocalName.ValueText == attribute) { return nameAttribute.Identifier.Identifier.ValueText; } } } return null; } private IEnumerable<CompletionItem> GetTagsForProperty( IPropertySymbol symbol, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); if (symbol.IsIndexer) { var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(CreateCompletionItem)); } return items; } RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p)))); } var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet(); items.AddRange(typeParameters.Select(t => CreateCompletionItem(TypeParamTagName, NameAttributeName, t))); items.Add(CreateCompletionItem("value")); return items; } private IEnumerable<CompletionItem> GetTagsForMethod( IMethodSymbol symbol, DocumentationCommentTriviaSyntax trivia, SyntaxToken token) { var items = new List<CompletionItem>(); var parameters = symbol.GetParameters().Select(p => p.Name).ToSet(); var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet(); // User is trying to write a name, try to suggest only names. if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) || (token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute))) { string parentElementName = null; var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>(); if (emptyElement != null) { parentElementName = emptyElement.Name.LocalName.Text; } // We're writing the name of a paramref or typeparamref if (parentElementName == ParamRefTagName) { items.AddRange(parameters.Select(CreateCompletionItem)); } else if (parentElementName == TypeParamRefTagName) { items.AddRange(typeParameters.Select(CreateCompletionItem)); } return items; } RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, ParamTagName)); RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, TypeParamTagName)); items.AddRange(parameters.Select(p => CreateCompletionItem(FormatParameter(ParamTagName, p)))); items.AddRange(typeParameters.Select(t => CreateCompletionItem(FormatParameter(TypeParamTagName, t)))); // Provide a return completion item in case the function returns something var returns = true; foreach (var node in trivia.Content) { var element = node as XmlElementSyntax; if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing) { var startTag = element.StartTag; if (startTag.Name.LocalName.ValueText == ReturnsTagName) { returns = false; break; } } } if (returns && !symbol.ReturnsVoid) { items.Add(CreateCompletionItem(ReturnsTagName)); } return items; } private static CompletionItemRules s_defaultRules = CompletionItemRules.Create( filterCharacterRules: FilterRules, commitCharacterRules: ImmutableArray.Create(CharacterSetModificationRule.Create(CharacterSetModificationKind.Add, '>', '\t')), enterKeyRule: EnterKeyRule.Never); protected override CompletionItemRules GetCompletionItemRules(string displayText) { var commitRules = s_defaultRules.CommitCharacterRules; if (displayText.Contains("\"")) { commitRules = commitRules.Add(WithoutQuoteRule); } if (displayText.Contains(" ")) { commitRules = commitRules.Add(WithoutSpaceRule); } return s_defaultRules.WithCommitCharacterRules(commitRules); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Contracts.Regression; using System.Diagnostics.CodeAnalysis; [assembly:RegressionOutcome(@"Method 'UserFeedback.AndrewArnott.IFaceImpl.Method(System.Object)' implements interface method 'UserFeedback.AndrewArnott.IFace.Method(System.Object)', thus cannot add Requires.")] //[assembly:RegressionOutcome("Detected call to method 'UserFeedback.MaF.CheckStructInvariant.PropIsTrue' without [Pure] in contracts of method 'UserFeedback.MaF.CheckStructInvariant.ObjectInvariant'.")] namespace UserFeedback { namespace AndrewArnott { [ContractClass(typeof(IFaceContract))] interface IFace { void Method(object param); } [ContractClassFor(typeof(IFace))] abstract class IFaceContract : IFace { #region IFace Members void IFace.Method(object param) { Contract.Requires<ArgumentNullException>(param != null); } #endregion } class IFaceImpl : IFace { #region IFace Members [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 19, MethodILOffset = 0)] public void Method(object param) { Contract.Requires<ArgumentNullException>(param != null); Contract.Assert(param != null); } #endregion } } namespace AlexeyR { class AlexeyR1 { Dictionary<string, object> _dict = new Dictionary<string, object>(); void AddItemToDict(string key, string value) { Contract.Requires(!_dict.ContainsKey(key)); _dict.Add(key, value); // do something with a newly added item } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 15, MethodILOffset = 17)] void ProcessItem(string key, string value) { if (!_dict.ContainsKey(key)) { AddItemToDict(key, value); return; } } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "requires unproven: !_dict.ContainsKey(key)", PrimaryILOffset = 15, MethodILOffset = 3)] void ProcessItemBad(string key, string value) { AddItemToDict(key, value); } } } namespace Mathias { class Mathias { [ClousotRegressionTest] void Test(int[] array, int index) { Contract.Requires(array[index] == 0); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 19, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 6, MethodILOffset = 8)] void Test2(int[] array, int index) { if (array[index] == 0) { Test(array, index); Contract.Assert(array[index] == 0); } } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 15, MethodILOffset = 0)] void Test3(int[] array, int index) { if (array[index] == 0) { array[5] = 5; Contract.Assert(array[index] == 0); } } } } namespace DevInstinct { class DevInstinct { public static void TestIsNullOrEmptyCollection(System.Collections.ICollection collection) { Contract.Requires(collection == null || collection.Count == 0); } [ClousotRegressionTest] // http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/a1b922cb-fd7d-4648-afb2-b68c5e3fff4d [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 15, MethodILOffset = 1)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 15, MethodILOffset = 12)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 15, MethodILOffset = 22)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 15, MethodILOffset = 49)] public static void Test() { TestIsNullOrEmptyCollection(null); // ok TestIsNullOrEmptyCollection(new int[] { }); // ok TestIsNullOrEmptyCollection(new List<int>() { }); // ok System.Collections.ICollection iCol = new int[] { } as System.Collections.ICollection; Contract.Assume(iCol.Count == 0); TestIsNullOrEmptyCollection(iCol); } } class LazyInit { string _name; public string Name { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 24, MethodILOffset = 50)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 24, MethodILOffset = 43)] //[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 50)] //[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 43)] get { Contract.Ensures(!IsInitialized || !String.IsNullOrEmpty(Contract.Result<string>())); if (_initialized) return _name; else { return _name; } } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 21)] set { Contract.Requires(!String.IsNullOrEmpty(value)); _name = value; } } public LazyInit() { } bool _initialized; public bool IsInitialized { [ClousotRegressionTest] //[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 6)] get { return _initialized; } } [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(!_initialized || !String.IsNullOrEmpty(_name)); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 25, MethodILOffset = 38)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 53, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 75, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 38)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 25, MethodILOffset = 106)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 25, MethodILOffset = 106)] [SuppressMessage("Microsoft.Contracts", "Assert-94-0")] public void FinalizeInit() { Contract.Requires(!string.IsNullOrEmpty(Name)); Contract.Ensures(IsInitialized); if (_initialized) { return; } Contract.Assert(!String.IsNullOrEmpty(Name)); Contract.Assert(Name == _name); Contract.Assert(!string.IsNullOrEmpty(_name)); _initialized = true; } } public class TestLazy { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 9, MethodILOffset = 30)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 14, MethodILOffset = 36)] public static void M() { var l = new LazyInit(); Contract.Assume(!String.IsNullOrEmpty("Hello")); l.Name = "Hello"; l.FinalizeInit(); } } } namespace ManfredSteyer { public class Account { [ContractPublicPropertyName("Value")] protected int value; public int Value { [ClousotRegressionTest] get { return value; } } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 20, MethodILOffset = 58)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 44, MethodILOffset = 58)] public virtual int calcInterest() { Contract.Ensures(Contract.Result<int>() >= 0 || value < 0); Contract.Ensures(value == Contract.OldValue(value)); return value / 50; } [ClousotRegressionTest] public virtual void Deposit(int amount) { Contract.Requires(amount > 0); value += amount; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 30, MethodILOffset = 49)] public virtual void Withdraw(int amount) { Contract.Requires(amount > 0); Contract.Ensures(value == Contract.OldValue(value) - amount); value -= amount; } } public class SavingsAccount : Account { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 4, MethodILOffset = 17)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 30, MethodILOffset = 22)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 22)] public override void Withdraw(int amount) { if (value < amount) throw new ApplicationException(); base.Withdraw(amount); } [ContractInvariantMethod()] void InvariantMethod() { Contract.Invariant(value >= 0); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 20, MethodILOffset = 22)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 44, MethodILOffset = 22)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 11, MethodILOffset = 22)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 12, MethodILOffset = 22)] public override int calcInterest() { Contract.Ensures(Contract.Result<int>() >= 0); return base.calcInterest(); } } } namespace Damden { public class BadReversedCondition { public long Wakeup { get { return _Wakeup; } protected set { #region require: At least 25 ms or 0 ms if (value < 25 && value != 0) { throw new InvalidOperationException("The wakeup mechanisme is not suited for smaller periods than 25 ms."); } Contract.EndContractBlock(); #endregion _Wakeup = value; } } private long _Wakeup; public static void Test() { var b = new BadReversedCondition(); b.Wakeup = 1234; } } } namespace Joost { class Rationaal { int Noemer { get; set; } int Deler { get; set; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "ensures unproven: Noemer == noemer", PrimaryILOffset = 43, MethodILOffset = 76)] [RegressionOutcome(Outcome = ProofOutcome.False, Message = "ensures is false: Deler == deler", PrimaryILOffset = 57, MethodILOffset = 76)] public Rationaal(int noemer, int deler) { Contract.Requires(noemer > 0, "noemer must be positive."); Contract.Requires(deler > 0, "deler must be positive."); Contract.Ensures(Noemer == noemer); Contract.Ensures(Deler == deler); // not satisfied! Noemer = noemer; Noemer = deler; // typo } } } namespace Sgro { [ContractClass(typeof(ITestClassWithInterfaceContract))] interface ITestClassWithInterface { string Name { get; set; } } [ContractClassFor(typeof(ITestClassWithInterface))] abstract class ITestClassWithInterfaceContract : ITestClassWithInterface { #region ITestClassWithInterface Members string ITestClassWithInterface.Name { get { Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())); throw new NotImplementedException(); } set { Contract.Requires(!String.IsNullOrEmpty(value)); throw new NotImplementedException(); } } #endregion } class TestWithInterface : ITestClassWithInterface { [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(!string.IsNullOrEmpty(this._name)); } #region ITestClassWithInterface Members [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.False, Message = "invariant is false: !string.IsNullOrEmpty(this._name)", PrimaryILOffset = 14, MethodILOffset = 6)] public TestWithInterface() { // buggy because invariant not established } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 27)] public TestWithInterface(string initialName) { Contract.Requires(!String.IsNullOrEmpty(initialName)); this._name = initialName; } private string _name; public string Name { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 13, MethodILOffset = 6)] // [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 6)] get { return this._name; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 7)] set { this._name = value; } } #endregion } class TestSimple { [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(!string.IsNullOrEmpty(this._name)); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.False, Message = "invariant is false: !string.IsNullOrEmpty(this._name)", PrimaryILOffset = 14, MethodILOffset = 6)] public TestSimple() { // buggy because invariant is not established } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 27)] public TestSimple(string initialName) { Contract.Requires(!String.IsNullOrEmpty(initialName)); this._name = initialName; } private string _name; public string Name { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 13, MethodILOffset = 24)] // [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 24)] get { Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>())); return this._name; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"invariant is valid", PrimaryILOffset = 14, MethodILOffset = 21)] set { Contract.Requires(!String.IsNullOrEmpty(value)); this._name = value; } } } } namespace Pelmens { class SomeClass { private int? number; private int? Prop { get; set; } [ClousotRegressionTest] public SomeClass(int? value) { number = value; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 19)] public int SomeMethod() { if (number.HasValue) { return number.Value; } return 0; } [ClousotRegressionTest] // We are not smart enough here. The ldflda accessing number causes us to havoc Prop [RegressionOutcome(Outcome = ProofOutcome.True, Message = "requires is valid", PrimaryILOffset = 12, MethodILOffset = 38)] public int SomeMethod2() { if (Prop.HasValue) { if (number.HasValue) { return Prop.Value; } } return 0; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 12, MethodILOffset = 11)] public int SomeMethod(int? num) { if (num.HasValue) { return num.Value; } return 0; } } } namespace JonSkeet { class Arithmetic { [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 13, MethodILOffset = 9)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"requires is valid", PrimaryILOffset = 13, MethodILOffset = 18)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 81, MethodILOffset = 0)] void Test() { Random rng = new Random(); int first = rng.Next(1, 7), second = rng.Next(1, 7); Contract.Assume(first >= 1 && first <= 6); Contract.Assume(second >= 1 && second <= 6); int sum = first + second; Contract.Assert(sum >= 2 && sum <= 12); } } } namespace MaF { class CheckInvariants { [ContractInvariantMethod] void ObjectInvariant() { //Contract.Assume(false); } } [SuppressMessage("Microsoft.Contracts", "CC1036")] struct CheckStructInvariant { [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(PropIsTrue()); } public bool PropIsTrue() { return true; } } class Disjuncts { [Pure] static bool DoIt(int x) { if (x < -100) return false; if (x > 100) return false; return true; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 56, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 37, MethodILOffset = 86)] public static int M(int x) { Contract.Requires(x < -5 || x > 5); Contract.Ensures(Contract.Result<int>() < -5 || Contract.Result<int>() > 5); // .. paths split while (DoIt(x)) { // .. no path splitting Contract.Assert(x < -5 || x > 5); // .. paths split if (x < 0) { x--; } else { x++; } // .. paths split } // ... paths split return x; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"ensures is valid", PrimaryILOffset = 20, MethodILOffset = 53)] public static int M(bool y) { Contract.Ensures(Contract.Result<int>() < -5 || Contract.Result<int>() > 5); var x = 0; // ... no path splitting while (x >= -10 && x <= 10) // loop exit condition establishes post state { // no path splitting if (y) { x--; } else { x++; } // no path splitting } // ... paths split according to < -5 || > 5 return x; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 49, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 63, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = @"assert is valid", PrimaryILOffset = 93, MethodILOffset = 0)] public static int SplittingBetter(int x, int y) { Contract.Ensures(x < 0 && Contract.Result<int>() == x - y || x >= 0 && Contract.Result<int>() == x + y); var oldx = x; //while (y > 0) { if (x < 0) { Contract.Assert(oldx < 0); } else { Contract.Assert(oldx >= 0); } Contract.Assert((x >= 0 || oldx < 0) && (x < 0 || oldx >= 0)); Contract.Assume(false); Contract.Assert(oldx < 0 && x == oldx - y || oldx >= 0 && x == oldx + y); if (x < 0) { x--; } else { x++; } y--; } return x; } } } namespace Onurg { public class Foo : IFoo { IEnumerable<T> IFoo.Bar<T>() { return null; } } [ContractClass(typeof(FooContract))] public interface IFoo { IEnumerable<T> Bar<T>(); } [ContractClassFor(typeof(IFoo))] abstract class FooContract : IFoo { IEnumerable<T> IFoo.Bar<T>() { Contract.Ensures(Contract.Result<IEnumerable<T>>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<T>>(), x => x != null)); return default(IEnumerable<T>); } } } namespace MatthijsWoord { } namespace Strilanc { public interface B { bool P { get; } } #region I contract binding [ContractClass(typeof(CI<>))] public partial interface I<T> : B { void S(); } [ContractClassFor(typeof(I<>))] abstract class CI<T> : I<T> { #region I Members public void S() { Contract.Requires(this.P); } #endregion #region B Members public bool P { get { return true; } } #endregion } #endregion public class C : I<bool> { public bool P { get { return true; } } public void S() { } } } namespace Jeannin { class MyList<T> { List<T> list = new List<T>(); [ContractInvariantMethod] void ObjectInvariant() { Contract.Invariant(list != null); } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "invariant is valid", PrimaryILOffset = 12, MethodILOffset = 32)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 11, MethodILOffset = 32)] public IEnumerator<T> GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator<T>>() != null); return this.list.GetEnumerator(); } } } namespace Sexton { class ProgramToTestReadonly { static void ReadonlyTest() { const string theName = "TheName"; var program = Factory(theName); Contract.Assert(program.Name == theName); } public string Name { get { Contract.Ensures(Contract.Result<string>() == name); return name; } } private readonly string name; private ProgramToTestReadonly(string name) { Contract.Ensures(this.name == name); this.name = name; } [ClousotRegressionTest] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 45, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "assert is valid", PrimaryILOffset = 62, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.Top, Message = "assert unproven", PrimaryILOffset = 79, MethodILOffset = 0)] [RegressionOutcome(Outcome = ProofOutcome.True, Message = "ensures is valid", PrimaryILOffset = 16, MethodILOffset = 85)] public static ProgramToTestReadonly Factory(string name) { Contract.Ensures(Contract.Result<ProgramToTestReadonly>().Name == name); var p = new ProgramToTestReadonly(name); Contract.Assert(p.Name == p.name); Contract.Assert(p.name == name); Contract.Assert(p.Name == name); return p; } } } }
using Avalonia.Media; using SkiaSharp; using System; using System.Collections.Generic; using System.Linq; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Rendering.Utilities; using Avalonia.Utilities; namespace Avalonia.Skia { internal class DrawingContextImpl : IDrawingContextImpl { private readonly Vector _dpi; private readonly Matrix? _postTransform; private readonly IDisposable[] _disposables; private readonly IVisualBrushRenderer _visualBrushRenderer; private Stack<PaintWrapper> maskStack = new Stack<PaintWrapper>(); protected bool CanUseLcdRendering = true; public SKCanvas Canvas { get; private set; } public DrawingContextImpl( SKCanvas canvas, Vector dpi, IVisualBrushRenderer visualBrushRenderer, params IDisposable[] disposables) { _dpi = dpi; if (dpi.X != 96 || dpi.Y != 96) _postTransform = Matrix.CreateScale(dpi.X / 96, dpi.Y / 96); _visualBrushRenderer = visualBrushRenderer; _disposables = disposables; Canvas = canvas; Transform = Matrix.Identity; } public void Clear(Color color) { Canvas.Clear(color.ToSKColor()); } public void DrawImage(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect) { var impl = (BitmapImpl)source.Item; var s = sourceRect.ToSKRect(); var d = destRect.ToSKRect(); using (var paint = new SKPaint() { Color = new SKColor(255, 255, 255, (byte)(255 * opacity * _currentOpacity)) }) { Canvas.DrawBitmap(impl.Bitmap, s, d, paint); } } public void DrawImage(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect) { PushOpacityMask(opacityMask, opacityMaskRect); DrawImage(source, 1, new Rect(0, 0, source.Item.PixelWidth, source.Item.PixelHeight), destRect); PopOpacityMask(); } public void DrawLine(Pen pen, Point p1, Point p2) { using (var paint = CreatePaint(pen, new Size(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y)))) { Canvas.DrawLine((float)p1.X, (float)p1.Y, (float)p2.X, (float)p2.Y, paint.Paint); } } public void DrawGeometry(IBrush brush, Pen pen, IGeometryImpl geometry) { var impl = (GeometryImpl)geometry; var size = geometry.Bounds.Size; using (var fill = brush != null ? CreatePaint(brush, size) : default(PaintWrapper)) using (var stroke = pen?.Brush != null ? CreatePaint(pen, size) : default(PaintWrapper)) { if (fill.Paint != null) { Canvas.DrawPath(impl.EffectivePath, fill.Paint); } if (stroke.Paint != null) { Canvas.DrawPath(impl.EffectivePath, stroke.Paint); } } } private struct PaintState : IDisposable { private readonly SKColor _color; private readonly SKShader _shader; private readonly SKPaint _paint; public PaintState(SKPaint paint, SKColor color, SKShader shader) { _paint = paint; _color = color; _shader = shader; } public void Dispose() { _paint.Color = _color; _paint.Shader = _shader; } } internal struct PaintWrapper : IDisposable { //We are saving memory allocations there //TODO: add more disposable fields if needed public readonly SKPaint Paint; private IDisposable _disposable1; private IDisposable _disposable2; public IDisposable ApplyTo(SKPaint paint) { var state = new PaintState(paint, paint.Color, paint.Shader); paint.Color = Paint.Color; paint.Shader = Paint.Shader; return state; } public void AddDisposable(IDisposable disposable) { if (_disposable1 == null) _disposable1 = disposable; else if (_disposable2 == null) _disposable2 = disposable; else throw new InvalidOperationException(); } public PaintWrapper(SKPaint paint) { Paint = paint; _disposable1 = null; _disposable2 = null; } public void Dispose() { Paint?.Dispose(); _disposable1?.Dispose(); _disposable2?.Dispose(); } } internal PaintWrapper CreatePaint(IBrush brush, Size targetSize) { SKPaint paint = new SKPaint(); var rv = new PaintWrapper(paint); paint.IsStroke = false; double opacity = brush.Opacity * _currentOpacity; paint.IsAntialias = true; var solid = brush as ISolidColorBrush; if (solid != null) { paint.Color = new SKColor(solid.Color.R, solid.Color.G, solid.Color.B, (byte) (solid.Color.A * opacity)); return rv; } paint.Color = (new SKColor(255, 255, 255, (byte)(255 * opacity))); var gradient = brush as IGradientBrush; if (gradient != null) { var tileMode = gradient.SpreadMethod.ToSKShaderTileMode(); var stopColors = gradient.GradientStops.Select(s => s.Color.ToSKColor()).ToArray(); var stopOffsets = gradient.GradientStops.Select(s => (float)s.Offset).ToArray(); var linearGradient = brush as ILinearGradientBrush; if (linearGradient != null) { var start = linearGradient.StartPoint.ToPixels(targetSize).ToSKPoint(); var end = linearGradient.EndPoint.ToPixels(targetSize).ToSKPoint(); // would be nice to cache these shaders possibly? using (var shader = SKShader.CreateLinearGradient(start, end, stopColors, stopOffsets, tileMode)) paint.Shader = shader; } else { var radialGradient = brush as IRadialGradientBrush; if (radialGradient != null) { var center = radialGradient.Center.ToPixels(targetSize).ToSKPoint(); var radius = (float)radialGradient.Radius; // TODO: There is no SetAlpha in SkiaSharp //paint.setAlpha(128); // would be nice to cache these shaders possibly? using (var shader = SKShader.CreateRadialGradient(center, radius, stopColors, stopOffsets, tileMode)) paint.Shader = shader; } } return rv; } var tileBrush = brush as ITileBrush; var visualBrush = brush as IVisualBrush; var tileBrushImage = default(BitmapImpl); if (visualBrush != null) { if (_visualBrushRenderer != null) { var intermediateSize = _visualBrushRenderer.GetRenderTargetSize(visualBrush); if (intermediateSize.Width >= 1 && intermediateSize.Height >= 1) { var intermediate = new BitmapImpl((int)intermediateSize.Width, (int)intermediateSize.Height, _dpi); using (var ctx = intermediate.CreateDrawingContext(_visualBrushRenderer)) { ctx.Clear(Colors.Transparent); _visualBrushRenderer.RenderVisualBrush(ctx, visualBrush); } tileBrushImage = intermediate; rv.AddDisposable(tileBrushImage); } } else { throw new NotSupportedException("No IVisualBrushRenderer was supplied to DrawingContextImpl."); } } else { tileBrushImage = (BitmapImpl)((tileBrush as IImageBrush)?.Source?.PlatformImpl.Item); } if (tileBrush != null && tileBrushImage != null) { var calc = new TileBrushCalculator(tileBrush, new Size(tileBrushImage.PixelWidth, tileBrushImage.PixelHeight), targetSize); var bitmap = new BitmapImpl((int)calc.IntermediateSize.Width, (int)calc.IntermediateSize.Height, _dpi); rv.AddDisposable(bitmap); using (var context = bitmap.CreateDrawingContext(null)) { var rect = new Rect(0, 0, tileBrushImage.PixelWidth, tileBrushImage.PixelHeight); context.Clear(Colors.Transparent); context.PushClip(calc.IntermediateClip); context.Transform = calc.IntermediateTransform; context.DrawImage(RefCountable.CreateUnownedNotClonable(tileBrushImage), 1, rect, rect); context.PopClip(); } SKMatrix translation = SKMatrix.MakeTranslation(-(float)calc.DestinationRect.X, -(float)calc.DestinationRect.Y); SKShaderTileMode tileX = tileBrush.TileMode == TileMode.None ? SKShaderTileMode.Clamp : tileBrush.TileMode == TileMode.FlipX || tileBrush.TileMode == TileMode.FlipXY ? SKShaderTileMode.Mirror : SKShaderTileMode.Repeat; SKShaderTileMode tileY = tileBrush.TileMode == TileMode.None ? SKShaderTileMode.Clamp : tileBrush.TileMode == TileMode.FlipY || tileBrush.TileMode == TileMode.FlipXY ? SKShaderTileMode.Mirror : SKShaderTileMode.Repeat; using (var shader = SKShader.CreateBitmap(bitmap.Bitmap, tileX, tileY, translation)) paint.Shader = shader; } return rv; } private PaintWrapper CreatePaint(Pen pen, Size targetSize) { var rv = CreatePaint(pen.Brush, targetSize); var paint = rv.Paint; paint.IsStroke = true; paint.StrokeWidth = (float)pen.Thickness; if (pen.StartLineCap == PenLineCap.Round) paint.StrokeCap = SKStrokeCap.Round; else if (pen.StartLineCap == PenLineCap.Square) paint.StrokeCap = SKStrokeCap.Square; else paint.StrokeCap = SKStrokeCap.Butt; if (pen.LineJoin == PenLineJoin.Miter) paint.StrokeJoin = SKStrokeJoin.Miter; else if (pen.LineJoin == PenLineJoin.Round) paint.StrokeJoin = SKStrokeJoin.Round; else paint.StrokeJoin = SKStrokeJoin.Bevel; paint.StrokeMiter = (float)pen.MiterLimit; if (pen.DashStyle?.Dashes != null && pen.DashStyle.Dashes.Count > 0) { var pe = SKPathEffect.CreateDash( pen.DashStyle?.Dashes.Select(x => (float)x).ToArray(), (float)pen.DashStyle.Offset); paint.PathEffect = pe; rv.AddDisposable(pe); } return rv; } public void DrawRectangle(Pen pen, Rect rect, float cornerRadius = 0) { using (var paint = CreatePaint(pen, rect.Size)) { var rc = rect.ToSKRect(); if (cornerRadius == 0) { Canvas.DrawRect(rc, paint.Paint); } else { Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint); } } } public void FillRectangle(IBrush brush, Rect rect, float cornerRadius = 0) { using (var paint = CreatePaint(brush, rect.Size)) { var rc = rect.ToSKRect(); if (cornerRadius == 0) { Canvas.DrawRect(rc, paint.Paint); } else { Canvas.DrawRoundRect(rc, cornerRadius, cornerRadius, paint.Paint); } } } public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text) { using (var paint = CreatePaint(foreground, text.Size)) { var textImpl = (FormattedTextImpl)text; textImpl.Draw(this, Canvas, origin.ToSKPoint(), paint, CanUseLcdRendering); } } public IRenderTargetBitmapImpl CreateLayer(Size size) { var pixelSize = size * (_dpi / 96); return new BitmapImpl((int)pixelSize.Width, (int)pixelSize.Height, _dpi); } public void PushClip(Rect clip) { Canvas.Save(); Canvas.ClipRect(clip.ToSKRect()); } public void PopClip() { Canvas.Restore(); } private double _currentOpacity = 1.0f; private readonly Stack<double> _opacityStack = new Stack<double>(); public void PushOpacity(double opacity) { _opacityStack.Push(_currentOpacity); _currentOpacity *= opacity; } public void PopOpacity() { _currentOpacity = _opacityStack.Pop(); } public virtual void Dispose() { if(_disposables!=null) foreach (var disposable in _disposables) disposable?.Dispose(); } public void PushGeometryClip(IGeometryImpl clip) { Canvas.Save(); Canvas.ClipPath(((StreamGeometryImpl)clip).EffectivePath); } public void PopGeometryClip() { Canvas.Restore(); } public void PushOpacityMask(IBrush mask, Rect bounds) { Canvas.SaveLayer(new SKPaint()); maskStack.Push(CreatePaint(mask, bounds.Size)); } public void PopOpacityMask() { Canvas.SaveLayer(new SKPaint { BlendMode = SKBlendMode.DstIn }); using (var paintWrapper = maskStack.Pop()) { Canvas.DrawPaint(paintWrapper.Paint); } Canvas.Restore(); Canvas.Restore(); } private Matrix _currentTransform; public Matrix Transform { get { return _currentTransform; } set { if (_currentTransform == value) return; _currentTransform = value; var transform = value; if (_postTransform.HasValue) transform *= _postTransform.Value; Canvas.SetMatrix(transform.ToSKMatrix()); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using NUnit.Framework; using NFluent; namespace FileHelpers.Tests.CommonTests { [TestFixture] [Category("BigSorter")] public class SorterTests { private const int MegaByte = 1024*1024; [Test] public void Sort6xhalf() { SortMb<OrdersTab>(4*MegaByte, (int) (0.5*MegaByte)); } [Test] public void Sort6x1() { SortMb<OrdersTab>(4*MegaByte, 1*MegaByte); } [Test] public void Sort6xthid() { SortMb<OrdersTab>(4*MegaByte, (int) (0.3*MegaByte)); } [Test] public void Sort6x35() { SortMb<OrdersTab>(4*MegaByte, (int) (3.5*MegaByte)); } [Test] public void Sort6x6() { SortMb<OrdersTab>(4*MegaByte, 4*MegaByte); } [Test] public void Sort6x20() { SortMb<OrdersTab>(4*MegaByte, 20*MegaByte); } [Test] [Category("NotOnMono")] public void Sort4x20Reverse() { SortMb<OrdersTab>(4*MegaByte, 20*MegaByte, false); } [Test] [Category("NotOnMono")] public void Sort6xhalfHeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, (int) (0.5*MegaByte)); } [Test] [Category("NotOnMono")] public void Sort6x1HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 1*MegaByte); } [Test] [Category("NotOnMono")] public void Sort6x2HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 2*MegaByte); } [Test] [Category("NotOnMono")] public void Sort6x35HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, (int) (3.5*MegaByte)); } [Test] [Category("NotOnMono")] public void Sort6x6HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 4*MegaByte); } [Test] [Category("NotOnMono")] public void Sort6x7HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 4*MegaByte); } [Test] [Category("NotOnMono")] public void Sort6x20HeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 20*MegaByte); } [Test] [Category("NotOnMono")] public void Sort6x2ReverseHeaderFooter() { SortMb<OrdersTabHeaderFooter>(4*MegaByte, 20*MegaByte, false); } private void SortMb<T>(int totalSize, int blockSize, bool ascending) where T : class, IComparable<T> { using (var temp = new TempFileFactory()) using (var temp2 = new TempFileFactory()) using (var temp3 = new TempFileFactory()) { if (typeof (T) == typeof (OrdersTab)) CreateTempFile(totalSize, temp, ascending); else CreateTempFileHeaderFooter(totalSize, temp, ascending); var sorter = new BigFileSorter(blockSize); sorter.Sort(temp, temp2); var sorter2 = new BigFileSorter<T>(blockSize); sorter2.Sort(temp, temp3); if (!ascending) ReverseFile(temp); AssertSameFile(temp, temp2); AssertSameFile(temp, temp3); } } private void ReverseFile(string temp) { var data = File.ReadAllLines(temp); Array.Sort(data); File.WriteAllLines(temp, data); } public void SortMb<T>(int totalSize, int blockSize) where T : class, IComparable<T> { SortMb<T>(totalSize, blockSize, true); } private void AssertSameFile(string temp, string temp2) { var fi1 = new FileInfo(temp); var fi2 = new FileInfo(temp2); Check.That(fi1.Length).IsEqualTo(fi2.Length); using (var sr1 = new StreamReader(temp)) using (var sr2 = new StreamReader(temp)) { while (true) { var line1 = sr1.ReadLine(); var line2 = sr2.ReadLine(); if (line1 != line2) { Check.That(line1).IsEqualTo(line2); } if (line1 == null) break; } } } private void CreateTempFile(int sizeOfFile, string fileName, bool ascending) { int size = 0; var engine = new FileHelperAsyncEngine<OrdersTab>(); engine.AfterWriteRecord += (sender, e) => size += e.RecordLine.Length; using (engine.BeginWriteFile(fileName)) { var i = 1; while (size < sizeOfFile) { var order = new OrdersTab(); order.CustomerID = "sdads"; order.EmployeeID = 123; order.Freight = 123; order.OrderDate = new DateTime(2009, 10, 23); if (ascending) order.OrderID = 1000000 + i; else order.OrderID = 1000000 - i; order.RequiredDate = new DateTime(2009, 10, 20); order.ShippedDate = new DateTime(2009, 10, 21); order.ShipVia = 123; engine.WriteNext(order); i++; } } } private void CreateTempFileHeaderFooter(int sizeOfFile, string fileName, bool ascending) { int size = 0; var engine = new FileHelperAsyncEngine<OrdersTabHeaderFooter>(); engine.AfterWriteRecord += (sender, e) => size += e.RecordLine.Length; engine.HeaderText = "Test Header, Test Header \r\nAnotherLine"; engine.FooterText = "Footer Text"; using (engine.BeginWriteFile(fileName)) { var i = 1; while (size < sizeOfFile) { var order = new OrdersTabHeaderFooter(); order.CustomerID = "sdads"; order.EmployeeID = 123; order.Freight = 123; order.OrderDate = new DateTime(2009, 10, 23); if (ascending) order.OrderID = 1000000 + i; else order.OrderID = 1000000 - i; order.RequiredDate = new DateTime(2009, 10, 20); order.ShippedDate = new DateTime(2009, 10, 21); order.ShipVia = 123; engine.WriteNext(order); i++; } } } [DelimitedRecord("\t")] [IgnoreFirst(2)] [IgnoreLast(2)] public class OrdersTabHeaderFooter : IComparable<OrdersTabHeaderFooter> { public int OrderID; public string CustomerID; public int EmployeeID; public DateTime OrderDate; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime RequiredDate; [FieldNullValue(typeof (DateTime), "2005-1-1")] public DateTime ShippedDate; public int ShipVia; public decimal Freight; public int CompareTo(OrdersTabHeaderFooter other) { return this.OrderID.CompareTo(other.OrderID); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; using System.Runtime.InteropServices; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { internal partial class frmMaster : System.Windows.Forms.Form { [DllImport("ODBCCP32.DLL", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] // Registry API functions private static extern int SQLConfigDataSource(int hWndParent, int fRequest, string lpszDriver, string lpszAttributes); // Add data source const short ODBC_ADD_DSN = 1; // Delete data source const short ODBC_REMOVE_DSN = 3; private struct STARTUPINFO { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public int dwFlags; public short wShowWindow; public short cbReserved2; public int lpReserved2; public int hStdInput; public int hStdOutput; public int hStdError; } private struct PROCESS_INFORMATION { public int hProcess; public int hThread; public int dwProcessID; public int dwThreadID; } [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int WaitForSingleObject(int hHandle, int dwMilliseconds); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] //UPGRADE_WARNING: Structure PROCESS_INFORMATION may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' //UPGRADE_WARNING: Structure STARTUPINFO may require marshalling attributes to be passed as an argument in this Declare statement. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="C429C3A5-5D47-4CD9-8F51-74A1616405DC"' private static extern int CreateProcessA(string lpApplicationName, string lpCommandLine, int lpProcessAttributes, int lpThreadAttributes, int bInheritHandles, int dwCreationFlags, int lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, ref PROCESS_INFORMATION lpProcessInformation); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int CloseHandle(int hObject); [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] private static extern int GetExitCodeProcess(int hProcess, ref int lpExitCode); private const int NORMAL_PRIORITY_CLASS = 0x20; private const short INFINITE = -1; ADODB.Connection cnnDBmaster; ADODB.Connection cnnDBWaitron; string gMasterPath; string gSecurityCode; string gSecKey; List<Label> Label1 = new List<Label>(); private void loadLanguage() { //frmMaster = No Code [4POS Company Loader...] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmMaster.Caption = rsLang("LanguageLayoutLnk_Description"): frmMaster.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //Label1(2) = No Code [Company] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(2).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(2).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //lblCompany = No Code/Dynamic/NA? //Label1(3) = No Code [Database] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(3).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(3).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //lblPath = No Code/Dynamic/NA? //Label1(4) = No Code [Directory] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(4).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(4).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //lblDir = No Code/Dynamic/NA? //Label1(0) = No Code [User ID] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then Label1(0).Caption = rsLang("LanguageLayoutLnk_Description"): Label1(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2490; //Password|Checked if (modRecordSet.rsLang.RecordCount){_Label1_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Label1_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1389; //OK|Checked if (modRecordSet.rsLang.RecordCount){cmdOK.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdOK.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} //cmdBuild = No Code [Synchronize Via Email] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then cmdBuild.Caption = rsLang("LanguageLayoutLnk_Description"): cmdBuild.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //NOTE: Caption has a spelling mistake!!! //frmRegister = No Code [Unregistered Version] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then frmRegister.Caption = rsLang("LanguageLayoutLnk_Description"): frmRegister.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //_lbl_0 = No Code [Store Name] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then _lbl_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") //cmdRegistration = No Code [Registration] //rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000 //If rsLang.RecordCount Then cmdRegistration.Caption = rsLang("LanguageLayoutLnk_Description"): cmdRegistration.RightToLeft = rsLang("LanguageLayoutLnk_RightTL") modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmMaster.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private int ExecCmd(ref string cmdline) { int ret = 0; PROCESS_INFORMATION proc = default(PROCESS_INFORMATION); STARTUPINFO start = default(STARTUPINFO); // Initialize the STARTUPINFO structure: start.cb = Strings.Len(start); // Start the shelled application: ret = CreateProcessA(Constants.vbNullString, cmdline, 0, 0, 1, NORMAL_PRIORITY_CLASS, 0, Constants.vbNullString, ref start, ref proc); // Wait for the shelled application to finish: ret = WaitForSingleObject(proc.hProcess, 1); // INFINITE) GetExitCodeProcess(proc.hProcess, ref ret); CloseHandle(proc.hThread); CloseHandle(proc.hProcess); return ret; } private bool AddDSN(string strDSN, string strDescription, ref string strDB, ref bool delete = false) { bool functionReturnValue = false; //------------------------------------ //Usage: // AddDSN "MyDSN", "This is a test", "C:\test\myDB.mdb" //------------------------------------ // ERROR: Not supported in C#: OnErrorStatement //win 7 Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); Scripting.TextStream textstream = default(Scripting.TextStream); string lString = null; if (Win7Ver() == true) { if (fso.FileExists("C:\\4POS\\4POSWinPath.txt")) fso.DeleteFile("C:\\4POS\\4POSWinPath.txt", true); lString = Strings.Replace(strDB, "\\pricing.mdb", "\\"); textstream = fso.OpenTextFile("C:\\4POS\\4POSWinPath.txt", Scripting.IOMode.ForWriting, true); textstream.Write(lString); textstream.Close(); } //win 7 //Set the Driver Name string strDriver = null; string strFolder = null; strFolder = strDB; while (!(Strings.Right(strFolder, 1) == "\\")) { strFolder = Strings.Left(strFolder, Strings.Len(strFolder) - 1); } strDriver = "Microsoft Access Driver (*.mdb)"; //Build the attributes - Attributes must be Null separated string strAttributes = ""; strAttributes = strAttributes + "DESCRIPTION=" + strDescription + Strings.Chr(0); strAttributes = strAttributes + "DSN=" + strDSN + Strings.Chr(0); //strAttributes = strAttributes & "DATABASE=" & strDB & Chr(0) strAttributes = strAttributes + "DBQ=" + strDB + Strings.Chr(0); strAttributes = strAttributes + "systemDB=" + strFolder + "Secured.mdw" + Strings.Chr(0); strAttributes = strAttributes + "UID=liquid" + Strings.Chr(0); strAttributes = strAttributes + "PWD=lqd" + Strings.Chr(0); //Create DSN functionReturnValue = SQLConfigDataSource(0, ODBC_REMOVE_DSN, strDriver, strAttributes); if (delete) { } else { functionReturnValue = SQLConfigDataSource(0, ODBC_ADD_DSN, strDriver, strAttributes); } functionReturnValue = true; return functionReturnValue; Hell: functionReturnValue = false; Interaction.MsgBox(Err().Description); return functionReturnValue; } public ADODB.Recordset getRSMaster(ref string sql) { ADODB.Recordset functionReturnValue = default(ADODB.Recordset); functionReturnValue = new ADODB.Recordset(); functionReturnValue.CursorLocation = ADODB.CursorLocationEnum.adUseClient; functionReturnValue.Open(sql, cnnDBmaster, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic); return functionReturnValue; } private bool getMasterDB() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement //getMasterDB = True cnnDBmaster = new ADODB.Connection(); string filename = null; if (modWinVer.Win7Ver() == true) { filename = "c:\\4posmaster\\4posmaster.mdb"; } else { filename = "4posmaster.mdb"; } if (System.IO.File.Exists(filename) == true) { var _with1 = cnnDBmaster; //.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0" _with1.Provider = "Microsoft.ACE.OLEDB.12.0"; _with1.Open(filename); //.Open() functionReturnValue = true; } else { functionReturnValue = false; } //cnnDBmaster.Open("4posMaster") //gMasterPath = Split(Split(cnnDBmaster.ConnectionString, ";DBQ=")(1), ";")(0) //gMasterPath = Split(LCase(gMasterPath), "4posmaster.mdb")(0) ' //win 7 Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); Scripting.TextStream textstream = default(Scripting.TextStream); string lString = null; if (modWinVer.Win7Ver() == true) { //If fso.FileExists("C:\4POS\4POSWinPath.txt") Then // Set textstream = fso.OpenTextFile("C:\4POS\4POSWinPath.txt", ForReading, True) // lString = textstream.ReadAll // serverPath = lString '& "pricing.mdb" //Else // serverPath = "C:\4POSServer\" '"pricing.mdb" //End If gMasterPath = "c:\\4posmaster\\"; return functionReturnValue; //getMasterDB = True } //win 7 gMasterPath = Strings.Split(Strings.Split(cnnDBmaster.ConnectionString, ";DBQ=")[1], ";")[0]; gMasterPath = Strings.Split(Strings.LCase(gMasterPath), "4posmaster.mdb")[0]; return functionReturnValue; openConnection_Error: // functionReturnValue = false; return functionReturnValue; } public bool openConnectionWaitron() { bool functionReturnValue = false; // ERROR: Not supported in C#: OnErrorStatement bool createDayend = false; string strDBPath = null; createDayend = false; functionReturnValue = true; cnnDBWaitron = new ADODB.Connection(); strDBPath = modRecordSet.serverPath + "Waitron.mdb"; var _with2 = cnnDBWaitron; _with2.Provider = "Microsoft.ACE.OLEDB.12.0"; _with2.Properties("Jet OLEDB:System Database").Value = modRecordSet.serverPath + "Secured.mdw"; _with2.Open(strDBPath, "liquid", "lqd"); return functionReturnValue; openConnection_Error: functionReturnValue = false; return functionReturnValue; } public void closeConnectionWaitron() { cnnDBWaitron.Close(); cnnDBWaitron = null; } public ADODB.Recordset getRSwaitron(ref object sql) { ADODB.Recordset functionReturnValue = default(ADODB.Recordset); functionReturnValue = new ADODB.Recordset(); functionReturnValue.CursorLocation = ADODB.CursorLocationEnum.adUseClient; functionReturnValue.Open(sql, cnnDBWaitron, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic); return functionReturnValue; } private void cmdBuild_Click(System.Object eventSender, System.EventArgs eventArgs) { int x = 0; string TMPgMasterPath = null; ADODB.Recordset rs = default(ADODB.Recordset); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); string lDir = null; // ERROR: Not supported in C#: OnErrorStatement if (Interaction.MsgBox("A data instruction will prepare a download for each store of the latest stock and pricing data." + Constants.vbCrLf + Constants.vbCrLf + "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Prepare Download") == MsgBoxResult.Yes) { TMPgMasterPath = gMasterPath; gMasterPath = "c:\\4POSServer\\"; if (fso.FolderExists(gMasterPath + "Data\\")) { } else { fso.CreateFolder(gMasterPath + "Data\\"); } lDir = FileSystem.Dir(gMasterPath + "data\\*.*"); while (!(string.IsNullOrEmpty(lDir))) { fso.DeleteFile(gMasterPath + "data\\" + lDir, true); lDir = FileSystem.Dir(); } this.Cursor = System.Windows.Forms.Cursors.WaitCursor; System.Windows.Forms.Application.DoEvents(); rs = getRSMaster(ref "SELECT 1 as MasterID, #" + DateAndTime.Today + "# as Master_DateReplica"); rs.save(gMasterPath + "Data\\Master.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Catalogue"); rs.save(gMasterPath + "Data\\catalogue.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PriceSet"); rs.save(gMasterPath + "Data\\PriceSet.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Channel ORDER BY ChannelID"); rs.save(gMasterPath + "Data\\channel.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Deposit ORDER BY DepositID"); rs.save(gMasterPath + "Data\\Deposit.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PackSize ORDER BY PackSizeID"); rs.save(gMasterPath + "Data\\PackSize.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Person ORDER BY PersonID"); rs.save(gMasterPath + "Data\\Person.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PersonChannelLnk"); rs.save(gMasterPath + "Data\\PersonChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PriceChannelLnk"); rs.save(gMasterPath + "Data\\PriceChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PricingGroup ORDER BY PricingGroupID"); rs.save(gMasterPath + "Data\\PricingGroup.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PricingGroupChannelLnk"); rs.save(gMasterPath + "Data\\PricingGroupChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PropChannelLnk"); rs.save(gMasterPath + "Data\\PropChannelLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM [Set] ORDER BY SetID"); rs.save(gMasterPath + "Data\\Set.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM SetItem"); rs.save(gMasterPath + "Data\\SetItem.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Shrink ORDER BY ShrinkID"); rs.save(gMasterPath + "Data\\Shrink.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM ShrinkItem"); rs.save(gMasterPath + "Data\\ShrinkItem.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM StockGroup ORDER BY StockGroupID"); rs.save(gMasterPath + "Data\\StockGroup.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM StockItem ORDER BY StockItemID"); rs.save(gMasterPath + "Data\\stockitem.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Supplier ORDER BY SupplierID"); rs.save(gMasterPath + "Data\\Supplier.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM SupplierDepositLnk"); rs.save(gMasterPath + "Data\\SupplierDepositLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Promotion"); rs.save(gMasterPath + "Data\\Promotion.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM PromotionItem"); rs.save(gMasterPath + "Data\\PromotionItem.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM StockBreak"); rs.save(gMasterPath + "Data\\StockBreak.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM RecipeStockItemLnk"); rs.save(gMasterPath + "Data\\RecipeStockItemLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM CashTransaction"); rs.save(gMasterPath + "Data\\CashTransaction.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Increment"); rs.save(gMasterPath + "Data\\Increment.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM IncrementStockItemLnk"); rs.save(gMasterPath + "Data\\IncrementStockItemLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM IncrementQuantity"); rs.save(gMasterPath + "Data\\IncrementQuantity.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM Message"); rs.save(gMasterPath + "Data\\Message.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM MessageItem"); rs.save(gMasterPath + "Data\\MessageItem.rs", ADODB.PersistFormatEnum.adPersistADTG); rs = modRecordSet.getRS(ref "SELECT * FROM StockItemMessageLnk"); rs.save(gMasterPath + "Data\\StockItemMessageLnk.rs", ADODB.PersistFormatEnum.adPersistADTG); openConnectionWaitron(); rs = getRSwaitron(ref "SELECT * FROM POSMenu"); rs.save(gMasterPath + "Data\\POSMenu.rs", ADODB.PersistFormatEnum.adPersistADTG); ExecCmd(ref gMasterPath + "wzzip.exe " + gMasterPath + "Data\\data.zip " + gMasterPath + "Data\\*.*"); if (fso.FileExists(gMasterPath + "Data.zip")) fso.DeleteFile(gMasterPath + "Data.zip", true); fso.CopyFile(gMasterPath + "Data\\data.zip", gMasterPath + "Data.zip", true); rs = getRSMaster(ref "SELECT locationCompany_1.locationCompanyID, locationCompany.locationCompany_Email FROM locationCompany INNER JOIN (locationCompany AS locationCompany_1 INNER JOIN location ON locationCompany_1.locationCompany_LocationID = location.locationID) ON locationCompany.locationCompany_LocationID = location.locationID WHERE (((locationCompany_1.locationCompanyID)=" + lblCompany.Tag + "));"); // ERROR: Not supported in C#: OnErrorStatement //MAPISession1.SignOn() //MAPIMessages1.SessionID = MAPISession1.SessionID //MAPIMessages1.Compose() x = -1; // ERROR: Not supported in C#: OnErrorStatement while (!(rs.EOF)) { if (!string.IsNullOrEmpty(rs.Fields("locationCompany_Email").Value)) { x = x + 1; //MAPIMessages1.RecipIndex = x //MAPIMessages1.RecipDisplayName = rs.Fields("locationCompany_Email").Value //MAPIMessages1.ResolveName() } rs.moveNext(); } rs = getRSMaster(ref "SELECT locationAudit.locationAuditID, locationAudit.locationAudit_Email FROM locationCompany INNER JOIN locationAudit ON locationCompany.locationCompany_LocationID = locationAudit.locationAudit_LocationID WHERE (((locationCompany.locationCompanyID)=" + lblCompany.Tag + "));"); while (!(rs.EOF)) { x = x + 1; //MAPIMessages1.RecipIndex = x //MAPIMessages1.RecipDisplayName = rs.Fields("locationAudit_Email").Value //MAPIMessages1.ResolveName() rs.moveNext(); } //MAPIMessages1.MsgSubject = "4POS Data" //MAPIMessages1.MsgNoteText = "4POS Pricing update as at " & Format(Now, "ddd, dd-mmm-yyyy hh:nn") //MAPIMessages1.AttachmentType = MSMAPI.AttachTypeConstants.mapData //MAPIMessages1.AttachmentName = "data.zip" //MAPIMessages1.AttachmentPathName = gMasterPath & "data.zip" //MAPIMessages1.Send() //MAPISession1.SignOff() gMasterPath = TMPgMasterPath; } this.Cursor = System.Windows.Forms.Cursors.Default; return; buildError: if (Err().Number == 53) { Interaction.MsgBox("Please ensure if you have 'WinZip Command Line Support Add-On' installed on your system."); } else { Interaction.MsgBox(Err().Number + " " + Err().Description); } } private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdCompany_Click(System.Object eventSender, System.EventArgs eventArgs) { cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Name = '" + Strings.Replace(txtCompany.Text, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + lblCompany.Tag + "));"); loadCompanies(); lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag]; lblCompany.Text = lvLocation.FocusedItem.Text + " - " + lvLocation.FocusedItem.SubItems[0].Text; } private void cmdDatabase_Click(System.Object eventSender, System.EventArgs eventArgs) { this.CDmasterOpen.Title = "Select the path to " + lvLocation.FocusedItem.SubItems[0].Text + " application database ..."; CDmasterOpen.Filter = "Application Data Base|pricing.mdb"; CDmasterOpen.FileName = ""; this.CDmasterOpen.ShowDialog(); if (string.IsNullOrEmpty(CDmasterOpen.FileName)) { } else { lblCompany.Tag = Strings.Mid(lvLocation.FocusedItem.Name, 2); cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Path = '" + Strings.Replace(CDmasterOpen.FileName, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + Strings.Mid(lvLocation.FocusedItem.Name, 2) + "));"); loadCompanies(); lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag]; lvLocation_DoubleClick(lvLocation, new System.EventArgs()); cmdCompany_Click(cmdCompany, new System.EventArgs()); } } private void cmdOK_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); bool createDayend = false; decimal x = default(decimal); string revName = ""; //loading languages files //Dim rs As Recordset short tempLID = 0; tempLID = 1; rs = modRecordSet.getRS(ref "SELECT Company_LanguageID, Company_RightTL From Company"); if (rs.RecordCount) { if (Information.IsDBNull(rs.Fields("Company_LanguageID").Value)) tempLID = 1; if (rs.Fields("Company_LanguageID").Value == 0) { tempLID = 1; } else { tempLID = rs.Fields("Company_LanguageID").Value; } if (Information.IsDBNull(rs.Fields("Company_RightTL").Value)) modRecordSet.iLangRTL = 0; if (rs.Fields("Company_RightTL").Value == 0) { modRecordSet.iLangRTL = 0; } else { modRecordSet.iLangRTL = rs.Fields("Company_RightTL").Value; } } else { tempLID = 1; modRecordSet.iLangRTL = 0; } modRecordSet.rsLang = modRecordSet.getRS(ref "SELECT * From LanguageLayoutLnk Where LanguageLayoutLnk_LanguageLayoutID = " + tempLID + ";"); //loading languages files //loading help file string helpPath = null; //helpPath = App.Path & "\4POS4Dummies.chm" //If Command = "1" Then helpPath = "C:\4POS\4POS4Dummies.chm" helpPath = "C:\\4POS\\4POS4Dummies.chm"; if (fso.FileExists(helpPath)) { modRecordSet.rsHelp = modRecordSet.getRS(ref "SELECT * From Help;"); } else { modRecordSet.rsHelp = modRecordSet.getRS(ref "SELECT 0 AS Help_Section, 'A' AS Help_Form From Help;"); } //loading help file // ERROR: Not supported in C#: OnErrorStatement rs = modRecordSet.getRS(ref "SELECT * FROM Person WHERE (Person_UserID = '" + Strings.Replace(this.txtUserName.Text, "'", "''") + "') AND (Person_Password = '" + Strings.Replace(this.txtPassword.Text, "'", "''") + "')"); ADODB.Recordset rsRpt = default(ADODB.Recordset); if (rs.BOF | rs.EOF) { Interaction.MsgBox("Invalid User Name or Password, try again!", MsgBoxStyle.Exclamation, "Login"); txtPassword.Focus(); } else { if (Convert.ToInt32(rs.Fields("Person_SecurityBit").Value + "0")) { this.Close(); My.MyProject.Forms.frmMenu.lblUser.Text = rs.Fields("Person_FirstName").Value + " " + rs.Fields("Person_LastName").Value; My.MyProject.Forms.frmMenu.lblUser.Tag = rs.Fields("PersonID").Value; My.MyProject.Forms.frmMenu.gBit = rs.Fields("Person_SecurityBit").Value; if (Strings.Len(rs.Fields("Person_QuickAccess").Value) > 0) { for (x = Strings.Len(rs.Fields("Person_QuickAccess").Value); x >= 1; x += -1) { revName = revName + Strings.Mid(rs.Fields("Person_QuickAccess").Value, x, 1); } if (Strings.LCase(Strings.Left(rs.Fields("Person_Position").Value, 8)) == "4posboss" & Strings.LCase(Strings.Right(rs.Fields("Person_Position").Value, Strings.Len(rs.Fields("Person_QuickAccess").Value))) == revName) { My.MyProject.Forms.frmMenu.lblUser.ForeColor = System.Drawing.Color.Yellow; My.MyProject.Forms.frmMenu.gSuper = true; } } rsRpt = modRecordSet.getRS(ref "SELECT Company_LoadTRpt From Company"); if (Information.IsDBNull(rsRpt.Fields("Company_LoadTRpt").Value)) { } else if (rsRpt.Fields("Company_LoadTRpt").Value == 0) { } else { if (fso.FileExists(modRecordSet.serverPath + "templateReport1.mdb")) { if (fso.FileExists(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb")) fso.DeleteFile(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb", true); if (fso.FileExists(modRecordSet.serverPath + "templateReport.mdb")) fso.DeleteFile(modRecordSet.serverPath + "templateReport.mdb", true); fso.CopyFile(modRecordSet.serverPath + "templateReport1.mdb", modRecordSet.serverPath + "templateReport.mdb", true); } } My.MyProject.Forms.frmMenu.loadMenu("stock"); if (fso.FileExists(modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb")) { } else { fso.CopyFile(modRecordSet.serverPath + "templateReport.mdb", modRecordSet.serverPath + "report" + My.MyProject.Forms.frmMenu.lblUser.Tag + ".mdb"); createDayend = true; } if (modReport.openConnectionReport()) { } else { Interaction.MsgBox("Unable to locate the Report Database!" + Constants.vbCrLf + Constants.vbCrLf + "The Update Controller wil terminate.", MsgBoxStyle.Critical, "SERVER ERROR"); System.Environment.Exit(0); } if (createDayend) { // cnnDBreport.Execute "DELETE * FROM Report" // cnnDBreport.Execute "INSERT INTO Report ( ReportID, Report_DayEndStartID, Report_DayEndEndID, Report_Heading ) SELECT 1 AS reportKey, Max(aDayEnd.DayEndID) AS MaxOfDayEndID, Max(aDayEnd.DayEndID) AS MaxOfDayEndID1, 'From ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' to ' & Format(Max([aDayEnd].[DayEnd_Date]),'ddd dd mmm yyyy') & ' covering a dayend range of 1 days' AS theHeading FROM aDayEnd;" // frmUpdateDayEnd.show 1 My.MyProject.Forms.frmMenu.cmdToday_Click(null, new System.EventArgs()); My.MyProject.Forms.frmMenu.cmdLoad_Click(null, new System.EventArgs()); } rs = modReport.getRSreport(ref "SELECT DayEnd.DayEnd_Date AS fromDate, DayEnd_1.DayEnd_Date AS toDate FROM (Report INNER JOIN DayEnd ON Report.Report_DayEndStartID = DayEnd.DayEndID) INNER JOIN DayEnd AS DayEnd_1 ON Report.Report_DayEndEndID = DayEnd_1.DayEndID;"); if (rs.RecordCount) { My.MyProject.Forms.frmMenu._DTPicker1_0.Value = Strings.Format(rs.Fields("fromDate").Value, "yyyy"); My.MyProject.Forms.frmMenu._DTPicker1_0.Value = Strings.Format(rs.Fields("fromDate").Value, "mm"); My.MyProject.Forms.frmMenu._DTPicker1_0.Value = Strings.Format(rs.Fields("fromDate").Value, "dd"); My.MyProject.Forms.frmMenu._DTPicker1_1.Value = Strings.Format(rs.Fields("toDate").Value, "yyyy"); My.MyProject.Forms.frmMenu._DTPicker1_1.Value = Strings.Format(rs.Fields("toDate").Value, "mm"); My.MyProject.Forms.frmMenu._DTPicker1_1.Value = Strings.Format(rs.Fields("toDate").Value, "dd"); } My.MyProject.Forms.frmMenu.setDayEndRange(); My.MyProject.Forms.frmMenu.lblDayEndCurrent.Text = My.MyProject.Forms.frmMenu.lblDayEnd.Text; } else { Interaction.MsgBox("You do not have the correct permissions to access the 4POS Office Application, try again!", MsgBoxStyle.Exclamation, "Login"); this.txtUserName.Focus(); System.Windows.Forms.SendKeys.Send("{Home}+{End}"); } } } private void BuildRegistrationKey() { short x = 0; string lCode = null; string leCode = null; gSecurityCode = Strings.UCase(txtCompany.Text) + "XDFHWPGMIJ"; gSecurityCode = Strings.Replace(gSecurityCode, " ", ""); gSecurityCode = Strings.Replace(gSecurityCode, "'", ""); gSecurityCode = Strings.Replace(gSecurityCode, "\"", ""); gSecurityCode = Strings.Replace(gSecurityCode, ",", ""); for (x = 1; x <= 10; x++) { gSecurityCode = Strings.Left(gSecurityCode, x) + Strings.Replace(Strings.Mid(gSecurityCode, x + 1), Strings.Mid(gSecurityCode, x, 1), ""); } gSecurityCode = Strings.Left(gSecurityCode, 10); lCode = getSerialNumber(); leCode = ""; // ERROR: Not supported in C#: OnErrorStatement for (x = 1; x <= Strings.Len(lCode); x++) { leCode = leCode + Strings.Mid(gSecurityCode, Convert.ToDouble(Strings.Mid(lCode, x, 1)) + 1, 1); } // ERROR: Not supported in C#: OnErrorStatement lblCode.Text = leCode; } private void Command1_Click() { if (checkSecurity()) { this.frmRegister.Visible = false; } else { this.frmRegister.Visible = true; BuildRegistrationKey(); } } private void cmdRegistration_Click_OLD() { string lCode = null; string lPassword = null; int x = 0; string lNewString = null; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); const string securtyStringReply = "9487203516"; //Exit Sub if (Interaction.MsgBox("By Clicking 'Yes' you confirm that your company name is correct and you understand the licensing agreement." + Constants.vbCrLf + Constants.vbCrLf + "Do you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "REGISTRATION") == MsgBoxResult.Yes) { if (Strings.Len(gSecKey) == 12) { lNewString = ""; for (x = 1; x <= Strings.Len(txtKey.Text); x++) { if (Information.IsNumeric(Strings.Mid(txtKey.Text, x, 1))) { lNewString = lNewString + Strings.InStr(securtyStringReply, Strings.Mid(txtKey.Text, x, 1)) - 1; } } cmdCompany_Click(cmdCompany, new System.EventArgs()); return; } else { lNewString = ""; for (x = 1; x <= Strings.Len(txtKey.Text); x++) { if (Information.IsNumeric(Strings.Mid(txtKey.Text, x, 1))) { lNewString = lNewString + Strings.InStr(securtyStringReply, Strings.Mid(txtKey.Text, x, 1)) - 1; } } if (!string.IsNullOrEmpty(lNewString)) { if (System.Math.Abs(Convert.ToDouble(lNewString)) == System.Math.Abs(Convert.ToDouble(getSerialNumber()))) { lPassword = "pospospospos"; lCode = getSerialNumber(); if (!string.IsNullOrEmpty(lCode)) { lCode = Encrypt(lCode, lPassword); cmdCompany_Click(cmdCompany, new System.EventArgs()); modRecordSet.cnnDB.Execute("UPDATE Company SET Company.Company_Code = '" + Strings.Replace(lCode, "'", "''") + "';"); frmRegister.Visible = false; } return; } } } } Interaction.MsgBox("The 'Activation key' is invalid!", MsgBoxStyle.Exclamation, "4POS REGISTRATION"); } private void cmdBegin_Click_OLD() { ADODB.Recordset rs = default(ADODB.Recordset); if (!string.IsNullOrEmpty(Strings.Trim(txtCompany.Text))) { //cnnDB.Execute "UPDATE Company SET Company_Name = '" & Replace(txtCompany.Text, "'", "''") & "'" rs = modRecordSet.getRS(ref "SELECT * From Company"); if (rs.RecordCount) { if (Information.IsDBNull(rs("Company_TerminateDate"))) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + DateAndTime.Today + "#;"); } else { //If (Date + 2) > rs("Company_TerminateDate") Then // cnnDB.Execute "UPDATE Company SET Company.Company_Code = '';" // checkSecurity = False // Exit Function //End If } } } } private void cmdBegin_Click() { ADODB.Recordset rs = default(ADODB.Recordset); string vValue = null; string hkey = null; int lRetVal = 0; if (!string.IsNullOrEmpty(Strings.Trim(txtCompany.Text))) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_Name = '" + Strings.Replace(txtCompany.Text, "'", "''") + "'"); rs = modRecordSet.getRS(ref "SELECT * From Company"); if (rs.RecordCount) { //check advance date expiry system // ERROR: Not supported in C#: OnErrorStatement vValue = ""; lRetVal = modUtilities.RegOpenKeyEx(modUtilities.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\ShellDls", 0, modUtilities.KEY_QUERY_VALUE, ref hkey); lRetVal = modUtilities.QueryValueEx(hkey, "ShellClass", ref vValue); modUtilities.RegCloseKey(hkey); if (string.IsNullOrEmpty(vValue)) { vValue = "0"; } else { if (vValue != "0") vValue = Convert.ToString(Convert.ToDateTime("&H" + vValue)); } if (Information.IsDBNull(rs("Company_TerminateDate")) & vValue == "0") { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + DateAndTime.Today + "#;"); lRetVal = modUtilities.RegCreateKeyEx(modUtilities.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\ShellDls\\MSOCache", 0, "soap", 0, modUtilities.KEY_ALL_ACCESS, 0, ref hkey, ref 0); lRetVal = modUtilities.RegOpenKeyEx(modUtilities.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\ShellDls", 0, modUtilities.KEY_ALL_ACCESS, ref hkey); modUtilities.SetValueEx(hkey, ref "ShellClass", ref modUtilities.REG_SZ, ref Conversion.Hex(DateAndTime.Today.ToOADate())); modUtilities.RegCloseKey(hkey); } else { if (Information.IsDBNull(rs("Company_TerminateDate")) & vValue != "0") { //db date tempered if (modApplication.posDemo() == true) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + DateAndTime.Today + "#;"); lRetVal = modUtilities.RegCreateKeyEx(modUtilities.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\ShellDls\\MSOCache", 0, "soap", 0, modUtilities.KEY_ALL_ACCESS, 0, ref hkey, ref 0); lRetVal = modUtilities.RegOpenKeyEx(modUtilities.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\ShellDls", 0, modUtilities.KEY_ALL_ACCESS, ref hkey); modUtilities.SetValueEx(hkey, ref "ShellClass", ref modUtilities.REG_SZ, ref Conversion.Hex(DateAndTime.Today.ToOADate())); modUtilities.RegCloseKey(hkey); } else { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + (System.DateTime.FromOADate(DateAndTime.Today.ToOADate() - 20)) + "#;"); Interaction.MsgBox("Invalid License found." + Constants.vbCrLf + "application will now exit", MsgBoxStyle.Critical, "Run Time Error"); System.Environment.Exit(0); } } if (Information.IsDBNull(rs("Company_TerminateDate"))) { } else { if (rs("Company_TerminateDate").Value > DateAndTime.Today) { //db date tempered modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + (System.DateTime.FromOADate(DateAndTime.Today.ToOADate() - 20)) + "#;"); Interaction.MsgBox("Invalid License found." + Constants.vbCrLf + "application will now exit", MsgBoxStyle.Critical, "Run Time Error"); System.Environment.Exit(0); } } //If (Date + 2) > rs("Company_TerminateDate") Then // cnnDB.Execute "UPDATE Company SET Company.Company_Code = '';" // checkSecurity = False // Exit Function //End If } } } } private void cmdRegistration_Click(System.Object eventSender, System.EventArgs eventArgs) { short x = 0; string lCode = null; string leCode = null; string lPassword = null; ADODB.Recordset rs = default(ADODB.Recordset); if (!string.IsNullOrEmpty(Strings.Trim(txtCompany.Text))) { //new serialization check //If Len(gSecKey) = 12 Then //is he really using Original CD to register if (My.MyProject.Forms.frmPOSCode.setupCode() == true) { if (Interaction.MsgBox("By Clicking 'Yes' you confirm that your company name is correct and you understand the licensing agreement." + Constants.vbCrLf + Constants.vbCrLf + "Do you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "REGISTRATION") == MsgBoxResult.Yes) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_TerminateDate = #" + DateAndTime.Today + "#;"); cmdBegin_Click(); //new serialization check cnnDB.Execute "UPDATE Company SET Company.Company_Code = [Company_Code] & '0';" //new serialization check cnnDB.Execute "UPDATE POS SET POS.POS_Code = '" & strCDKey & "';" lPassword = "pospospospos"; lCode = getSerialNumber(); lCode = Encrypt(lCode, lPassword); modRecordSet.cnnDB.Execute("UPDATE Company SET Company.Company_Code = '" + Strings.Replace(lCode, "'", "''") + "';"); lPassword = Strings.LTrim(Strings.Replace(txtCompany.Text, "'", "")); lPassword = Strings.RTrim(Strings.Replace(lPassword, " ", "")); lPassword = Strings.Trim(Strings.Replace(lPassword, ".", "")); lPassword = Strings.LCase(lPassword); leCode = ""; lCode = ""; for (x = 1; x <= Strings.Len(lPassword); x++) { lCode = Strings.Mid(lPassword, x, 1); lCode = Convert.ToString(Strings.Asc(lCode)); if (Convert.ToDouble(lCode) > 96 & Convert.ToDouble(lCode) < 123) { leCode = leCode + Strings.Mid(lPassword, x, 1); } } lPassword = leCode; rs = modRecordSet.getRS(ref "SELECT * FROM POS;"); //WHERE POS_IPAddress = 'localhost';") if (rs.RecordCount) { while (rs.EOF == false) { if (rs.Fields("POS_IPAddress").Value == "localhost" & rs.Fields("POS_Name").Value == "Server") { lCode = Convert.ToString(rs.Fields("POS_CID").Value * 135792468); leCode = Encrypt(lCode, lPassword); leCode = leCode + Strings.Chr(255) + basCryptoProcs.strCDKey; modRecordSet.cnnDB.Execute("UPDATE POS SET POS.POS_Code = '" + Strings.Replace(leCode, "'", "''") + "' WHERE POS.POS_CID=" + rs.Fields("POS_CID").Value + ";"); modRecordSet.cnnDB.Execute("UPDATE POS SET POS.POS_Code = '0' WHERE POS.POS_CID<>" + rs.Fields("POS_CID").Value + ";"); break; // TODO: might not be correct. Was : Exit Do } else if (rs.Fields("POS_IPAddress").Value == "localhost") { lCode = Convert.ToString(rs.Fields("POS_CID").Value * 135792468); leCode = Encrypt(lCode, lPassword); leCode = leCode + Strings.Chr(255) + basCryptoProcs.strCDKey; modRecordSet.cnnDB.Execute("UPDATE POS SET POS.POS_Code = '" + Strings.Replace(leCode, "'", "''") + "' WHERE POS.POS_CID=" + rs.Fields("POS_CID").Value + ";"); modRecordSet.cnnDB.Execute("UPDATE POS SET POS.POS_Code = '0' WHERE POS.POS_CID<>" + rs.Fields("POS_CID").Value + ";"); break; // TODO: might not be correct. Was : Exit Do //Else // cnnDB.Execute "UPDATE POS SET POS.POS_Code = '0' WHERE POS.POS_CID=" & rs("POS_CID") & ";" } rs.moveNext(); } } //new serialization check frmRegister.Visible = false; } } } else { Interaction.MsgBox("A Company name is required." + Constants.vbCrLf + Constants.vbCrLf + "If you do not want to register now, Press then 'Exit Button'.", MsgBoxStyle.Exclamation, "4POS REGISTRATION"); txtCompany.Focus(); } } private void frmMaster_Load(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); string lFile = null; Label1.AddRange(new Label[] { _Label1_0, _Label1_1, _Label1_2, _Label1_3, _Label1_4 }); //ResizeForm(Me, pixelToTwips(Me.Width, True), pixelToTwips(Me.Height, False), 0) ExecCmd(ref "cmd /C DEL c:\\*.tmp"); if (fso.FileExists("C:\\4POS\\pos\\data.ug")) { if (fso.FileExists("C:\\4POS\\pos\\4POSupgrade.exe")) { Interaction.Shell("C:\\4POS\\pos\\4POSupgrade.exe", AppWinStyle.NormalFocus); } else { Interaction.MsgBox("An upgrade is required, but the upgrade unility can not be located!" + Constants.vbCrLf + Constants.vbCrLf + "Please contact a 4POS representative to assist you in resolving this problem.", MsgBoxStyle.Critical, "UPGRADE"); } System.Environment.Exit(0); } modUtilities.setShortDateFormat(); short tempLID = 0; string helpPath = null; Scripting.TextStream DayEndtextstream = default(Scripting.TextStream); string lString = null; if (getMasterDB()) { //loadLanguage loadCompanies(); } else { if (modRecordSet.openConnection()) { } else { if (fso.FileExists("c:\\4posServer\\pricing.mdb")) { lFile = "c:\\4posServer\\pricing.mdb"; } else { this.CDmasterOpen.Title = "Select the path to the application database ..."; //UPGRADE_WARNING: Filter has a new behavior. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="9B7D5ADD-D8FE-4819-A36C-6DEDAF088CC7"' CDmasterOpen.Filter = "Application Data Base|pricing.mdb"; CDmasterOpen.FileName = ""; this.CDmasterOpen.ShowDialog(); lFile = CDmasterOpen.FileName; } if (string.IsNullOrEmpty(lFile)) { System.Environment.Exit(0); } else { if (AddDSN("4POS", "4POS Pricing File", lFile)) { this.Close(); Interaction.MsgBox("The new data source has just been configured into the application suite." + Constants.vbCrLf + Constants.vbCrLf + "Please restart this application", MsgBoxStyle.Information, "DATA SOURCE"); System.Environment.Exit(0); } else { System.Environment.Exit(0); } } } //loading languages files //Dim rs As Recordset tempLID = 1; rs = modRecordSet.getRS(ref "SELECT Company_LanguageID, Company_RightTL From Company"); if (rs.RecordCount) { if (Information.IsDBNull(rs.Fields("Company_LanguageID").Value)) tempLID = 1; if (rs.Fields("Company_LanguageID").Value == 0) { tempLID = 1; } else { tempLID = rs.Fields("Company_LanguageID").Value; } if (Information.IsDBNull(rs.Fields("Company_RightTL").Value)) modRecordSet.iLangRTL = 0; if (rs.Fields("Company_RightTL").Value == 0) { modRecordSet.iLangRTL = 0; } else { modRecordSet.iLangRTL = rs.Fields("Company_RightTL").Value; } } else { tempLID = 1; modRecordSet.iLangRTL = 0; } modRecordSet.rsLang = modRecordSet.getRS(ref "SELECT * From LanguageLayoutLnk Where LanguageLayoutLnk_LanguageLayoutID = " + tempLID + ";"); //loading languages files //loading help file //helpPath = App.Path & "\4POS4Dummies.chm" //If Command = "1" Then helpPath = "C:\4POS\4POS4Dummies.chm" helpPath = "C:\\4POS\\4POS4Dummies.chm"; if (fso.FileExists(helpPath)) { modRecordSet.rsHelp = modRecordSet.getRS(ref "SELECT * From Help;"); } else { modRecordSet.rsHelp = modRecordSet.getRS(ref "SELECT 0 AS Help_Section, 'A' AS Help_Form From Help;"); } //loading help file //Dim lTextstream As textstream lString = modRecordSet.serverPath + "data\\4POSInterface\\4POSAUTODE.txt"; if (fso.FileExists(lString)) { DayEndtextstream = fso.OpenTextFile(lString, Scripting.IOMode.ForReading, true); lString = DayEndtextstream.ReadAll; DayEndtextstream.Close(); DayEndtextstream = null; if (Information.IsDate(lString)) { modApplication.bolAutoDE = true; modApplication.dateDayEnd = Convert.ToDateTime(lString); modApplication.doMenuForms(ref "frmdayend"); System.Windows.Forms.Application.DoEvents(); } else { Interaction.MsgBox("Auto DayEnd file was detected but file is invalid."); System.Environment.Exit(0); } } else { loadLanguage(); frmLogin f = new frmLogin(); f.Show(); //frmLogin.Show() } //Me.Close() this.Hide(); } } //Private Sub Label3_Click() // Dim rs As Recordset // Set rs = getRS("SELECT * FROM aTransactionItem") // If rs.RecordCount = 0 Then // rs.save gMasterPath & "Data\aTransactionItem.rs", adPersistADTG // End If //End Sub private void lvLocation_DoubleClick(System.Object eventSender, System.EventArgs eventArgs) { string[] lArray = null; short x = 0; if (AddDSN("4POS", "4POS Pricing Data", this.lvLocation.FocusedItem.SubItems[1].Text)) { System.Windows.Forms.Application.DoEvents(); if (modRecordSet.openConnection()) { lblCompany.Text = lvLocation.FocusedItem.Text + " - " + lvLocation.FocusedItem.SubItems[0].Text; lblCompany.Tag = Strings.Mid(lvLocation.FocusedItem.Name, 2); lblPath.Text = lvLocation.FocusedItem.SubItems[1].Text; lArray = Strings.Split(lblPath.Text, "\\"); //lblDir.Text = lArray(0) & "\" for (x = 1; x <= Information.UBound(lArray) - 1; x++) { lblDir.Text = lblDir.Text + lArray[x] + "\\"; } for (x = 0; x <= Label1.Count; x++) { Label1[x].Enabled = true; } cmdCompany.Enabled = true; cmdBuild.Enabled = true; cmdDatabase.Enabled = true; this.txtUserName.Enabled = true; txtPassword.Enabled = true; this.cmdOK.Enabled = true; if (checkSecurity()) { this.frmRegister.Visible = false; } else { this.frmRegister.Visible = true; BuildRegistrationKey(); } if (txtUserName.Visible) txtUserName.Focus(); return; } } lblCompany.Text = "..."; lblCompany.Tag = ""; lblPath.Text = "..."; lblDir.Text = "..."; for (x = 0; x <= Label1.Count; x++) { Label1[x].Enabled = false; } this.txtUserName.Enabled = false; txtPassword.Enabled = false; this.cmdOK.Enabled = false; cmdCompany.Enabled = false; cmdBuild.Enabled = false; cmdDatabase.Enabled = false; this.CDmasterOpen.Title = "Select the path to " + lvLocation.FocusedItem.SubItems[0].Text + " application database ..."; CDmasterOpen.Filter = "Application Data Base|pricing.mdb"; CDmasterOpen.FileName = ""; this.CDmasterOpen.ShowDialog(); if (string.IsNullOrEmpty(CDmasterOpen.FileName)) { } else { lblCompany.Tag = Strings.Mid(lvLocation.FocusedItem.Name, 2); cnnDBmaster.Execute("UPDATE locationCompany SET locationCompany.locationCompany_Path = '" + Strings.Replace(CDmasterOpen.FileName, "'", "''") + "' WHERE (((locationCompany.locationCompanyID)=" + Strings.Mid(lvLocation.FocusedItem.Name, 2) + "));"); loadCompanies(); lvLocation.FocusedItem = lvLocation.Items["k" + lblCompany.Tag]; lvLocation_DoubleClick(lvLocation, new System.EventArgs()); } } private void loadCompanies() { ADODB.Recordset rs = new ADODB.Recordset(); System.Windows.Forms.ListViewItem lListitem = null; rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient; //If openConnection Then //End If rs.Open("SELECT locationCompany.locationCompanyID, location.location_Name, locationCompany.locationCompany_Name, locationCompany.locationCompany_Path FROM location INNER JOIN locationCompany ON location.locationID = locationCompany.locationCompany_LocationID ORDER BY location.location_Name, locationCompany.locationCompany_Name;", cnnDBmaster, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic); //If lvLocation.Items.Count <> 0 Then //Me.lvLocation.Items.Clear() //End If if (rs.RecordCount) { while (!(rs.EOF)) { lListitem = lvLocation.Items.Add("k" + rs.Fields("locationCompanyID").Value, rs.Fields("locationCompany_Name").Value, 2); if (lListitem.SubItems.Count > 0) { lListitem.SubItems[0].Text = rs.Fields("location_Name").Value + ""; } else { lListitem.SubItems.Insert(0, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("location_Name").Value + "")); } if (lListitem.SubItems.Count > 1) { lListitem.SubItems[1].Text = rs.Fields("locationCompany_Path").Value + ""; } else { lListitem.SubItems.Insert(1, new System.Windows.Forms.ListViewItem.ListViewSubItem(null, rs.Fields("locationCompany_Path").Value + "")); } if (Strings.LCase(rs.Fields("locationCompany_Path").Value + "") == Strings.LCase(modRecordSet.serverPath + "pricing.mdb")) { lListitem.Selected = true; lvLocation_DoubleClick(lvLocation, new System.EventArgs()); } rs.MoveNext(); } } } private void txtCompany_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtCompany.SelectionStart = 0; txtCompany.SelectionLength = 9999; } private void txtCompany_Leave(System.Object eventSender, System.EventArgs eventArgs) { if (!string.IsNullOrEmpty(Strings.Trim(txtCompany.Text))) { modRecordSet.cnnDB.Execute("UPDATE Company SET Company_Name = '" + Strings.Replace(txtCompany.Text, "'", "''") + "'"); } BuildRegistrationKey(); } private void txtKey_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtKey.SelectionStart = 0; txtKey.SelectionLength = 9999; } private void txtPassword_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtPassword.SelectionStart = 0; txtPassword.SelectionLength = 9999; } private void txtPassword_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13) { KeyAscii = 0; cmdOK_Click(cmdOK, new System.EventArgs()); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void txtUserName_Enter(System.Object eventSender, System.EventArgs eventArgs) { txtUserName.SelectionStart = 0; txtUserName.SelectionLength = 9999; } private void txtUserName_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 13) { KeyAscii = 0; txtPassword.Focus(); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private string getSerialNumber() { string functionReturnValue = null; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); Scripting.Folder fsoFolder = default(Scripting.Folder); functionReturnValue = ""; if (fso.FolderExists(modRecordSet.serverPath)) { fsoFolder = fso.GetFolder(modRecordSet.serverPath); functionReturnValue = Convert.ToString(fsoFolder.Drive.SerialNumber); } return functionReturnValue; } private string Encrypt(string secret, string password) { int l = 0; short x = 0; string Char_Renamed = null; l = Strings.Len(password); for (x = 1; x <= Strings.Len(secret); x++) { Char_Renamed = Convert.ToString(Strings.Asc(Strings.Mid(password, (x % l) - l * Convert.ToInt16((x % l) == 0), 1))); Strings.Mid(secret, x, 1) = Strings.Chr(Strings.Asc(Strings.Mid(secret, x, 1)) ^ Char_Renamed); } return secret; } public bool checkSecurity() { bool functionReturnValue = false; string lCode = null; string leCode = null; string lPassword = null; ADODB.Recordset rs = default(ADODB.Recordset); short x = 0; modApplication.getLoginDate(); //Piracy check functionReturnValue = false; rs = modRecordSet.getRS(ref "SELECT * From Company"); if (rs.RecordCount) { gSecKey = rs.Fields("Company_Code").Value + ""; if (Information.IsNumeric(rs.Fields("Company_Code").Value)) { if (Strings.Len(rs.Fields("Company_Code").Value) == 13) { functionReturnValue = true; return functionReturnValue; } } lPassword = "pospospospos"; lCode = getSerialNumber(); if (lCode == "0" & Strings.LCase(Strings.Left(modRecordSet.serverPath, 3)) != "c:\\" & !string.IsNullOrEmpty(rs.Fields("Company_Code").Value)) { functionReturnValue = true; } else { leCode = Encrypt(lCode, lPassword); for (x = 1; x <= Strings.Len(leCode); x++) { if (Strings.Asc(Strings.Mid(leCode, x, 1)) < 33) { leCode = Strings.Left(leCode, x - 1) + Strings.Chr(33) + Strings.Mid(leCode, x + 1); } } if (rs.Fields("Company_Code").Value == leCode) { //If IsNull(rs("Company_TerminateDate")) Then functionReturnValue = true; return functionReturnValue; //Else // If Date > rs("Company_TerminateDate") Then // cnnDB.Execute "UPDATE Company SET Company.Company_Code = '';" // checkSecurity = False // End If //End If } else { txtCompany.Text = rs.Fields("Company_Name").Value; txtCompany.SelectionStart = 0; txtCompany.SelectionLength = 999; } } } else { Interaction.MsgBox("Unable to locate the '4POS Application Suite' database.", MsgBoxStyle.Critical, "4POS"); System.Environment.Exit(0); } return functionReturnValue; } } }
using System.Collections.Generic; using NUnit.Framework; using IBatisNet.DataMapper.Test.Domain; namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests.Generics { /// <summary> /// Tests generic list /// /// Interface tests /// 1) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt /// 2) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt Lazy load /// 3) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 /// 4) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 lazy /// Strongly typed collection tests /// 5) LineItemCollection2 (Order.LineItemCollection2) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 /// 6) LineItemCollection2 (Order.LineItemCollection2) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 Lazy load /// </summary> [TestFixture] public class ResultMapTest : BaseTest { #region SetUp & TearDown /// <summary> /// SetUp /// </summary> [SetUp] public void Init() { InitScript(sqlMap.DataSource, ScriptDirectory + "account-init.sql"); InitScript(sqlMap.DataSource, ScriptDirectory + "order-init.sql"); InitScript(sqlMap.DataSource, ScriptDirectory + "line-item-init.sql"); InitScript(sqlMap.DataSource, ScriptDirectory + "enumeration-init.sql"); InitScript(sqlMap.DataSource, ScriptDirectory + "coupons-init.sql"); } /// <summary> /// TearDown /// </summary> [TearDown] public void Dispose() { /* ... */ } #endregion #region Result Map test /// <summary> /// Coupons /// </summary> [Test] public void TestJIRA243WithGoupBy() { IList<Coupon> coupons = sqlMap.QueryForList<Coupon>("GetCouponBrand", null); Assert.That(coupons.Count, Is.EqualTo(5)); Assert.That(coupons[0].BrandIds[0], Is.EqualTo(1)); Assert.That(coupons[0].BrandIds[1], Is.EqualTo(2)); Assert.That(coupons[0].BrandIds[2], Is.EqualTo(3)); Assert.That(coupons[1].BrandIds[0], Is.EqualTo(4)); Assert.That(coupons[1].BrandIds[1], Is.EqualTo(5)); Assert.That(coupons[2].BrandIds.Count, Is.EqualTo(0)); Assert.That(coupons[3].BrandIds.Count, Is.EqualTo(0)); Assert.That(coupons[4].BrandIds[0], Is.EqualTo(6)); } /// <summary> /// Coupons /// </summary> [Test] public void Test243WithoutGoupBy() { IList<Coupon> coupons = sqlMap.QueryForList<Coupon>("GetCoupons", null); Assert.That(coupons.Count, Is.EqualTo(5)); Assert.That(coupons[0].BrandIds[0], Is.EqualTo(1)); Assert.That(coupons[0].BrandIds[1], Is.EqualTo(2)); Assert.That(coupons[0].BrandIds[2], Is.EqualTo(3)); Assert.That(coupons[1].BrandIds[0], Is.EqualTo(4)); Assert.That(coupons[1].BrandIds[1], Is.EqualTo(5)); Assert.That(coupons[2].BrandIds.Count, Is.EqualTo(0)); Assert.That(coupons[3].BrandIds.Count, Is.EqualTo(0)); Assert.That(coupons[4].BrandIds[0], Is.EqualTo(6)); } /// <summary> /// Test generic Ilist : /// 1) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt /// </summary> [Test] public void TestGenericList() { Order order = sqlMap.QueryForObject<Order>("GetOrderWithGenericListLineItem", 1); AssertOrder1(order); // Check generic IList collection Assert.IsNotNull(order.LineItemsGenericList); Assert.AreEqual(3, order.LineItemsGenericList.Count); } /// <summary> /// Test generic Ilist with lazy loading : /// 2) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt Lazy load /// </summary> [Test] public void TestGenericListLazyLoad() { Order order = sqlMap.QueryForObject<Order>("GetOrderWithGenericLazyLoad", 1); AssertOrder1(order); // Check generic IList collection Assert.IsNotNull(order.LineItemsGenericList); Assert.AreEqual(3, order.LineItemsGenericList.Count); } /// <summary> /// Test generic typed generic Collection on generic IList /// 3) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 /// </summary> [Test] public void TestGenericCollectionOnIList() { Order order = sqlMap.QueryForObject<Order>("GetOrderWithGenericLineItemCollection", 1); AssertOrder1(order); // Check generic collection Assert.IsNotNull(order.LineItemsGenericList); Assert.AreEqual(3, order.LineItemsGenericList.Count); LineItemCollection2 lines = (LineItemCollection2)order.LineItemsGenericList; } /// <summary> /// Test generic IList with lazy typed collection /// 4) IList&lgt;LineItem&glt (Order.LineItemsGenericList) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 lazy /// </summary> [Test] public void TestLazyListGenericMapping() { Order order = (Order)sqlMap.QueryForObject("GetOrderWithGenericLineItemsLazy", 1); AssertOrder1(order); Assert.IsNotNull(order.LineItemsGenericList); Assert.AreEqual(3, order.LineItemsGenericList.Count); LineItemCollection2 lines = (LineItemCollection2)order.LineItemsGenericList; } /// <summary> /// Test generic typed generic Collection on generic typed generic Collection /// 5) LineItemCollection2 (Order.LineItemCollection2) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 /// </summary> [Test] public void TestTypedCollectionOnTypedCollection() { Order order = (Order)sqlMap.QueryForObject("GetOrderWithGenericTypedLineItemCollection", 1); AssertOrder1(order); Assert.IsNotNull(order.LineItemsCollection2); Assert.AreEqual(3, order.LineItemsCollection2.Count); IEnumerator<LineItem> e = ((IEnumerable<LineItem>)order.LineItemsCollection2).GetEnumerator(); while (e.MoveNext()) { LineItem item = e.Current; Assert.IsNotNull(item); } } /// <summary> /// Test generic typed generic Collection lazy /// 6) LineItemCollection2 (Order.LineItemCollection2) <--- QueryForList&lgt;LineItem&glt with listClass = LineItemCollection2 Lazy load /// </summary> [Test] public void TestTypedCollectionLazy() { Order order = (Order)sqlMap.QueryForObject("GetOrderWithGenericTypedLineItemCollectionLazy", 1); AssertOrder1(order); Assert.IsNotNull(order.LineItemsCollection2); Assert.AreEqual(3, order.LineItemsCollection2.Count); IEnumerator<LineItem> e = ((IEnumerable<LineItem>)order.LineItemsCollection2).GetEnumerator(); while (e.MoveNext()) { LineItem item = e.Current; Assert.IsNotNull(item); } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.Editor.Implementation.Preview; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview { public class PreviewWorkspaceTests { [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationDefault() { using (var previewWorkspace = new PreviewWorkspace()) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithExplicitHostServices() { var assembly = typeof(ISolutionCrawlerService).Assembly; using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly)))) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewCreationWithSolution() { using (var custom = new AdhocWorkspace()) using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution)) { Assert.NotNull(previewWorkspace.CurrentSolution); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewAddRemoveProject() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id); Assert.True(previewWorkspace.TryApplyChanges(newSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewProjectChanges() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); Assert.True(previewWorkspace.TryApplyChanges(project.Solution)); var addedSolution = previewWorkspace.CurrentSolution.Projects.First() .AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("document", "").Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(addedSolution)); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); var text = "class C {}"; var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution; Assert.True(previewWorkspace.TryApplyChanges(changedSolution)); Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text); var removedSolution = previewWorkspace.CurrentSolution.Projects.First() .RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0]) .RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution; Assert.True(previewWorkspace.TryApplyChanges(removedSolution)); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count); Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count); } } [WorkItem(923121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923121")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewOpenCloseFile() { using (var previewWorkspace = new PreviewWorkspace()) { var solution = previewWorkspace.CurrentSolution; var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp); var document = project.AddDocument("document", ""); Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution)); previewWorkspace.OpenDocument(document.Id); Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count()); Assert.True(previewWorkspace.IsDocumentOpen(document.Id)); previewWorkspace.CloseDocument(document.Id); Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count()); Assert.False(previewWorkspace.IsDocumentOpen(document.Id)); } } [Fact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewServices() { using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider()))) { var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>(); Assert.True(service is PreviewSolutionCrawlerRegistrationServiceFactory.Service); var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>(); Assert.NotNull(persistentService); var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution); Assert.True(storage is NoOpPersistentStorage); } } [WorkItem(923196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/923196")] [WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)] public void TestPreviewDiagnostic() { var diagnosticService = EditorServicesUtil.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource; var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a); using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(EditorServicesUtil.ExportProvider.AsExportProvider()))) { var solution = previewWorkspace.CurrentSolution .AddProject("project", "project.dll", LanguageNames.CSharp) .AddDocument("document", "class { }") .Project .Solution; Assert.True(previewWorkspace.TryApplyChanges(solution)); previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]); previewWorkspace.EnableDiagnostic(); // wait 20 seconds taskSource.Task.Wait(20000); Assert.True(taskSource.Task.IsCompleted); var args = taskSource.Task.Result; Assert.True(args.Diagnostics.Length > 0); } } [WpfFact] public async Task TestPreviewDiagnosticTagger() { using (var workspace = TestWorkspace.CreateCSharp("class { }", exportProvider: EditorServicesUtil.ExportProvider)) using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution)) { //// preview workspace and owner of the solution now share solution and its underlying text buffer var hostDocument = workspace.Projects.First().Documents.First(); //// enable preview diagnostics previewWorkspace.EnableDiagnostic(); var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpansAsync<IErrorTag>(workspace); const string AnalzyerCount = "Analyzer Count: "; Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length); const string SquigglesCount = "Squiggles Count: "; Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Length); } } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14444")] public async Task TestPreviewDiagnosticTaggerInPreviewPane() { using (var workspace = TestWorkspace.CreateCSharp("class { }", exportProvider: EditorServicesUtil.ExportProvider)) { // set up listener to wait until diagnostic finish running var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService; // no easy way to setup waiter. kind of hacky way to setup waiter var source = new CancellationTokenSource(); var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>(); diagnosticService.DiagnosticsUpdated += (s, a) => { source.Cancel(); source = new CancellationTokenSource(); var cancellationToken = source.Token; Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); }; var hostDocument = workspace.Projects.First().Documents.First(); // make a change to remove squiggle var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id); var oldText = oldDocument.GetTextAsync().Result; var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }"))); // create a diff view WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(DifferenceViewerPreview)}"); var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>(); using (var diffView = (DifferenceViewerPreview)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None))) { var foregroundService = workspace.GetService<IForegroundNotificationService>(); var waiter = new ErrorSquiggleWaiter(); var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter); // set up tagger for both buffers var leftBuffer = diffView.Viewer.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var leftProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners); var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer); using (var leftDisposable = leftTagger as IDisposable) { var rightBuffer = diffView.Viewer.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First(); var rightProvider = new DiagnosticsSquiggleTaggerProvider(diagnosticService, foregroundService, listeners); var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer); using (var rightDisposable = rightTagger as IDisposable) { // wait up to 20 seconds for diagnostics taskSource.Task.Wait(20000); if (!taskSource.Task.IsCompleted) { // something is wrong FatalError.Report(new System.Exception("not finished after 20 seconds")); } // wait taggers await waiter.CreateWaitTask(); // check left buffer var leftSnapshot = leftBuffer.CurrentSnapshot; var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(1, leftSpans.Count); // check right buffer var rightSnapshot = rightBuffer.CurrentSnapshot; var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList(); Assert.Equal(0, rightSpans.Count); } } } } } private class ErrorSquiggleWaiter : AsynchronousOperationListener { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MVCDemo.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Security.Cryptography; using System.IO; using System.Reflection; using System.Text.Json; using System.Threading.Tasks; using Azure.Identity; using System.ComponentModel; using System.Linq; using NUnit.Framework; namespace Azure.Core.TestFramework { /// <summary> /// Represents the ambient environment in which the test suite is /// being run. /// </summary> public abstract class TestEnvironment { [EditorBrowsableAttribute(EditorBrowsableState.Never)] public static string RepositoryRoot { get; } private static readonly Dictionary<Type, Task> s_environmentStateCache = new Dictionary<Type, Task>(); private readonly string _prefix; private TokenCredential _credential; private TestRecording _recording; private readonly Dictionary<string, string> _environmentFile = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); protected TestEnvironment() { if (RepositoryRoot == null) { throw new InvalidOperationException("Unexpected error, repository root not found"); } var testProject = GetSourcePath(GetType().Assembly); var sdkDirectory = Path.GetFullPath(Path.Combine(RepositoryRoot, "sdk")); var serviceName = Path.GetFullPath(testProject) .Substring(sdkDirectory.Length) .Trim(Path.DirectorySeparatorChar) .Split(Path.DirectorySeparatorChar).FirstOrDefault(); if (string.IsNullOrWhiteSpace(serviceName)) { throw new InvalidOperationException($"Unable to determine the service name from test project path {testProject}"); } var serviceSdkDirectory = Path.Combine(sdkDirectory, serviceName); if (!Directory.Exists(sdkDirectory)) { throw new InvalidOperationException($"SDK directory {serviceSdkDirectory} not found"); } _prefix = serviceName.ToUpperInvariant() + "_"; var testEnvironmentFile = Path.Combine(serviceSdkDirectory, "test-resources.json.env"); if (File.Exists(testEnvironmentFile)) { var json = JsonDocument.Parse( ProtectedData.Unprotect(File.ReadAllBytes(testEnvironmentFile), null, DataProtectionScope.CurrentUser) ); foreach (var property in json.RootElement.EnumerateObject()) { _environmentFile[property.Name] = property.Value.GetString(); } } } static TestEnvironment() { // Traverse parent directories until we find an "artifacts" directory // parent of that would become a repo root for test environment resolution purposes var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location); while (directoryInfo.Name != "artifacts") { if (directoryInfo.Parent == null) { return; } directoryInfo = directoryInfo.Parent; } RepositoryRoot = directoryInfo?.Parent?.FullName; } public RecordedTestMode? Mode { get; set; } /// <summary> /// The name of the Azure subscription containing the resource group to be used for Live tests. Recorded. /// </summary> public string SubscriptionId => GetRecordedVariable("SUBSCRIPTION_ID"); /// <summary> /// The name of the Azure resource group to be used for Live tests. Recorded. /// </summary> public string ResourceGroup => GetRecordedVariable("RESOURCE_GROUP"); /// <summary> /// The location of the Azure resource group to be used for Live tests (e.g. westus2). Recorded. /// </summary> public string Location => GetRecordedVariable("LOCATION"); /// <summary> /// The environment of the Azure resource group to be used for Live tests (e.g. AzureCloud). Recorded. /// </summary> public string AzureEnvironment => GetRecordedVariable("ENVIRONMENT"); /// <summary> /// The name of the Azure Active Directory tenant that holds the service principal to use during Live tests. Recorded. /// </summary> public string TenantId => GetRecordedVariable("TENANT_ID"); /// <summary> /// The URL of the Azure Resource Manager to be used for management plane operations. Recorded. /// </summary> public string ResourceManagerUrl => GetRecordedOptionalVariable("RESOURCE_MANAGER_URL"); /// <summary> /// The URL of the Azure Service Management endpoint to be used for management plane authentication. Recorded. /// </summary> public string ServiceManagementUrl => GetRecordedOptionalVariable("SERVICE_MANAGEMENT_URL"); /// <summary> /// The URL of the Azure Authority host to be used for authentication. Recorded. /// </summary> public string AuthorityHostUrl => GetRecordedOptionalVariable("AZURE_AUTHORITY_HOST") ?? AzureAuthorityHosts.AzurePublicCloud.ToString(); /// <summary> /// The suffix for Azure Storage accounts for the active cloud environment, such as "core.windows.net". Recorded. /// </summary> public string StorageEndpointSuffix => GetRecordedOptionalVariable("STORAGE_ENDPOINT_SUFFIX"); /// <summary> /// The client id of the Azure Active Directory service principal to use during Live tests. Recorded. /// </summary> public string ClientId => GetRecordedVariable("CLIENT_ID"); /// <summary> /// The client secret of the Azure Active Directory service principal to use during Live tests. Not recorded. /// </summary> public string ClientSecret => GetVariable("CLIENT_SECRET"); public TokenCredential Credential { get { if (_credential != null) { return _credential; } if (Mode == RecordedTestMode.Playback) { _credential = new MockCredential(); } else { _credential = new ClientSecretCredential( GetVariable("TENANT_ID"), GetVariable("CLIENT_ID"), GetVariable("CLIENT_SECRET") ); } return _credential; } } /// <summary> /// Returns whether environment is ready to use. Should be overriden to provide service specific sampling scenario. /// The test framework will wait until this returns true before starting tests. /// Use this place to hook up logic that polls if eventual consistency has happened. /// /// Return true if environment is ready to use. /// Return false if environment is not ready to use and framework should wait. /// Throw if you want to fail the run fast. /// </summary> /// <returns>Whether environment is ready to use.</returns> protected virtual ValueTask<bool> IsEnvironmentReadyAsync() { return new ValueTask<bool>(true); } /// <summary> /// Waits until environment becomes ready to use. See <see cref="IsEnvironmentReadyAsync"/> to define sampling scenario. /// </summary> /// <returns>A task.</returns> public async ValueTask WaitForEnvironmentAsync() { if (GlobalIsRunningInCI && Mode == RecordedTestMode.Live) { Task task; lock (s_environmentStateCache) { if (!s_environmentStateCache.TryGetValue(GetType(), out task)) { task = WaitForEnvironmentInternalAsync(); s_environmentStateCache[GetType()] = task; } } await task; } } private async Task WaitForEnvironmentInternalAsync() { int numberOfTries = 60; TimeSpan delay = TimeSpan.FromSeconds(10); for (int i = 0; i < numberOfTries; i++) { var isReady = await IsEnvironmentReadyAsync(); if (isReady) { return; } await Task.Delay(delay); } throw new InvalidOperationException("The environment has not become ready, check your TestEnvironment.IsEnvironmentReady scenario."); } /// <summary> /// Returns and records an environment variable value when running live or recorded value during playback. /// </summary> protected string GetRecordedOptionalVariable(string name) { return GetRecordedOptionalVariable(name, _ => { }); } /// <summary> /// Returns and records an environment variable value when running live or recorded value during playback. /// </summary> protected string GetRecordedOptionalVariable(string name, Action<RecordedVariableOptions> options) { if (Mode == RecordedTestMode.Playback) { return GetRecordedValue(name); } string value = GetOptionalVariable(name); if (!Mode.HasValue) { return value; } if (_recording == null) { throw new InvalidOperationException("Recorded value should not be set outside the test method invocation"); } // If the value was populated, sanitize before recording it. string sanitizedValue = value; if (!string.IsNullOrEmpty(value)) { var optionsInstance = new RecordedVariableOptions(); options?.Invoke(optionsInstance); sanitizedValue = optionsInstance.Apply(sanitizedValue); } _recording?.SetVariable(name, sanitizedValue); return value; } /// <summary> /// Returns and records an environment variable value when running live or recorded value during playback. /// Throws when variable is not found. /// </summary> protected string GetRecordedVariable(string name) { return GetRecordedVariable(name, null); } /// <summary> /// Returns and records an environment variable value when running live or recorded value during playback. /// Throws when variable is not found. /// </summary> protected string GetRecordedVariable(string name, Action<RecordedVariableOptions> options) { var value = GetRecordedOptionalVariable(name, options); EnsureValue(name, value); return value; } /// <summary> /// Returns an environment variable value or null when variable is not found. /// </summary> protected string GetOptionalVariable(string name) { var prefixedName = _prefix + name; // Prefixed name overrides non-prefixed var value = Environment.GetEnvironmentVariable(prefixedName); if (value == null) { _environmentFile.TryGetValue(prefixedName, out value); } if (value == null) { value = Environment.GetEnvironmentVariable(name); } if (value == null) { _environmentFile.TryGetValue(name, out value); } return value; } /// <summary> /// Returns an environment variable value. /// Throws when variable is not found. /// </summary> protected string GetVariable(string name) { var value = GetOptionalVariable(name); EnsureValue(name, value); return value; } private void EnsureValue(string name, string value) { if (value == null) { var prefixedName = _prefix + name; throw new InvalidOperationException( $"Unable to find environment variable {prefixedName} or {name} required by test." + Environment.NewLine + "Make sure the test environment was initialized using eng/common/TestResources/New-TestResources.ps1 script."); } } public void SetRecording(TestRecording recording) { _credential = null; _recording = recording; } private string GetRecordedValue(string name) { if (_recording == null) { throw new InvalidOperationException("Recorded value should not be retrieved outside the test method invocation"); } return _recording.GetVariable(name, null); } internal static string GetSourcePath(Assembly assembly) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); var testProject = assembly.GetCustomAttributes<AssemblyMetadataAttribute>().Single(a => a.Key == "SourcePath").Value; if (string.IsNullOrEmpty(testProject)) { throw new InvalidOperationException($"Unable to determine the test directory for {assembly}"); } return testProject; } /// <summary> /// Determines if the current environment is Azure DevOps. /// </summary> public static bool GlobalIsRunningInCI => Environment.GetEnvironmentVariable("TF_BUILD") != null; /// <summary> /// Determines if the current global test mode. /// </summary> internal static RecordedTestMode GlobalTestMode { get { string modeString = TestContext.Parameters["TestMode"] ?? Environment.GetEnvironmentVariable("AZURE_TEST_MODE"); RecordedTestMode mode = RecordedTestMode.Playback; if (!string.IsNullOrEmpty(modeString)) { mode = (RecordedTestMode)Enum.Parse(typeof(RecordedTestMode), modeString, true); } return mode; } } /// <summary> /// Determines if tests that use <see cref="ClientTestFixtureAttribute"/> should only test the latest version. /// </summary> internal static bool GlobalTestOnlyLatestVersion { get { string switchString = TestContext.Parameters["OnlyLiveTestLatestServiceVersion"] ?? Environment.GetEnvironmentVariable("AZURE_ONLY_TEST_LATEST_SERVICE_VERSION"); bool.TryParse(switchString, out bool onlyTestLatestServiceVersion); return onlyTestLatestServiceVersion; } } /// <summary> /// Determines service versions that would be tested in tests that use <see cref="ClientTestFixtureAttribute"/>. /// NOTE: this variable only narrows the set of versions defined in the attribute /// </summary> internal static string[] GlobalTestServiceVersions { get { string switchString = TestContext.Parameters["LiveTestServiceVersions"] ?? Environment.GetEnvironmentVariable("AZURE_LIVE_TEST_SERVICE_VERSIONS") ?? string.Empty; return switchString.Split(new char[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries); } } /// <summary> /// Determines if tests that use <see cref="RecordedTestAttribute"/> should try to re-record on failure. /// </summary> internal static bool GlobalDisableAutoRecording { get { string switchString = TestContext.Parameters["DisableAutoRecording"] ?? Environment.GetEnvironmentVariable("AZURE_DISABLE_AUTO_RECORDING"); bool.TryParse(switchString, out bool disableAutoRecording); return disableAutoRecording || GlobalIsRunningInCI; } } } }
using System; using System.Collections; using System.Reflection; using Mono.Unix; namespace Stetic.Editor { [PropertyEditor ("Value", "Changed")] public class Image : Gtk.HBox, IPropertyEditor { Gtk.Image image; Gtk.ComboBoxEntry combo; Gtk.Entry entry; Gtk.Button button; Gtk.ListStore store; const int IconColumn = 0; const int LabelColumn = 1; static string[] stockIds, stockLabels; static int imgWidth, imgHeight; static Image () { ArrayList tmpIds = new ArrayList (); // We can't use Gtk.Stock.ListIds, because that returns different // values depending on what version of libgtk you have installed... foreach (PropertyInfo info in typeof (Gtk.Stock).GetProperties (BindingFlags.Public | BindingFlags.Static)) { if (info.CanRead && info.PropertyType == typeof (string)) tmpIds.Add (info.GetValue (null, null)); } foreach (PropertyInfo info in typeof (Gnome.Stock).GetProperties (BindingFlags.Public | BindingFlags.Static)) { if (info.CanRead && info.PropertyType == typeof (string)) tmpIds.Add (info.GetValue (null, null)); } ArrayList items = new ArrayList (), nonItems = new ArrayList (); foreach (string id in tmpIds) { Gtk.StockItem item = Gtk.Stock.Lookup (id); if (item.StockId == null) nonItems.Add (id); else { item.Label = item.Label.Replace ("_", ""); items.Add (item); } } items.Sort (new StockItemSorter ()); nonItems.Sort (); stockIds = new string[items.Count + nonItems.Count]; stockLabels = new string[items.Count + nonItems.Count]; for (int i = 0; i < items.Count; i++) { stockIds[i] = ((Gtk.StockItem)items[i]).StockId; stockLabels[i] = ((Gtk.StockItem)items[i]).Label; } for (int i = 0; i < nonItems.Count; i++) { stockIds[i + items.Count] = nonItems[i] as string; stockLabels[i + items.Count] = nonItems[i] as string; } Gtk.Icon.SizeLookup (Gtk.IconSize.Button, out imgWidth, out imgHeight); } class StockItemSorter : IComparer { public int Compare (object itemx, object itemy) { Gtk.StockItem x = (Gtk.StockItem)itemx; Gtk.StockItem y = (Gtk.StockItem)itemy; return string.Compare (x.Label, y.Label); } } public Image () : this (true, true) {} public Image (bool allowStock, bool allowFile) : base (false, 6) { image = new Gtk.Image (Gnome.Stock.Blank, Gtk.IconSize.Button); PackStart (image, false, false, 0); if (allowStock) { store = new Gtk.ListStore (typeof (string), typeof (string)); store.AppendValues (Gnome.Stock.Blank, Catalog.GetString ("(None)")); for (int i = 0; i < stockIds.Length; i++) store.AppendValues (stockIds[i], stockLabels[i]); combo = new Gtk.ComboBoxEntry (store, LabelColumn); Gtk.CellRendererPixbuf iconRenderer = new Gtk.CellRendererPixbuf (); iconRenderer.StockSize = (uint)Gtk.IconSize.Menu; combo.PackStart (iconRenderer, false); combo.Reorder (iconRenderer, 0); combo.AddAttribute (iconRenderer, "stock-id", IconColumn); combo.Changed += combo_Changed; // Pack the combo non-expandily into a VBox so it doesn't // get stretched to the file button's height Gtk.VBox vbox = new Gtk.VBox (false, 0); vbox.PackStart (combo, true, false, 0); PackStart (vbox, true, true, 0); entry = (Gtk.Entry)combo.Child; entry.Changed += entry_Changed; useStock = true; } if (allowFile) { if (!allowStock) { entry = new Gtk.Entry (); PackStart (entry, true, true, 0); entry.Changed += entry_Changed; } button = new Gtk.Button (); Gtk.Image icon = new Gtk.Image (Gtk.Stock.Open, Gtk.IconSize.Button); button.Add (icon); PackStart (button, false, false, 0); button.Clicked += button_Clicked; } ShowAll (); } public void Initialize (PropertyDescriptor prop) { if (prop.PropertyType != typeof(string)) throw new ApplicationException ("Image editor does not support editing values of type " + prop.PropertyType); } public void AttachObject (object ob) { } public event EventHandler ValueChanged; bool syncing; void combo_Changed (object obj, EventArgs args) { if (syncing) return; useStock = true; syncing = true; if (combo.Active > 0) StockId = stockIds[combo.Active - 1]; else StockId = null; if (ValueChanged != null) ValueChanged (this, EventArgs.Empty); syncing = false; } void entry_Changed (object obj, EventArgs args) { if (syncing) return; useStock = true; syncing = true; StockId = entry.Text; if (ValueChanged != null) ValueChanged (this, EventArgs.Empty); syncing = false; } void button_Clicked (object obj, EventArgs args) { Gtk.FileChooserDialog dialog = new Gtk.FileChooserDialog (Catalog.GetString ("Image"), null, Gtk.FileChooserAction.Open, Gtk.Stock.Cancel, Gtk.ResponseType.Cancel, Gtk.Stock.Open, Gtk.ResponseType.Ok); int response = dialog.Run (); string file = dialog.Filename; dialog.Destroy (); if (response == (int)Gtk.ResponseType.Ok) { syncing = true; useStock = false; entry.Text = file; File = file; if (ValueChanged != null) ValueChanged (this, EventArgs.Empty); syncing = false; } } bool useStock; string stockId; public string StockId { get { return stockId; } set { useStock = true; stockId = value; file = null; image.SetFromStock (stockId, Gtk.IconSize.Button); if (!syncing) { int id = Array.IndexOf (stockIds, value); if (id != -1) { syncing = true; combo.Active = id + 1; syncing = false; } } } } string file; public string File { get { return file; } set { useStock = false; stockId = null; file = value; if (value == null) value = ""; try { image.Pixbuf = new Gdk.Pixbuf (value, imgWidth, imgHeight); } catch { image.SetFromStock (Gnome.Stock.Blank, Gtk.IconSize.Button); } if (!syncing) { syncing = true; entry.Text = value; syncing = false; } } } public virtual object Value { get { if (useStock) { if (StockId != null) return "stock:" + StockId; else return null; } else { if (File != null) return "file:" + File; else return null; } } set { string val = value as string; if (val == null) File = null; else if (val.StartsWith ("stock:")) StockId = val.Substring (6); else if (val.StartsWith ("file:")) File = val.Substring (5); } } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Globalization; using NodaTime.Text.Patterns; using NodaTime.TimeZones; using System; using System.Collections.Generic; namespace NodaTime.Text { internal sealed class ZonedDateTimePatternParser : IPatternParser<ZonedDateTime> { private readonly ZonedDateTime templateValue; private readonly IDateTimeZoneProvider? zoneProvider; private readonly ZoneLocalMappingResolver? resolver; private static readonly Dictionary<char, CharacterHandler<ZonedDateTime, ZonedDateTimeParseBucket>> PatternCharacterHandlers = new Dictionary<char, CharacterHandler<ZonedDateTime, ZonedDateTimeParseBucket>> { { '%', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePercent }, { '\'', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleQuote }, { '\"', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleQuote }, { '\\', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandleBackslash }, { '/', (pattern, builder) => builder.AddLiteral(builder.FormatInfo.DateSeparator, ParseResult<ZonedDateTime>.DateSeparatorMismatch) }, { 'T', (pattern, builder) => builder.AddLiteral('T', ParseResult<ZonedDateTime>.MismatchedCharacter) }, { 'y', DatePatternHelper.CreateYearOfEraHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.YearOfEra, (bucket, value) => bucket.Date.YearOfEra = value) }, { 'u', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (4, PatternFields.Year, -9999, 9999, value => value.Year, (bucket, value) => bucket.Date.Year = value) }, { 'M', DatePatternHelper.CreateMonthOfYearHandler<ZonedDateTime, ZonedDateTimeParseBucket> (value => value.Month, (bucket, value) => bucket.Date.MonthOfYearText = value, (bucket, value) => bucket.Date.MonthOfYearNumeric = value) }, { 'd', DatePatternHelper.CreateDayHandler<ZonedDateTime, ZonedDateTimeParseBucket> (value => value.Day, value => (int) value.DayOfWeek, (bucket, value) => bucket.Date.DayOfMonth = value, (bucket, value) => bucket.Date.DayOfWeek = value) }, { '.', TimePatternHelper.CreatePeriodHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { ';', TimePatternHelper.CreateCommaDotHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { ':', (pattern, builder) => builder.AddLiteral(builder.FormatInfo.TimeSeparator, ParseResult<ZonedDateTime>.TimeSeparatorMismatch) }, { 'h', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Hours12, 1, 12, value => value.ClockHourOfHalfDay, (bucket, value) => bucket.Time.Hours12 = value) }, { 'H', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Hours24, 0, 24, value => value.Hour, (bucket, value) => bucket.Time.Hours24 = value) }, { 'm', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Minutes, 0, 59, value => value.Minute, (bucket, value) => bucket.Time.Minutes = value) }, { 's', SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>.HandlePaddedField (2, PatternFields.Seconds, 0, 59, value => value.Second, (bucket, value) => bucket.Time.Seconds = value) }, { 'f', TimePatternHelper.CreateFractionHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { 'F', TimePatternHelper.CreateFractionHandler<ZonedDateTime, ZonedDateTimeParseBucket>(9, value => value.NanosecondOfSecond, (bucket, value) => bucket.Time.FractionalSeconds = value) }, { 't', TimePatternHelper.CreateAmPmHandler<ZonedDateTime, ZonedDateTimeParseBucket>(time => time.Hour, (bucket, value) => bucket.Time.AmPm = value) }, { 'c', DatePatternHelper.CreateCalendarHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.LocalDateTime.Calendar, (bucket, value) => bucket.Date.Calendar = value) }, { 'g', DatePatternHelper.CreateEraHandler<ZonedDateTime, ZonedDateTimeParseBucket>(value => value.Era, bucket => bucket.Date) }, { 'z', HandleZone }, { 'x', HandleZoneAbbreviation }, { 'o', HandleOffset }, { 'l', (cursor, builder) => builder.AddEmbeddedLocalPartial(cursor, bucket => bucket.Date, bucket => bucket.Time, value => value.Date, value => value.TimeOfDay, value => value.LocalDateTime) }, }; internal ZonedDateTimePatternParser(ZonedDateTime templateValue, ZoneLocalMappingResolver? resolver, IDateTimeZoneProvider? zoneProvider) { this.templateValue = templateValue; this.resolver = resolver; this.zoneProvider = zoneProvider; } // Note: public to implement the interface. It does no harm, and it's simpler than using explicit // interface implementation. public IPattern<ZonedDateTime> ParsePattern(string patternText, NodaFormatInfo formatInfo) { // Nullity check is performed in ZonedDateTimePattern. if (patternText.Length == 0) { throw new InvalidPatternException(TextErrorMessages.FormatStringEmpty); } // Handle standard patterns if (patternText.Length == 1) { return patternText[0] switch { 'G' => ZonedDateTimePattern.Patterns.GeneralFormatOnlyPatternImpl .WithZoneProvider(zoneProvider) .WithResolver(resolver), 'F' => ZonedDateTimePattern.Patterns.ExtendedFormatOnlyPatternImpl .WithZoneProvider(zoneProvider) .WithResolver(resolver), _ => throw new InvalidPatternException(TextErrorMessages.UnknownStandardFormat, patternText, typeof(ZonedDateTime)) }; } var patternBuilder = new SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket>(formatInfo, () => new ZonedDateTimeParseBucket(templateValue, resolver, zoneProvider)); if (zoneProvider is null || resolver is null) { patternBuilder.SetFormatOnly(); } patternBuilder.ParseCustomPattern(patternText, PatternCharacterHandlers); patternBuilder.ValidateUsedFields(); return patternBuilder.Build(templateValue); } private static void HandleZone(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.Zone, pattern.Current); builder.AddParseAction(ParseZone); builder.AddFormatAction((value, sb) => sb.Append(value.Zone.Id)); } private static void HandleZoneAbbreviation(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.ZoneAbbreviation, pattern.Current); builder.SetFormatOnly(); builder.AddFormatAction((value, sb) => sb.Append(value.GetZoneInterval().Name)); } private static void HandleOffset(PatternCursor pattern, SteppedPatternBuilder<ZonedDateTime, ZonedDateTimeParseBucket> builder) { builder.AddField(PatternFields.EmbeddedOffset, pattern.Current); string embeddedPattern = pattern.GetEmbeddedPattern(); var offsetPattern = OffsetPattern.Create(embeddedPattern, builder.FormatInfo).UnderlyingPattern; builder.AddEmbeddedPattern(offsetPattern, (bucket, offset) => bucket.Offset = offset, zdt => zdt.Offset); } private static ParseResult<ZonedDateTime>? ParseZone(ValueCursor value, ZonedDateTimeParseBucket bucket) => bucket.ParseZone(value); private sealed class ZonedDateTimeParseBucket : ParseBucket<ZonedDateTime> { internal readonly LocalDatePatternParser.LocalDateParseBucket Date; internal readonly LocalTimePatternParser.LocalTimeParseBucket Time; private DateTimeZone Zone; internal Offset Offset; private readonly ZoneLocalMappingResolver? resolver; private readonly IDateTimeZoneProvider? zoneProvider; internal ZonedDateTimeParseBucket(ZonedDateTime templateValue, ZoneLocalMappingResolver? resolver, IDateTimeZoneProvider? zoneProvider) { Date = new LocalDatePatternParser.LocalDateParseBucket(templateValue.Date); Time = new LocalTimePatternParser.LocalTimeParseBucket(templateValue.TimeOfDay); Zone = templateValue.Zone; this.resolver = resolver; this.zoneProvider = zoneProvider; } internal ParseResult<ZonedDateTime>? ParseZone(ValueCursor value) { DateTimeZone? zone = TryParseFixedZone(value) ?? TryParseProviderZone(value); if (zone is null) { return ParseResult<ZonedDateTime>.NoMatchingZoneId(value); } Zone = zone; return null; } /// <summary> /// Attempts to parse a fixed time zone from "UTC" with an optional /// offset, expressed as +HH, +HH:mm, +HH:mm:ss or +HH:mm:ss.fff - i.e. the /// general format. If it manages, it will move the cursor and return the /// zone. Otherwise, it will return null and the cursor will remain where /// it was. /// </summary> private static DateTimeZone? TryParseFixedZone(ValueCursor value) { if (value.CompareOrdinal(DateTimeZone.UtcId) != 0) { return null; } value.Move(value.Index + 3); var pattern = OffsetPattern.GeneralInvariant.UnderlyingPattern; var parseResult = pattern.ParsePartial(value); return parseResult.Success ? DateTimeZone.ForOffset(parseResult.Value) : DateTimeZone.Utc; } /// <summary> /// Tries to parse a time zone ID from the provider. Returns the zone /// on success (after moving the cursor to the end of the ID) or null on failure /// (leaving the cursor where it was). /// </summary> private DateTimeZone? TryParseProviderZone(ValueCursor value) { // Note: this method only called when zoneProvider is non-null, i.e. not a format-only pattern. // The IDs from the provider are guaranteed to be in order (using ordinal comparisons). // Use a binary search to find a match, then make sure it's the longest possible match. var ids = zoneProvider!.Ids; int lowerBound = 0; // Inclusive int upperBound = ids.Count; // Exclusive while (lowerBound < upperBound) { int guess = (lowerBound + upperBound) / 2; int result = value.CompareOrdinal(ids[guess]); if (result < 0) { // Guess is later than our text: lower the upper bound upperBound = guess; } else if (result > 0) { // Guess is earlier than our text: raise the lower bound lowerBound = guess + 1; } else { // We've found a match! But it may not be as long as it // could be. Keep track of a "longest match so far" (starting with the match we've found), // and keep looking through the IDs until we find an ID which doesn't start with that "longest // match so far", at which point we know we're done. // // We can't just look through all the IDs from "guess" to "lowerBound" and stop when we hit // a non-match against "value", because of situations like this: // value=Etc/GMT-12 // guess=Etc/GMT-1 // IDs includes { Etc/GMT-1, Etc/GMT-10, Etc/GMT-11, Etc/GMT-12, Etc/GMT-13 } // We can't stop when we hit Etc/GMT-10, because otherwise we won't find Etc/GMT-12. // We *can* stop when we get to Etc/GMT-13, because by then our longest match so far will // be Etc/GMT-12, and we know that anything beyond Etc/GMT-13 won't match that. // We can also stop when we hit upperBound, without any more comparisons. string longestSoFar = ids[guess]; for (int i = guess + 1; i < upperBound; i++) { string candidate = ids[i]; if (candidate.Length < longestSoFar.Length) { break; } if (string.CompareOrdinal(longestSoFar, 0, candidate, 0, longestSoFar.Length) != 0) { break; } if (value.CompareOrdinal(candidate) == 0) { longestSoFar = candidate; } } value.Move(value.Index + longestSoFar.Length); return zoneProvider![longestSoFar]; } } return null; } internal override ParseResult<ZonedDateTime> CalculateValue(PatternFields usedFields, string text) { var localResult = LocalDateTimePatternParser.LocalDateTimeParseBucket.CombineBuckets(usedFields, Date, Time, text); if (!localResult.Success) { return localResult.ConvertError<ZonedDateTime>(); } var localDateTime = localResult.Value; // No offset - so just use the resolver if ((usedFields & PatternFields.EmbeddedOffset) == 0) { try { // Note: this method is only called when resolver is non-null, i.e. not a format-only pattern. return ParseResult<ZonedDateTime>.ForValue(Zone.ResolveLocal(localDateTime, resolver!)); } catch (SkippedTimeException) { return ParseResult<ZonedDateTime>.SkippedLocalTime(text); } catch (AmbiguousTimeException) { return ParseResult<ZonedDateTime>.AmbiguousLocalTime(text); } } // We were given an offset, so we can resolve and validate using that var mapping = Zone.MapLocal(localDateTime); ZonedDateTime result; switch (mapping.Count) { // If the local time was skipped, the offset has to be invalid. case 0: return ParseResult<ZonedDateTime>.InvalidOffset(text); case 1: result = mapping.First(); // We'll validate in a minute break; case 2: result = mapping.First().Offset == Offset ? mapping.First() : mapping.Last(); break; default: throw new InvalidOperationException("Mapping has count outside range 0-2; should not happen."); } if (result.Offset != Offset) { return ParseResult<ZonedDateTime>.InvalidOffset(text); } return ParseResult<ZonedDateTime>.ForValue(result); } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Runtime { using System; using System.Diagnostics.CodeAnalysis; using System.Runtime; using System.Runtime.Serialization; using System.Security; using System.Threading; using System.Runtime.Diagnostics; [DataContract(Name = XD.Runtime.Scheduler, Namespace = XD.Runtime.Namespace)] class Scheduler { static ContinueAction continueAction = new ContinueAction(); static YieldSilentlyAction yieldSilentlyAction = new YieldSilentlyAction(); static AbortAction abortAction = new AbortAction(); WorkItem firstWorkItem; static SendOrPostCallback onScheduledWorkCallback = Fx.ThunkCallback(new SendOrPostCallback(OnScheduledWork)); SynchronizationContext synchronizationContext; bool isPausing; bool isRunning; bool resumeTraceRequired; Callbacks callbacks; Quack<WorkItem> workItemQueue; public Scheduler(Callbacks callbacks) { this.Initialize(callbacks); } public static RequestedAction Continue { get { return continueAction; } } public static RequestedAction YieldSilently { get { return yieldSilentlyAction; } } public static RequestedAction Abort { get { return abortAction; } } public bool IsRunning { get { return this.isRunning; } } public bool IsIdle { get { return this.firstWorkItem == null; } } [DataMember(EmitDefaultValue = false, Name = "firstWorkItem")] internal WorkItem SerializedFirstWorkItem { get { return this.firstWorkItem; } set { this.firstWorkItem = value; } } [DataMember(EmitDefaultValue = false)] [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.AvoidUncalledPrivateCode)] internal WorkItem[] SerializedWorkItemQueue { get { if (this.workItemQueue != null && this.workItemQueue.Count > 0) { return this.workItemQueue.ToArray(); } else { return null; } } set { Fx.Assert(value != null, "EmitDefaultValue is false so we should never get null."); // this.firstWorkItem is serialized out separately, so don't use ScheduleWork() here this.workItemQueue = new Quack<WorkItem>(value); } } public void FillInstanceMap(ActivityInstanceMap instanceMap) { if (this.firstWorkItem != null) { ActivityInstanceMap.IActivityReference activityReference = this.firstWorkItem as ActivityInstanceMap.IActivityReference; if (activityReference != null) { instanceMap.AddEntry(activityReference, true); } if (this.workItemQueue != null && this.workItemQueue.Count > 0) { for (int i = 0; i < this.workItemQueue.Count; i++) { activityReference = this.workItemQueue[i] as ActivityInstanceMap.IActivityReference; if (activityReference != null) { instanceMap.AddEntry(activityReference, true); } } } } } public static RequestedAction CreateNotifyUnhandledExceptionAction(Exception exception, ActivityInstance sourceInstance) { return new NotifyUnhandledExceptionAction(exception, sourceInstance); } public void ClearAllWorkItems(ActivityExecutor executor) { if (this.firstWorkItem != null) { this.firstWorkItem.Release(executor); this.firstWorkItem = null; if (this.workItemQueue != null) { while (this.workItemQueue.Count > 0) { WorkItem item = this.workItemQueue.Dequeue(); item.Release(executor); } } } Fx.Assert(this.workItemQueue == null || this.workItemQueue.Count == 0, "We either didn't have a first work item and therefore don't have anything in the queue, or we drained the queue."); // For consistency we set this to null even if it is empty this.workItemQueue = null; } public void OnDeserialized(Callbacks callbacks) { Initialize(callbacks); Fx.Assert(this.firstWorkItem != null || this.workItemQueue == null, "cannot have items in the queue unless we also have a firstWorkItem set"); } // This method should only be called when we relinquished the thread but did not // complete the operation (silent yield is the current example) public void InternalResume(RequestedAction action) { Fx.Assert(this.isRunning, "We should still be processing work - we just don't have a thread"); bool isTracingEnabled = FxTrace.ShouldTraceInformation; bool notifiedCompletion = false; bool isInstanceComplete = false; if (this.callbacks.IsAbortPending) { this.isPausing = false; this.isRunning = false; this.NotifyWorkCompletion(); notifiedCompletion = true; if (isTracingEnabled) { isInstanceComplete = this.callbacks.IsCompleted; } // After calling SchedulerIdle we no longer have the lock. That means // that any subsequent processing in this method won't have the single // threaded guarantee. this.callbacks.SchedulerIdle(); } else if (object.ReferenceEquals(action, continueAction)) { ScheduleWork(false); } else { Fx.Assert(action is NotifyUnhandledExceptionAction, "This is the only other choice because we should never have YieldSilently here"); NotifyUnhandledExceptionAction notifyAction = (NotifyUnhandledExceptionAction)action; // We only set isRunning back to false so that the host doesn't // have to treat this like a pause notification. As an example, // a host could turn around and call run again in response to // UnhandledException without having to go through its operation // dispatch loop first (or request pause again). If we reset // isPausing here then any outstanding operations wouldn't get // signaled with that type of host. this.isRunning = false; this.NotifyWorkCompletion(); notifiedCompletion = true; if (isTracingEnabled) { isInstanceComplete = this.callbacks.IsCompleted; } this.callbacks.NotifyUnhandledException(notifyAction.Exception, notifyAction.Source); } if (isTracingEnabled) { if (notifiedCompletion) { Guid oldActivityId = Guid.Empty; bool resetId = false; if (isInstanceComplete) { if (TD.WorkflowActivityStopIsEnabled()) { oldActivityId = DiagnosticTraceBase.ActivityId; DiagnosticTraceBase.ActivityId = this.callbacks.WorkflowInstanceId; resetId = true; TD.WorkflowActivityStop(this.callbacks.WorkflowInstanceId); } } else { if (TD.WorkflowActivitySuspendIsEnabled()) { oldActivityId = DiagnosticTraceBase.ActivityId; DiagnosticTraceBase.ActivityId = this.callbacks.WorkflowInstanceId; resetId = true; TD.WorkflowActivitySuspend(this.callbacks.WorkflowInstanceId); } } if (resetId) { DiagnosticTraceBase.ActivityId = oldActivityId; } } } } // called from ctor and OnDeserialized intialization paths void Initialize(Callbacks callbacks) { this.callbacks = callbacks; } public void Open(SynchronizationContext synchronizationContext) { Fx.Assert(this.synchronizationContext == null, "can only open when in the created state"); if (synchronizationContext != null) { this.synchronizationContext = synchronizationContext; } else { this.synchronizationContext = SynchronizationContextHelper.GetDefaultSynchronizationContext(); } } internal void Open(Scheduler oldScheduler) { Fx.Assert(this.synchronizationContext == null, "can only open when in the created state"); this.synchronizationContext = SynchronizationContextHelper.CloneSynchronizationContext(oldScheduler.synchronizationContext); } void ScheduleWork(bool notifyStart) { if (notifyStart) { this.synchronizationContext.OperationStarted(); this.resumeTraceRequired = true; } else { this.resumeTraceRequired = false; } this.synchronizationContext.Post(Scheduler.onScheduledWorkCallback, this); } void NotifyWorkCompletion() { this.synchronizationContext.OperationCompleted(); } // signal the scheduler to stop processing work. If we are processing work // then we will catch this signal at our next iteration. Pause process completes // when idle is signalled. Can be called while we're processing work since // the worst thing that could happen in a ---- is that we pause one extra work item later public void Pause() { this.isPausing = true; } public void MarkRunning() { this.isRunning = true; } public void Resume() { Fx.Assert(this.isRunning, "This should only be called after we've been set to process work."); if (this.IsIdle || this.isPausing || this.callbacks.IsAbortPending) { this.isPausing = false; this.isRunning = false; this.callbacks.SchedulerIdle(); } else { ScheduleWork(true); } } public void PushWork(WorkItem workItem) { if (this.firstWorkItem == null) { this.firstWorkItem = workItem; } else { if (this.workItemQueue == null) { this.workItemQueue = new Quack<WorkItem>(); } this.workItemQueue.PushFront(this.firstWorkItem); this.firstWorkItem = workItem; } // To avoid the virt call on EVERY work item we check // the Verbose flag. All of our Schedule traces are // verbose. if (FxTrace.ShouldTraceVerboseToTraceSource) { workItem.TraceScheduled(); } } public void EnqueueWork(WorkItem workItem) { if (this.firstWorkItem == null) { this.firstWorkItem = workItem; } else { if (this.workItemQueue == null) { this.workItemQueue = new Quack<WorkItem>(); } this.workItemQueue.Enqueue(workItem); } if (FxTrace.ShouldTraceVerboseToTraceSource) { workItem.TraceScheduled(); } } static void OnScheduledWork(object state) { Scheduler thisPtr = (Scheduler)state; // We snapshot these values here so that we can // use them after calling OnSchedulerIdle. bool isTracingEnabled = FxTrace.Trace.ShouldTraceToTraceSource(TraceEventLevel.Informational); Guid oldActivityId = Guid.Empty; Guid workflowInstanceId = Guid.Empty; if (isTracingEnabled) { oldActivityId = DiagnosticTraceBase.ActivityId; workflowInstanceId = thisPtr.callbacks.WorkflowInstanceId; FxTrace.Trace.SetAndTraceTransfer(workflowInstanceId, true); if (thisPtr.resumeTraceRequired) { if (TD.WorkflowActivityResumeIsEnabled()) { TD.WorkflowActivityResume(workflowInstanceId); } } } thisPtr.callbacks.ThreadAcquired(); RequestedAction nextAction = continueAction; bool idleOrPaused = false; while (object.ReferenceEquals(nextAction, continueAction)) { if (thisPtr.IsIdle || thisPtr.isPausing) { idleOrPaused = true; break; } // cycle through (queue->thisPtr.firstWorkItem->currentWorkItem) WorkItem currentWorkItem = thisPtr.firstWorkItem; // promote an item out of our work queue if necessary if (thisPtr.workItemQueue != null && thisPtr.workItemQueue.Count > 0) { thisPtr.firstWorkItem = thisPtr.workItemQueue.Dequeue(); } else { thisPtr.firstWorkItem = null; } if (TD.ExecuteWorkItemStartIsEnabled()) { TD.ExecuteWorkItemStart(); } nextAction = thisPtr.callbacks.ExecuteWorkItem(currentWorkItem); if (TD.ExecuteWorkItemStopIsEnabled()) { TD.ExecuteWorkItemStop(); } } bool notifiedCompletion = false; bool isInstanceComplete = false; if (idleOrPaused || object.ReferenceEquals(nextAction, abortAction)) { thisPtr.isPausing = false; thisPtr.isRunning = false; thisPtr.NotifyWorkCompletion(); notifiedCompletion = true; if (isTracingEnabled) { isInstanceComplete = thisPtr.callbacks.IsCompleted; } // After calling SchedulerIdle we no longer have the lock. That means // that any subsequent processing in this method won't have the single // threaded guarantee. thisPtr.callbacks.SchedulerIdle(); } else if (!object.ReferenceEquals(nextAction, yieldSilentlyAction)) { Fx.Assert(nextAction is NotifyUnhandledExceptionAction, "This is the only other option"); NotifyUnhandledExceptionAction notifyAction = (NotifyUnhandledExceptionAction)nextAction; // We only set isRunning back to false so that the host doesn't // have to treat this like a pause notification. As an example, // a host could turn around and call run again in response to // UnhandledException without having to go through its operation // dispatch loop first (or request pause again). If we reset // isPausing here then any outstanding operations wouldn't get // signaled with that type of host. thisPtr.isRunning = false; thisPtr.NotifyWorkCompletion(); notifiedCompletion = true; if (isTracingEnabled) { isInstanceComplete = thisPtr.callbacks.IsCompleted; } thisPtr.callbacks.NotifyUnhandledException(notifyAction.Exception, notifyAction.Source); } if (isTracingEnabled) { if (notifiedCompletion) { if (isInstanceComplete) { if (TD.WorkflowActivityStopIsEnabled()) { TD.WorkflowActivityStop(workflowInstanceId); } } else { if (TD.WorkflowActivitySuspendIsEnabled()) { TD.WorkflowActivitySuspend(workflowInstanceId); } } } DiagnosticTraceBase.ActivityId = oldActivityId; } } public struct Callbacks { readonly ActivityExecutor activityExecutor; public Callbacks(ActivityExecutor activityExecutor) { this.activityExecutor = activityExecutor; } public Guid WorkflowInstanceId { get { return this.activityExecutor.WorkflowInstanceId; } } public bool IsAbortPending { get { return this.activityExecutor.IsAbortPending || this.activityExecutor.IsTerminatePending; } } public bool IsCompleted { get { return ActivityUtilities.IsCompletedState(this.activityExecutor.State); } } public RequestedAction ExecuteWorkItem(WorkItem workItem) { Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in ExecuteWorkItem."); // We check the Verbose flag to avoid the // virt call if possible if (FxTrace.ShouldTraceVerboseToTraceSource) { workItem.TraceStarting(); } RequestedAction action = this.activityExecutor.OnExecuteWorkItem(workItem); if (!object.ReferenceEquals(action, Scheduler.YieldSilently)) { if (this.activityExecutor.IsAbortPending || this.activityExecutor.IsTerminatePending) { action = Scheduler.Abort; } // if the caller yields, then the work item is still active and the callback // is responsible for releasing it back to the pool workItem.Dispose(this.activityExecutor); } return action; } public void SchedulerIdle() { Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in SchedulerIdle."); this.activityExecutor.OnSchedulerIdle(); } public void ThreadAcquired() { Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in ThreadAcquired."); this.activityExecutor.OnSchedulerThreadAcquired(); } public void NotifyUnhandledException(Exception exception, ActivityInstance source) { Fx.Assert(this.activityExecutor != null, "ActivityExecutor null in NotifyUnhandledException."); this.activityExecutor.NotifyUnhandledException(exception, source); } } internal abstract class RequestedAction { protected RequestedAction() { } } class ContinueAction : RequestedAction { public ContinueAction() { } } class YieldSilentlyAction : RequestedAction { public YieldSilentlyAction() { } } class AbortAction : RequestedAction { public AbortAction() { } } class NotifyUnhandledExceptionAction : RequestedAction { public NotifyUnhandledExceptionAction(Exception exception, ActivityInstance source) { this.Exception = exception; this.Source = source; } public Exception Exception { get; private set; } public ActivityInstance Source { get; private set; } } } }
/* Copyright (c) 2006-2008 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. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #region Using directives using System; using System.Collections; using System.Text; using System.Xml; using Google.GData.Client; using System.Collections.Generic; #endregion namespace Google.GData.GoogleBase { /////////////////////////////////////////////////////////////////////// /// <summary>A convenience class for accessing GBaseAttribute /// extensions in an atom feed or entry (Level 1). /// /// This class provides simple, but still low-level access to /// attributes in an atom feed or entry. It's the 1st level /// of the hierarchy. Subclasses provide more convenient accessor /// methods with type conversion and accessors for the most common /// Google base tags. /// /// Everything this object does is access and modify the extension /// list of the atom feed or entry. It has no state of its own. /// </summary> /////////////////////////////////////////////////////////////////////// public class GBaseAttributeCollection : IEnumerable { private ExtensionList extensionElements; /////////////////////////////////////////////////////////////////////// /// <summary>Creates an attribute collection and link it to an /// extension list.</summary> /// <param name="atomElement">atom element, usually a feed or /// an entry.</param> /////////////////////////////////////////////////////////////////////// public GBaseAttributeCollection(AtomBase atomElement) : this(atomElement.ExtensionElements) { } /////////////////////////////////////////////////////////////////////// /// <summary>Creates an attribute collection and link it to an /// extension list.</summary> /// <param name="extensionElements">extension list to be queried and /// modified</param> /////////////////////////////////////////////////////////////////////// public GBaseAttributeCollection(ExtensionList extensionElements) : base() { this.extensionElements = extensionElements; } /////////////////////////////////////////////////////////////////////// /// <summary>Gets all attributes with a specific name and any type. /// </summary> /// <param name="name">attribute name</param> /// <returns>all attributes on the list that have this name, in order /// </returns> /////////////////////////////////////////////////////////////////////// public List<GBaseAttribute> GetAttributes(string name) { List<GBaseAttribute> retVal = new List<GBaseAttribute>(); foreach (GBaseAttribute var in GetAttributeList(name)) { retVal.Add(var); } return retVal; } /////////////////////////////////////////////////////////////////////// /// <summary>Gets all attributes with a specific name and a specific /// type.</summary> /// <param name="name">attribute name</param> /// <param name="type">attribute type</param> /// <returns>all attributes on the list that have this name and /// type (or one of its subtypes), in order</returns> /////////////////////////////////////////////////////////////////////// public List<GBaseAttribute> GetAttributes(string name, GBaseAttributeType type) { List<GBaseAttribute> retVal = new List<GBaseAttribute>(); foreach (GBaseAttribute var in GetAttributeList(name, type)) { retVal.Add(var); } return retVal; } /////////////////////////////////////////////////////////////////////// /// <summary>Gets the first attribute with a specific name and any type. /// </summary> /// <param name="name">attribute name</param> /// <returns>the first attribute found or null</returns> /////////////////////////////////////////////////////////////////////// public GBaseAttribute GetAttribute(string name) { foreach (GBaseAttribute attribute in this) { if (name == attribute.Name) { return attribute; } } return null; } /////////////////////////////////////////////////////////////////////// /// <summary>Gets the first attribute with a specific name and type. /// </summary> /// <param name="name">attribute name</param> /// <param name="type">attribute type</param> /// <returns>the first attribute found with this name and type (or /// one of its subtypes) or null</returns> /////////////////////////////////////////////////////////////////////// public GBaseAttribute GetAttribute(string name, GBaseAttributeType type) { foreach (GBaseAttribute attribute in this) { if (HasNameAndType(attribute, name, type)) { return attribute; } } return null; } private bool HasNameAndType(GBaseAttribute attr, String name, GBaseAttributeType type) { return name == attr.Name && (type == null || type.IsSupertypeOf(attr.Type)); } private ExtensionList GetAttributeList(string name) { ExtensionList retval = ExtensionList.NotVersionAware(); foreach (GBaseAttribute attribute in this) { if (name == attribute.Name) { retval.Add(attribute); } } return retval; } private ExtensionList GetAttributeList(string name, GBaseAttributeType type) { ExtensionList retval = ExtensionList.NotVersionAware(); foreach (GBaseAttribute attribute in this) { if (HasNameAndType(attribute, name, type)) { retval.Add(attribute); } } return retval; } /////////////////////////////////////////////////////////////////////// /// <summary>Adds an attribute at the end of the list. /// The might exist attributes with the same name, type and even /// value. This method will not remove them.</summary> /////////////////////////////////////////////////////////////////////// public GBaseAttribute Add(GBaseAttribute value) { extensionElements.Add(value); return value; } /////////////////////////////////////////////////////////////////////// /// <summary>Adds an attribute at the end of the list. /// The might exist attributes with the same name, type and even /// value. This method will not remove them.</summary> /// <param name="name">attribute name</param> /// <param name="type">attribute type</param> /// <param name="content">value, as a string</param> /////////////////////////////////////////////////////////////////////// public GBaseAttribute Add(String name, GBaseAttributeType type, String content) { GBaseAttribute attribute = new GBaseAttribute(name, type, content); Add(attribute); return attribute; } /////////////////////////////////////////////////////////////////////// /// <summary>Remove all attributes with a specific name and any type. /// This method is dangerous. You might be better off calling /// the version of this method that takes a name and type.</summary> /// <param name="name">attribute name</param> /////////////////////////////////////////////////////////////////////// public void RemoveAll(String name) { RemoveAll(GetAttributeList(name)); } /////////////////////////////////////////////////////////////////////// /// <summary>Remove all attributes with a specific name and type or /// on of its subtypes.</summary> /// <param name="name">attribute name</param> /// <param name="type">attribute type</param> /////////////////////////////////////////////////////////////////////// public void RemoveAll(String name, GBaseAttributeType type) { RemoveAll(GetAttributeList(name, type)); } private void RemoveAll(IList<IExtensionElementFactory> list) { foreach (GBaseAttribute attribute in list) { Remove(attribute); } } /////////////////////////////////////////////////////////////////////// /// <summary>Remove a specific attribute, if it's there.</summary> /// <param name="attribute">attribute to remove</param> /////////////////////////////////////////////////////////////////////// public void Remove(GBaseAttribute attribute) { extensionElements.Remove(attribute); } /////////////////////////////////////////////////////////////////////// /// <summary>Checks whether an attribute can be found in the element. /// This method looks for an attribute with the exact same name, type /// and content.</summary> /// <returns>true if the attribute exists</returns> /////////////////////////////////////////////////////////////////////// public bool Contains(GBaseAttribute value) { return extensionElements.Contains(value); } /////////////////////////////////////////////////////////////////////// /// <summary>Removes all Google Base attributes.</summary> /////////////////////////////////////////////////////////////////////// public void Clear() { ExtensionList toRemove = ExtensionList.NotVersionAware(); foreach (GBaseAttribute attribute in this) { toRemove.Add(attribute); } RemoveAll(toRemove); } /////////////////////////////////////////////////////////////////////// /// <summary>Reads an attribute from XML and add it.</summary> /////////////////////////////////////////////////////////////////////// public void AddFromXml(XmlNode node) { Add(GBaseAttribute.ParseGBaseAttribute(node)); } /////////////////////////////////////////////////////////////////////// /// <summary>Gets an enumerator over all GBaseAttribute in the /// atom feed or entry.</summary> /////////////////////////////////////////////////////////////////////// public IEnumerator GetEnumerator() { return new GBaseAttributeFilterEnumerator(extensionElements); } } /////////////////////////////////////////////////////////////////////// /// <summary>Filters an IEnumerator, ignoring all elements that /// are not GBaseAttribute objects.</summary> /////////////////////////////////////////////////////////////////////// class GBaseAttributeFilterEnumerator : IEnumerator { private readonly IEnumerator orig; public GBaseAttributeFilterEnumerator(IEnumerable collection) : this(collection.GetEnumerator()) { } public GBaseAttributeFilterEnumerator(IEnumerator orig) { this.orig = orig; } public bool MoveNext() { while (orig.MoveNext()) { if (orig.Current is GBaseAttribute) { return true; } } return false; } public void Reset() { orig.Reset(); } public object Current { get { return orig.Current; } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof(int)/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, Constant: 4) (Syntax: 'sizeof(int)') TypeOperand: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_NonPrimitiveTypeArgument() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof(C)/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, IsInvalid) (Syntax: 'sizeof(C)') TypeOperand: C "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C') // i = /*<bind>*/sizeof(C)/*</bind>*/; Diagnostic(ErrorCode.ERR_ManagedAddr, "sizeof(C)").WithArguments("C").WithLocation(8, 23), // CS0233: 'C' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // i = /*<bind>*/sizeof(C)/*</bind>*/; Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(C)").WithArguments("C").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_PointerTypeArgument() { string source = @" using System; class C { unsafe void M(int i) { i = /*<bind>*/sizeof(void**)/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32) (Syntax: 'sizeof(void**)') TypeOperand: System.Void** "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, compilationOptions: TestOptions.UnsafeReleaseDll); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_ErrorTypeArgument() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof(UndefinedType)/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, IsInvalid) (Syntax: 'sizeof(UndefinedType)') TypeOperand: UndefinedType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?) // i = /*<bind>*/sizeof(UndefinedType)/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UndefinedType").WithArguments("UndefinedType").WithLocation(8, 30), // CS0233: 'UndefinedType' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // i = /*<bind>*/sizeof(UndefinedType)/*</bind>*/; Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(UndefinedType)").WithArguments("UndefinedType").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_IdentifierArgument() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof(i)/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, IsInvalid) (Syntax: 'sizeof(i)') TypeOperand: i "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0118: 'i' is a variable but is used like a type // i = /*<bind>*/sizeof(i)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKknown, "i").WithArguments("i", "variable", "type").WithLocation(8, 30), // CS0233: 'i' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // i = /*<bind>*/sizeof(i)/*</bind>*/; Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(i)").WithArguments("i").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_ExpressionArgument() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof(M2()/*</bind>*/); } int M2() => 0; } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'sizeof(M2()') Children(1): ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, IsInvalid) (Syntax: 'sizeof(M2') TypeOperand: M2 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1026: ) expected // i = /*<bind>*/sizeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_CloseParenExpected, "(").WithLocation(8, 32), // CS1002: ; expected // i = /*<bind>*/sizeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(8, 45), // CS1513: } expected // i = /*<bind>*/sizeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(8, 45), // CS0246: The type or namespace name 'M2' could not be found (are you missing a using directive or an assembly reference?) // i = /*<bind>*/sizeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "M2").WithArguments("M2").WithLocation(8, 30), // CS0233: 'M2' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // i = /*<bind>*/sizeof(M2()/*</bind>*/); Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof(M2").WithArguments("M2").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestSizeOfExpression_MissingArgument() { string source = @" using System; class C { void M(int i) { i = /*<bind>*/sizeof()/*</bind>*/; } } "; string expectedOperationTree = @" ISizeOfOperation (OperationKind.SizeOf, Type: System.Int32, IsInvalid) (Syntax: 'sizeof()') TypeOperand: ? "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1031: Type expected // i = /*<bind>*/sizeof()/*</bind>*/; Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(8, 30), // CS0233: '?' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) // i = /*<bind>*/sizeof()/*</bind>*/; Diagnostic(ErrorCode.ERR_SizeofUnsafe, "sizeof()").WithArguments("?").WithLocation(8, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SizeOfExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Test { // a key part of cancellation testing is 'promptness'. Those tests appear in pfxperfunittests. // the tests here are only regarding basic API correctness and sanity checking. public static class WithCancellationTests { [Fact] public static void PreCanceledToken_ForAll() { OperationCanceledException caughtException = null; var cs = new CancellationTokenSource(); cs.Cancel(); int[] srcEnumerable = Enumerable.Range(0, 1000).ToArray(); ThrowOnFirstEnumerable<int> throwOnFirstEnumerable = new ThrowOnFirstEnumerable<int>(srcEnumerable); try { throwOnFirstEnumerable .AsParallel() .WithCancellation(cs.Token) .ForAll((x) => { Console.WriteLine(x.ToString()); }); } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(cs.Token, caughtException.CancellationToken); } [Fact] public static void PreCanceledToken_SimpleEnumerator() { OperationCanceledException caughtException = null; var cs = new CancellationTokenSource(); cs.Cancel(); int[] srcEnumerable = Enumerable.Range(0, 1000).ToArray(); ThrowOnFirstEnumerable<int> throwOnFirstEnumerable = new ThrowOnFirstEnumerable<int>(srcEnumerable); try { var query = throwOnFirstEnumerable .AsParallel() .WithCancellation(cs.Token); foreach (var item in query) { } } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(cs.Token, caughtException.CancellationToken); } [Fact] public static void MultiplesWithCancellationIsIllegal() { InvalidOperationException caughtException = null; try { CancellationTokenSource cs = new CancellationTokenSource(); CancellationToken ct = cs.Token; var query = Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(2).WithDegreeOfParallelism(2); query.ToArray(); } catch (InvalidOperationException ex) { caughtException = ex; //Program.TestHarness.Log("IOE caught. message = " + ex.Message); } Assert.NotNull(caughtException); } [Fact] public static void CTT_Sorting_ToArray() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); OperationCanceledException caughtException = null; try { Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select(i => { tokenSource.Cancel(); return i; }) .ToArray(); } catch (OperationCanceledException ex) { caughtException = ex; } Assert.NotNull(caughtException); Assert.Equal(tokenSource.Token, caughtException.CancellationToken); } [Fact] public static void CTT_NonSorting_AsynchronousMergerEnumeratorDispose() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); Exception caughtException = null; IEnumerator<int> enumerator = null; ParallelQuery<int> query = null; query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select(i => { enumerator.Dispose(); return i; }); enumerator = query.GetEnumerator(); try { for (int j = 0; j < 1000; j++) { enumerator.MoveNext(); } } catch (Exception ex) { caughtException = ex; } Assert.NotNull(caughtException); } [Fact] public static void CTT_NonSorting_SynchronousMergerEnumeratorDispose() { int size = 10000; CancellationTokenSource tokenSource = new CancellationTokenSource(); Exception caughtException = null; IEnumerator<int> enumerator = null; var query = Enumerable.Range(1, size).AsParallel() .WithCancellation(tokenSource.Token) .Select( i => { enumerator.Dispose(); return i; }).WithMergeOptions(ParallelMergeOptions.FullyBuffered); enumerator = query.GetEnumerator(); try { // This query should run for at least a few seconds due to the sleeps in the select-delegate for (int j = 0; j < 1000; j++) { enumerator.MoveNext(); } } catch (ObjectDisposedException ex) { caughtException = ex; } Assert.NotNull(caughtException); } /// <summary> /// /// [Regression Test] /// This issue occured because the QuerySettings structure was not being deep-cloned during /// query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) /// that occur in SelectMany were sharing CancellationState that they should not have. /// The result was that enumerators could falsely believe they had been canceled when /// another inner-enumerator was disposed. /// /// Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). /// </summary> /// <returns></returns> [Fact] public static void CloningQuerySettingsForSelectMany() { var plinq_src = ParallelEnumerable.Range(0, 1999).AsParallel(); Exception caughtException = null; try { var inner = ParallelEnumerable.Range(0, 20).AsParallel().Select(_item => _item); var output = plinq_src .SelectMany( _x => inner, (_x, _y) => _x ) .ToArray(); } catch (Exception ex) { caughtException = ex; } Assert.Null(caughtException); } // [Regression Test] // Use of the async channel can block both the consumer and producer threads.. before the cancellation work // these had no means of being awoken. // // However, only the producers need to wake up on cancellation as the consumer // will wake up once all the producers have gone away (via AsynchronousOneToOneChannel.SetDone()) // // To specifically verify this test, we want to know that the Async channels were blocked in TryEnqueChunk before Dispose() is called // -> this was verified manually, but is not simple to automate [Fact] [OuterLoop] // explicit timeouts / delays public static void ChannelCancellation_ProducerBlocked() { Console.WriteLine("PlinqCancellationTests.ChannelCancellation_ProducerBlocked()"); Console.WriteLine(" Query running (should be few seconds max).."); var query1 = Enumerable.Range(0, 100000000) //provide 100million elements to ensure all the cores get >64K ints. Good up to 1600cores .AsParallel() .Select(x => x); var enumerator1 = query1.GetEnumerator(); enumerator1.MoveNext(); Task.Delay(1000).Wait(); enumerator1.MoveNext(); enumerator1.Dispose(); //can potentially hang Console.WriteLine(" Done (success)."); } /// <summary> /// [Regression Test] /// This issue occurred because aggregations like Sum or Average would incorrectly /// wrap OperationCanceledException with AggregateException. /// </summary> [Fact] public static void AggregatesShouldntWrapOCE() { var cs = new CancellationTokenSource(); cs.Cancel(); // Expect OperationCanceledException rather than AggregateException or something else try { Enumerable.Range(0, 1000).AsParallel().WithCancellation(cs.Token).Sum(x => x); } catch (OperationCanceledException) { return; } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: got {0}, expected OperationCanceledException", e.GetType().ToString())); } Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: no exception occured, expected OperationCanceledException")); } // Plinq supresses OCE(externalCT) occuring in worker threads and then throws a single OCE(ct) // if a manual OCE(ct) is thrown but ct is not canceled, Plinq should not suppress it, else things // get confusing... // ONLY an OCE(ct) for ct.IsCancellationRequested=true is co-operative cancellation [Fact] public static void OnlySuppressOCEifCTCanceled() { AggregateException caughtException = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken externalToken = cts.Token; try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(externalToken) .Select( x => { if (x % 2 == 0) throw new OperationCanceledException(externalToken); return x; } ) .ToArray(); } catch (AggregateException ae) { caughtException = ae; } Assert.NotNull(caughtException); } // a specific repro where inner queries would see an ODE on the merged cancellation token source // when the implementation involved disposing and recreating the token on each worker thread [Fact] public static void Cancellation_ODEIssue() { AggregateException caughtException = null; try { Enumerable.Range(0, 1999).ToArray() .AsParallel().AsUnordered() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .Zip<int, int, int>( Enumerable.Range(1000, 20).Select<int, int>(_item => (int)_item).AsParallel().AsUnordered(), (first, second) => { throw new OperationCanceledException(); }) .ForAll(x => { }); } catch (AggregateException ae) { caughtException = ae; } //the failure was an ODE coming out due to an ephemeral disposed merged cancellation token source. Assert.True(caughtException != null, "Cancellation_ODEIssue: We expect an aggregate exception with OCEs in it."); } [Fact] [OuterLoop] // explicit timeouts / delays public static void CancellationSequentialWhere() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); var q = src.AsParallel().WithCancellation(tokenSrc.Token).Where(x => false).TakeWhile(x => true); Task task = Task.Run( () => { try { foreach (var x in q) { } Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { if (oce.CancellationToken != tokenSrc.Token) { Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: Wrong cancellation token.")); } } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.Delay(100).Wait(); //Thread.Sleep(100); tokenSrc.Cancel(); task.Wait(); } [Fact] [OuterLoop] // explicit timeouts / delays public static void CancellationSequentialElementAt() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); Task task = Task.Run( () => { try { int res = src.AsParallel() .WithCancellation(tokenSrc.Token) .Where(x => true) .TakeWhile(x => true) .ElementAt(int.MaxValue - 1); Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialElementAt: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { Assert.Equal(oce.CancellationToken, tokenSrc.Token); } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.Delay(100).Wait(); tokenSrc.Cancel(); task.Wait(); } [Fact] [OuterLoop] // explicit timeouts / delays public static void CancellationSequentialDistinct() { IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue); CancellationTokenSource tokenSrc = new CancellationTokenSource(); Task task = Task.Run( () => { try { var q = src.AsParallel() .WithCancellation(tokenSrc.Token) .Distinct() .TakeWhile(x => true); foreach (var x in q) { } Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialDistinct: > Failed: OperationCanceledException was not caught.")); } catch (OperationCanceledException oce) { Assert.Equal(oce.CancellationToken, tokenSrc.Token); } } ); // We wait for 100 ms. If we canceled the token source immediately, the cancellation // would occur at the query opening time. The goal of this test is to test cancellation // at query execution time. Task.Delay(100).Wait(); tokenSrc.Cancel(); task.Wait(); } // Regression test for an issue causing ODE if a queryEnumator is disposed before moveNext is called. [Fact] public static void ImmediateDispose() { var queryEnumerator = Enumerable.Range(1, 10).AsParallel().Select(x => x).GetEnumerator(); queryEnumerator.Dispose(); } // REPRO 1 -- cancellation [Fact] public static void SetOperationsThrowAggregateOnCancelOrDispose_1() { CancellationTokenSource cs = new CancellationTokenSource(); var plinq_src = Enumerable.Range(0, 5000000).Select(x => { cs.Cancel(); return x; }); try { var plinq = plinq_src .AsParallel().WithCancellation(cs.Token) .WithDegreeOfParallelism(1) .Union(Enumerable.Range(0, 10).AsParallel()); var walker = plinq.GetEnumerator(); while (walker.MoveNext()) { var item = walker.Current; } Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but no exception occured.")); } catch (OperationCanceledException) { //This is expected. } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but a different exception occured. " + e.ToString())); } } // throwing a fake OCE(ct) when the ct isn't canceled should produce an AggregateException. [Fact] public static void SetOperationsThrowAggregateOnCancelOrDispose_2() { try { CancellationTokenSource cs = new CancellationTokenSource(); var plinq = Enumerable.Range(0, 50) .AsParallel().WithCancellation(cs.Token) .WithDegreeOfParallelism(1) .Union(Enumerable.Range(0, 10).AsParallel().Select<int, int>(x => { throw new OperationCanceledException(cs.Token); })); var walker = plinq.GetEnumerator(); while (walker.MoveNext()) { } Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2: failed. AggregateException was expected, but no exception occured.")); } catch (AggregateException) { // expected } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2. failed. AggregateExcption was expected, but some other exception occured." + e.ToString())); } } // Changes made to hash-partitioning (April'09) lost the cancellation checks during the // main repartitioning loop (matrix building). [Fact] public static void HashPartitioningCancellation() { OperationCanceledException caughtException = null; CancellationTokenSource cs = new CancellationTokenSource(); //Without ordering var queryUnordered = Enumerable.Range(0, int.MaxValue) .Select(x => { if (x == 0) cs.Cancel(); return x; }) .AsParallel() .WithCancellation(cs.Token) .Intersect(Enumerable.Range(0, 1000000).AsParallel()); try { foreach (var item in queryUnordered) { } } catch (OperationCanceledException oce) { caughtException = oce; } Assert.NotNull(caughtException); caughtException = null; //With ordering var queryOrdered = Enumerable.Range(0, int.MaxValue) .Select(x => { if (x == 0) cs.Cancel(); return x; }) .AsParallel().AsOrdered() .WithCancellation(cs.Token) .Intersect(Enumerable.Range(0, 1000000).AsParallel()); try { foreach (var item in queryOrdered) { } } catch (OperationCanceledException oce) { caughtException = oce; } Assert.NotNull(caughtException); } // If a query is cancelled and immediately disposed, the dispose should not throw an OCE. [Fact] public static void CancelThenDispose() { try { CancellationTokenSource cancel = new CancellationTokenSource(); var q = ParallelEnumerable.Range(0, 1000).WithCancellation(cancel.Token).Select(x => x); IEnumerator<int> e = q.GetEnumerator(); e.MoveNext(); cancel.Cancel(); e.Dispose(); } catch (Exception e) { Assert.True(false, string.Format("PlinqCancellationTests.CancelThenDispose: > Failed. Expected no exception, got " + e.GetType())); } } [Fact] public static void DontDoWorkIfTokenAlreadyCanceled() { OperationCanceledException oce = null; CancellationTokenSource cs = new CancellationTokenSource(); var query = Enumerable.Range(0, 100000000) .Select(x => { if (x > 0) // to avoid the "Error:unreachable code detected" throw new ArgumentException("User-delegate exception."); return x; }) .AsParallel() .WithCancellation(cs.Token) .Select(x => x); cs.Cancel(); try { foreach (var item in query) //We expect an OperationCancelledException during the MoveNext { } } catch (OperationCanceledException ex) { oce = ex; } Assert.NotNull(oce); } // To help the user, we will check if a cancellation token passed to WithCancellation() is // not backed by a disposed CTS. This will help them identify incorrect cts.Dispose calls, but // doesn't solve all their problems if they don't manage CTS lifetime correctly. // We test via a few random queries that have shown inconsistent behaviour in the past. [Fact] public static void PreDisposedCTSPassedToPlinq() { ArgumentException ae1 = null; ArgumentException ae2 = null; ArgumentException ae3 = null; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; cts.Dispose(); // Early dispose try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .OrderBy(x => x) .ToArray(); } catch (Exception ex) { ae1 = (ArgumentException)ex; } try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .Last(); } catch (Exception ex) { ae2 = (ArgumentException)ex; } try { Enumerable.Range(1, 10).AsParallel() .WithCancellation(ct) .OrderBy(x => x) .Last(); } catch (Exception ex) { ae3 = (ArgumentException)ex; } Assert.NotNull(ae1); Assert.NotNull(ae2); Assert.NotNull(ae3); } public static void SimulateThreadSleep(int milliseconds) { ManualResetEvent mre = new ManualResetEvent(false); mre.WaitOne(milliseconds); } } // --------------------------- // Helper classes // --------------------------- internal class ThrowOnFirstEnumerable<T> : IEnumerable<T> { private readonly IEnumerable<T> _innerEnumerable; public ThrowOnFirstEnumerable(IEnumerable<T> innerEnumerable) { _innerEnumerable = innerEnumerable; } public IEnumerator<T> GetEnumerator() { return new ThrowOnFirstEnumerator<T>(_innerEnumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal class ThrowOnFirstEnumerator<T> : IEnumerator<T> { private IEnumerator<T> _innerEnumerator; public ThrowOnFirstEnumerator(IEnumerator<T> sourceEnumerator) { _innerEnumerator = sourceEnumerator; } public void Dispose() { _innerEnumerator.Dispose(); } public bool MoveNext() { throw new InvalidOperationException("ThrowOnFirstEnumerator throws on the first MoveNext"); } public T Current { get { return _innerEnumerator.Current; } } object IEnumerator.Current { get { return Current; } } public void Reset() { _innerEnumerator.Reset(); } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class StatementSyntaxComparer : SyntaxComparer { internal static readonly StatementSyntaxComparer Default = new StatementSyntaxComparer(); private readonly SyntaxNode _oldRootChild; private readonly SyntaxNode _newRootChild; private readonly SyntaxNode _oldRoot; private readonly SyntaxNode _newRoot; private StatementSyntaxComparer() { } internal StatementSyntaxComparer(SyntaxNode oldRootChild, SyntaxNode newRootChild) { _oldRootChild = oldRootChild; _newRootChild = newRootChild; _oldRoot = oldRootChild.Parent; _newRoot = newRootChild.Parent; } #region Tree Traversal protected internal override bool TryGetParent(SyntaxNode node, out SyntaxNode parent) { parent = node.Parent; while (parent != null && !HasLabel(parent)) { parent = parent.Parent; } return parent != null; } protected internal override IEnumerable<SyntaxNode> GetChildren(SyntaxNode node) { Debug.Assert(HasLabel(node)); if (node == _oldRoot || node == _newRoot) { return EnumerateRootChildren(node); } return IsLeaf(node) ? null : EnumerateNonRootChildren(node); } private IEnumerable<SyntaxNode> EnumerateNonRootChildren(SyntaxNode node) { foreach (var child in node.ChildNodes()) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child)) { continue; } if (HasLabel(child)) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } } private IEnumerable<SyntaxNode> EnumerateRootChildren(SyntaxNode root) { Debug.Assert(_oldRoot != null && _newRoot != null); var child = (root == _oldRoot) ? _oldRootChild : _newRootChild; if (GetLabelImpl(child) != Label.Ignored) { yield return child; } else { foreach (var descendant in child.DescendantNodes(DescendIntoChildren)) { if (HasLabel(descendant)) { yield return descendant; } } } } private bool DescendIntoChildren(SyntaxNode node) { return !LambdaUtilities.IsLambdaBodyStatementOrExpression(node) && !HasLabel(node); } protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node) { if (node == _oldRoot || node == _newRoot) { Debug.Assert(_oldRoot != null && _newRoot != null); var rootChild = (node == _oldRoot) ? _oldRootChild : _newRootChild; if (HasLabel(rootChild)) { yield return rootChild; } node = rootChild; } // TODO: avoid allocation of closure foreach (var descendant in node.DescendantNodes(descendIntoChildren: c => !IsLeaf(c) && (c == node || !LambdaUtilities.IsLambdaBodyStatementOrExpression(c)))) { if (!LambdaUtilities.IsLambdaBodyStatementOrExpression(descendant) && HasLabel(descendant)) { yield return descendant; } } } private static bool IsLeaf(SyntaxNode node) { bool isLeaf; Classify(node.Kind(), node, out isLeaf); return isLeaf; } #endregion #region Labels // Assumptions: // - Each listed label corresponds to one or more syntax kinds. // - Nodes with same labels might produce Update edits, nodes with different labels don't. // - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. // (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). internal enum Label { ConstructorDeclaration, Block, CheckedStatement, UnsafeStatement, TryStatement, CatchClause, // tied to parent CatchDeclaration, // tied to parent CatchFilterClause, // tied to parent FinallyClause, // tied to parent ForStatement, ForStatementPart, // tied to parent ForEachStatement, UsingStatement, FixedStatement, LockStatement, WhileStatement, DoStatement, IfStatement, ElseClause, // tied to parent SwitchStatement, SwitchSection, YieldStatement, // tied to parent GotoStatement, GotoCaseStatement, BreakContinueStatement, ReturnThrowStatement, ExpressionStatement, LabeledStatement, // TODO: // Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.) // Also consider handling LocalDeclarationStatement as just a bag of variable declarators, // so that variable declarators contained in one can be matched with variable declarators contained in the other. LocalDeclarationStatement, // tied to parent LocalVariableDeclaration, // tied to parent LocalVariableDeclarator, // tied to parent AwaitExpression, LocalFunction, Lambda, FromClause, QueryBody, FromClauseLambda, // tied to parent LetClauseLambda, // tied to parent WhereClauseLambda, // tied to parent OrderByClause, // tied to parent OrderingLambda, // tied to parent SelectClauseLambda, // tied to parent JoinClauseLambda, // tied to parent JoinIntoClause, // tied to parent GroupClauseLambda, // tied to parent QueryContinuation, // tied to parent // helpers: Count, Ignored = IgnoredNode } private static int TiedToAncestor(Label label) { switch (label) { case Label.LocalDeclarationStatement: case Label.LocalVariableDeclaration: case Label.LocalVariableDeclarator: case Label.GotoCaseStatement: case Label.BreakContinueStatement: case Label.ElseClause: case Label.CatchClause: case Label.CatchDeclaration: case Label.CatchFilterClause: case Label.FinallyClause: case Label.ForStatementPart: case Label.YieldStatement: case Label.LocalFunction: case Label.FromClauseLambda: case Label.LetClauseLambda: case Label.WhereClauseLambda: case Label.OrderByClause: case Label.OrderingLambda: case Label.SelectClauseLambda: case Label.JoinClauseLambda: case Label.JoinIntoClause: case Label.GroupClauseLambda: case Label.QueryContinuation: return 1; default: return 0; } } /// <summary> /// <paramref name="nodeOpt"/> is null only when comparing value equality of a tree node. /// </summary> internal static Label Classify(SyntaxKind kind, SyntaxNode nodeOpt, out bool isLeaf) { // Notes: // A descendant of a leaf node may be a labeled node that we don't want to visit if // we are comparing its parent node (used for lambda bodies). // // Expressions are ignored but they may contain nodes that should be matched by tree comparer. // (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren. isLeaf = false; // If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart". // We need to capture it in the match since these expressions can be "active statements" and as such we need to map them. // // The parent is not available only when comparing nodes for value equality. if (nodeOpt != null && nodeOpt.Parent.IsKind(SyntaxKind.ForStatement) && nodeOpt is ExpressionSyntax) { return Label.ForStatementPart; } switch (kind) { case SyntaxKind.ConstructorDeclaration: // Root when matching constructor bodies. return Label.ConstructorDeclaration; case SyntaxKind.Block: return Label.Block; case SyntaxKind.LocalDeclarationStatement: return Label.LocalDeclarationStatement; case SyntaxKind.VariableDeclaration: return Label.LocalVariableDeclaration; case SyntaxKind.VariableDeclarator: return Label.LocalVariableDeclarator; case SyntaxKind.LabeledStatement: return Label.LabeledStatement; case SyntaxKind.EmptyStatement: isLeaf = true; return Label.Ignored; case SyntaxKind.GotoStatement: isLeaf = true; return Label.GotoStatement; case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: isLeaf = true; return Label.GotoCaseStatement; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: isLeaf = true; return Label.BreakContinueStatement; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: return Label.ReturnThrowStatement; case SyntaxKind.ExpressionStatement: return Label.ExpressionStatement; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: return Label.YieldStatement; case SyntaxKind.DoStatement: return Label.DoStatement; case SyntaxKind.WhileStatement: return Label.WhileStatement; case SyntaxKind.ForStatement: return Label.ForStatement; case SyntaxKind.ForEachStatement: return Label.ForEachStatement; case SyntaxKind.UsingStatement: return Label.UsingStatement; case SyntaxKind.FixedStatement: return Label.FixedStatement; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return Label.CheckedStatement; case SyntaxKind.UnsafeStatement: return Label.UnsafeStatement; case SyntaxKind.LockStatement: return Label.LockStatement; case SyntaxKind.IfStatement: return Label.IfStatement; case SyntaxKind.ElseClause: return Label.ElseClause; case SyntaxKind.SwitchStatement: return Label.SwitchStatement; case SyntaxKind.SwitchSection: return Label.SwitchSection; case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: // Switch labels are included in the "value" of the containing switch section. // We don't need to analyze case expressions. isLeaf = true; return Label.Ignored; case SyntaxKind.TryStatement: return Label.TryStatement; case SyntaxKind.CatchClause: return Label.CatchClause; case SyntaxKind.CatchDeclaration: // the declarator of the exception variable return Label.CatchDeclaration; case SyntaxKind.CatchFilterClause: return Label.CatchFilterClause; case SyntaxKind.FinallyClause: return Label.FinallyClause; case SyntaxKind.LocalFunctionStatement: return Label.LocalFunction; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return Label.Lambda; case SyntaxKind.FromClause: // The first from clause of a query is not a lambda. // We have to assign it a label different from "FromClauseLambda" // so that we won't match lambda-from to non-lambda-from. // // Since FromClause declares range variables we need to include it in the map, // so that we are able to map range variable declarations. // Therefore we assign it a dedicated label. // // The parent is not available only when comparing nodes for value equality. // In that case it doesn't matter what label the node has as long as it has some. if (nodeOpt == null || nodeOpt.Parent.IsKind(SyntaxKind.QueryExpression)) { return Label.FromClause; } return Label.FromClauseLambda; case SyntaxKind.QueryBody: return Label.QueryBody; case SyntaxKind.QueryContinuation: return Label.QueryContinuation; case SyntaxKind.LetClause: return Label.LetClauseLambda; case SyntaxKind.WhereClause: return Label.WhereClauseLambda; case SyntaxKind.OrderByClause: return Label.OrderByClause; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return Label.OrderingLambda; case SyntaxKind.SelectClause: return Label.SelectClauseLambda; case SyntaxKind.JoinClause: return Label.JoinClauseLambda; case SyntaxKind.JoinIntoClause: return Label.JoinIntoClause; case SyntaxKind.GroupClause: return Label.GroupClauseLambda; case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: case SyntaxKind.GenericName: case SyntaxKind.TypeArgumentList: case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: case SyntaxKind.ArrayType: case SyntaxKind.ArrayRankSpecifier: case SyntaxKind.PointerType: case SyntaxKind.NullableType: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.NameColon: case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.DefaultExpression: // can't contain a lambda/await/anonymous type: isLeaf = true; return Label.Ignored; case SyntaxKind.AwaitExpression: return Label.AwaitExpression; default: // any other node may contain a lambda: return Label.Ignored; } } protected internal override int GetLabel(SyntaxNode node) { return (int)GetLabelImpl(node); } internal static Label GetLabelImpl(SyntaxNode node) { bool isLeaf; return Classify(node.Kind(), node, out isLeaf); } internal static bool HasLabel(SyntaxNode node) { return GetLabelImpl(node) != Label.Ignored; } protected internal override int LabelCount { get { return (int)Label.Count; } } protected internal override int TiedToAncestor(int label) { return TiedToAncestor((Label)label); } #endregion #region Comparisons internal static bool IgnoreLabeledChild(SyntaxKind kind) { // In most cases we can determine Label based on child kind. // The only cases when we can't are // - for Initializer, Condition and Incrementor expressions in ForStatement. // - first from clause of a query expression. bool isLeaf; return Classify(kind, null, out isLeaf) != Label.Ignored; } public override bool ValuesEqual(SyntaxNode left, SyntaxNode right) { // only called from the tree matching alg, which only operates on nodes that are labeled. Debug.Assert(HasLabel(left)); Debug.Assert(HasLabel(right)); Func<SyntaxKind, bool> ignoreChildNode; switch (left.Kind()) { case SyntaxKind.SwitchSection: return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right); case SyntaxKind.ForStatement: // The only children of ForStatement are labeled nodes and punctuation. return true; default: // When comparing the value of a node with its partner we are deciding whether to add an Update edit for the pair. // If the actual change is under a descendant labeled node we don't want to attribute it to the node being compared, // so we skip all labeled children when recursively checking for equivalence. if (IsLeaf(left)) { ignoreChildNode = null; } else { ignoreChildNode = IgnoreLabeledChild; } break; } return SyntaxFactory.AreEquivalent(left, right, ignoreChildNode); } private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right) { return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null) && SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: IgnoreLabeledChild); } protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance) { switch (leftNode.Kind()) { case SyntaxKind.VariableDeclarator: distance = ComputeDistance( ((VariableDeclaratorSyntax)leftNode).Identifier, ((VariableDeclaratorSyntax)rightNode).Identifier); return true; case SyntaxKind.ForStatement: var leftFor = (ForStatementSyntax)leftNode; var rightFor = (ForStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFor, rightFor); return true; case SyntaxKind.ForEachStatement: { var leftForEach = (ForEachStatementSyntax)leftNode; var rightForEach = (ForEachStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftForEach, rightForEach); return true; } case SyntaxKind.UsingStatement: var leftUsing = (UsingStatementSyntax)leftNode; var rightUsing = (UsingStatementSyntax)rightNode; if (leftUsing.Declaration != null && rightUsing.Declaration != null) { distance = ComputeWeightedDistance( leftUsing.Declaration, leftUsing.Statement, rightUsing.Declaration, rightUsing.Statement); } else { distance = ComputeWeightedDistance( (SyntaxNode)leftUsing.Expression ?? leftUsing.Declaration, leftUsing.Statement, (SyntaxNode)rightUsing.Expression ?? rightUsing.Declaration, rightUsing.Statement); } return true; case SyntaxKind.LockStatement: var leftLock = (LockStatementSyntax)leftNode; var rightLock = (LockStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement); return true; case SyntaxKind.FixedStatement: var leftFixed = (FixedStatementSyntax)leftNode; var rightFixed = (FixedStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement); return true; case SyntaxKind.WhileStatement: var leftWhile = (WhileStatementSyntax)leftNode; var rightWhile = (WhileStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement); return true; case SyntaxKind.DoStatement: var leftDo = (DoStatementSyntax)leftNode; var rightDo = (DoStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement); return true; case SyntaxKind.IfStatement: var leftIf = (IfStatementSyntax)leftNode; var rightIf = (IfStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement); return true; case SyntaxKind.Block: BlockSyntax leftBlock = (BlockSyntax)leftNode; BlockSyntax rightBlock = (BlockSyntax)rightNode; return TryComputeWeightedDistance(leftBlock, rightBlock, out distance); case SyntaxKind.CatchClause: distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode); return true; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: distance = ComputeWeightedDistanceOfLambdas(leftNode, rightNode); return true; case SyntaxKind.LocalFunctionStatement: distance = ComputeWeightedDistanceOfLocalFunctions((LocalFunctionStatementSyntax)leftNode, (LocalFunctionStatementSyntax)rightNode); return true; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: // Ignore the expression of yield return. The structure of the state machine is more important than the yielded values. distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1; return true; default: distance = 0; return false; } } private static double ComputeWeightedDistanceOfLocalFunctions(LocalFunctionStatementSyntax leftNode, LocalFunctionStatementSyntax rightNode) { double modifierDistance = ComputeDistance(leftNode.Modifiers, rightNode.Modifiers); double returnTypeDistance = ComputeDistance(leftNode.ReturnType, rightNode.ReturnType); double identifierDistance = ComputeDistance(leftNode.Identifier, rightNode.Identifier); double typeParameterDistance = ComputeDistance(leftNode.TypeParameterList, rightNode.TypeParameterList); double parameterDistance = ComputeDistance(leftNode.ParameterList.Parameters, rightNode.ParameterList.Parameters); double bodyDistance = ComputeDistance((SyntaxNode)leftNode.Body ?? leftNode.ExpressionBody, (SyntaxNode)rightNode.Body ?? rightNode.ExpressionBody); return modifierDistance * 0.1 + returnTypeDistance * 0.1 + identifierDistance * 0.2 + typeParameterDistance * 0.2 + parameterDistance * 0.2 + bodyDistance * 0.2; } private static double ComputeWeightedDistanceOfLambdas(SyntaxNode leftNode, SyntaxNode rightNode) { IEnumerable<SyntaxToken> leftParameters, rightParameters; SyntaxToken leftAsync, rightAsync; SyntaxNode leftBody, rightBody; GetLambdaParts(leftNode, out leftParameters, out leftAsync, out leftBody); GetLambdaParts(rightNode, out rightParameters, out rightAsync, out rightBody); if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword)) { return 1.0; } double parameterDistance = ComputeDistance(leftParameters, rightParameters); double bodyDistance = ComputeDistance(leftBody, rightBody); return parameterDistance * 0.6 + bodyDistance * 0.4; } private static void GetLambdaParts(SyntaxNode lambda, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body) { switch (lambda.Kind()) { case SyntaxKind.SimpleLambdaExpression: var simple = (SimpleLambdaExpressionSyntax)lambda; parameters = simple.Parameter.DescendantTokens(); asyncKeyword = simple.AsyncKeyword; body = simple.Body; break; case SyntaxKind.ParenthesizedLambdaExpression: var parenthesized = (ParenthesizedLambdaExpressionSyntax)lambda; parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters); asyncKeyword = parenthesized.AsyncKeyword; body = parenthesized.Body; break; case SyntaxKind.AnonymousMethodExpression: var anonymous = (AnonymousMethodExpressionSyntax)lambda; if (anonymous.ParameterList != null) { parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters); } else { parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>(); } asyncKeyword = anonymous.AsyncKeyword; body = anonymous.Block; break; default: throw ExceptionUtilities.Unreachable; } } private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance) { // No block can be matched with the root block. // Note that in constructors the root is the constructor declaration, since we need to include // the constructor initializer in the match. if (leftBlock.Parent == null || rightBlock.Parent == null || leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) || rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { distance = 0.0; return true; } if (leftBlock.Parent.Kind() != rightBlock.Parent.Kind()) { distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; } switch (leftBlock.Parent.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.FixedStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.SwitchSection: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); return true; case SyntaxKind.CatchClause: var leftCatch = (CatchClauseSyntax)leftBlock.Parent; var rightCatch = (CatchClauseSyntax)rightBlock.Parent; if (leftCatch.Declaration == null && leftCatch.Filter == null && rightCatch.Declaration == null && rightCatch.Filter == null) { var leftTry = (TryStatementSyntax)leftCatch.Parent; var rightTry = (TryStatementSyntax)rightCatch.Parent; distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) + 0.5 * ComputeValueDistance(leftBlock, rightBlock); } else { // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); } return true; case SyntaxKind.Block: case SyntaxKind.LabeledStatement: distance = ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; case SyntaxKind.UnsafeStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.ElseClause: case SyntaxKind.FinallyClause: case SyntaxKind.TryStatement: distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock); return true; default: throw ExceptionUtilities.Unreachable; } } private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock) { double distance; if (TryComputeLocalsDistance(leftBlock, rightBlock, out distance)) { return distance; } return ComputeValueDistance(leftBlock, rightBlock); } private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right) { double blockDistance = ComputeDistance(left.Block, right.Block); double distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter); return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3); } private static double ComputeWeightedDistance(ForEachStatementSyntax left, ForEachStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double expressionDistance = ComputeDistance(left.Expression, right.Expression); double identifierDistance = ComputeDistance(left.Identifier, right.Identifier); double distance = identifierDistance * 0.7 + expressionDistance * 0.2 + statementDistance * 0.1; return AdjustForLocalsInBlock(distance, left.Statement, right.Statement, localsWeight: 0.6); } private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { double statementDistance = ComputeDistance(left.Statement, right.Statement); double conditionDistance = ComputeDistance(left.Condition, right.Condition); double incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); double distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; double localsDistance; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; } private static double ComputeWeightedDistance( VariableDeclarationSyntax leftVariables, StatementSyntax leftStatement, VariableDeclarationSyntax rightVariables, StatementSyntax rightStatement) { double distance = ComputeDistance(leftStatement, rightStatement); // Put maximum weight behind the variables declared in the header of the statement. double localsDistance; if (TryComputeLocalsDistance(leftVariables, rightVariables, out localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } // If the statement is a block that declares local variables, // weight them more than the rest of the statement. return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2); } private static double ComputeWeightedDistance( SyntaxNode leftHeaderOpt, StatementSyntax leftStatement, SyntaxNode rightHeaderOpt, StatementSyntax rightStatement) { Debug.Assert(leftStatement != null); Debug.Assert(rightStatement != null); double headerDistance = ComputeDistance(leftHeaderOpt, rightHeaderOpt); double statementDistance = ComputeDistance(leftStatement, rightStatement); double distance = headerDistance * 0.6 + statementDistance * 0.4; return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5); } private static double AdjustForLocalsInBlock( double distance, StatementSyntax leftStatement, StatementSyntax rightStatement, double localsWeight) { // If the statement is a block that declares local variables, // weight them more than the rest of the statement. if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block) { double localsDistance; if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out localsDistance)) { return localsDistance * localsWeight + distance * (1 - localsWeight); } } return distance; } private static bool TryComputeLocalsDistance(VariableDeclarationSyntax leftOpt, VariableDeclarationSyntax rightOpt, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; if (leftOpt != null) { GetLocalNames(leftOpt, ref leftLocals); } if (rightOpt != null) { GetLocalNames(rightOpt, ref rightLocals); } if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance) { List<SyntaxToken> leftLocals = null; List<SyntaxToken> rightLocals = null; GetLocalNames(left, ref leftLocals); GetLocalNames(right, ref rightLocals); if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } // doesn't include variables declared in declaration expressions private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken> result) { foreach (var child in block.ChildNodes()) { if (child.IsKind(SyntaxKind.LocalDeclarationStatement)) { GetLocalNames(((LocalDeclarationStatementSyntax)child).Declaration, ref result); } } } // doesn't include variables declared in declaration expressions private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken> result) { foreach (var local in localDeclaration.Variables) { if (result == null) { result = new List<SyntaxToken>(); } result.Add(local.Identifier); } } private static double CombineOptional( double distance0, SyntaxNode leftOpt1, SyntaxNode rightOpt1, SyntaxNode leftOpt2, SyntaxNode rightOpt2, double weight0 = 0.8, double weight1 = 0.5) { bool one = leftOpt1 != null || rightOpt1 != null; bool two = leftOpt2 != null || rightOpt2 != null; if (!one && !two) { return distance0; } double distance1 = ComputeDistance(leftOpt1, rightOpt1); double distance2 = ComputeDistance(leftOpt2, rightOpt2); double d; if (one && two) { d = distance1 * weight1 + distance2 * (1 - weight1); } else if (one) { d = distance1; } else { d = distance2; } return distance0 * weight0 + d * (1 - weight0); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid { public class LocalGridServicesConnector : ISharedRegionModule, IGridService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static LocalGridServicesConnector m_MainInstance; private IGridService m_GridService; private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>(); private bool m_Enabled = false; public LocalGridServicesConnector() { } public LocalGridServicesConnector(IConfigSource source) { m_log.Debug("[LOCAL GRID CONNECTOR]: LocalGridServicesConnector instantiated"); m_MainInstance = this; InitialiseService(source); } #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalGridServicesConnector"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("GridServices", ""); if (name == Name) { InitialiseService(source); m_MainInstance = this; m_Enabled = true; m_log.Info("[LOCAL GRID CONNECTOR]: Local grid connector enabled"); } } } private void InitialiseService(IConfigSource source) { IConfig assetConfig = source.Configs["GridService"]; if (assetConfig == null) { m_log.Error("[LOCAL GRID CONNECTOR]: GridService missing from OpenSim.ini"); return; } string serviceDll = assetConfig.GetString("LocalServiceModule", String.Empty); if (serviceDll == String.Empty) { m_log.Error("[LOCAL GRID CONNECTOR]: No LocalServiceModule named in section GridService"); return; } Object[] args = new Object[] { source }; m_GridService = ServerUtils.LoadPlugin<IGridService>(serviceDll, args); if (m_GridService == null) { m_log.Error("[LOCAL GRID CONNECTOR]: Can't load grid service"); return; } } public void PostInitialise() { if (m_MainInstance == this) { MainConsole.Instance.Commands.AddCommand("LocalGridConnector", false, "show neighbours", "show neighbours", "Shows the local regions' neighbours", NeighboursCommand); } } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) scene.RegisterModuleInterface<IGridService>(this); if (m_MainInstance == this) { if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID)) m_log.ErrorFormat("[LOCAL GRID CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!"); else m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene)); } } public void RemoveRegion(Scene scene) { if (m_MainInstance == this) { m_LocalCache[scene.RegionInfo.RegionID].Clear(); m_LocalCache.Remove(scene.RegionInfo.RegionID); } } public void RegionLoaded(Scene scene) { } #endregion #region IGridService public string RegisterRegion(UUID scopeID, GridRegion regionInfo) { return m_GridService.RegisterRegion(scopeID, regionInfo); } public bool DeregisterRegion(UUID regionID) { return m_GridService.DeregisterRegion(regionID); } public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) { return m_GridService.GetNeighbours(scopeID, regionID); } public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) { return m_GridService.GetRegionByUUID(scopeID, regionID); } public GridRegion GetRegionByPosition(UUID scopeID, int x, int y) { GridRegion region = null; // First see if it's a neighbour, even if it isn't on this sim. // Neighbour data is cached in memory, so this is fast foreach (RegionCache rcache in m_LocalCache.Values) { region = rcache.GetRegionByPosition(x, y); if (region != null) { return region; } } // Then try on this sim (may be a lookup in DB if this is using MySql). return m_GridService.GetRegionByPosition(scopeID, x, y); } public GridRegion GetRegionByName(UUID scopeID, string regionName) { return m_GridService.GetRegionByName(scopeID, regionName); } public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber) { return m_GridService.GetRegionsByName(scopeID, name, maxNumber); } public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) { return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); } public List<GridRegion> GetDefaultRegions(UUID scopeID) { return m_GridService.GetDefaultRegions(scopeID); } public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y) { return m_GridService.GetFallbackRegions(scopeID, x, y); } public List<GridRegion> GetHyperlinks(UUID scopeID) { return m_GridService.GetHyperlinks(scopeID); } public int GetRegionFlags(UUID scopeID, UUID regionID) { return m_GridService.GetRegionFlags(scopeID, regionID); } #endregion public void NeighboursCommand(string module, string[] cmdparams) { foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache) { m_log.InfoFormat("*** Neighbours of {0} {1} ***", kvp.Key, kvp.Value.RegionName); List<GridRegion> regions = kvp.Value.GetNeighbours(); foreach (GridRegion r in regions) m_log.InfoFormat(" {0} @ {1}={2}", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Authorization.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Authorization { /// <summary> /// TBD (see http://TBD for more information) /// </summary> internal partial class RoleDefinitionOperations : IServiceOperations<AuthorizationManagementClient>, IRoleDefinitionOperations { /// <summary> /// Initializes a new instance of the RoleDefinitionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal RoleDefinitionOperations(AuthorizationManagementClient client) { this._client = client; } private AuthorizationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient. /// </summary> public AuthorizationManagementClient Client { get { return this._client; } } /// <summary> /// Creates or updates a role definition. /// </summary> /// <param name='roleDefinitionId'> /// Required. Role definition id. /// </param> /// <param name='parameters'> /// Required. Role definition. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Role definition create or update operation result. /// </returns> public async Task<RoleDefinitionCreateOrUpdateResult> CreateOrUpdateAsync(Guid roleDefinitionId, RoleDefinitionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("roleDefinitionId", roleDefinitionId); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Authorization/roleDefinitions/"; url = url + Uri.EscapeDataString(roleDefinitionId.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-10-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject propertiesValue = new JObject(); requestDoc = propertiesValue; if (parameters.RoleDefinition != null) { if (parameters.RoleDefinition.Id != null) { propertiesValue["id"] = parameters.RoleDefinition.Id; } propertiesValue["name"] = parameters.RoleDefinition.Name.ToString(); if (parameters.RoleDefinition.Type != null) { propertiesValue["type"] = parameters.RoleDefinition.Type; } if (parameters.RoleDefinition.Properties != null) { JObject propertiesValue2 = new JObject(); propertiesValue["properties"] = propertiesValue2; if (parameters.RoleDefinition.Properties.RoleName != null) { propertiesValue2["roleName"] = parameters.RoleDefinition.Properties.RoleName; } if (parameters.RoleDefinition.Properties.Description != null) { propertiesValue2["description"] = parameters.RoleDefinition.Properties.Description; } if (parameters.RoleDefinition.Properties.Scope != null) { propertiesValue2["scope"] = parameters.RoleDefinition.Properties.Scope; } if (parameters.RoleDefinition.Properties.Type != null) { propertiesValue2["type"] = parameters.RoleDefinition.Properties.Type; } if (parameters.RoleDefinition.Properties.Permissions != null) { if (parameters.RoleDefinition.Properties.Permissions is ILazyCollection == false || ((ILazyCollection)parameters.RoleDefinition.Properties.Permissions).IsInitialized) { JArray permissionsArray = new JArray(); foreach (Permission permissionsItem in parameters.RoleDefinition.Properties.Permissions) { if (permissionsItem.Actions != null) { if (permissionsItem.Actions is ILazyCollection == false || ((ILazyCollection)permissionsItem.Actions).IsInitialized) { JArray actionsArray = new JArray(); foreach (string actionsItem in permissionsItem.Actions) { actionsArray.Add(actionsItem); } requestDoc = actionsArray; } } if (permissionsItem.NotActions != null) { if (permissionsItem.NotActions is ILazyCollection == false || ((ILazyCollection)permissionsItem.NotActions).IsInitialized) { JArray notActionsArray = new JArray(); foreach (string notActionsItem in permissionsItem.NotActions) { notActionsArray.Add(notActionsItem); } requestDoc = notActionsArray; } } } propertiesValue2["permissions"] = permissionsArray; } } if (parameters.RoleDefinition.Properties.AssignableScopes != null) { if (parameters.RoleDefinition.Properties.AssignableScopes is ILazyCollection == false || ((ILazyCollection)parameters.RoleDefinition.Properties.AssignableScopes).IsInitialized) { JArray assignablescopesArray = new JArray(); foreach (string assignablescopesItem in parameters.RoleDefinition.Properties.AssignableScopes) { assignablescopesArray.Add(assignablescopesItem); } propertiesValue2["assignablescopes"] = assignablescopesArray; } } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RoleDefinitionCreateOrUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RoleDefinitionCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RoleDefinition roleDefinitionInstance = new RoleDefinition(); result.RoleDefinition = roleDefinitionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); roleDefinitionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Guid nameInstance = Guid.Parse(((string)nameValue)); roleDefinitionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); roleDefinitionInstance.Type = typeInstance; } JToken propertiesValue3 = responseDoc["properties"]; if (propertiesValue3 != null && propertiesValue3.Type != JTokenType.Null) { RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties(); roleDefinitionInstance.Properties = propertiesInstance; JToken roleNameValue = propertiesValue3["roleName"]; if (roleNameValue != null && roleNameValue.Type != JTokenType.Null) { string roleNameInstance = ((string)roleNameValue); propertiesInstance.RoleName = roleNameInstance; } JToken descriptionValue = propertiesValue3["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken scopeValue = propertiesValue3["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken typeValue2 = propertiesValue3["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); propertiesInstance.Type = typeInstance2; } JToken permissionsArray2 = propertiesValue3["permissions"]; if (permissionsArray2 != null && permissionsArray2.Type != JTokenType.Null) { foreach (JToken permissionsValue in ((JArray)permissionsArray2)) { Permission permissionInstance = new Permission(); propertiesInstance.Permissions.Add(permissionInstance); JToken actionsArray2 = permissionsValue["actions"]; if (actionsArray2 != null && actionsArray2.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray2)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray2 = permissionsValue["notActions"]; if (notActionsArray2 != null && notActionsArray2.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray2)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } JToken assignablescopesArray2 = propertiesValue3["assignablescopes"]; if (assignablescopesArray2 != null && assignablescopesArray2.Type != JTokenType.Null) { foreach (JToken assignablescopesValue in ((JArray)assignablescopesArray2)) { propertiesInstance.AssignableScopes.Add(((string)assignablescopesValue)); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes the role definition. /// </summary> /// <param name='roleDefinitionId'> /// Required. Role definition id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Role definition delete operation result. /// </returns> public async Task<RoleDefinitionDeleteResult> DeleteAsync(string roleDefinitionId, CancellationToken cancellationToken) { // Validate if (roleDefinitionId == null) { throw new ArgumentNullException("roleDefinitionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("roleDefinitionId", roleDefinitionId); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + roleDefinitionId; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-10-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RoleDefinitionDeleteResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RoleDefinitionDeleteResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RoleDefinition roleDefinitionInstance = new RoleDefinition(); result.RoleDefinition = roleDefinitionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); roleDefinitionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Guid nameInstance = Guid.Parse(((string)nameValue)); roleDefinitionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); roleDefinitionInstance.Type = typeInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties(); roleDefinitionInstance.Properties = propertiesInstance; JToken roleNameValue = propertiesValue["roleName"]; if (roleNameValue != null && roleNameValue.Type != JTokenType.Null) { string roleNameInstance = ((string)roleNameValue); propertiesInstance.RoleName = roleNameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); propertiesInstance.Type = typeInstance2; } JToken permissionsArray = propertiesValue["permissions"]; if (permissionsArray != null && permissionsArray.Type != JTokenType.Null) { foreach (JToken permissionsValue in ((JArray)permissionsArray)) { Permission permissionInstance = new Permission(); propertiesInstance.Permissions.Add(permissionInstance); JToken actionsArray = permissionsValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = permissionsValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } JToken assignablescopesArray = propertiesValue["assignablescopes"]; if (assignablescopesArray != null && assignablescopesArray.Type != JTokenType.Null) { foreach (JToken assignablescopesValue in ((JArray)assignablescopesArray)) { propertiesInstance.AssignableScopes.Add(((string)assignablescopesValue)); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='roleDefinitionName'> /// Required. Role definition name (GUID). /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Role definition get operation result. /// </returns> public async Task<RoleDefinitionGetResult> GetAsync(Guid roleDefinitionName, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("roleDefinitionName", roleDefinitionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Authorization/roleDefinitions/"; url = url + Uri.EscapeDataString(roleDefinitionName.ToString()); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-10-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RoleDefinitionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RoleDefinitionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RoleDefinition roleDefinitionInstance = new RoleDefinition(); result.RoleDefinition = roleDefinitionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); roleDefinitionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Guid nameInstance = Guid.Parse(((string)nameValue)); roleDefinitionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); roleDefinitionInstance.Type = typeInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties(); roleDefinitionInstance.Properties = propertiesInstance; JToken roleNameValue = propertiesValue["roleName"]; if (roleNameValue != null && roleNameValue.Type != JTokenType.Null) { string roleNameInstance = ((string)roleNameValue); propertiesInstance.RoleName = roleNameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); propertiesInstance.Type = typeInstance2; } JToken permissionsArray = propertiesValue["permissions"]; if (permissionsArray != null && permissionsArray.Type != JTokenType.Null) { foreach (JToken permissionsValue in ((JArray)permissionsArray)) { Permission permissionInstance = new Permission(); propertiesInstance.Permissions.Add(permissionInstance); JToken actionsArray = permissionsValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = permissionsValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } JToken assignablescopesArray = propertiesValue["assignablescopes"]; if (assignablescopesArray != null && assignablescopesArray.Type != JTokenType.Null) { foreach (JToken assignablescopesValue in ((JArray)assignablescopesArray)) { propertiesInstance.AssignableScopes.Add(((string)assignablescopesValue)); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get role definition by name (GUID). /// </summary> /// <param name='roleDefinitionId'> /// Required. Role definition Id /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Role definition get operation result. /// </returns> public async Task<RoleDefinitionGetResult> GetByIdAsync(string roleDefinitionId, CancellationToken cancellationToken) { // Validate if (roleDefinitionId == null) { throw new ArgumentNullException("roleDefinitionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("roleDefinitionId", roleDefinitionId); TracingAdapter.Enter(invocationId, this, "GetByIdAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + roleDefinitionId; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-10-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RoleDefinitionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RoleDefinitionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { RoleDefinition roleDefinitionInstance = new RoleDefinition(); result.RoleDefinition = roleDefinitionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); roleDefinitionInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Guid nameInstance = Guid.Parse(((string)nameValue)); roleDefinitionInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); roleDefinitionInstance.Type = typeInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties(); roleDefinitionInstance.Properties = propertiesInstance; JToken roleNameValue = propertiesValue["roleName"]; if (roleNameValue != null && roleNameValue.Type != JTokenType.Null) { string roleNameInstance = ((string)roleNameValue); propertiesInstance.RoleName = roleNameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); propertiesInstance.Type = typeInstance2; } JToken permissionsArray = propertiesValue["permissions"]; if (permissionsArray != null && permissionsArray.Type != JTokenType.Null) { foreach (JToken permissionsValue in ((JArray)permissionsArray)) { Permission permissionInstance = new Permission(); propertiesInstance.Permissions.Add(permissionInstance); JToken actionsArray = permissionsValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = permissionsValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } JToken assignablescopesArray = propertiesValue["assignablescopes"]; if (assignablescopesArray != null && assignablescopesArray.Type != JTokenType.Null) { foreach (JToken assignablescopesValue in ((JArray)assignablescopesArray)) { propertiesInstance.AssignableScopes.Add(((string)assignablescopesValue)); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Get all role definitions. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Role definition list operation result. /// </returns> public async Task<RoleDefinitionListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Authorization/roleDefinitions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-10-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result RoleDefinitionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new RoleDefinitionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { RoleDefinition roleDefinitionInstance = new RoleDefinition(); result.RoleDefinitions.Add(roleDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); roleDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { Guid nameInstance = Guid.Parse(((string)nameValue)); roleDefinitionInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); roleDefinitionInstance.Type = typeInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { RoleDefinitionProperties propertiesInstance = new RoleDefinitionProperties(); roleDefinitionInstance.Properties = propertiesInstance; JToken roleNameValue = propertiesValue["roleName"]; if (roleNameValue != null && roleNameValue.Type != JTokenType.Null) { string roleNameInstance = ((string)roleNameValue); propertiesInstance.RoleName = roleNameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken typeValue2 = propertiesValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); propertiesInstance.Type = typeInstance2; } JToken permissionsArray = propertiesValue["permissions"]; if (permissionsArray != null && permissionsArray.Type != JTokenType.Null) { foreach (JToken permissionsValue in ((JArray)permissionsArray)) { Permission permissionInstance = new Permission(); propertiesInstance.Permissions.Add(permissionInstance); JToken actionsArray = permissionsValue["actions"]; if (actionsArray != null && actionsArray.Type != JTokenType.Null) { foreach (JToken actionsValue in ((JArray)actionsArray)) { permissionInstance.Actions.Add(((string)actionsValue)); } } JToken notActionsArray = permissionsValue["notActions"]; if (notActionsArray != null && notActionsArray.Type != JTokenType.Null) { foreach (JToken notActionsValue in ((JArray)notActionsArray)) { permissionInstance.NotActions.Add(((string)notActionsValue)); } } } } JToken assignablescopesArray = propertiesValue["assignablescopes"]; if (assignablescopesArray != null && assignablescopesArray.Type != JTokenType.Null) { foreach (JToken assignablescopesValue in ((JArray)assignablescopesArray)) { propertiesInstance.AssignableScopes.Add(((string)assignablescopesValue)); } } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections; using System.Linq; using System.Text.RegularExpressions; using System.Web; using Umbraco.Core; using Umbraco.Core.CodeAnnotations; using Umbraco.Core.Configuration; using Umbraco.Core.Profiling; using umbraco.BusinessLogic; using System.Xml; using umbraco.presentation; namespace umbraco { /// <summary> /// Summary description for helper. /// </summary> public class helper { public static bool IsNumeric(string Number) { int result; return int.TryParse(Number, out result); } public static User GetCurrentUmbracoUser() { return umbraco.BasePages.UmbracoEnsuredPage.CurrentUser; } [Obsolete("This method has been superceded. Use the extension method for HttpRequest or HttpRequestBase method: GetItemAsString instead.")] public static string Request(string text) { if (HttpContext.Current == null) return string.Empty; if (HttpContext.Current.Request[text.ToLower()] != null) if (HttpContext.Current.Request[text] != string.Empty) return HttpContext.Current.Request[text]; return String.Empty; } [Obsolete("Has been superceded by Umbraco.Core.XmlHelper.GetAttributesFromElement")] public static Hashtable ReturnAttributes(String tag) { var h = new Hashtable(); foreach(var i in Umbraco.Core.XmlHelper.GetAttributesFromElement(tag)) { h.Add(i.Key, i.Value); } return h; } public static String FindAttribute(IDictionary attributes, String key) { return FindAttribute(null, attributes, key); } public static String FindAttribute(IDictionary pageElements, IDictionary attributes, String key) { // fix for issue 14862: lowercase for case insensitive matching key = key.ToLower(); string attributeValue = string.Empty; if (attributes[key] != null) attributeValue = attributes[key].ToString(); attributeValue = parseAttribute(pageElements, attributeValue); return attributeValue; } /// <summary> /// This method will parse the attribute value to look for some special syntax such as /// [@requestKey] /// [%sessionKey] /// [#pageElement] /// [$recursiveValue] /// </summary> /// <param name="pageElements"></param> /// <param name="attributeValue"></param> /// <returns></returns> /// <remarks> /// You can even apply fallback's separated by comma's like: /// /// [@requestKey],[%sessionKey] /// /// </remarks> public static string parseAttribute(IDictionary pageElements, string attributeValue) { // Check for potential querystring/cookie variables // SD: not sure why we are checking for len 3 here? if (attributeValue.Length > 3 && attributeValue.StartsWith("[")) { var attributeValueSplit = (attributeValue).Split(','); attributeValueSplit = attributeValueSplit.Select(x => x.Trim()).ToArray(); // before proceeding, we don't want to process anything here unless each item starts/ends with a [ ] // this is because the attribute value could actually just be a json array like [1,2,3] which we don't want to parse // // however, the last one can be a literal, must take care of this! // so here, don't check the last one, which can be just anything if (attributeValueSplit.Take(attributeValueSplit.Length - 1).All(x => //must end with [ x.EndsWith("]") && //must start with [ and a special char (x.StartsWith("[@") || x.StartsWith("[%") || x.StartsWith("[#") || x.StartsWith("[$"))) == false) { return attributeValue; } foreach (var attributeValueItem in attributeValueSplit) { attributeValue = attributeValueItem; var trimmedValue = attributeValue.Trim(); // Check for special variables (always in square-brackets like [name]) if (trimmedValue.StartsWith("[") && trimmedValue.EndsWith("]")) { attributeValue = trimmedValue; // find key name var keyName = attributeValue.Substring(2, attributeValue.Length - 3); var keyType = attributeValue.Substring(1, 1); switch (keyType) { case "@": attributeValue = HttpContext.Current.Request[keyName]; break; case "%": attributeValue = StateHelper.GetSessionValue<string>(keyName); if (String.IsNullOrEmpty(attributeValue)) attributeValue = StateHelper.GetCookieValue(keyName); break; case "#": if (pageElements == null) pageElements = GetPageElements(); if (pageElements[keyName] != null) attributeValue = pageElements[keyName].ToString(); else attributeValue = ""; break; case "$": if (pageElements == null) pageElements = GetPageElements(); if (pageElements[keyName] != null && pageElements[keyName].ToString() != string.Empty) { attributeValue = pageElements[keyName].ToString(); } else { // reset attribute value in case no value has been found on parents attributeValue = String.Empty; XmlDocument umbracoXML = presentation.UmbracoContext.Current.GetXml(); String[] splitpath = (String[])pageElements["splitpath"]; for (int i = 0; i < splitpath.Length - 1; i++) { XmlNode element = umbracoXML.GetElementById(splitpath[splitpath.Length - i - 1].ToString()); if (element == null) continue; string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "{0}"; XmlNode currentNode = element.SelectSingleNode(string.Format(xpath, keyName)); if (currentNode != null && currentNode.FirstChild != null && !string.IsNullOrEmpty(currentNode.FirstChild.Value) && !string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim())) { HttpContext.Current.Trace.Write("parameter.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]); attributeValue = currentNode.FirstChild.Value; break; } } } break; } if (attributeValue != null) { attributeValue = attributeValue.Trim(); if (attributeValue != string.Empty) break; } else attributeValue = string.Empty; } } } return attributeValue; } private static IDictionary GetPageElements() { IDictionary pageElements = null; if (HttpContext.Current.Items["pageElements"] != null) pageElements = (IDictionary)HttpContext.Current.Items["pageElements"]; return pageElements; } [UmbracoWillObsolete("We should really obsolete that one.")] public static string SpaceCamelCasing(string text) { return text.SplitPascalCasing().ToFirstUpperInvariant(); } [Obsolete("Use umbraco.presentation.UmbracContext.Current.GetBaseUrl()")] public static string GetBaseUrl(HttpContext Context) { return Context.Request.Url.GetLeftPart(UriPartial.Authority); } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Xml; namespace BasecampAPI { /// <summary> /// Represents an active project in Basecamp. /// </summary> public class Project : BasecampItem, IComparable<Project> { private string companyID; private Person me; /// <summary> /// Constructor. /// </summary> /// <param name="camp"></param> public Project(Basecamp camp) : this(camp, null) { } /// <summary> /// Constructor /// </summary> /// <param name="camp"></param> /// <param name="node"></param> public Project(Basecamp camp, XmlNode node) : base(camp) { if (node != null) { name = node["name"].InnerText.Trim(); id = node["id"].InnerText.Trim(); companyID = node["company"]["id"].InnerText.Trim(); } } /// <summary> /// The company ID of this project. /// </summary> public string CompanyID { get { return companyID; } set { companyID = value; } } /// <summary> /// The ID of this project. /// </summary> public string ID { get { return id; } set { id = value; } } /// <summary> /// The name of the project. /// </summary> public string Name { get { return name; } set { name = value; } } Dictionary<string, Person> people; /// <summary> /// Gets the cached list of people for this project. /// Makes the actual API if this is the first request. /// </summary> public Dictionary<string, Person> People { get { if (people == null) { people = new Dictionary<string, Person>(); foreach (Person person in GetPeople()) people[person.ID] = person; } return people; } } /// <summary> /// Gets the list of people on this project. /// </summary> /// <returns></returns> public List<Person> GetPeople() { List<Person> people = new List<Person>(); me = null; foreach (string compid in camp.CompanyIDs) { List<Person> somePeople = Slurp<Person>( string.Format("/projects/{0}/contacts/people/{1}", id, compid), @"//person"); foreach (Person person in somePeople) { if (person.Username == camp.User) { me = person; break; } } people.AddRange(somePeople); } return people; } /// <summary> /// Get message categories. /// </summary> /// <returns></returns> public List<MessageCategory> GetMessageCategories() { return Slurp<MessageCategory>( string.Format("/projects/{0}/post_categories", id), @"//post-category"); } /// <summary> /// Adds a message to this project. /// </summary> /// <param name="title"></param> /// <param name="body"></param> /// <param name="filename"></param> /// <param name="category"></param> /// <returns></returns> public Message AddMessage(string title, string body, MessageCategory category, string filename) { if (category == null) throw new ArgumentNullException("category"); string url = string.Format(@"/projects/{0}/msg/create", id); string filekey = (String.IsNullOrEmpty(filename) ? null : camp.UploadFileForMessage(filename)); string xml = Message.XmlForCreate(title, body, category.ID, filename, filekey); return new Message(camp, camp.Call(url, xml).SelectSingleNode("/post")); } List<Message> messages; List<MessageCategory> messageCategories; /// <summary> /// Gets the list of message categories; caches results for subsequent access. /// </summary> public List<MessageCategory> MessageCategories { get { if (messageCategories == null) messageCategories = GetMessageCategories(); return messageCategories; } } /// <summary> /// Gets the list of messages; caches results for subsequent access. /// </summary> public List<Message> Messages { get { if (messages == null) messages = GetMessages(); return messages; } } /// <summary> /// Gets the list of messages from Basecamp. /// </summary> /// <returns></returns> public List<Message> GetMessages() { List<PostSummary> summaries = GetMessageSummaries(); if (summaries.Count > 25) summaries = summaries.GetRange(0, 25); List<string> ids = new List<string>(); foreach (PostSummary post in summaries) ids.Add(post.ID); List<Message> messages = Slurp<Message>(@"/msg/get/" + string.Join(@",", ids.ToArray()), @"//post"); messages.Sort(); return messages; } /// <summary> /// Gets a list of abbreviated messages. /// </summary> /// <returns></returns> public List<PostSummary> GetMessageSummaries() { return Slurp<PostSummary>( string.Format("/projects/{0}/msg/archive", id), @"//post"); } List<ToDoList> toDoLists; /// <summary> /// Get the list of to-do lists. Pulled from cache /// </summary> public List<ToDoList> ToDoLists { get { if (toDoLists == null) toDoLists = GetToDoLists(); return toDoLists; } } /// <summary> /// Gets the to-do lists for this project. /// </summary> /// <returns></returns> public List<ToDoList> GetToDoLists() { return Slurp<ToDoList>( string.Format("/projects/{0}/todos/lists", id), @"//todo-list"); } /// <summary> /// Represents the Person who is currently logged in. /// </summary> public Person Me { get { return me; } } /// <summary> /// Creates a new To-Do list. /// </summary> /// <param name="title">The title of the list.</param> /// <param name="description"></param> /// <param name="milestone"></param> /// <returns></returns> public ToDoList CreateToDoList(string title, string description, Milestone milestone) { return CreateToDoList(title, string.Empty, milestone == null ? string.Empty : milestone.ID ); } /// <summary> /// Creates a new To-Do list. /// </summary> /// <param name="title">The title of the list.</param> /// <returns></returns> public ToDoList CreateToDoList(string title) { return CreateToDoList(title, string.Empty, string.Empty); } /// <summary> /// Creates a new To-Do list. /// </summary> /// <param name="title">The title of the list.</param> /// <param name="description">A short description for this list.</param> /// <returns></returns> public ToDoList CreateToDoList(string title, string description) { return CreateToDoList(title, description, string.Empty); } private ToDoList CreateToDoList(string title, string description, string milestoneID) { string url = string.Format(@"/projects/{0}/todos/create_list", id); string xml = string.Format(@"<request><milestone-id>{2}</milestone-id> <private>false</private> <tracked>false</tracked> <name>{0}</name> <description>{1}</description></request>", title, description, milestoneID); return new ToDoList(camp, camp.Call(url, xml).SelectSingleNode("/todo-list")); } /// <summary> /// Gets the milestones for this project. /// </summary> /// <returns></returns> public List<Milestone> GetMilestones() { return Slurp<Milestone>( string.Format("/projects/{0}/milestones/list", id), @"//milestone"); } /// <summary> /// Deletes a milestone. /// </summary> /// <param name="milestone"></param> public void DeleteMilestone(Milestone milestone) { if (milestone == null) return; camp.Call("/milestones/delete/" + milestone.ID); } /// <summary> /// Create a milesone. /// </summary> /// <param name="title"></param> /// <param name="deadline"></param> /// <param name="responsible"></param> /// <param name="notify"></param> /// <returns></returns> public Milestone CreateMilestone(string title, DateTime deadline, Person responsible, bool notify) { if (responsible == null) throw new ArgumentException("A person must be responsible for a milestone"); string url = string.Format(@"/projects/{0}/milestones/create", id); string req = string.Format(@"<request><milestone><title>{0}</title> <deadline type=""date"">{1}</deadline> <responsible-party>{2}</responsible-party> <notify>{3}</notify></milestone></request>", title, deadline.ToShortDateString(), responsible.ID, notify); return new Milestone(camp, camp.Call(url, req).SelectSingleNode("//milestone")); } #region IComparable<Project> Members /// <summary> /// Comparison. /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(Project other) { return Name.CompareTo(other.Name); } #endregion } }
#region Modification Notes // August 12 2005 // Modified by Jose Luis Barreda G. (joseluiseco 'at' hotmail 'dot' com) // Changed name 'AssemblyCache' for 'GacHelper' // Added 'FindAssembly' method and removed anything not needed by this method. // Based on code from http://www.codeproject.com/csharp/GacApi.asp // Used to simulate 'Assembly.LoadWithPartialName' (obsolete since .NET 2.0 Beta) #endregion #region Original notes // Source: Microsoft KB Article KB317540 /* SUMMARY The native code application programming interfaces (APIs) that allow you to interact with the Global Assembly Cache (GAC) are not documented in the .NET Framework Software Development Kit (SDK) documentation. MORE INFORMATION CAUTION: Do not use these APIs in your application to perform assembly binds or to test for the presence of assemblies or other run time, development, or design-time operations. Only administrative tools and setup programs must use these APIs. If you use the GAC, this directly exposes your application to assembly binding fragility or may cause your application to work improperly on future versions of the .NET Framework. The GAC stores assemblies that are shared across all applications on a computer. The actual storage location and structure of the GAC is not documented and is subject to change in future versions of the .NET Framework and the Microsoft Windows operating system. The only supported method to access assemblies in the GAC is through the APIs that are documented in this article. Most applications do not have to use these APIs because the assembly binding is performed automatically by the common language runtime. Only custom setup programs or management tools must use these APIs. Microsoft Windows Installer has native support for installing assemblies to the GAC. For more information about assemblies and the GAC, see the .NET Framework SDK. Use the GAC API in the following scenarios: When you install nativeName assembly to the GAC. When you remove nativeName assembly from the GAC. When you export nativeName assembly from the GAC. When you enumerate assemblies that are available in the GAC. NOTE: CoInitialize(Ex) must be called before you use any of the functions and interfaces that are described in this specification. */ #endregion #region Using directives using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using System.Globalization; #endregion namespace AspectSharp.Lang { /// <summary> /// Provides a method to find nativeName assembly in the GAC by it's simple name. /// </summary> internal static class GacHelper { #region FindAssembly /// <summary> /// /// </summary> /// <param name="assemblyName"></param> /// <returns></returns> public static Assembly FindAssembly(string assemblyName) { IAssemblyEnum assemblyEnum = GacHelper.CreateGACEnum(); IAssemblyName nativeName; List<AssemblyName> matches = new List<AssemblyName>(); while(GacHelper.GetNextAssembly(assemblyEnum, out nativeName) == 0) { string nameString = GacHelper.GetName(nativeName); if(StringComparer.InvariantCultureIgnoreCase.Compare(nameString, assemblyName) == 0) { AssemblyName name = GacHelper.GetAssemblyName(nativeName); matches.Add(name); } } AssemblyName last = null; for(int i = 0; i < matches.Count; i++) { AssemblyName current = matches[i]; if(last != null) { if(last.Version.Major <= current.Version.Major) { if(last.Version.Major < current.Version.Major) { last = current; } else { if(last.Version.Minor < current.Version.Minor) { last = current; } } } } else { last = current; } } if(last != null) { return Assembly.Load(last); } else { return null; } } #endregion #region GetAssemblyName private static AssemblyName GetAssemblyName(IAssemblyName nameRef) { AssemblyName name = new AssemblyName(); name.Name = GacHelper.GetName(nameRef); name.Version = GacHelper.GetVersion(nameRef); name.CultureInfo = GacHelper.GetCulture(nameRef); name.SetPublicKeyToken(GacHelper.GetPublicKeyToken(nameRef)); return name; } #endregion #region GetName private static string GetName(IAssemblyName name) { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int)bufferSize); name.GetName(ref bufferSize, buffer); return buffer.ToString(); } #endregion #region GetVersion private static Version GetVersion(IAssemblyName name) { uint majorOut; uint minorOut; name.GetVersion(out majorOut, out minorOut); int major = (int)majorOut >> 16; int minor = (int)majorOut & 0xFFFF; int build = (int)minorOut >> 16; int revision = (int)minorOut & 0xFFFF; if(major < 0) { major = major * -1; } if(minor < 0) { minor = minor * -1; } if(build < 0) { build = build * -1; } if(revision < 0) { revision = revision * -1; } return new Version(major, minor, build, revision); } #endregion #region GetCulture private static CultureInfo GetCulture(IAssemblyName name) { uint bufferSize = 255; IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize); name.GetProperty(ASM_NAME.ASM_NAME_CULTURE, buffer, ref bufferSize); string result = Marshal.PtrToStringAuto(buffer); Marshal.FreeHGlobal(buffer); return new CultureInfo(result); } #endregion #region GetPublicKeyToken private static byte[] GetPublicKeyToken(IAssemblyName name) { byte[] result = new byte[8]; uint bufferSize = 8; IntPtr buffer = Marshal.AllocHGlobal((int)bufferSize); name.GetProperty(ASM_NAME.ASM_NAME_PUBLIC_KEY_TOKEN, buffer, ref bufferSize); for(int i = 0; i < 8; i++) result[i] = Marshal.ReadByte(buffer, i); Marshal.FreeHGlobal(buffer); return result; } #endregion #region CreateGACEnum private static IAssemblyEnum CreateGACEnum() { IAssemblyEnum ae; GacHelper.CreateAssemblyEnum(out ae, (IntPtr)0, null, ASM_CACHE_FLAGS.ASM_CACHE_GAC, (IntPtr)0); return ae; } #endregion #region GetNextAssembly /// <summary> /// Get the next assembly name in the current enumerator or fail /// </summary> /// <param name="enumerator"></param> /// <param name="name"></param> /// <returns>0 if the enumeration is not at its end</returns> private static int GetNextAssembly(IAssemblyEnum enumerator, out IAssemblyName name) { return enumerator.GetNextAssembly((IntPtr)0, out name, 0); } #endregion #region External methods /// <summary> /// To obtain nativeName instance of the CreateAssemblyEnum API, call the CreateAssemblyNameObject API. /// </summary> /// <param name="pEnum">Pointer to a memory location that contains the IAssemblyEnum pointer.</param> /// <param name="pUnkReserved">Must be null.</param> /// <param name="pName">An assembly name that is used to filter the enumeration. Can be null to enumerate all assemblies in the GAC.</param> /// <param name="dwFlags">Exactly one bit from the ASM_CACHE_FLAGS enumeration.</param> /// <param name="pvReserved">Must be NULL.</param> [DllImport("fusion.dll", SetLastError = true, PreserveSig = false)] private static extern void CreateAssemblyEnum( out IAssemblyEnum pEnum, IntPtr pUnkReserved, IAssemblyName pName, ASM_CACHE_FLAGS dwFlags, IntPtr pvReserved); #endregion } #region Flags #region ASM_DISPLAY_FLAGS /// <summary> /// <see cref="IAssemblyName.GetDisplayName"/> /// </summary> [Flags] internal enum ASM_DISPLAY_FLAGS { VERSION = 0x1, CULTURE = 0x2, PUBLIC_KEY_TOKEN = 0x4, PUBLIC_KEY = 0x8, CUSTOM = 0x10, PROCESSORARCHITECTURE = 0x20, LANGUAGEID = 0x40 } #endregion #region ASM_CMP_FLAGS [Flags] internal enum ASM_CMP_FLAGS { NAME = 0x1, MAJOR_VERSION = 0x2, MINOR_VERSION = 0x4, BUILD_NUMBER = 0x8, REVISION_NUMBER = 0x10, PUBLIC_KEY_TOKEN = 0x20, CULTURE = 0x40, CUSTOM = 0x80, ALL = NAME | MAJOR_VERSION | MINOR_VERSION | REVISION_NUMBER | BUILD_NUMBER | PUBLIC_KEY_TOKEN | CULTURE | CUSTOM, DEFAULT = 0x100 } #endregion #region ASM_NAME /// <summary> /// The ASM_NAME enumeration property ID describes the valid names of the name-value pairs in nativeName assembly name. /// See the .NET Framework SDK for a description of these properties. /// </summary> internal enum ASM_NAME { ASM_NAME_PUBLIC_KEY = 0, ASM_NAME_PUBLIC_KEY_TOKEN, ASM_NAME_HASH_VALUE, ASM_NAME_NAME, ASM_NAME_MAJOR_VERSION, ASM_NAME_MINOR_VERSION, ASM_NAME_BUILD_NUMBER, ASM_NAME_REVISION_NUMBER, ASM_NAME_CULTURE, ASM_NAME_PROCESSOR_ID_ARRAY, ASM_NAME_OSINFO_ARRAY, ASM_NAME_HASH_ALGID, ASM_NAME_ALIAS, ASM_NAME_CODEBASE_URL, ASM_NAME_CODEBASE_LASTMOD, ASM_NAME_NULL_PUBLIC_KEY, ASM_NAME_NULL_PUBLIC_KEY_TOKEN, ASM_NAME_CUSTOM, ASM_NAME_NULL_CUSTOM, ASM_NAME_MVID, ASM_NAME_MAX_PARAMS } #endregion #region ASM_CACHE_FLAGS /// <summary> /// The ASM_CACHE_FLAGS enumeration contains the following values: /// ASM_CACHE_ZAP - Enumerates the cache of precompiled assemblies by using Ngen.exe. /// ASM_CACHE_GAC - Enumerates the GAC. /// ASM_CACHE_DOWNLOAD - Enumerates the assemblies that have been downloaded on-demand or that have been shadow-copied. /// </summary> [Flags] internal enum ASM_CACHE_FLAGS { ASM_CACHE_ZAP = 0x1, ASM_CACHE_GAC = 0x2, ASM_CACHE_DOWNLOAD = 0x4 } #endregion #endregion #region IAssemblyName interface /// <summary> /// The IAssemblyName interface represents nativeName assembly name. An assembly name includes a predetermined set of name-value pairs. /// The assembly name is described in detail in the .NET Framework SDK. /// </summary> [ComImport, Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IAssemblyName { /// <summary> /// The IAssemblyName::SetProperty method adds a name-value pair to the assembly name, or, if a name-value pair /// with the same name already exists, modifies or deletes the value of a name-value pair. /// </summary> /// <param name="PropertyId">The ID that represents the name part of the name-value pair that is to be /// added or to be modified. Valid property IDs are defined in the ASM_NAME enumeration.</param> /// <param name="pvProperty">A pointer to a buffer that contains the value of the property.</param> /// <param name="cbProperty">The length of the pvProperty buffer in bytes. If cbProperty is zero, the name-value pair /// is removed from the assembly name.</param> /// <returns></returns> [PreserveSig] int SetProperty( ASM_NAME PropertyId, IntPtr pvProperty, uint cbProperty); /// <summary> /// The IAssemblyName::GetProperty method retrieves the value of a name-value pair in the assembly name that specifies the name. /// </summary> /// <param name="PropertyId">The ID that represents the name of the name-value pair whose value is to be retrieved. /// Specified property IDs are defined in the ASM_NAME enumeration.</param> /// <param name="pvProperty">A pointer to a buffer that is to contain the value of the property.</param> /// <param name="pcbProperty">The length of the pvProperty buffer, in bytes.</param> /// <returns></returns> [PreserveSig] int GetProperty( ASM_NAME PropertyId, IntPtr pvProperty, ref uint pcbProperty); /// <summary> /// The IAssemblyName::Finalize method freezes nativeName assembly name. Additional calls to IAssemblyName::SetProperty are /// unsuccessful after this method has been called. /// </summary> /// <returns></returns> [PreserveSig] int Finalize(); /// <summary> /// The IAssemblyName::GetDisplayName method returns a string representation of the assembly name. /// </summary> /// <param name="szDisplayName">A pointer to a buffer that is to contain the display name. The display name is returned in Unicode.</param> /// <param name="pccDisplayName">The size of the buffer in characters (on input). The length of the returned display name (on return).</param> /// <param name="dwDisplayFlags">One or more of the bits defined in the ASM_DISPLAY_FLAGS enumeration: /// *_VERSION - Includes the version number as part of the display name. /// *_CULTURE - Includes the culture. /// *_PUBLIC_KEY_TOKEN - Includes the public key token. /// *_PUBLIC_KEY - Includes the public key. /// *_CUSTOM - Includes the custom part of the assembly name. /// *_PROCESSORARCHITECTURE - Includes the processor architecture. /// *_LANGUAGEID - Includes the language ID.</param> /// <returns></returns> /// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks> [PreserveSig] int GetDisplayName( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szDisplayName, ref uint pccDisplayName, ASM_DISPLAY_FLAGS dwDisplayFlags); /// <summary> /// Undocumented /// </summary> /// <param name="refIID"></param> /// <param name="pUnkSink"></param> /// <param name="pUnkContext"></param> /// <param name="szCodeBase"></param> /// <param name="llFlags"></param> /// <param name="pvReserved"></param> /// <param name="cbReserved"></param> /// <param name="ppv"></param> /// <returns></returns> [PreserveSig] int BindToObject( ref Guid refIID, [MarshalAs(UnmanagedType.IUnknown)] object pUnkSink, [MarshalAs(UnmanagedType.IUnknown)] object pUnkContext, [MarshalAs(UnmanagedType.LPWStr)] string szCodeBase, long llFlags, IntPtr pvReserved, uint cbReserved, out IntPtr ppv); /// <summary> /// The IAssemblyName::GetName method returns the name part of the assembly name. /// </summary> /// <param name="lpcwBuffer">Size of the pwszName buffer (on input). Length of the name (on return).</param> /// <param name="pwzName">Pointer to the buffer that is to contain the name part of the assembly name.</param> /// <returns></returns> /// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks> [PreserveSig] int GetName( ref uint lpcwBuffer, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzName); /// <summary> /// The IAssemblyName::GetVersion method returns the version part of the assembly name. /// </summary> /// <param name="pdwVersionHi">Pointer to a DWORD that contains the upper 32 bits of the version number.</param> /// <param name="pdwVersionLow">Pointer to a DWORD that contain the lower 32 bits of the version number.</param> /// <returns></returns> [PreserveSig] int GetVersion( out uint pdwVersionHi, out uint pdwVersionLow); /// <summary> /// The IAssemblyName::IsEqual method compares the assembly name to another assembly names. /// </summary> /// <param name="pName">The assembly name to compare to.</param> /// <param name="dwCmpFlags">Indicates which part of the assembly name to use in the comparison. /// Values are one or more of the bits defined in the ASM_CMP_FLAGS enumeration.</param> /// <returns></returns> [PreserveSig] int IsEqual( IAssemblyName pName, ASM_CMP_FLAGS dwCmpFlags); /// <summary> /// The IAssemblyName::Clone method creates a copy of nativeName assembly name. /// </summary> /// <param name="pName"></param> /// <returns></returns> [PreserveSig] int Clone( out IAssemblyName pName); } #endregion #region IAssemblyEnum interface /// <summary> /// The IAssemblyEnum interface enumerates the assemblies in the GAC. /// </summary> [ComImport, Guid("21b8916c-f28e-11d2-a473-00c04f8ef448"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IAssemblyEnum { /// <summary> /// The IAssemblyEnum::GetNextAssembly method enumerates the assemblies in the GAC. /// </summary> /// <param name="pvReserved">Must be null.</param> /// <param name="ppName">Pointer to a memory location that is to receive the interface pointer to the assembly /// name of the next assembly that is enumerated.</param> /// <param name="dwFlags">Must be zero.</param> /// <returns></returns> [PreserveSig()] int GetNextAssembly( IntPtr pvReserved, out IAssemblyName ppName, uint dwFlags); /// <summary> /// Undocumented. Best guess: reset the enumeration to the first assembly. /// </summary> /// <returns></returns> [PreserveSig()] int Reset(); /// <summary> /// Undocumented. Create a copy of the assembly enum that is independently enumerable. /// </summary> /// <param name="ppEnum"></param> /// <returns></returns> [PreserveSig()] int Clone( out IAssemblyEnum ppEnum); } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Serialization; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optomized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. // [Serializable] public class ASCIIEncoding : Encoding { // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncoding s_default = new ASCIIEncoding(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // NOTE: Many methods in this class forward to EncodingForwarder for // validating arguments/wrapping the unsafe methods in this class // which do the actual work. That class contains // shared logic for doing this which is used by // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding, // UTF7Encoding, and UTF8Encoding. // The reason the code is separated out into a static class, rather // than a base class which overrides all of these methods for us // (which is what EncodingNLS is for internal Encodings) is because // that's really more of an implementation detail so it's internal. // At the same time, C# doesn't allow a public class subclassing an // internal/private one, so we end up having to re-override these // methods in all of the public Encodings + EncodingNLS. // Returns the number of bytes required to encode a range of characters in // a character array. public override int GetByteCount(char[] chars, int index, int count) { return EncodingForwarder.GetByteCount(this, chars, index, count); } public override int GetByteCount(String chars) { return EncodingForwarder.GetByteCount(this, chars); } [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { return EncodingForwarder.GetByteCount(this, chars, count); } public override int GetBytes(String chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex); } [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. public override int GetCharCount(byte[] bytes, int index, int count) { return EncodingForwarder.GetCharCount(this, bytes, index, count); } [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { return EncodingForwarder.GetCharCount(this, bytes, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex); } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. public override String GetString(byte[] bytes, int byteIndex, int byteCount) { return EncodingForwarder.GetString(this, bytes, byteIndex, byteCount); } // End of overridden methods which use EncodingForwarder // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder"); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; if (encoder != null) { charLeftOver = encoder.charLeftOver; Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer"); // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if (fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if (charLeftOver > 0) charCount++; return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false); // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if (ch > 0x7f) { if (fallbackBuffer == null) { // Initialize the buffer if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false); } // Get Fallback fallbackBuffer.InternalFallback(ch, ref chars); continue; } // We'll use this one byteCount++; } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer"); return byteCount; } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative"); // Assert because we shouldn't be able to have a null encoder. Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback"); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if (encoder != null) { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if (encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType())); // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer"); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if (fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if (cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if (charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if (byteCount == 0) ThrowBytesOverflow(encoder, true); // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if (byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow(encoder, byteCount < 1); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while (chars < charEnd) { char ch2 = *(chars++); if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement; else *(bytes++) = unchecked((byte)(ch2)); } // Clear encoder if (encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { // Initialize the buffer Debug.Assert(encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over"); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback(charLeftOver, ref chars); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if (ch > 0x7f) { // Initialize the buffer if (fallbackBuffer == null) { if (encoder == null) fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); else fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true); } // Get Fallback fallbackBuffer.InternalFallback(ch, ref chars); // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if (bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { Debug.Assert(chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already."); chars--; // don't use last char } else fallbackBuffer.MovePrevious(); // Are we throwing or using buffer? ThrowBytesOverflow(encoder, bytes == byteStart); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked((byte)ch); bytes++; } // Need to do encoder stuff if (encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) // Clear it in case of MustFlush encoder.charLeftOver = (char)0; // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end"); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder) { // Just assert, we're called internally so these should be safe, checked already Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null"); Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative"); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if (b >= 0x80) { if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - count, null); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes); } } // Fallback buffer must be empty Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer"); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS decoder) { // Just need to ASSERT, this is called by something else internal that checked parameters already Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null"); Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative"); Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null"); Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative"); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if (decoder == null) fallback = this.DecoderFallback as DecoderReplacementFallback; else { fallback = decoder.Fallback as DecoderReplacementFallback; Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer"); } if (fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if (charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow(decoder, charCount < 1); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while (bytes < byteEnd) { byte b = *(bytes++); if (b >= 0x80) // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; else *(chars++) = unchecked((char)b); } // bytes & chars used are the same if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while (bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if (b >= 0x80) { // This is an invalid byte in the ASCII encoding. if (fallbackBuffer == null) { if (decoder == null) fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); else fallbackBuffer = decoder.FallbackBuffer; fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars)) { // May or may not throw, but we didn't get this byte Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)"); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if (chars >= charEnd) { Debug.Assert(bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)"); bytes--; // unused byte ThrowCharsOverflow(decoder, chars == charStart); // throw? break; // don't throw, but stop loop } *(chars) = unchecked((char)b); chars++; } } // Might have had decoder fallback stuff. if (decoder != null) decoder.m_bytesUsed = (int)(bytes - byteStart); // Expect Empty fallback buffer for GetChars Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer"); return (int)(chars - charStart); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow")); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow")); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte { get { return true; } } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.UseExpressionBody; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Options; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody { public class UseExpressionBodyForPropertiesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new UseExpressionBodyForPropertiesDiagnosticAnalyzer(), new UseExpressionBodyForPropertiesCodeFixProvider()); private IDictionary<OptionKey, object> UseExpressionBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement)); private IDictionary<OptionKey, object> UseBlockBody => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithNoneEnforcement)); private IDictionary<OptionKey, object> UseBlockBodyExceptAccessor => OptionsSet( SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithNoneEnforcement), SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement)); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody1() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|return|] Bar(); } } }", @"class C { int Foo => Bar(); }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithSetter() { await TestMissingInRegularAndScriptAsync( @"class C { int Foo { get { [|return|] Bar(); } set { } } }", new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingWithAttribute() { await TestMissingInRegularAndScriptAsync( @"class C { int Foo { [A] get { [|return|] Bar(); } } }", new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestMissingOnSetter1() { await TestMissingInRegularAndScriptAsync( @"class C { int Foo { set { [|Bar|](); } } }", new TestParameters(options: UseExpressionBody)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody3() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|throw|] new NotImplementedException(); } } }", @"class C { int Foo => throw new NotImplementedException(); }", options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBody4() { await TestInRegularAndScriptAsync( @"class C { int Foo { get { [|throw|] new NotImplementedException(); // comment } } }", @"class C { int Foo => throw new NotImplementedException(); // comment }", ignoreTrivia: false, options: UseExpressionBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody1() { await TestInRegularAndScriptAsync( @"class C { int Foo [|=>|] Bar(); }", @"class C { int Foo { get { return Bar(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBodyIfAccessorWantExpression1() { await TestInRegularAndScriptAsync( @"class C { int Foo [|=>|] Bar(); }", @"class C { int Foo { get => Bar(); } }", options: UseBlockBodyExceptAccessor); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody3() { await TestInRegularAndScriptAsync( @"class C { int Foo [|=>|] throw new NotImplementedException(); }", @"class C { int Foo { get { throw new NotImplementedException(); } } }", options: UseBlockBody); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseBlockBody4() { await TestInRegularAndScriptAsync( @"class C { int Foo [|=>|] throw new NotImplementedException(); // comment }", @"class C { int Foo { get { throw new NotImplementedException(); // comment } } }", ignoreTrivia: false, options: UseBlockBody); } [WorkItem(16386, "https://github.com/dotnet/roslyn/issues/16386")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)] public async Task TestUseExpressionBodyKeepTrailingTrivia() { await TestInRegularAndScriptAsync( @"class C { private string _prop = ""HELLO THERE!""; public string Prop { get { [|return|] _prop; } } public string OtherThing => ""Pickles""; }", @"class C { private string _prop = ""HELLO THERE!""; public string Prop => _prop; public string OtherThing => ""Pickles""; }", ignoreTrivia: false, options: UseExpressionBody); } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Linq; using System.Threading.Tasks; using Orleans.Tests.SqlUtils; using Tester.RelationalUtilities; namespace UnitTests.General { public abstract class RelationalStorageForTesting { private static readonly Dictionary<string, Func<string, RelationalStorageForTesting>> instanceFactory = new Dictionary<string, Func<string, RelationalStorageForTesting>> { {AdoNetInvariants.InvariantNameSqlServer, cs => new SqlServerStorageForTesting(cs)}, {AdoNetInvariants.InvariantNameMySql, cs => new MySqlStorageForTesting(cs)}, {AdoNetInvariants.InvariantNamePostgreSql, cs => new PostgreSqlStorageForTesting(cs)} }; public IRelationalStorage Storage { get; private set; } public string CurrentConnectionString { get { return Storage.ConnectionString; } } /// <summary> /// Default connection string for testing /// </summary> public abstract string DefaultConnectionString { get; } /// <summary> /// A delayed query that is then cancelled in a test to see if cancellation works. /// </summary> public abstract string CancellationTestQuery { get; } public abstract string CreateStreamTestTable { get; } public virtual string DeleteStreamTestTable { get { return "DELETE StreamingTest;"; } } public virtual string StreamTestSelect { get { return "SELECT Id, StreamData FROM StreamingTest WHERE Id = @streamId;"; } } public virtual string StreamTestInsert { get { return "INSERT INTO StreamingTest(Id, StreamData) VALUES(@id, @streamData);"; } } /// <summary> /// The script that creates Orleans schema in the database, usually CreateOrleansTables_xxxx.sql /// </summary> protected abstract string[] SetupSqlScriptFileNames { get; } /// <summary> /// A query template to create a database with a given name. /// </summary> protected abstract string CreateDatabaseTemplate { get; } /// <summary> /// A query template to drop a database with a given name. /// </summary> protected abstract string DropDatabaseTemplate { get; } /// <summary> /// A query template if a database with a given name exists. /// </summary> protected abstract string ExistsDatabaseTemplate { get; } /// <summary> /// Converts the given script into batches to execute sequentially /// </summary> /// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param> /// <param name="databaseName">the name of the database</param> protected abstract IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName); public static async Task<RelationalStorageForTesting> SetupInstance(string invariantName, string testDatabaseName, string connectionString = null) { if (string.IsNullOrWhiteSpace(invariantName)) { throw new ArgumentException("The name of invariant must contain characters", "invariantName"); } if (string.IsNullOrWhiteSpace(testDatabaseName)) { throw new ArgumentException("database string must contain characters", "testDatabaseName"); } Console.WriteLine("Initializing relational databases..."); RelationalStorageForTesting testStorage; if(connectionString == null) { testStorage = CreateTestInstance(invariantName); } else { testStorage = CreateTestInstance(invariantName, connectionString); } Console.WriteLine("Dropping and recreating database '{0}' with connectionstring '{1}'", testDatabaseName, connectionString ?? testStorage.DefaultConnectionString); if (await testStorage.ExistsDatabaseAsync(testDatabaseName)) { await testStorage.DropDatabaseAsync(testDatabaseName); } await testStorage.CreateDatabaseAsync(testDatabaseName); //The old storage instance has the previous connection string, time have a new handle with a new connection string... testStorage = testStorage.CopyInstance(testDatabaseName); Console.WriteLine("Creating database tables..."); var setupScript = String.Empty; // Concatenate scripts foreach (var fileName in testStorage.SetupSqlScriptFileNames) { setupScript += File.ReadAllText(fileName); // Just in case add a CRLF between files, but they should end in a new line. setupScript += "\r\n"; } await testStorage.ExecuteSetupScript(setupScript, testDatabaseName); Console.WriteLine("Initializing relational databases done."); return testStorage; } private static RelationalStorageForTesting CreateTestInstance(string invariantName, string connectionString) { return instanceFactory[invariantName](connectionString); } private static RelationalStorageForTesting CreateTestInstance(string invariantName) { return CreateTestInstance(invariantName, CreateTestInstance(invariantName, "notempty").DefaultConnectionString); } /// <summary> /// Constructor /// </summary> /// <param name="invariantName"></param> /// <param name="connectionString"></param> protected RelationalStorageForTesting(string invariantName, string connectionString) { Storage = RelationalStorage.CreateInstance(invariantName, connectionString); } /// <summary> /// Executes the given script in a test context. /// </summary> /// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param> /// <param name="dataBaseName">the target database to be populated</param> /// <returns></returns> private async Task ExecuteSetupScript(string setupScript, string dataBaseName) { var splitScripts = ConvertToExecutableBatches(setupScript, dataBaseName); foreach (var script in splitScripts) { _ = await Storage.ExecuteAsync(script); } } /// <summary> /// Checks the existence of a database using the given <see paramref="storage"/> storage object. /// </summary> /// <param name="databaseName">The name of the database existence of which to check.</param> /// <returns><em>TRUE</em> if the given database exists. <em>FALSE</em> otherwise.</returns> private async Task<bool> ExistsDatabaseAsync(string databaseName) { var ret = await Storage.ReadAsync(string.Format(ExistsDatabaseTemplate, databaseName), command => { }, (selector, resultSetCount, cancellationToken) => { return Task.FromResult(selector.GetBoolean(0)); }).ConfigureAwait(continueOnCapturedContext: false); return ret.First(); } /// <summary> /// Creates a database with a given name. /// </summary> /// <param name="databaseName">The name of the database to create.</param> /// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns> private async Task CreateDatabaseAsync(string databaseName) { await Storage.ExecuteAsync(string.Format(CreateDatabaseTemplate, databaseName), command => { }).ConfigureAwait(continueOnCapturedContext: false); } /// <summary> /// Drops a database with a given name. /// </summary> /// <param name="databaseName">The name of the database to drop.</param> /// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns> private Task DropDatabaseAsync(string databaseName) { return Storage.ExecuteAsync(string.Format(DropDatabaseTemplate, databaseName), command => { }); } /// <summary> /// Creates a new instance of the storage based on the old connection string by changing the database name. /// </summary> /// <param name="newDatabaseName">Connection string instance name of the database.</param> /// <returns>A new <see cref="RelationalStorageForTesting"/> instance with having the same connection string but with a new databaseName.</returns> private RelationalStorageForTesting CopyInstance(string newDatabaseName) { var csb = new DbConnectionStringBuilder(); csb.ConnectionString = Storage.ConnectionString; csb["Database"] = newDatabaseName; return CreateTestInstance(Storage.InvariantName, csb.ConnectionString); } } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Xml; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Utilities; namespace Prebuild.Core.Nodes { /// <summary> /// /// </summary> [DataNode("Configuration")] public class ConfigurationNode : DataNode, ICloneable, IComparable { #region Fields private string m_Name = "unknown"; private string m_Platform = "AnyCPU"; private OptionsNode m_Options; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ConfigurationNode"/> class. /// </summary> public ConfigurationNode() { m_Options = new OptionsNode(); } #endregion #region Properties /// <summary> /// Gets or sets the parent. /// </summary> /// <value>The parent.</value> public override IDataNode Parent { get { return base.Parent; } set { base.Parent = value; if(base.Parent is SolutionNode) { SolutionNode node = (SolutionNode)base.Parent; if(node != null && node.Options != null) { node.Options.CopyTo(m_Options); } } } } /// <summary> /// Identifies the platform for this specific configuration. /// </summary> public string Platform { get { return m_Platform; } set { switch ((value + "").ToLower()) { case "x86": case "x64": m_Platform = value; break; case "itanium": m_Platform = "Itanium"; break; default: m_Platform = "AnyCPU"; break; } } } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return m_Name; } } /// <summary> /// Gets the name and platform for the configuration. /// </summary> /// <value>The name and platform.</value> public string NameAndPlatform { get { string platform = m_Platform; if (platform == "AnyCPU") platform = "Any CPU"; return String.Format("{0}|{1}", m_Name, platform); } } /// <summary> /// Gets or sets the options. /// </summary> /// <value>The options.</value> public OptionsNode Options { get { return m_Options; } set { m_Options = value; } } #endregion #region Public Methods /// <summary> /// Parses the specified node. /// </summary> /// <param name="node">The node.</param> public override void Parse(XmlNode node) { m_Name = Helper.AttributeValue(node, "name", m_Name); Platform = Helper.AttributeValue(node, "platform", m_Platform); if (node == null) { throw new ArgumentNullException("node"); } foreach(XmlNode child in node.ChildNodes) { IDataNode dataNode = Kernel.Instance.ParseNode(child, this); if(dataNode is OptionsNode) { ((OptionsNode)dataNode).CopyTo(m_Options); } } } /// <summary> /// Copies to. /// </summary> /// <param name="conf">The conf.</param> public void CopyTo(ConfigurationNode conf) { m_Options.CopyTo(conf.m_Options); } #endregion #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> public object Clone() { ConfigurationNode ret = new ConfigurationNode(); ret.m_Name = m_Name; ret.m_Platform = m_Platform; m_Options.CopyTo(ret.m_Options); return ret; } #endregion #region IComparable Members public int CompareTo(object obj) { ConfigurationNode that = (ConfigurationNode) obj; return this.m_Name.CompareTo(that.m_Name); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class VisitorTests { private class UsingExpression : Expression { public UsingExpression(Expression disposable, Expression body) { if (!typeof(IDisposable).IsAssignableFrom(disposable.Type)) { throw new ArgumentException(); } // Omit other exception handling as this is just an example for testing purposes. Disposable = disposable; Body = body; } private Expression Disposable { get; } private Expression Body { get; } public override bool CanReduce => true; public override Expression Reduce() { if (Disposable.Type.IsValueType) { return TryFinally( Body, Call( Disposable, typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose)) ) ); } return TryFinally( Body, IfThen( ReferenceNotEqual(Disposable, Constant(null)), Call( Disposable, typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose)) ) ) ); } public override Type Type => Body.Type; public override ExpressionType NodeType => ExpressionType.Extension; } private class ForEachExpression : Expression { public ForEachExpression(ParameterExpression item, Expression enumerable, Expression body) { ItemVariable = item; Enumerable = enumerable; Body = body; } public ParameterExpression ItemVariable { get; } public Expression Enumerable { get; } public Expression Body { get; } public override bool CanReduce => true; public override Type Type => typeof(void); public override ExpressionType NodeType => ExpressionType.Extension; public override Expression Reduce() { Type enType = typeof(IEnumerator<>).MakeGenericType(ItemVariable.Type); ParameterExpression enumerator = Variable(enType); LabelTarget breakLabel = Label(); return Block( new[] {ItemVariable, enumerator}, Assign(enumerator, Call(Enumerable, typeof(IEnumerable<>).MakeGenericType(ItemVariable.Type).GetMethod(nameof(IEnumerable.GetEnumerator)))), new UsingExpression( enumerator, Loop( Block( IfThen( IsFalse( Call(enumerator, typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext))) ), Break(breakLabel) ), Assign(ItemVariable, Property(enumerator, enType.GetProperty(nameof(IEnumerator.Current)))), Body ), breakLabel ) ) ); } } private class DefaultVisitor : ExpressionVisitor { } private class ConstantRefreshingVisitor : ExpressionVisitor { protected override Expression VisitConstant(ConstantExpression node) => Expression.Constant(node.Value, node.Type); } private class ResultExpression : Expression { } private class SourceExpression : Expression { protected override Expression Accept(ExpressionVisitor visitor) => new ResultExpression(); } private class NullBecomingExpression : Expression { protected override Expression Accept(ExpressionVisitor visitor) => null; } private static string UpperCaseIfNotAlready(string value) { if (string.IsNullOrEmpty(value)) { return value; } string upper = value.ToUpperInvariant(); return upper == value ? value : upper; } [Fact] public void IsAbstract() { Assert.True(typeof(ExpressionVisitor).IsAbstract); } [Fact] public void VisitNullDefaultsToReturnNull() { Assert.Null(new DefaultVisitor().Visit(default(Expression))); } [Fact] public void VisitExpressionDefaultsCallAccept() { Assert.IsType<ResultExpression>(new DefaultVisitor().Visit(new SourceExpression())); } [Fact] public void VisitNullCollection() { AssertExtensions.Throws<ArgumentNullException>("nodes", () => new DefaultVisitor().Visit(default(ReadOnlyCollection<Expression>))); } [Fact] public void VisitNullCollectionWithVisitorFunction() { AssertExtensions.Throws<ArgumentNullException>("nodes", () => ExpressionVisitor.Visit(null, (Expression i) => i)); } [Fact] public void VisitCollectionVisitorWithNullFunction() { AssertExtensions.Throws<ArgumentNullException>("elementVisitor", () => ExpressionVisitor.Visit(new List<Expression> { Expression.Empty() }.AsReadOnly(), null)); } [Fact] public void VisitAndConvertNullNode() { Assert.Null(new DefaultVisitor().VisitAndConvert(default(Expression), "")); } [Fact] public void VisitAndConvertNullCollection() { AssertExtensions.Throws<ArgumentNullException>("nodes", () => new DefaultVisitor().VisitAndConvert(default(ReadOnlyCollection<Expression>), "")); } [Fact] public void VisitCollectionReturnSameIfChildrenUnchanged() { ReadOnlyCollection<Expression> collection = new List<Expression> { Expression.Constant(0), Expression.Constant(2), Expression.DebugInfo(Expression.SymbolDocument("fileName"), 1, 1, 1, 1) }.AsReadOnly(); Assert.Same(collection, new DefaultVisitor().Visit(collection)); } [Fact] public void VisitCollectionDifferOnFirst() { string value = new string(new[] { 'a', 'b', 'c' }); ReadOnlyCollection<Expression> collection = new List<Expression> { Expression.Constant(value) }.AsReadOnly(); ReadOnlyCollection<Expression> visited = new ConstantRefreshingVisitor().Visit(collection); Assert.NotSame(collection, visited); Assert.NotSame(collection[0], visited[0]); Assert.Same(value, ((ConstantExpression)visited[0]).Value); } [Fact] public void VisitCollectionDifferOnLater() { string value = new string(new[] { 'a', 'b', 'c' }); ReadOnlyCollection<Expression> collection = new List<Expression> { Expression.Empty(), Expression.Constant(value) }.AsReadOnly(); ReadOnlyCollection<Expression> visited = new ConstantRefreshingVisitor().Visit(collection); Assert.NotSame(collection, visited); Assert.Same(collection[0], visited[0]); Assert.NotSame(collection[1], visited[1]); Assert.Same(value, ((ConstantExpression)visited[1]).Value); } [Fact] public void VisitCollectionNullNodes() { ReadOnlyCollection<Expression> collection = new List<Expression> { null, null, null }.AsReadOnly(); Assert.Same(collection, new DefaultVisitor().Visit(collection)); } [Fact] public void VisitCollectionWithElementVisitorReturnSameIfChildrenUnchanged() { ReadOnlyCollection<string> collection = new List<string> { "ABC", "DEF" }.AsReadOnly(); Assert.Same(collection, ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready)); } [Fact] public void VisitCollectionWithElementVisitorDifferOnFirst() { ReadOnlyCollection<string> collection = new List<string> { "abc" }.AsReadOnly(); ReadOnlyCollection<string> visited = ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready); Assert.NotSame(collection, visited); Assert.NotSame(collection[0], visited[0]); } [Fact] public void VisitCollectionWithElementVisitorDifferOnLater() { ReadOnlyCollection<string> collection = new List<string> { "ABC", "def", "GHI", "jkl" }.AsReadOnly(); ReadOnlyCollection<string> visited = ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready); Assert.NotSame(collection, visited); Assert.Same(collection[0], visited[0]); Assert.NotSame(collection[1], visited[1]); Assert.Same(collection[2], visited[2]); Assert.NotSame(collection[3], visited[3]); } [Fact] public void VisitCollectionWithElementVisitorNullNodes() { ReadOnlyCollection<string> collection = new List<string> { null, null, null }.AsReadOnly(); Assert.Same(collection, ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready)); } [Fact] public void VisitAndConvertReturnsSameIfVisitDoes() { ConstantExpression constant = Expression.Constant(0); Assert.Same(constant, new DefaultVisitor().Visit(constant)); Assert.Same(constant, new DefaultVisitor().VisitAndConvert(constant, "foo")); } [Fact] public void VisitAndConvertThrowsIfVisitReturnsNull() { string slug = "Won't be found by chance 3f8d0006-32f9-4622-9ff4-c88e95c9babc"; string errMsg = Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new NullBecomingExpression(), slug)).Message; Assert.Contains(slug, errMsg); } [Fact] public void VisitAndConvertThrowsIfVisitChangesType() { string slug = "Won't be found by chance 5154E15C-A475-49B0-B596-8F822D7ACFC4"; string errMsg = Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new SourceExpression(), slug)).Message; Assert.Contains(slug, errMsg); } [Fact] public void VisitAndConvertNullName() { new DefaultVisitor().VisitAndConvert(Expression.Constant(0), null); Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new SourceExpression(), null)); } [Fact] public void VisitAndConvertReturnsIfForcedToCommonBase() { Assert.IsNotType<SourceExpression>(new DefaultVisitor().VisitAndConvert<Expression>(new SourceExpression(), "")); } [Fact] public void VisitAndConvertSameResultAsVisit() { ConstantExpression constant = Expression.Constant(0); ConstantExpression visited = new ConstantRefreshingVisitor().VisitAndConvert(constant, ""); Assert.NotSame(constant, visited); Assert.Equal(0, visited.Value); } [Fact] public void ReduceChildrenCascades() { ParameterExpression intVar = Expression.Variable(typeof(int)); List<int> list = new List<int>(); var foreachExp = new ForEachExpression( intVar, Expression.Constant(Enumerable.Range(5, 4)), Expression.Call( Expression.Constant(list), typeof(List<int>).GetMethod(nameof(List<int>.Insert)), Expression.Constant(0), intVar ) ); // Check that not only has the visitor reduced the foreach into a block // but the using within that block into a try...finally. Expression reduced = new DefaultVisitor().Visit(foreachExp); var block = (BlockExpression)reduced; var tryExp = (TryExpression)block.Expressions[1]; var loop = (LoopExpression)tryExp.Body; var innerBlock = (BlockExpression)loop.Body; var call = (MethodCallExpression)innerBlock.Expressions.Last(); var instance = (ConstantExpression)call.Object; Assert.Same(list, instance.Value); } [Fact] public void Visit_DebugInfoExpression_DoesNothing() { DebugInfoExpression expression = Expression.DebugInfo(Expression.SymbolDocument("fileName"), 1, 1, 1, 1); Assert.Same(expression, new DefaultVisitor().Visit(expression)); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcbav = Google.Cloud.Bigtable.Admin.V2; using gcbcv = Google.Cloud.Bigtable.Common.V2; using sys = System; namespace Google.Cloud.Bigtable.Admin.V2 { /// <summary>Resource name for the <c>Snapshot</c> resource.</summary> public sealed partial class SnapshotName : gax::IResourceName, sys::IEquatable<SnapshotName> { /// <summary>The possible contents of <see cref="SnapshotName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </summary> ProjectInstanceClusterSnapshot = 1, } private static gax::PathTemplate s_projectInstanceClusterSnapshot = new gax::PathTemplate("projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}"); /// <summary>Creates a <see cref="SnapshotName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SnapshotName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static SnapshotName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SnapshotName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SnapshotName"/> with the pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SnapshotName"/> constructed from the provided ids.</returns> public static SnapshotName FromProjectInstanceClusterSnapshot(string projectId, string instanceId, string clusterId, string snapshotId) => new SnapshotName(ResourceNameType.ProjectInstanceClusterSnapshot, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), snapshotId: gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </returns> public static string Format(string projectId, string instanceId, string clusterId, string snapshotId) => FormatProjectInstanceClusterSnapshot(projectId, instanceId, clusterId, snapshotId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c>. /// </returns> public static string FormatProjectInstanceClusterSnapshot(string projectId, string instanceId, string clusterId, string snapshotId) => s_projectInstanceClusterSnapshot.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))); /// <summary>Parses the given resource name string into a new <see cref="SnapshotName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns> public static SnapshotName Parse(string snapshotName) => Parse(snapshotName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SnapshotName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns> public static SnapshotName Parse(string snapshotName, bool allowUnparsed) => TryParse(snapshotName, allowUnparsed, out SnapshotName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SnapshotName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SnapshotName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string snapshotName, out SnapshotName result) => TryParse(snapshotName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SnapshotName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SnapshotName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string snapshotName, bool allowUnparsed, out SnapshotName result) { gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName)); gax::TemplatedResourceName resourceName; if (s_projectInstanceClusterSnapshot.TryParseName(snapshotName, out resourceName)) { result = FromProjectInstanceClusterSnapshot(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(snapshotName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SnapshotName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clusterId = null, string instanceId = null, string projectId = null, string snapshotId = null) { Type = type; UnparsedResource = unparsedResourceName; ClusterId = clusterId; InstanceId = instanceId; ProjectId = projectId; SnapshotId = snapshotId; } /// <summary> /// Constructs a new instance of a <see cref="SnapshotName"/> class from the component parts of pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/snapshots/{snapshot}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> public SnapshotName(string projectId, string instanceId, string clusterId, string snapshotId) : this(ResourceNameType.ProjectInstanceClusterSnapshot, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), snapshotId: gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Cluster</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ClusterId { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Snapshot</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SnapshotId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectInstanceClusterSnapshot: return s_projectInstanceClusterSnapshot.Expand(ProjectId, InstanceId, ClusterId, SnapshotId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SnapshotName); /// <inheritdoc/> public bool Equals(SnapshotName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SnapshotName a, SnapshotName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SnapshotName a, SnapshotName b) => !(a == b); } /// <summary>Resource name for the <c>Backup</c> resource.</summary> public sealed partial class BackupName : gax::IResourceName, sys::IEquatable<BackupName> { /// <summary>The possible contents of <see cref="BackupName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </summary> ProjectInstanceClusterBackup = 1, } private static gax::PathTemplate s_projectInstanceClusterBackup = new gax::PathTemplate("projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}"); /// <summary>Creates a <see cref="BackupName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="BackupName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static BackupName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new BackupName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="BackupName"/> with the pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="BackupName"/> constructed from the provided ids.</returns> public static BackupName FromProjectInstanceClusterBackup(string projectId, string instanceId, string clusterId, string backupId) => new BackupName(ResourceNameType.ProjectInstanceClusterBackup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), backupId: gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </returns> public static string Format(string projectId, string instanceId, string clusterId, string backupId) => FormatProjectInstanceClusterBackup(projectId, instanceId, clusterId, backupId); /// <summary> /// Formats the IDs into the string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="BackupName"/> with pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c>. /// </returns> public static string FormatProjectInstanceClusterBackup(string projectId, string instanceId, string clusterId, string backupId) => s_projectInstanceClusterBackup.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))); /// <summary>Parses the given resource name string into a new <see cref="BackupName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="BackupName"/> if successful.</returns> public static BackupName Parse(string backupName) => Parse(backupName, false); /// <summary> /// Parses the given resource name string into a new <see cref="BackupName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="BackupName"/> if successful.</returns> public static BackupName Parse(string backupName, bool allowUnparsed) => TryParse(backupName, allowUnparsed, out BackupName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BackupName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="BackupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string backupName, out BackupName result) => TryParse(backupName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="BackupName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="backupName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="BackupName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string backupName, bool allowUnparsed, out BackupName result) { gax::GaxPreconditions.CheckNotNull(backupName, nameof(backupName)); gax::TemplatedResourceName resourceName; if (s_projectInstanceClusterBackup.TryParseName(backupName, out resourceName)) { result = FromProjectInstanceClusterBackup(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(backupName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private BackupName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string backupId = null, string clusterId = null, string instanceId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; BackupId = backupId; ClusterId = clusterId; InstanceId = instanceId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="BackupName"/> class from the component parts of pattern /// <c>projects/{project}/instances/{instance}/clusters/{cluster}/backups/{backup}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="instanceId">The <c>Instance</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="backupId">The <c>Backup</c> ID. Must not be <c>null</c> or empty.</param> public BackupName(string projectId, string instanceId, string clusterId, string backupId) : this(ResourceNameType.ProjectInstanceClusterBackup, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), instanceId: gax::GaxPreconditions.CheckNotNullOrEmpty(instanceId, nameof(instanceId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId)), backupId: gax::GaxPreconditions.CheckNotNullOrEmpty(backupId, nameof(backupId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Backup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string BackupId { get; } /// <summary> /// The <c>Cluster</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ClusterId { get; } /// <summary> /// The <c>Instance</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string InstanceId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectInstanceClusterBackup: return s_projectInstanceClusterBackup.Expand(ProjectId, InstanceId, ClusterId, BackupId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as BackupName); /// <inheritdoc/> public bool Equals(BackupName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(BackupName a, BackupName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(BackupName a, BackupName b) => !(a == b); } /// <summary>Resource name for the <c>CryptoKeyVersion</c> resource.</summary> public sealed partial class CryptoKeyVersionName : gax::IResourceName, sys::IEquatable<CryptoKeyVersionName> { /// <summary>The possible contents of <see cref="CryptoKeyVersionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </summary> ProjectLocationKeyRingCryptoKeyCryptoKeyVersion = 1, } private static gax::PathTemplate s_projectLocationKeyRingCryptoKeyCryptoKeyVersion = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}"); /// <summary>Creates a <see cref="CryptoKeyVersionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CryptoKeyVersionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CryptoKeyVersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CryptoKeyVersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CryptoKeyVersionName"/> with the pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyVersionId">The <c>CryptoKeyVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CryptoKeyVersionName"/> constructed from the provided ids.</returns> public static CryptoKeyVersionName FromProjectLocationKeyRingCryptoKeyCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string cryptoKeyVersionId) => new CryptoKeyVersionName(ResourceNameType.ProjectLocationKeyRingCryptoKeyCryptoKeyVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), keyRingId: gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), cryptoKeyId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)), cryptoKeyVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyVersionId, nameof(cryptoKeyVersionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CryptoKeyVersionName"/> with pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyVersionId">The <c>CryptoKeyVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CryptoKeyVersionName"/> with pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </returns> public static string Format(string projectId, string locationId, string keyRingId, string cryptoKeyId, string cryptoKeyVersionId) => FormatProjectLocationKeyRingCryptoKeyCryptoKeyVersion(projectId, locationId, keyRingId, cryptoKeyId, cryptoKeyVersionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CryptoKeyVersionName"/> with pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyVersionId">The <c>CryptoKeyVersion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CryptoKeyVersionName"/> with pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// . /// </returns> public static string FormatProjectLocationKeyRingCryptoKeyCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string cryptoKeyVersionId) => s_projectLocationKeyRingCryptoKeyCryptoKeyVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)), gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyVersionId, nameof(cryptoKeyVersionId))); /// <summary> /// Parses the given resource name string into a new <see cref="CryptoKeyVersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="cryptoKeyVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CryptoKeyVersionName"/> if successful.</returns> public static CryptoKeyVersionName Parse(string cryptoKeyVersionName) => Parse(cryptoKeyVersionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CryptoKeyVersionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="cryptoKeyVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CryptoKeyVersionName"/> if successful.</returns> public static CryptoKeyVersionName Parse(string cryptoKeyVersionName, bool allowUnparsed) => TryParse(cryptoKeyVersionName, allowUnparsed, out CryptoKeyVersionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CryptoKeyVersionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="cryptoKeyVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CryptoKeyVersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string cryptoKeyVersionName, out CryptoKeyVersionName result) => TryParse(cryptoKeyVersionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CryptoKeyVersionName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="cryptoKeyVersionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CryptoKeyVersionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string cryptoKeyVersionName, bool allowUnparsed, out CryptoKeyVersionName result) { gax::GaxPreconditions.CheckNotNull(cryptoKeyVersionName, nameof(cryptoKeyVersionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationKeyRingCryptoKeyCryptoKeyVersion.TryParseName(cryptoKeyVersionName, out resourceName)) { result = FromProjectLocationKeyRingCryptoKeyCryptoKeyVersion(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(cryptoKeyVersionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CryptoKeyVersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string cryptoKeyId = null, string cryptoKeyVersionId = null, string keyRingId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; CryptoKeyId = cryptoKeyId; CryptoKeyVersionId = cryptoKeyVersionId; KeyRingId = keyRingId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="CryptoKeyVersionName"/> class from the component parts of pattern /// <c> /// projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="keyRingId">The <c>KeyRing</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyId">The <c>CryptoKey</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="cryptoKeyVersionId">The <c>CryptoKeyVersion</c> ID. Must not be <c>null</c> or empty.</param> public CryptoKeyVersionName(string projectId, string locationId, string keyRingId, string cryptoKeyId, string cryptoKeyVersionId) : this(ResourceNameType.ProjectLocationKeyRingCryptoKeyCryptoKeyVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), keyRingId: gax::GaxPreconditions.CheckNotNullOrEmpty(keyRingId, nameof(keyRingId)), cryptoKeyId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyId, nameof(cryptoKeyId)), cryptoKeyVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(cryptoKeyVersionId, nameof(cryptoKeyVersionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CryptoKey</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CryptoKeyId { get; } /// <summary> /// The <c>CryptoKeyVersion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CryptoKeyVersionId { get; } /// <summary> /// The <c>KeyRing</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string KeyRingId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationKeyRingCryptoKeyCryptoKeyVersion: return s_projectLocationKeyRingCryptoKeyCryptoKeyVersion.Expand(ProjectId, LocationId, KeyRingId, CryptoKeyId, CryptoKeyVersionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CryptoKeyVersionName); /// <inheritdoc/> public bool Equals(CryptoKeyVersionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CryptoKeyVersionName a, CryptoKeyVersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CryptoKeyVersionName a, CryptoKeyVersionName b) => !(a == b); } public partial class Table { /// <summary> /// <see cref="gcbcv::TableName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::TableName TableName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::TableName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class EncryptionInfo { /// <summary> /// <see cref="CryptoKeyVersionName"/>-typed view over the <see cref="KmsKeyVersion"/> resource name property. /// </summary> public CryptoKeyVersionName KmsKeyVersionAsCryptoKeyVersionName { get => string.IsNullOrEmpty(KmsKeyVersion) ? null : CryptoKeyVersionName.Parse(KmsKeyVersion, allowUnparsed: true); set => KmsKeyVersion = value?.ToString() ?? ""; } } public partial class Snapshot { /// <summary> /// <see cref="gcbav::SnapshotName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::SnapshotName SnapshotName { get => string.IsNullOrEmpty(Name) ? null : gcbav::SnapshotName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Backup { /// <summary> /// <see cref="gcbav::BackupName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbav::BackupName BackupName { get => string.IsNullOrEmpty(Name) ? null : gcbav::BackupName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace The_Borg { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D[] gunTurrets = new Texture2D[4], torpedos = new Texture2D[4]; Texture2D borg; Rectangle[] gunTurRcts = new Rectangle[4], torpedosRct = new Rectangle[4]; Rectangle borgRct; SpriteFont lsuFont; KeyboardState oldKb = Keyboard.GetState(); Keys[] numPad = {Keys.NumPad0, Keys.NumPad1, Keys.NumPad2, Keys.NumPad3, Keys.NumPad4, Keys.NumPad5, Keys.NumPad6, Keys.NumPad7, Keys.NumPad8, Keys.NumPad9}; int delay = -1; int time = 0; int lsuEnergy = 100, mjChoice = 0; int index = 0, shootingIndex = -1; int torpedoX = 0, torpedoY = 0; bool[] showBorg = { false, false, false, false }; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here this.IsMouseVisible = true; gunTurRcts[0] = new Rectangle(350, 100, 78, 100); gunTurRcts[1] = new Rectangle(420, 200, 100, 78); gunTurRcts[2] = new Rectangle(350, 270, 78, 100); gunTurRcts[3] = new Rectangle(250, 200, 100, 78); torpedosRct[0] = new Rectangle(375, 100, 25, 100); torpedosRct[1] = new Rectangle(420, 225, 100, 25); torpedosRct[2] = new Rectangle(375, 270, 25, 100); torpedosRct[3] = new Rectangle(250, 225, 100, 25); borgRct = new Rectangle(0, 0, 100, 100); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here gunTurrets[0] = this.Content.Load<Texture2D>("gun_turret_up"); gunTurrets[1] = this.Content.Load<Texture2D>("gun_turret_right"); gunTurrets[2] = this.Content.Load<Texture2D>("gun_turret_down"); gunTurrets[3] = this.Content.Load<Texture2D>("gun_turret_left"); torpedos[0] = this.Content.Load<Texture2D>("torpedo_up"); torpedos[1] = this.Content.Load<Texture2D>("torpedo_right"); torpedos[2] = this.Content.Load<Texture2D>("torpedo_down"); torpedos[3] = this.Content.Load<Texture2D>("torpedo_left"); borg = this.Content.Load<Texture2D>("borg"); lsuFont = this.Content.Load<SpriteFont>("LSUFont"); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { KeyboardState kb = Keyboard.GetState(); // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape)) this.Exit(); time += 1; int seconds = time / 60; // TODO: Add your update logic here if (kb.IsKeyDown(Keys.Up) && !oldKb.IsKeyDown(Keys.Up)) index = 0; else if (kb.IsKeyDown(Keys.Right) && !oldKb.IsKeyDown(Keys.Right)) index = 1; else if (kb.IsKeyDown(Keys.Down) && !oldKb.IsKeyDown(Keys.Down)) index = 2; else if (kb.IsKeyDown(Keys.Left) && !oldKb.IsKeyDown(Keys.Left)) index = 3; for (int i = 0; i < numPad.Length;i++) { if (kb.IsKeyDown(numPad[i])) { mjChoice = i; } } // TODO: Add torpedo motion if (kb.IsKeyDown(Keys.Space) && !oldKb.IsKeyDown(Keys.Space) && delay == -1) { switch (index) { case 0: torpedoX = 375; torpedoY = 100; break; case 1: torpedoX = 420; torpedoY = 225; break; case 2: torpedoX = 375; torpedoY = 270; break; case 3: torpedoX = 250; torpedoY = 225; break; } shootingIndex = index; delay = gameTime.TotalGameTime.Seconds; lsuEnergy -= mjChoice; } if (delay != -1) { if ((gameTime.TotalGameTime.Seconds - delay) < 3) { switch (shootingIndex) { case 0: torpedoY -= 5; torpedosRct[shootingIndex] = new Rectangle(torpedoX, torpedoY, 25, 100); break; case 1: torpedoX += 5; torpedosRct[shootingIndex] = new Rectangle(torpedoX, torpedoY, 100, 25); break; case 2: torpedoY += 5; torpedosRct[shootingIndex] = new Rectangle(torpedoX, torpedoY, 25, 100); break; case 3: torpedoX -= 5; torpedosRct[shootingIndex] = new Rectangle(torpedoX, torpedoY, 100, 25); break; } } else { delay = shootingIndex = -1; torpedoX = torpedoY = 0; } } if (lsuEnergy < 100 && (time % 60) == 0) { lsuEnergy += 3; } else if (lsuEnergy > 100) lsuEnergy = 100; if (seconds == 5) { Random rnd = new Random(); showBorg[rnd.Next(4)] = true; } oldKb = kb; base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); // TODO: Add your drawing code here if (shootingIndex != -1) spriteBatch.Draw(torpedos[shootingIndex], torpedosRct[shootingIndex], Color.White); for (int i = 0; i < 4; i++) { if (i == index && shootingIndex == -1) spriteBatch.Draw(gunTurrets[i], gunTurRcts[i], Color.LightGreen); else spriteBatch.Draw(gunTurrets[i], gunTurRcts[i], Color.Red); } spriteBatch.DrawString(lsuFont, lsuEnergy+"MJ", new Vector2(360, 220), Color.White); if (showBorg[0]) borgRct = new Rectangle(350, 0, 75, 75); else if (showBorg[1]) borgRct = new Rectangle(700, 200, 75, 75); else if (showBorg[2]) borgRct = new Rectangle(350, 400, 75, 75); else if (showBorg[3]) borgRct = new Rectangle(0, 200, 75, 75); if (showBorg[0] || showBorg[1] || showBorg[2] || showBorg[3]) spriteBatch.Draw(borg, borgRct, Color.Red); spriteBatch.End(); base.Draw(gameTime); } } }
// 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: Generic hash table implementation ** ** #DictionaryVersusHashtableThreadSafety ** Hashtable has multiple reader/single writer (MR/SW) thread safety built into ** certain methods and properties, whereas Dictionary doesn't. If you're ** converting framework code that formerly used Hashtable to Dictionary, it's ** important to consider whether callers may have taken a dependence on MR/SW ** thread safety. If a reader writer lock is available, then that may be used ** with a Dictionary to get the same thread safety guarantee. ** ** Reader writer locks don't exist in silverlight, so we do the following as a ** result of removing non-generic collections from silverlight: ** 1. If the Hashtable was fully synchronized, then we replace it with a ** Dictionary with full locks around reads/writes (same thread safety ** guarantee). ** 2. Otherwise, the Hashtable has the default MR/SW thread safety behavior, ** so we do one of the following on a case-by-case basis: ** a. If the race condition can be addressed by rearranging the code and using a temp ** variable (for example, it's only populated immediately after created) ** then we address the race condition this way and use Dictionary. ** b. If there's concern about degrading performance with the increased ** locking, we ifdef with FEATURE_NONGENERIC_COLLECTIONS so we can at ** least use Hashtable in the desktop build, but Dictionary with full ** locks in silverlight builds. Note that this is heavier locking than ** MR/SW, but this is the only option without rewriting (or adding back) ** the reader writer lock. ** c. If there's no performance concern (e.g. debug-only code) we ** consistently replace Hashtable with Dictionary plus full locks to ** reduce complexity. ** d. Most of serialization is dead code in silverlight. Instead of updating ** those Hashtable occurences in serialization, we carved out references ** to serialization such that this code doesn't need to build in ** silverlight. ===========================================================*/ namespace System.Collections.Generic { using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; [DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] buckets; private Entry[] entries; private int count; private int version; private int freeList; private int freeCount; private IEqualityComparer<TKey> comparer; private KeyCollection keys; private ValueCollection values; private Object _syncRoot; // constants for serialization private const String VersionName = "Version"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; private const String ComparerName = "Comparer"; public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); this.comparer = comparer ?? EqualityComparer<TKey>.Default; #if FEATURE_RANDOMIZED_STRING_HASHING if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default) { this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default; } #endif // FEATURE_RANDOMIZED_STRING_HASHING } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } // It is likely that the passed-in dictionary is Dictionary<TKey,TValue>. When this is the case, // avoid the enumerator allocation and overhead by looping through the entries array directly. // We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain // back-compat with subclasses that may have overridden the enumerator behavior. if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>)) { Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary; int count = d.count; Entry[] entries = d.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { Add(entries[i].key, entries[i].value); } } return; } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) : this(collection, null) { } public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) : this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer) { if (collection == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } foreach (KeyValuePair<TKey, TValue> pair in collection) { Add(pair.Key, pair.Value); } } protected Dictionary(SerializationInfo info, StreamingContext context) { //We can't do anything with the keys and values until the entire graph has been deserialized //and we have a resonable estimate that GetHashCode is not going to fail. For the time being, //we'll just cache this. The graph is not valid until OnDeserialization has been called. HashHelpers.SerializationInfoTable.Add(this, info); } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public int Count { get { return count - freeCount; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (keys == null) keys = new KeyCollection(this); return keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (values == null) values = new ValueCollection(this); return values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return entries[i].value; ThrowHelper.ThrowKeyNotFoundException(); return default(TValue); } set { Insert(key, value, false); } } public void Add(TKey key, TValue value) { Insert(key, value, true); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { if (count > 0) { for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; Array.Clear(entries, 0, count); freeList = -1; count = 0; freeCount = 0; version++; } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && entries[i].value == null) return true; } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue(VersionName, version); #if FEATURE_RANDOMIZED_STRING_HASHING info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>)); #else info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>)); #endif info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array. if (buckets != null) { KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count]; CopyTo(array, 0); info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[])); } } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i; } } return -1; } private void Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[size]; freeList = -1; } private void Insert(TKey key, TValue value, bool add) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets == null) Initialize(0); int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % buckets.Length; #if FEATURE_RANDOMIZED_STRING_HASHING int collisionCount = 0; #endif for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (add) { ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key); } entries[i].value = value; version++; return; } #if FEATURE_RANDOMIZED_STRING_HASHING collisionCount++; #endif } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = hashCode % buckets.Length; } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = buckets[targetBucket]; entries[index].key = key; entries[index].value = value; buckets[targetBucket] = index; version++; #if FEATURE_RANDOMIZED_STRING_HASHING // In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing // in this case will be EqualityComparer<string>.Default. // Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will // be using randomized string hashing if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default) { comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default; Resize(entries.Length, true); } #endif } public virtual void OnDeserialization(Object sender) { SerializationInfo siInfo; HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo); if (siInfo == null) { // It might be necessary to call OnDeserialization from a container if the container object also implements // OnDeserialization. However, remoting will call OnDeserialization again. // We can return immediately if this function is called twice. // Note we set remove the serialization info from the table at the end of this method. return; } int realVersion = siInfo.GetInt32(VersionName); int hashsize = siInfo.GetInt32(HashSizeName); comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>)); if (hashsize != 0) { buckets = new int[hashsize]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[hashsize]; freeList = -1; KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[]) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[])); if (array == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys); } for (int i = 0; i < array.Length; i++) { if (array[i].Key == null) { ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey); } Insert(array[i].Key, array[i].Value, true); } } else { buckets = null; } version = realVersion; HashHelpers.SerializationInfoTable.Remove(this); } private void Resize() { Resize(HashHelpers.ExpandPrime(count), false); } private void Resize(int newSize, bool forceNewHashCodes) { Debug.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); if (forceNewHashCodes) { for (int i = 0; i < count; i++) { if (newEntries[i].hashCode != -1) { newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (newEntries[i].hashCode >= 0) { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } } buckets = newBuckets; entries = newEntries; } public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % buckets.Length; int last = -1; for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (last < 0) { buckets[bucket] = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; entries[i].key = default(TKey); entries[i].value = default(TValue); freeList = i; freeCount++; version++; return true; } } } return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = entries[i].value; return true; } value = default(TValue); return false; } // Method similar to TryGetValue that returns the value instead of putting it in an out param. public TValue GetValueOrDefault(TKey key) => GetValueOrDefault(key, default(TValue)); // Method similar to TryGetValue that returns the value instead of putting it in an out param. If the entry // doesn't exist, returns the defaultValue instead. public TValue GetValueOrDefault(TKey key, TValue defaultValue) { int i = FindEntry(key); if (i >= 0) { return entries[i].value; } return defaultValue; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if (array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } try { int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } [Serializable] public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> dictionary; private int version; private int index; private KeyValuePair<TKey, TValue> current; private int getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value); index++; return true; } index++; } index = dictionary.count + 1; current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return current; } } public void Dispose() { } object IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } if (getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(current.Key, current.Value); } else { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } } void IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return current.Key; } } object IDictionaryEnumerator.Value { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return current.Value; } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TKey currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentKey = dictionary.entries[index].key; index++; return true; } index++; } index = dictionary.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; currentKey = default(TKey); } } } [DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (array.Length - index < dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TValue currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentValue = dictionary.entries[index].value; index++; return true; } index++; } index = dictionary.count + 1; currentValue = default(TValue); return false; } public TValue Current { get { return currentValue; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion(); } index = 0; currentValue = default(TValue); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentStackTests { [Fact] public static void TestBasicScenarios() { ConcurrentStack<int> cs = new ConcurrentStack<int>(); cs.Push(1); Task[] tks = new Task[2]; tks[0] = Task.Run(() => { cs.Push(2); cs.Push(3); cs.Push(4); }); tks[1] = Task.Run(() => { int item1, item2; var ret1 = cs.TryPop(out item1); // at least one item Assert.True(ret1); var ret2 = cs.TryPop(out item2); // two item if (ret2) { Assert.True(item1 > item2, String.Format("{0} should greater than {1}", item1, item2)); } else // one item { Assert.Equal(1, item1); } }); Task.WaitAll(tks); } [Fact] public static void Test0_Empty() { ConcurrentStack<int> s = new ConcurrentStack<int>(); int item; Assert.False(s.TryPop(out item), "Test0_Empty: TryPop returned true when the stack is empty"); Assert.False(s.TryPeek(out item), "Test0_Empty: TryPeek returned true when the stack is empty"); Assert.True(s.TryPopRange(new int[1]) == 0, "Test0_Empty: TryPopRange returned non zero when the stack is empty"); int count = 15; for (int i = 0; i < count; i++) s.Push(i); Assert.Equal(count, s.Count); Assert.False(s.IsEmpty); } [Fact] public static void Test1_PushAndPop() { Test1_PushAndPop(0, 0); Test1_PushAndPop(9, 9); } [Fact] [OuterLoop] public static void Test1_PushAndPop01() { Test1_PushAndPop(3, 0); Test1_PushAndPop(1024, 512); } [Fact] public static void Test2_ConcPushAndPop() { Test2_ConcPushAndPop(3, 1024, 0); } [Fact] public static void Test2_ConcPushAndPop01() { Test2_ConcPushAndPop(8, 1024, 512); } [Fact] public static void Test3_Clear() { Test3_Clear(0); Test3_Clear(16); Test3_Clear(1024); } [Fact] public static void Test4_Enumerator() { Test4_Enumerator(0); Test4_Enumerator(16); } [Fact] [OuterLoop] public static void Test4_Enumerator01() { Test4_Enumerator(1024); } [Fact] public static void Test5_CtorAndCopyToAndToArray() { Test5_CtorAndCopyToAndToArray(0); Test5_CtorAndCopyToAndToArray(16); } [Fact] [OuterLoop] public static void Test5_CtorAndCopyToAndToArray01() { Test5_CtorAndCopyToAndToArray(1024); } [Fact] public static void Test6_PushRange() { Test6_PushRange(8, 10); Test6_PushRange(16, 100); } [Fact] public static void Test7_PopRange() { Test7_PopRange(8, 10); Test7_PopRange(16, 100); } [Fact] [OuterLoop] public static void Test_PushPopRange() { Test6_PushRange(128, 100); Test7_PopRange(128, 100); } // Pushes and pops a certain number of times, and validates the resulting count. // These operations happen sequentially in a somewhat-interleaved fashion. We use // a BCL stack on the side to validate contents are correctly maintained. private static void Test1_PushAndPop(int pushes, int pops) { // It utilised a random generator to do x number of pushes and // y number of pops where x = random, y = random. Removed it // because it used System.Runtime.Extensions. ConcurrentStack<int> s = new ConcurrentStack<int>(); Stack<int> s2 = new Stack<int>(); int donePushes = 0, donePops = 0; while (donePushes < pushes || donePops < pops) { for (int i = 0; i < 10; i++) { if (donePushes == pushes) break; int val = i; s.Push(val); s2.Push(val); donePushes++; Assert.Equal(s.Count, s2.Count); } for (int i = 0; i < 6; i++) { if (donePops == pops) break; if ((donePushes - donePops) <= 0) break; int e0, e1, e2; bool b0 = s.TryPeek(out e0); bool b1 = s.TryPop(out e1); e2 = s2.Pop(); donePops++; Assert.True(b0); Assert.True(b1); Assert.Equal(e0, e1); Assert.Equal(e1, e2); Assert.Equal(s.Count, s2.Count); } } Assert.Equal(pushes - pops, s.Count); } // Pushes and pops a certain number of times, and validates the resulting count. // These operations happen sconcurrently. private static void Test2_ConcPushAndPop(int threads, int pushes, int pops) { // It utilised a random generator to do x number of pushes and // y number of pops where x = random, y = random. Removed it // because it used System.Runtime.Extensions. ConcurrentStack<int> s = new ConcurrentStack<int>(); ManualResetEvent mre = new ManualResetEvent(false); Task[] tt = new Task[threads]; // Create all threads. for (int k = 0; k < tt.Length; k++) { tt[k] = Task.Run(delegate() { mre.WaitOne(); int donePushes = 0, donePops = 0; while (donePushes < pushes || donePops < pops) { for (int i = 0; i < 8; i++) { if (donePushes == pushes) break; s.Push(i); donePushes++; } for (int i = 0; i < 4; i++) { if (donePops == pops) break; if ((donePushes - donePops) <= 0) break; int e; if (s.TryPop(out e)) donePops++; } } }); } // Kick 'em off and wait for them to finish. mre.Set(); Task.WaitAll(tt); // Validate the count. Assert.Equal(threads * (pushes - pops), s.Count); } // Just validates clearing the stack's contents. private static void Test3_Clear(int count) { ConcurrentStack<int> s = new ConcurrentStack<int>(); for (int i = 0; i < count; i++) s.Push(i); s.Clear(); Assert.True(s.IsEmpty); Assert.Equal(0, s.Count); } // Just validates enumerating the stack. private static void Test4_Enumerator(int count) { ConcurrentStack<int> s = new ConcurrentStack<int>(); for (int i = 0; i < count; i++) s.Push(i); // Test enumerator. int j = count - 1; foreach (int x in s) { // Clear the stack to ensure concurrent modifications are dealt w/. if (x == count - 1) { int e; while (s.TryPop(out e)) ; } Assert.Equal(j, x); j--; } Assert.True(j <= 0, " > did not enumerate all elements in the stack"); } // Instantiates the stack w/ the enumerator ctor and validates the resulting copyto & toarray. private static void Test5_CtorAndCopyToAndToArray(int count) { int[] arr = new int[count]; for (int i = 0; i < count; i++) arr[i] = i; ConcurrentStack<int> s = new ConcurrentStack<int>(arr); // try toarray. int[] sa1 = s.ToArray(); Assert.Equal(arr.Length, sa1.Length); for (int i = 0; i < sa1.Length; i++) { Assert.Equal(arr[count - i - 1], sa1[i]); } int[] sa2 = new int[count]; s.CopyTo(sa2, 0); Assert.Equal(arr.Length, sa2.Length); for (int i = 0; i < sa2.Length; i++) { Assert.Equal(arr[count - i - 1], sa2[i]); } object[] sa3 = new object[count]; // test array variance. ((System.Collections.ICollection)s).CopyTo(sa3, 0); Assert.Equal(arr.Length, sa3.Length); for (int i = 0; i < sa3.Length; i++) { Assert.Equal(arr[count - i - 1], (int)sa3[i]); } } //Tests COncurrentSTack.PushRange private static void Test6_PushRange(int NumOfThreads, int localArraySize) { ConcurrentStack<int> stack = new ConcurrentStack<int>(); Task[] threads = new Task[NumOfThreads]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Factory.StartNew((obj) => { int index = (int)obj; int[] array = new int[localArraySize]; for (int j = 0; j < localArraySize; j++) { array[j] = index + j; } stack.PushRange(array); }, i * localArraySize, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } Task.WaitAll(threads); //validation for (int i = 0; i < threads.Length; i++) { int lastItem = -1; for (int j = 0; j < localArraySize; j++) { int currentItem = 0; Assert.True(stack.TryPop(out currentItem), String.Format("* Test6_PushRange({0},{1})L TryPop returned false.", NumOfThreads, localArraySize)); Assert.True((lastItem <= -1) || lastItem - currentItem == 1, String.Format("* Test6_PushRange({0},{1}): Failed {2} - {3} shouldn't be consecutive", NumOfThreads, localArraySize, lastItem, currentItem)); lastItem = currentItem; } } } //Tests ConcurrentStack.PopRange by pushing consecutove numbers and run n threads each thread tries to pop m itmes // the popped m items should be consecutive private static void Test7_PopRange(int NumOfThreads, int elementsPerThread) { int lastValue = NumOfThreads * elementsPerThread; List<int> allValues = new List<int>(); for (int i = 1; i <= lastValue; i++) allValues.Add(i); ConcurrentStack<int> stack = new ConcurrentStack<int>(allValues); Task[] threads = new Task[NumOfThreads]; int[] array = new int[threads.Length * elementsPerThread]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Factory.StartNew((obj) => { int index = (int)obj; int res = stack.TryPopRange(array, index, elementsPerThread); Assert.Equal(elementsPerThread, res); }, i * elementsPerThread, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } Task.WaitAll(threads); // validation for (int i = 0; i < NumOfThreads; i++) { for (int j = 1; j < elementsPerThread; j++) { int currentIndex = i * elementsPerThread + j; Assert.Equal(array[currentIndex - 1], array[currentIndex] + 1); } } } [Fact] public static void Test8_Exceptions() { ConcurrentStack<int> stack = null; Assert.Throws<ArgumentNullException>( () => stack = new ConcurrentStack<int>((IEnumerable<int>)null)); // "Test8_Exceptions: The constructor didn't throw ANE when null collection passed"); stack = new ConcurrentStack<int>(); //CopyTo Assert.Throws<ArgumentNullException>( () => stack.CopyTo(null, 0)); // "Test8_Exceptions: CopyTo didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.CopyTo(new int[1], -1)); // "Test8_Exceptions: CopyTo didn't throw AORE when negative array index passed"); //PushRange Assert.Throws<ArgumentNullException>( () => stack.PushRange(null)); // "Test8_Exceptions: PushRange didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], 0, -1)); // "Test8_Exceptions: PushRange didn't throw AORE when negative count passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], -1, 1)); // "Test8_Exceptions: PushRange didn't throw AORE when negative index passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.PushRange(new int[1], 2, 1)); // "Test8_Exceptions: PushRange didn't throw AORE when start index > array length"); Assert.Throws<ArgumentException>( () => stack.PushRange(new int[1], 0, 10)); // "Test8_Exceptions: PushRange didn't throw AE when count + index > array length"); //PopRange Assert.Throws<ArgumentNullException>( () => stack.TryPopRange(null)); // "Test8_Exceptions: TryPopRange didn't throw ANE when null array passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], 0, -1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when negative count passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], -1, 1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when negative index passed"); Assert.Throws<ArgumentOutOfRangeException>( () => stack.TryPopRange(new int[1], 2, 1)); // "Test8_Exceptions: TryPopRange didn't throw AORE when start index > array length"); Assert.Throws<ArgumentException>( () => stack.TryPopRange(new int[1], 0, 10)); // "Test8_Exceptions: TryPopRange didn't throw AE when count + index > array length"); } [Fact] public static void Test9_Interfaces_Negative() { ConcurrentStack<int> stack = new ConcurrentStack<int>(); ICollection collection = stack; Assert.Throws<ArgumentNullException>( () => collection.CopyTo(null, 0)); // "TestICollection: ICollection.CopyTo didn't throw ANE when null collection passed for collection type: ConcurrentStack"); Assert.Throws<NotSupportedException>( () => { object obj = collection.SyncRoot; }); // "TestICollection: ICollection.SyncRoot didn't throw NotSupportedException! for collection type: ConcurrentStack"); } [Fact] public static void Test9_Interfaces() { ConcurrentStack<int> stack = new ConcurrentStack<int>(); IProducerConsumerCollection<int> ipcc = stack; Assert.Equal(0, ipcc.Count); int item; Assert.False(ipcc.TryTake(out item)); Assert.True(ipcc.TryAdd(1)); ICollection collection = stack; Assert.False(collection.IsSynchronized); stack.Push(1); int count = stack.Count; IEnumerable enumerable = stack; foreach (object o in enumerable) count--; Assert.Equal(0, count); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; //using Semver; using CSemVer; namespace CSemVer.Tests { [TestFixture] public class CSVersionTests { [Explicit] [TestCase( "v0.0.0-alpha.1" )] [TestCase( "v0.0.0-alpha.2" )] [TestCase( "v0.0.0-alpha.0.1" )] [TestCase( "v1.0.0" )] [TestCase( "v1.0.1" )] [TestCase( "v1.1.0" )] [TestCase( "v1.1.0" )] [TestCase( "v2.0.0-rc" )] [TestCase( "v1.2.3" )] [TestCase( "v1.2.3-alpha" )] [TestCase( "v1.2.3-delta.5" )] [TestCase( "v1.2.3-prerelease.2.3" )] [TestCase( "v1.2.3-rc" )] public void display_successors_samples( string v ) { CSVersion t = CSVersion.TryParse( v ); var succ = t.GetDirectSuccessors( false ); Console.WriteLine( " -> - found {0} successors for '{1}' (Ordered Version = {2}, File = {3}):", succ.Count(), t, t.OrderedVersion, t.ToStringFileVersion( false ) ); Console.WriteLine( " " + string.Join( ", ", succ.Select( s => s.ToString() ) ) ); var closest = t.GetDirectSuccessors( true ).Select( s => s.ToString() ).ToList(); Console.WriteLine( " - {0} next fixes:", closest.Count, t ); Console.WriteLine( " " + string.Join( ", ", closest ) ); } [TestCase( "0.0.0" )] [TestCase( "3.0.1" )] [TestCase( "3.0.1" )] [TestCase( "99999.49999.9999" )] public void parsing_valid_release( string tag ) { CSVersion t = CSVersion.TryParse( tag ); Assert.That( t.IsValid ); Assert.That( t.IsPrerelease, Is.False ); Assert.That( t.IsPreReleasePatch, Is.False ); Assert.That( t.ToNuGetPackageString(), Is.EqualTo( tag ) ); Assert.That( t.ToString(), Is.EqualTo( tag ) ); Assert.That( t.NormalizedText, Is.EqualTo( tag ) ); Assert.That( t.NormalizedTextWithBuildMetaData, Is.EqualTo( tag ) ); } [TestCase( "v0.0.0-alpha", 0, 0, 0, 1 )] [TestCase( "v0.0.0-alpha.0.1", 0, 0, 0, 2 )] [TestCase( "v0.0.0-alpha.0.2", 0, 0, 0, 3 )] [TestCase( "v0.0.0-alpha.1", 0, 0, 0, 101 )] [TestCase( "v0.0.0-beta", 0, 0, 0, 100 * 99 + 101 )] public void version_ordering_starts_at_1_for_the_very_first_possible_version( string tag, int oMajor, int oMinor, int oBuild, int oRevision ) { var t = CSVersion.TryParse( tag, true ); Assert.That( t.IsValid ); Assert.That( t.OrderedVersionMajor, Is.EqualTo( oMajor ) ); Assert.That( t.OrderedVersionMinor, Is.EqualTo( oMinor ) ); Assert.That( t.OrderedVersionBuild, Is.EqualTo( oBuild ) ); Assert.That( t.OrderedVersionRevision, Is.EqualTo( oRevision ) ); long vf = t.OrderedVersion << 1; Assert.That( t.ToStringFileVersion( false ), Is.EqualTo( string.Format( "{0}.{1}.{2}.{3}", vf >> 48, (vf >> 32) & 0xFFFF, (vf >> 16) & 0xFFFF, vf & 0xFFFF ) ) ); vf |= 1; Assert.That( t.ToStringFileVersion( true ), Is.EqualTo( string.Format( "{0}.{1}.{2}.{3}", vf >> 48, (vf >> 32) & 0xFFFF, (vf >> 16) & 0xFFFF, vf & 0xFFFF ) ) ); } [TestCase( "0", 0, "Invalid are always 0." )] [TestCase( "0.0.0-prerelease", 1, "Normal = 1." )] [TestCase( "0.0.0", 1, "Normal = 1" )] [TestCase( "0.0.0-gamma", 1, "Normal = 1" )] [TestCase( "88.88.88-rc+Invalid", 2, "Invalid = 2" )] [TestCase( "88.88.88+Invalid", 2, "Marked Invalid = 2" )] public void equal_release_tags_can_have_different_definition_strengths( string tag, int level, string message ) { var t = CSVersion.TryParse( tag ); Assert.That( t.DefinitionStrength, Is.EqualTo( level ), message ); } [TestCase( "0.0.0-alpha", false, 0 )] [TestCase( "0.0.0-alpha.0.1", false, 1 )] [TestCase( "0.0.0-alpha.0.2", false, 2 )] [TestCase( "0.0.0-alpha.99.99", false, 100 * 99 + 100 - 1 )] [TestCase( "0.0.0-beta", false, 100 * 99 + 100 )] [TestCase( "0.0.0-delta", false, 2 * (100 * 99 + 100) )] [TestCase( "0.0.0-rc", false, 7 * (100 * 99 + 100) )] [TestCase( "0.0.0-rc.99.99", false, 7 * (100 * 99 + 100) + 100 * 99 + 99 )] [TestCase( "0.0.0", false, 8 * 100 * 100 )] [TestCase( "0.0.1-alpha", false, (8 * 100 * 100) + 1 )] [TestCase( "0.0.1-alpha.0.1", false, ((8 * 100 * 100) + 1) + 1 )] [TestCase( "0.0.1-alpha.0.2", false, ((8 * 100 * 100) + 1) + 2 )] [TestCase( "0.0.1-alpha.99.99", false, ((8 * 100 * 100) + 1) + 100 * 99 + 100 - 1 )] [TestCase( "0.0.1-beta", false, ((8 * 100 * 100) + 1) + 100 * 99 + 100 )] [TestCase( "0.0.1-delta", false, ((8 * 100 * 100) + 1) + 2 * (100 * 99 + 100) )] [TestCase( "0.0.1-epsilon", false, ((8 * 100 * 100) + 1) + 3 * (100 * 99 + 100) )] [TestCase( "0.0.1-rc", false, ((8 * 100 * 100) + 1) + 7 * (100 * 99 + 100) )] [TestCase( "0.0.1-rc.99.99", false, ((8 * 100 * 100) + 1) + 7 * (100 * 99 + 100) + 100 * 99 + 99 )] [TestCase( "0.0.1", false, ((8 * 100 * 100) + 1) + 8 * 100 * 100 )] [TestCase( "99999.49999.9998", true, (8 * 100 * 100) + 1 )] [TestCase( "99999.49999.9999-prerelease", true, 2 * (100 * 99 + 100) )] [TestCase( "99999.49999.9999-prerelease.99.99", true, 100 * 99 + 100 + 1 )] [TestCase( "99999.49999.9999-rc", true, 100 * 99 + 100 )] [TestCase( "99999.49999.9999-rc.99.98", true, 2 )] [TestCase( "99999.49999.9999-rc.99.99", true, 1 )] [TestCase( "99999.49999.9999", true, 0 )] public void checking_extreme_version_ordering( string tag, bool atEnd, int expectedRank ) { var t = CSVersion.TryParse( tag ); if( atEnd ) { Assert.That( t.OrderedVersion - (CSVersion.VeryLastVersion.OrderedVersion - expectedRank), Is.EqualTo( 0 ) ); } else { Assert.That( t.OrderedVersion - (CSVersion.VeryFirstVersion.OrderedVersion + expectedRank), Is.EqualTo( 0 ) ); } var t2 = CSVersion.Create( t.OrderedVersion ); Assert.That( t2.ToString(), Is.EqualTo( t.ToString() ) ); Assert.That( t.Equals( t2 ) ); } [Test] public void checking_version_ordering() { var orderedTags = new[] { "0.0.0-alpha", "0.0.0-alpha.0.1", "0.0.0-alpha.0.2", "0.0.0-alpha.1", "0.0.0-alpha.1.1", "0.0.0-beta", "0.0.0-beta.1", "0.0.0-beta.1.1", "0.0.0-gamma", "0.0.0-gamma.0.1", "0.0.0-gamma.50", "0.0.0-gamma.50.20", "0.0.0-prerelease", "0.0.0-prerelease.0.1", "0.0.0-prerelease.2", "0.0.0-rc", "0.0.0-rc.0.1", "0.0.0-rc.2", "0.0.0-rc.2.58", "0.0.0-rc.3", "0.0.0", "0.0.1", "0.0.2", "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.2", "1.0.0-alpha.2.1", "1.0.0-alpha.3", "1.0.0", "99999.49999.0", "99999.49999.9999-alpha.99", "99999.49999.9999-alpha.99.99", "99999.49999.9999-rc", "99999.49999.9999-rc.0.1", "99999.49999.9999" }; var releasedTags = orderedTags .Select( ( tag, idx ) => new { Tag = tag, Index = idx, ReleasedTag = CSVersion.TryParse( tag ) } ) .Select( s => { Assert.That( s.ReleasedTag.IsValid, s.Tag ); return s; } ); var orderedByFileVersion = releasedTags .OrderBy( s => s.ReleasedTag.OrderedVersion ); var orderedByFileVersionParts = releasedTags .OrderBy( s => s.ReleasedTag.OrderedVersionMajor ) .ThenBy( s => s.ReleasedTag.OrderedVersionMinor ) .ThenBy( s => s.ReleasedTag.OrderedVersionBuild ) .ThenBy( s => s.ReleasedTag.OrderedVersionRevision ); Assert.That( orderedByFileVersion.Select( ( s, idx ) => s.Index - idx ).All( delta => delta == 0 ) ); Assert.That( orderedByFileVersionParts.Select( ( s, idx ) => s.Index - idx ).All( delta => delta == 0 ) ); } // A Major.0.0 can be reached from any major version below. // One can jump to any prerelease of it. [TestCase( "4.0.0, 4.0.0-alpha, 4.0.0-rc", true, "3.0.0, 3.5.44, 3.0.0-alpha, 3.49999.9999-rc.87, 3.0.3-rc.99.99, 3.0.3-alpha.54.99, 3.999.999" )] [TestCase( "4.1.0, 4.1.0-alpha, 4.1.0-rc", false, "3.0.0, 3.5.44, 3.0.0-alpha, 3.49999.9999-rc.87, 3.0.3-rc.99.99, 3.0.3-alpha.54.99, 3.999.999" )] // Same for a minor bump of 1. [TestCase( "4.3.0, 4.3.0-alpha, 4.3.0-rc", true, "4.2.0, 4.2.0-alpha, 4.2.44, 4.2.3-rc.87, 4.2.3-rc.99.99, 4.2.3-rc.5.8, 4.2.3-alpha, 4.2.3-alpha.54.99, 4.2.9999" )] [TestCase( "4.3.0, 4.3.0-rc", true, "4.3.0-alpha, 4.3.0-beta.99.99, 4.3.0-prerelease.99.99" )] // Patch differs: [TestCase( "4.3.2", true, "4.3.1, 4.3.2-alpha, 4.3.2-rc, 4.3.2-rc.99.99" )] [TestCase( "4.3.2", false, "4.3.1-alpha, 4.3.1-rc, 4.3.1-rc.99.99" )] public void checking_some_versions_predecessors( string targets, bool previous, string candidates ) { var targ = targets.Split( ',' ) .Select( v => v.Trim() ) .Where( v => v.Length > 0 ) .Select( v => CSVersion.TryParse( v ) ); var prev = candidates.Split( ',' ) .Select( v => v.Trim() ) .Where( v => v.Length > 0 ) .Select( v => CSVersion.TryParse( v ) ); foreach( var vTarget in targ ) { foreach( var p in prev ) { Assert.That( vTarget.IsDirectPredecessor( p ), Is.EqualTo( previous ), p.ToString() + (previous ? " is a previous of " : " is NOT a previous of ") + vTarget.ToString() ); } } } [TestCase( "0.0.0-alpha", "0.0.0-alpha.0.1" )] [TestCase( "0.0.0-alpha.0.1", "0.0.0-alpha.0.2" )] [TestCase( "0.0.0-rc.99", "0.0.0-rc.99.1" )] [TestCase( "0.0.0-rc.1.99", "" )] [TestCase( "0.0.0", "0.0.1-alpha, 0.0.1-beta, 0.0.1-delta, 0.0.1-epsilon, 0.0.1-gamma, 0.0.1-kappa, 0.0.1-prerelease, 0.0.1-rc, 0.0.1" )] public void checking_next_fixes_and_predecessors( string start, string nextVersions ) { var next = nextVersions.Split( ',' ) .Select( v => v.Trim() ) .Where( v => v.Length > 0 ) .ToArray(); var rStart = CSVersion.TryParse( start ); Assert.That( rStart != null && rStart.IsValid ); // Checks successors (and that they are ordered). var cNext = rStart.GetDirectSuccessors( true ).Select( v => v.ToString() ).ToArray(); CollectionAssert.AreEqual( next, cNext, start + " => " + string.Join( ", ", cNext ) ); Assert.That( rStart.GetDirectSuccessors( true ), Is.Ordered ); // For each successor, check that the start is a predecessor. foreach( var n in rStart.GetDirectSuccessors( true ) ) { Assert.That( n.IsDirectPredecessor( rStart ), "{0} < {1}", rStart, n ); } } [TestCase( 1, 2, 1000 )] [TestCase( -1, 2, 1000 ), Description( "Random seed version." )] public void randomized_checking_of_ordered_versions_mapping_and_extended_successors_and_predecessors( int seed, int count, int span ) { Random r = seed >= 0 ? new Random( seed ) : new Random(); while( --count > 0 ) { long start = (long)decimal.Ceiling( r.NextDecimal() * (CSVersion.VeryLastVersion.OrderedVersion + 1) + 1 ); CSVersion rStart = CheckMapping( start ); Assert.That( rStart, Is.Not.Null ); CSVersion rCurrent; for( int i = 1; i < span; ++i ) { rCurrent = CheckMapping( start + i ); if( rCurrent == null ) break; Assert.That( rStart < rCurrent ); } for( int i = 1; i < span; ++i ) { rCurrent = CheckMapping( start - i ); if( rCurrent == null ) break; Assert.That( rStart > rCurrent ); } } //Console.WriteLine( "Greatest successors count = {0}.", _greatersuccessorCount ); } //static int _greatersuccessorCount = 0; CSVersion CheckMapping( long v ) { if( v < 0 || v > CSVersion.VeryLastVersion.OrderedVersion ) { Assert.Throws<ArgumentException>( () => CSVersion.Create( v ) ); return null; } var t = CSVersion.Create( v ); Assert.That( (v == 0) == !t.IsValid ); Assert.That( t.OrderedVersion, Is.EqualTo( v ) ); var sSemVer = t.NormalizedText; var tSemVer = CSVersion.TryParse( sSemVer ); var tNormalized = CSVersion.TryParse( t.ToString( CSVersionFormat.Normalized ) ); Assert.That( tSemVer.OrderedVersion, Is.EqualTo( v ) ); Assert.That( tNormalized.OrderedVersion, Is.EqualTo( v ) ); Assert.That( tNormalized.Equals( t ) ); Assert.That( tSemVer.Equals( t ) ); Assert.That( tNormalized.Equals( (object)t ) ); Assert.That( tSemVer.Equals( (object)t ) ); Assert.That( tNormalized.CompareTo( t ) == 0 ); Assert.That( tSemVer == t ); Assert.That( tSemVer.ToString(), Is.EqualTo( t.ToString() ) ); Assert.That( tNormalized.ToString(), Is.EqualTo( t.ToString() ) ); // Successors/Predecessors check. var vSemVer = SVersion.Parse( sSemVer ); int count = 0; foreach( var succ in t.GetDirectSuccessors( false ) ) { ++count; Assert.That( succ.IsDirectPredecessor( t ) ); var vSemVerSucc = SVersion.Parse( succ.NormalizedText ); Assert.That( vSemVer < vSemVerSucc, "{0} < {1}", vSemVer, vSemVerSucc ); } //if( count > _greatersuccessorCount ) //{ // Console.WriteLine( " -> - found {0} successors for '{1}':", count, t ); // Console.WriteLine( " " + string.Join( ", ", t.GetDirectSuccessors( false ).Select( s => s.ToString() ) ) ); // var closest = t.GetDirectSuccessors( true ).Select( s => s.ToString() ).ToList(); // Console.WriteLine( " - {0} closest successors:", closest.Count, t ); // Console.WriteLine( " " + string.Join( ", ", closest ) ); // _greatersuccessorCount = count; //} return t; } [Test] public void check_first_possible_versions() { string firstPossibleVersions = @" 0.0.0-alpha, 0.0.0-beta, 0.0.0-delta, 0.0.0-epsilon, 0.0.0-gamma, 0.0.0-kappa, 0.0.0-prerelease, 0.0.0-rc, 0.0.0, 0.1.0-alpha, 0.1.0-beta, 0.1.0-delta, 0.1.0-epsilon, 0.1.0-gamma, 0.1.0-kappa, 0.1.0-prerelease, 0.1.0-rc, 0.1.0, 1.0.0-alpha, 1.0.0-beta, 1.0.0-delta, 1.0.0-epsilon, 1.0.0-gamma, 1.0.0-kappa, 1.0.0-prerelease, 1.0.0-rc, 1.0.0"; var next = firstPossibleVersions.Split( ',' ) .Select( v => v.Trim() ) .Where( v => v.Length > 0 ) .ToArray(); CollectionAssert.AreEqual( next, CSVersion.FirstPossibleVersions.Select( v => v.ToString() ).ToArray() ); } [Test] public void operators_overloads() { // Two variables to avoid Compiler Warning (level 3) CS1718 CSVersion null2 = null; CSVersion null1 = null; Assert.That( null1 == null2 ); Assert.That( null1 >= null2 ); Assert.That( null1 <= null2 ); Assert.That( null1 != null2, Is.False ); Assert.That( null1 > null2, Is.False ); Assert.That( null1 < null2, Is.False ); NullIsAlwaysSmaller( CSVersion.VeryFirstVersion ); NullIsAlwaysSmaller( CSVersion.TryParse( "1.0.0" ) ); NullIsAlwaysSmaller( CSVersion.TryParse( "bug" ) ); } private static void NullIsAlwaysSmaller( CSVersion v ) { Assert.That( null != v ); Assert.That( null == v, Is.False ); Assert.That( null >= v, Is.False ); Assert.That( null <= v ); Assert.That( null > v, Is.False ); Assert.That( null < v ); Assert.That( v != null ); Assert.That( v == null, Is.False ); Assert.That( v >= null ); Assert.That( v <= null, Is.False ); Assert.That( v > null ); Assert.That( v < null, Is.False ); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class RemoveObjListDictionaryTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; ListDictionary ld; // simple string values string[] values = { "", " ", "a", "aA", "text", " SPaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "oNe", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] ListDictionary is constructed as expected //----------------------------------------------------------------- ld = new ListDictionary(); // [] Remove() on empty dictionary // cnt = ld.Count; Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); }); cnt = ld.Count; ld.Remove("some_string"); if (ld.Count != cnt) { Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)")); } cnt = ld.Count; ld.Remove(new Hashtable()); if (ld.Count != cnt) { Assert.False(true, string.Format("Error, changed dictionary after Remove(some_string)")); } // [] add simple strings and Remove() // cnt = ld.Count; int len = values.Length; for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, values.Length)); } // for (int i = 0; i < len; i++) { cnt = ld.Count; ld.Remove(keys[i]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(keys[i])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // Intl strings // [] Add Intl strings and Remove() // string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper()) caseInsensitive = true; } cnt = ld.Count; for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); } if (ld.Count != (cnt + len)) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len)); } for (int i = 0; i < len; i++) { // cnt = ld.Count; ld.Remove(intlValues[i + len]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(intlValues[i + len])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // [] Case sensitivity // string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpper(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLower(); } ld.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // for (int i = 0; i < len; i++) { // uppercase key cnt = ld.Count; ld.Remove(intlValues[i + len]); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, returned: failed to remove item", i)); } if (ld.Contains(intlValues[i + len])) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } ld.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings } // LD is case-sensitive by default for (int i = 0; i < len; i++) { // lowercase key cnt = ld.Count; ld.Remove(intlValuesLower[i + len]); if (!caseInsensitive && ld.Count != cnt) { Assert.False(true, string.Format("Error, failed: removed item using lowercase key", i)); } } // // [] Remove() on LD with case-insensitive comparer // ld = new ListDictionary(new InsensitiveComparer()); len = values.Length; ld.Clear(); string kk = "key"; for (int i = 0; i < len; i++) { ld.Add(kk + i, values[i]); } if (ld.Count != len) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len)); } for (int i = 0; i < len; i++) { cnt = ld.Count; ld.Remove(kk.ToUpper() + i); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, failed to remove item", i)); } if (ld.Contains(kk + i)) { Assert.False(true, string.Format("Error, removed wrong item", i)); } } // // [] Remove(null) // ld = new ListDictionary(); cnt = ld.Count; if (ld.Count < len) { ld.Clear(); for (int i = 0; i < len; i++) { ld.Add(keys[i], values[i]); } } Assert.Throws<ArgumentNullException>(() => { ld.Remove(null); }); ld = new ListDictionary(); ld.Clear(); ArrayList b = new ArrayList(); ArrayList b1 = new ArrayList(); Hashtable lbl = new Hashtable(); Hashtable lbl1 = new Hashtable(); ld.Add(lbl, b); ld.Add(lbl1, b1); if (ld.Count != 2) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2)); } cnt = ld.Count; ld.Remove(lbl); if (ld.Count != cnt - 1) { Assert.False(true, string.Format("Error, failed to remove special object")); } if (ld.Contains(lbl)) { Assert.False(true, string.Format("Error, removed wrong special object")); } } } }
// 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 Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpMarkMembersAsStaticFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.QualityGuidelines.MarkMembersAsStaticAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicMarkMembersAsStaticFixer>; namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests { public class MarkMembersAsStaticFixerTests { [Fact] public async Task TestCSharp_SimpleMembers_NoReferences() { await VerifyCS.VerifyCodeFixAsync(@" public class MembersTests { internal static int s_field; public const int Zero = 0; public int [|Method1|](string name) { return name.Length; } public void [|Method2|]() { } public void [|Method3|]() { s_field = 4; } public int [|Method4|]() { return Zero; } public int [|Property|] { get { return 5; } } public int [|Property2|] { set { s_field = value; } } public int [|MyProperty|] { get { return 10; } set { System.Console.WriteLine(value); } } public event System.EventHandler<System.EventArgs> [|CustomEvent|] { add {} remove {} } }", @" public class MembersTests { internal static int s_field; public const int Zero = 0; public static int Method1(string name) { return name.Length; } public static void Method2() { } public static void Method3() { s_field = 4; } public static int Method4() { return Zero; } public static int Property { get { return 5; } } public static int Property2 { set { s_field = value; } } public static int MyProperty { get { return 10; } set { System.Console.WriteLine(value); } } public static event System.EventHandler<System.EventArgs> CustomEvent { add {} remove {} } }"); } [Fact] public async Task TestBasic_SimpleMembers_NoReferences() { await VerifyVB.VerifyCodeFixAsync(@" Imports System Public Class MembersTests Shared s_field As Integer Public Const Zero As Integer = 0 Public Function [|Method1|](name As String) As Integer Return name.Length End Function Public Sub [|Method2|]() End Sub Public Sub [|Method3|]() s_field = 4 End Sub Public Function [|Method4|]() As Integer Return Zero End Function Public Property [|MyProperty|] As Integer Get Return 10 End Get Set System.Console.WriteLine(Value) End Set End Property Public Custom Event [|CustomEvent|] As EventHandler(Of EventArgs) AddHandler(value As EventHandler(Of EventArgs)) End AddHandler RemoveHandler(value As EventHandler(Of EventArgs)) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class", @" Imports System Public Class MembersTests Shared s_field As Integer Public Const Zero As Integer = 0 Public Shared Function Method1(name As String) As Integer Return name.Length End Function Public Shared Sub Method2() End Sub Public Shared Sub Method3() s_field = 4 End Sub Public Shared Function Method4() As Integer Return Zero End Function Public Shared Property MyProperty As Integer Get Return 10 End Get Set System.Console.WriteLine(Value) End Set End Property Public Shared Custom Event CustomEvent As EventHandler(Of EventArgs) AddHandler(value As EventHandler(Of EventArgs)) End AddHandler RemoveHandler(value As EventHandler(Of EventArgs)) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class"); } [Fact] public async Task TestCSharp_ReferencesInSameType_MemberReferences() { await VerifyCS.VerifyCodeFixAsync(@" using System; public class C { private C fieldC; private C PropertyC { get; set; } public int [|M1|]() { return 0; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = M1, m2 = paramC.M1, m3 = localC.M1, m4 = fieldC.M1, m5 = PropertyC.M1, m6 = fieldC.PropertyC.M1, m7 = this.M1; } }", @" using System; public class C { private C fieldC; private C PropertyC { get; set; } public static int M1() { return 0; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = M1, m2 = M1, m3 = M1, m4 = M1, m5 = M1, m6 = M1, m7 = M1; } }"); } [Fact] public async Task TestBasic_ReferencesInSameType_MemberReferences() { await VerifyVB.VerifyCodeFixAsync(@" Imports System Public Class C Private fieldC As C Private Property PropertyC As C Public Function [|M1|]() As Integer Return 0 End Function Public Sub M2(paramC As C) Dim localC = fieldC Dim m As Func(Of Integer) = AddressOf M1, m2 As Func(Of Integer) = AddressOf paramC.M1, m3 As Func(Of Integer) = AddressOf localC.M1, m4 As Func(Of Integer) = AddressOf fieldC.M1, m5 As Func(Of Integer) = AddressOf PropertyC.M1, m6 As Func(Of Integer) = AddressOf fieldC.PropertyC.M1, m7 As Func(Of Integer) = AddressOf Me.M1 End Sub End Class", @" Imports System Public Class C Private fieldC As C Private Property PropertyC As C Public Shared Function M1() As Integer Return 0 End Function Public Sub M2(paramC As C) Dim localC = fieldC Dim m As Func(Of Integer) = AddressOf M1, m2 As Func(Of Integer) = AddressOf M1, m3 As Func(Of Integer) = AddressOf M1, m4 As Func(Of Integer) = AddressOf M1, m5 As Func(Of Integer) = AddressOf M1, m6 As Func(Of Integer) = AddressOf M1, m7 As Func(Of Integer) = AddressOf M1 End Sub End Class"); } [Fact] public async Task TestCSharp_ReferencesInSameType_Invocations() { await VerifyCS.VerifyCodeFixAsync(@" public class C { private int x; private C fieldC; private C PropertyC { get; set; } private static C staticFieldC; private static C StaticPropertyC { get; set; } public int [|M1|]() { return 0; } public void M2(C paramC) { var localC = fieldC; x = M1() + paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1() + this.M1() + C.staticFieldC.M1() + StaticPropertyC.M1(); } }", @" public class C { private int x; private C fieldC; private C PropertyC { get; set; } private static C staticFieldC; private static C StaticPropertyC { get; set; } public static int M1() { return 0; } public void M2(C paramC) { var localC = fieldC; x = M1() + M1() + M1() + M1() + M1() + M1() + M1() + M1() + M1(); } }"); } [Fact] public async Task TestBasic_ReferencesInSameType_Invocations() { await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private x As Integer Private fieldC As C Private Property PropertyC As C Public Function [|M1|]() As Integer Return 0 End Function Public Sub M2(paramC As C) Dim localC = fieldC x = M1() + paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1() + Me.M1() End Sub End Class", @" Public Class C Private x As Integer Private fieldC As C Private Property PropertyC As C Public Shared Function M1() As Integer Return 0 End Function Public Sub M2(paramC As C) Dim localC = fieldC x = M1() + M1() + M1() + M1() + M1() + M1() + M1() End Sub End Class"); } [Fact] public async Task TestCSharp_ReferencesInSameFile_MemberReferences() { await VerifyCS.VerifyCodeFixAsync(@" using System; public class C { public C PropertyC { get; set; } public int [|M1|]() { return 0; } } class C2 { private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = paramC.M1, m2 = localC.M1, m3 = fieldC.M1, m4 = PropertyC.M1, m5 = fieldC.PropertyC.M1; } }", @" using System; public class C { public C PropertyC { get; set; } public static int M1() { return 0; } } class C2 { private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = C.M1, m2 = C.M1, m3 = C.M1, m4 = C.M1, m5 = C.M1; } }"); } [Fact] public async Task TestCSharp_ReferencesInSameFile_Invocations() { await VerifyCS.VerifyCodeFixAsync(@" using System; public class C { public C PropertyC { get; set; } public int [|M1|]() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1(); } }", @" using System; public class C { public C PropertyC { get; set; } public static int M1() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1(); } }"); } [Fact] public async Task TestCSharp_ReferencesInMultipleFiles_MemberReferences() { await new VerifyCS.Test { TestState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public int [|M1|]() { return 0; } } class C2 { private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = paramC.M1, m2 = localC.M1, m3 = fieldC.M1, m4 = PropertyC.M1, m5 = fieldC.PropertyC.M1; } }", @" using System; class C3 { private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; Func<int> m1 = paramC.M1, m2 = localC.M1, m3 = fieldC.M1, m4 = PropertyC.M1, m5 = fieldC.PropertyC.M1; } }", }, }, FixedState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public static int M1() { return 0; } } class C2 { private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; Func<int> m1 = C.M1, m2 = C.M1, m3 = C.M1, m4 = C.M1, m5 = C.M1; } }", @" using System; class C3 { private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; Func<int> m1 = C.M1, m2 = C.M1, m3 = C.M1, m4 = C.M1, m5 = C.M1; } }", }, }, }.RunAsync(); } [Fact] public async Task TestCSharp_ReferencesInMultipleFiles_Invocations() { await new VerifyCS.Test { TestState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public int [|M1|]() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1(); } }", @" using System; class C3 { private int x; private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; x = paramC.M1() + localC.M1() + fieldC.M1() + PropertyC.M1() + fieldC.PropertyC.M1(); } }", }, }, FixedState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public static int M1() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1(); } }", @" using System; class C3 { private int x; private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; x = C.M1() + C.M1() + C.M1() + C.M1() + C.M1(); } }", }, }, }.RunAsync(); } [Fact] public async Task TestCSharp_ReferenceInArgument() { await VerifyCS.VerifyCodeFixAsync(@" public class C { private C fieldC; public C [|M1|](C c) { return c; } public C M2(C paramC) { var localC = fieldC; return this.M1(paramC.M1(localC)); } }", @" public class C { private C fieldC; public static C M1(C c) { return c; } public C M2(C paramC) { var localC = fieldC; return M1(M1(localC)); } }"); } [Fact] public async Task TestBasic_ReferenceInArgument() { await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private fieldC As C Public Function [|M1|](c As C) As C Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return Me.M1(paramC.M1(localC)) End Function End Class", @" Public Class C Private fieldC As C Public Shared Function M1(c As C) As C Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return M1(M1(localC)) End Function End Class"); } [Fact] public async Task TestCSharp_GenericMethod() { await VerifyCS.VerifyCodeFixAsync(@" public class C { private C fieldC; public C [|M1|]<T>(C c, T t) { return c; } public C M1<T>(T t, int i) { return fieldC; } } public class C2<T2> { private C fieldC; public void M2(C paramC) { // Explicit type argument paramC.M1<int>(fieldC, 0); // Implicit type argument paramC.M1(fieldC, this); } }", @" public class C { private C fieldC; public static C M1<T>(C c, T t) { return c; } public C M1<T>(T t, int i) { return fieldC; } } public class C2<T2> { private C fieldC; public void M2(C paramC) { // Explicit type argument C.M1(fieldC, 0); // Implicit type argument C.M1(fieldC, this); } }"); } [Fact] public async Task TestCSharp_GenericMethod_02() { await VerifyCS.VerifyCodeFixAsync(@" public class C { private C fieldC; public C [|M1|]<T>(C c) { return c; } public C M1<T>(T t) { return fieldC; } } public class C2<T2> { private C fieldC; public void M2(C paramC) { // Explicit type argument paramC.M1<int>(fieldC); } }", @" public class C { private C fieldC; public static C M1<T>(C c) { return c; } public C M1<T>(T t) { return fieldC; } } public class C2<T2> { private C fieldC; public void M2(C paramC) { // Explicit type argument C.M1<int>(fieldC); } }"); } [Fact] public async Task TestBasic_GenericMethod() { await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private fieldC As C Public Function [|M1|](Of T)(c As C, t1 As T) As C Return c End Function Public Function M1(Of T)(t1 As T, i As Integer) As C Return fieldC End Function End Class Public Class C2(Of T2) Private fieldC As C Public Sub M2(paramC As C) ' Explicit type argument paramC.M1(Of Integer)(fieldC, 0) ' Implicit type argument paramC.M1(fieldC, Me) End Sub End Class", @" Public Class C Private fieldC As C Public Shared Function M1(Of T)(c As C, t1 As T) As C Return c End Function Public Function M1(Of T)(t1 As T, i As Integer) As C Return fieldC End Function End Class Public Class C2(Of T2) Private fieldC As C Public Sub M2(paramC As C) ' Explicit type argument C.M1(Of Integer)(fieldC, 0) ' Implicit type argument C.M1(fieldC, Me) End Sub End Class"); } [Fact] public async Task TestCSharp_InvocationInInstance() { // We don't make the replacement if instance has an invocation. await new VerifyCS.Test { TestState = { Sources = { @" public class C { private C fieldC; public C [|M1|](C c) { return c; } public C M2(C paramC) { var localC = fieldC; return localC.M1(paramC).M1(paramC.M1(localC)); } }", }, }, FixedState = { Sources = { @" public class C { private C fieldC; public static C M1(C c) { return c; } public C M2(C paramC) { var localC = fieldC; return {|CS0176:M1(paramC).M1|}(M1(localC)); } }", }, }, }.RunAsync(); } [Fact] public async Task TestBasic_InvocationInInstance() { // We don't make the replacement if instance has an invocation. await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private fieldC As C Public Function [|M1|](c As C) As C Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return localC.M1(paramC).M1(paramC.M1(localC)) End Function End Class", @" Public Class C Private fieldC As C Public Shared Function M1(c As C) As C Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return M1(paramC).M1(M1(localC)) End Function End Class"); } [Fact] public async Task TestCSharp_ConversionInInstance() { // We don't make the replacement if instance has a conversion. await new VerifyCS.Test { TestState = { Sources = { @" public class C { private C fieldC; public object [|M1|](C c) { return c; } public C M2(C paramC) { var localC = fieldC; return {|CS0266:((C)paramC).M1(localC)|}; } }" }, }, FixedState = { Sources = { @" public class C { private C fieldC; public static object M1(C c) { return c; } public C M2(C paramC) { var localC = fieldC; return {|CS0176:((C)paramC).M1|}(localC); } }", }, }, }.RunAsync(); } [Fact] public async Task TestBasic_ConversionInInstance() { // We don't make the replacement if instance has a conversion. await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private fieldC As C Public Function [|M1|](c As C) As Object Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return (CType(paramC, C)).M1(localC) End Function End Class", @" Public Class C Private fieldC As C Public Shared Function M1(c As C) As Object Return c End Function Public Function M2(paramC As C) As C Dim localC = fieldC Return (CType(paramC, C)).M1(localC) End Function End Class"); } [Fact] public async Task TestCSharp_FixAll() { await new VerifyCS.Test { TestState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public int [|M1|]() { return 0; } public int [|M2|]() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = paramC.M1() + localC.M2() + fieldC.M1() + PropertyC.M2() + fieldC.PropertyC.M1(); } }", @" using System; class C3 { private int x; private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; x = paramC.M2() + localC.M1() + fieldC.M2() + PropertyC.M1() + fieldC.PropertyC.M2(); } }", }, }, FixedState = { Sources = { @" using System; public class C { public C PropertyC { get; set; } public static int M1() { return 0; } public static int M2() { return 0; } } class C2 { private int x; private C fieldC; private C PropertyC { get; set; } public void M2(C paramC) { var localC = fieldC; x = C.M1() + C.M2() + C.M1() + C.M2() + C.M1(); } }", @" using System; class C3 { private int x; private C fieldC; private C PropertyC { get; set; } public void M3(C paramC) { var localC = fieldC; x = C.M2() + C.M1() + C.M2() + C.M1() + C.M2(); } }", }, }, }.RunAsync(); } [Fact] public async Task TestBasic_FixAll() { await new VerifyVB.Test { TestState = { Sources = { @" Imports System Public Class C Public Property PropertyC As C Public Function [|M1|]() As Integer Return 0 End Function Public Function [|M2|]() As Integer Return 0 End Function End Class Class C2 Private x As Integer Private fieldC As C Private Property PropertyC As C Public Sub M2(paramC As C) Dim localC = fieldC x = paramC.M1() + localC.M2() + fieldC.M1() + PropertyC.M2() + fieldC.PropertyC.M1() End Sub End Class", @" Imports System Class C3 Private x As Integer Private fieldC As C Private Property PropertyC As C Public Sub M3(paramC As C) Dim localC = fieldC x = paramC.M2() + localC.M1() + fieldC.M2() + PropertyC.M1() + fieldC.PropertyC.M2() End Sub End Class", }, }, FixedState = { Sources = { @" Imports System Public Class C Public Property PropertyC As C Public Shared Function M1() As Integer Return 0 End Function Public Shared Function M2() As Integer Return 0 End Function End Class Class C2 Private x As Integer Private fieldC As C Private Property PropertyC As C Public Sub M2(paramC As C) Dim localC = fieldC x = C.M1() + C.M2() + C.M1() + C.M2() + C.M1() End Sub End Class", @" Imports System Class C3 Private x As Integer Private fieldC As C Private Property PropertyC As C Public Sub M3(paramC As C) Dim localC = fieldC x = C.M2() + C.M1() + C.M2() + C.M1() + C.M2() End Sub End Class", }, }, }.RunAsync(); } [Fact] public async Task TestCSharp_PropertyWithReferences() { await VerifyCS.VerifyCodeFixAsync(@" public class C { private C fieldC; public C [|M1|] { get { return null; } set { } } public C M2(C paramC) { var x = this.M1; paramC.M1 = x; return fieldC; } }", @" public class C { private C fieldC; public static C M1 { get { return null; } set { } } public C M2(C paramC) { var x = M1; M1 = x; return fieldC; } }"); } [Fact] public async Task TestBasic_PropertyWithReferences() { await VerifyVB.VerifyCodeFixAsync(@" Public Class C Private fieldC As C Public Property [|M1|] As C Get Return Nothing End Get Set(ByVal value As C) End Set End Property Public Function M2(paramC As C) As C Dim x = Me.M1 paramC.M1 = x Return fieldC End Function End Class", @" Public Class C Private fieldC As C Public Shared Property M1 As C Get Return Nothing End Get Set(ByVal value As C) End Set End Property Public Function M2(paramC As C) As C Dim x = M1 M1 = x Return fieldC End Function End Class"); } [Fact, WorkItem(2888, "https://github.com/dotnet/roslyn-analyzers/issues/2888")] public async Task CA1822_CSharp_AsyncModifier() { await VerifyCS.VerifyCodeFixAsync(@" using System.Threading.Tasks; public class C { public async Task<int> [|M1|]() { await Task.Delay(20).ConfigureAwait(false); return 20; } }", @" using System.Threading.Tasks; public class C { public static async Task<int> M1() { await Task.Delay(20).ConfigureAwait(false); return 20; } }"); await VerifyVB.VerifyCodeFixAsync(@" Imports System.Threading.Tasks Public Class C Public Async Function [|M1|]() As Task(Of Integer) Await Task.Delay(20).ConfigureAwait(False) Return 20 End Function End Class", @" Imports System.Threading.Tasks Public Class C Public Shared Async Function M1() As Task(Of Integer) Await Task.Delay(20).ConfigureAwait(False) Return 20 End Function End Class"); } } }
using Signum.Entities; using Signum.Entities.Authorization; using Signum.Entities.Basics; using Signum.Entities.UserAssets; using Signum.Utilities; using System; using System.ComponentModel; using System.Linq.Expressions; using System.Xml.Linq; namespace Signum.Entities.Workflow { [Serializable, EntityKind(EntityKind.Main, EntityData.Master)] public class WorkflowEntity : Entity, IUserAssetEntity { [UniqueIndex] [StringLengthValidator(Min = 3, Max = 100)] public string Name { get; set; } public TypeEntity MainEntityType { get; set; } public MList<WorkflowMainEntityStrategy> MainEntityStrategies { get; set; } = new MList<WorkflowMainEntityStrategy>(); public DateTime? ExpirationDate { get; set; } /// <summary> /// REDUNDANT! Only for diff logging /// </summary> [InTypeScript(false), AvoidDump] public WorkflowXmlEmbedded? FullDiagramXml { get; set; } [UniqueIndex] public Guid Guid { get; set; } = Guid.NewGuid(); public XElement ToXml(IToXmlContext ctx) { return ctx.GetFullWorkflowElement(this); } public void FromXml(XElement element, IFromXmlContext ctx) { ctx.SetFullWorkflowElement(this, element); } [AutoExpressionField] public override string ToString() => As.Expression(() => Name); } [AutoInit] public static class WorkflowOperation { public static readonly ConstructSymbol<WorkflowEntity>.Simple Create; public static readonly ConstructSymbol<WorkflowEntity>.From<WorkflowEntity> Clone; public static readonly ExecuteSymbol<WorkflowEntity> Save; public static readonly DeleteSymbol<WorkflowEntity> Delete; public static readonly ExecuteSymbol<WorkflowEntity> Activate; public static readonly ExecuteSymbol<WorkflowEntity> Deactivate; } [InTypeScript(true)] public enum WorkflowMainEntityStrategy { CreateNew, SelectByUser, Clone, } [InTypeScript(true), DescriptionOptions(DescriptionOptions.Members)] public enum WorkflowIssueType { Warning, Error, } [Serializable] public class WorkflowModel : ModelEntity { public string DiagramXml { get; set; } public MList<BpmnEntityPairEmbedded> Entities { get; set; } = new MList<BpmnEntityPairEmbedded>(); } [Serializable] public class BpmnEntityPairEmbedded : EmbeddedEntity { [ImplementedBy()] public ModelEntity Model { get; set; } public string BpmnElementId { get; set; } public override string ToString() { return $"{BpmnElementId} -> {Model}"; } } public interface IWithModel { ModelEntity GetModel(); void SetModel(ModelEntity model); } public enum WorkflowMessage { [Description("'{0}' belongs to a different workflow")] _0BelongsToADifferentWorkflow, [Description("Condition '{0}' is defined for '{1}' not '{2}'")] Condition0IsDefinedFor1Not2, JumpsToSameActivityNotAllowed, [Description("Jump to '{0}' failed because '{1}'")] JumpTo0FailedBecause1, [Description("To use '{0}', you should save workflow")] ToUse0YouSouldSaveWorkflow, [Description("To use new nodes on jumps, you should save workflow")] ToUseNewNodesOnJumpsYouSouldSaveWorkflow, [Description("To use '{0}', you should set the workflow '{1}'")] ToUse0YouSouldSetTheWorkflow1, [Description("Change workflow main entity type is not allowed because we have nodes that use it.")] ChangeWorkflowMainEntityTypeIsNotAllowedBecauseWeHaveNodesThatUseIt, [Description("Workflow uses in {0} for decomposition or call workflow.")] WorkflowUsedIn0ForDecompositionOrCallWorkflow, [Description("Workflow '{0}' already activated.")] Workflow0AlreadyActivated, [Description("Workflow '{0}' has expired on '{1}'.")] Workflow0HasExpiredOn1, HasExpired, DeactivateWorkflow, PleaseChooseExpirationDate, ResetZoom, [Description("Color: ")] Color, [Description("Workflow Issues")] WorkflowIssues, WorkflowProperties, [Description("{0} not allowed for {1} (no constructor has been defined in 'WithWorkflow')")] _0NotAllowedFor1NoConstructorHasBeenDefinedInWithWorkflow, [Description("You are not member of any lane containing an Start event in workflow '{0}'")] YouAreNotMemberOfAnyLaneContainingAnStartEventInWorkflow0, } [Serializable] public class WorkflowXmlEmbedded : EmbeddedEntity { [StringLengthValidator(Min = 3, Max = int.MaxValue, MultiLine = true)] public string DiagramXml { get; set; } public XElement ToXml() { return new XElement("DiagramXml", new XCData(this.DiagramXml)); } } public interface IWorkflowObjectEntity : IEntity { WorkflowXmlEmbedded Xml { get; set; } string? GetName(); string BpmnElementId { get; set; } } public interface IWorkflowNodeEntity : IWorkflowObjectEntity { WorkflowLaneEntity Lane { get; set; } } [Serializable] public class WorkflowReplacementModel: ModelEntity { public MList<WorkflowReplacementItemEmbedded> Replacements { get; set; } = new MList<WorkflowReplacementItemEmbedded>(); public MList<NewTasksEmbedded> NewTasks { get; set; } = new MList<NewTasksEmbedded>(); public override string ToString() { return NicePropertyName(()=> Replacements) + ": " + Replacements.Count; } } [Serializable] public class NewTasksEmbedded : EmbeddedEntity { public string BpmnId { get; set; } public string? Name { get; set; } public Lite<WorkflowEntity>? SubWorkflow { get; set; } } [Serializable] public class WorkflowReplacementItemEmbedded : EmbeddedEntity { [ImplementedBy(typeof(WorkflowActivityEntity), typeof(WorkflowEventEntity))] public Lite<IWorkflowNodeEntity> OldNode { get; set; } public Lite<WorkflowEntity>? SubWorkflow { get; set; } public string NewNode { get; set; } } public class WorkflowTransitionContext { public WorkflowTransitionContext(CaseEntity? @case, CaseActivityEntity? previous, WorkflowConnectionEntity? conn) { this.Case = @case; this.PreviousCaseActivity = previous; this.Connection = conn; } public CaseActivityEntity? PreviousCaseActivity { get; internal set; } public WorkflowConnectionEntity? Connection { get; internal set; } public CaseEntity? Case { get; set; } public Action<CaseActivityEntity>? OnNextCaseActivityCreated; } public enum WorkflowValidationMessage { [Description("Node type {0} with Id {1} is invalid.")] NodeType0WithId1IsInvalid, [Description("Participants and Processes are not synchronized.")] ParticipantsAndProcessesAreNotSynchronized, [Description("Multiple start events are not allowed.")] MultipleStartEventsAreNotAllowed, [Description("Start event is required. Each workflow could have one and only one start event.")] SomeStartEventIsRequired, [Description("Normal start event is required when the '{0}' are '{1}' or '{2}'.")] NormalStartEventIsRequiredWhenThe0Are1Or2, [Description("The following tasks are going to be deleted :")] TheFollowingTasksAreGoingToBeDeleted, FinishEventIsRequired, [Description("'{0}' has inputs.")] _0HasInputs, [Description("'{0}' has outputs.")] _0HasOutputs, [Description("'{0}' has no inputs.")] _0HasNoInputs, [Description("'{0}' has no outputs.")] _0HasNoOutputs, [Description("'{0}' has just one input and one output.")] _0HasJustOneInputAndOneOutput, [Description("'{0}' has multiple outputs.")] _0HasMultipleOutputs, IsNotInWorkflow, [Description("Activity '{0}' can not jump to '{1}' because '{2}'.")] Activity0CanNotJumpTo1Because2, [Description("Activity '{0}' can not timeout to '{1}' because '{2}'.")] Activity0CanNotTimeoutTo1Because2, IsStart, IsSelfJumping, IsInDifferentParallelTrack, [Description("'{0}' (Track {1}) can not be connected to '{2}' (Track {3} instead of Track {4}).")] _0Track1CanNotBeConnectedTo2Track3InsteadOfTrack4, StartEventNextNodeShouldBeAnActivity, ParallelGatewaysShouldPair, TimerOrConditionalStartEventsCanNotGoToJoinGateways, [Description("Inclusive Gateway '{0}' should have one default connection without condition.")] InclusiveGateway0ShouldHaveOneConnectionWithoutCondition, [Description("Gateway '{0}' should has condition or decision on each output except the last one.")] Gateway0ShouldHasConditionOrDecisionOnEachOutputExceptTheLast, [Description("'{0}' can not be connected to a parallel join because has no previous parallel split.")] _0CanNotBeConnectedToAParallelJoinBecauseHasNoPreviousParallelSplit, [Description("Activity '{0}' with decision type should go to an exclusive or inclusive gateways.")] Activity0WithDecisionTypeShouldGoToAnExclusiveOrInclusiveGateways, [Description("Activity '{0}' should be decision.")] Activity0ShouldBeDecision, [Description("'{0}' is timer start and scheduler is mandatory.")] _0IsTimerStartAndSchedulerIsMandatory, [Description("'{0}' is timer start and task is mandatory.")] _0IsTimerStartAndTaskIsMandatory, [Description("'{0}' is conditional start and condition is mandatory.")] _0IsConditionalStartAndTaskConditionIsMandatory, DelayActivitiesShouldHaveExactlyOneInterruptingTimer, [Description("Activity '{0}' of type '{1}' should have exactly one connection of type '{2}'.")] Activity0OfType1ShouldHaveExactlyOneConnectionOfType2, [Description("Activity '{0}' of type '{1}' can not have connections of type '{2}'.")] Activity0OfType1CanNotHaveConnectionsOfType2, [Description("Boundary timer '{0}' of activity '{1}' should have exactly one connection of type '{2}'.")] BoundaryTimer0OfActivity1ShouldHaveExactlyOneConnectionOfType2, [Description("Intermediate timer '{0}' should have one output of type '{1}'.")] IntermediateTimer0ShouldHaveOneOutputOfType1, [Description("Intermediate timer '{0}' should have name.")] IntermediateTimer0ShouldHaveName, [Description("Parallel Split '{0}' should have at least one connection.")] ParallelSplit0ShouldHaveAtLeastOneConnection, [Description("Parallel Split '{0}' should have only normal connections without conditions.")] ParallelSplit0ShouldHaveOnlyNormalConnectionsWithoutConditions, [Description("Join '{0}' (of type {1}) does not match with its pair, the Split '{2}' (of type {3})")] Join0OfType1DoesNotMatchWithItsPairTheSplit2OfType3, [Description("Decision option '{0}' is declared but never used in a connection")] DecisionOption0IsDeclaredButNeverUsedInAConnection, [Description("Decision option name '{0}' is not declared in any activity")] DecisionOptionName0IsNotDeclaredInAnyActivity, } public enum WorkflowActivityMonitorMessage { WorkflowActivityMonitor, Draw, ResetZoom, Find, Filters, Columns } [AutoInit] public static class WorkflowPermission { public static PermissionSymbol ViewWorkflowPanel; public static PermissionSymbol ViewCaseFlow; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using sly.buildresult; using sly.i18n; using sly.lexer; using sly.lexer.fsm; using sly.parser.generator.visitor; using sly.parser.llparser; using sly.parser.parser; using sly.parser.syntax.grammar; namespace sly.parser.generator { public delegate BuildResult<Parser<IN, OUT>> ParserChecker<IN, OUT>(BuildResult<Parser<IN, OUT>> result, NonTerminal<IN> nonterminal) where IN : struct; /// <summary> /// this class provides API to build parser /// </summary> public class ParserBuilder<IN, OUT> where IN : struct { #region API public string I18n { get; set; } public ParserBuilder(string i18n) { if (string.IsNullOrEmpty(i18n)) { i18n = CultureInfo.CurrentCulture.TwoLetterISOLanguageName; } I18n = i18n; } public ParserBuilder() : this(null) { } /// <summary> /// Builds a parser (lexer, syntax parser and syntax tree visitor) according to a parser definition instance /// </summary> /// <typeparam name="IN"></typeparam> /// <param name="parserInstance"> /// a parser definition instance , containing /// [Reduction] methods for grammar rules /// <param name="parserType"> /// a ParserType enum value stating the analyser type (LR, LL ...) for now only LL recurive /// descent parser available /// </param> /// <param name="rootRule">the name of the root non terminal of the grammar</param> /// <returns></returns> public virtual BuildResult<Parser<IN, OUT>> BuildParser(object parserInstance, ParserType parserType, string rootRule, BuildExtension<IN> extensionBuilder = null, LexerPostProcess<IN> lexerPostProcess = null) { Parser<IN, OUT> parser = null; var result = new BuildResult<Parser<IN, OUT>>(); if (parserType == ParserType.LL_RECURSIVE_DESCENT) { var configuration = ExtractParserConfiguration(parserInstance.GetType()); var (foundRecursion, recursions) = LeftRecursionChecker<IN,OUT>.CheckLeftRecursion(configuration); if (foundRecursion) { var recs = string.Join("\n", recursions.Select(x => string.Join(" > ",x))); result.AddError(new ParserInitializationError(ErrorLevel.FATAL, I18N.Instance.GetText(I18n,Message.LeftRecursion, recs), ErrorCodes.PARSER_LEFT_RECURSIVE)); return result; } configuration.StartingRule = rootRule; var syntaxParser = BuildSyntaxParser(configuration, parserType, rootRule); var visitor = new SyntaxTreeVisitor<IN, OUT>(configuration, parserInstance); parser = new Parser<IN, OUT>(I18n,syntaxParser, visitor); var lexerResult = BuildLexer(extensionBuilder, lexerPostProcess); parser.Lexer = lexerResult.Result; if (lexerResult.IsError) { result.Errors.AddRange(lexerResult.Errors); return result; } parser.Instance = parserInstance; parser.Configuration = configuration; result.Result = parser; } else if (parserType == ParserType.EBNF_LL_RECURSIVE_DESCENT) { var builder = new EBNFParserBuilder<IN, OUT>(I18n); result = builder.BuildParser(parserInstance, ParserType.EBNF_LL_RECURSIVE_DESCENT, rootRule, extensionBuilder,lexerPostProcess); } parser = result.Result; if (!result.IsError) { var expressionResult = parser.BuildExpressionParser(result, rootRule); if (expressionResult.IsError) result.AddErrors(expressionResult.Errors); result.Result.Configuration = expressionResult.Result; result = CheckParser(result); if (result.IsError) { result.Result = null; } } else { result.Result = null; } return result; } protected virtual ISyntaxParser<IN, OUT> BuildSyntaxParser(ParserConfiguration<IN, OUT> conf, ParserType parserType, string rootRule) { ISyntaxParser<IN, OUT> parser = null; switch (parserType) { case ParserType.LL_RECURSIVE_DESCENT: { parser = new RecursiveDescentSyntaxParser<IN, OUT>(conf, rootRule,I18n); break; } default: { parser = null; break; } } return parser; } #endregion #region CONFIGURATION private Tuple<string, string> ExtractNTAndRule(string ruleString) { Tuple<string, string> result = null; if (ruleString != null) { var nt = ""; var rule = ""; var i = ruleString.IndexOf(":"); if (i > 0) { nt = ruleString.Substring(0, i).Trim(); rule = ruleString.Substring(i + 1); result = new Tuple<string, string>(nt, rule); } } return result; } protected virtual BuildResult<ILexer<IN>> BuildLexer(BuildExtension<IN> extensionBuilder = null, LexerPostProcess<IN> lexerPostProcess = null) { var lexer = LexerBuilder.BuildLexer(new BuildResult<ILexer<IN>>(), extensionBuilder, I18n, lexerPostProcess); return lexer; } protected virtual ParserConfiguration<IN, OUT> ExtractParserConfiguration(Type parserClass) { var conf = new ParserConfiguration<IN, OUT>(); var functions = new Dictionary<string, MethodInfo>(); var nonTerminals = new Dictionary<string, NonTerminal<IN>>(); var methods = parserClass.GetMethods().ToList(); methods = methods.Where(m => { var attributes = m.GetCustomAttributes().ToList(); var attr = attributes.Find(a => a.GetType() == typeof(ProductionAttribute)); return attr != null; }).ToList(); parserClass.GetMethods(); methods.ForEach(m => { var attributes = (ProductionAttribute[]) m.GetCustomAttributes(typeof(ProductionAttribute), true); foreach (var attr in attributes) { var ntAndRule = ExtractNTAndRule(attr.RuleString); var r = BuildNonTerminal(ntAndRule); r.SetVisitor(m); r.NonTerminalName = ntAndRule.Item1; var key = ntAndRule.Item1 + "__" + r.Key; functions[key] = m; NonTerminal<IN> nonT = null; if (!nonTerminals.ContainsKey(ntAndRule.Item1)) nonT = new NonTerminal<IN>(ntAndRule.Item1, new List<Rule<IN>>()); else nonT = nonTerminals[ntAndRule.Item1]; nonT.Rules.Add(r); nonTerminals[ntAndRule.Item1] = nonT; } }); conf.NonTerminals = nonTerminals; return conf; } private Rule<IN> BuildNonTerminal(Tuple<string, string> ntAndRule) { var rule = new Rule<IN>(); rule.RuleString = $"{ntAndRule.Item1} : {ntAndRule.Item2}"; var clauses = new List<IClause<IN>>(); var ruleString = ntAndRule.Item2; var clausesString = ruleString.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); foreach (var item in clausesString) { IClause<IN> clause = null; var isTerminal = false; var token = default(IN); try { var tIn = typeof(IN); var b = Enum.TryParse(item, out token); if (b) { isTerminal = true; } //token = (IN)Enum.Parse(tIn , item); //isTerminal = true; } catch (ArgumentException) { isTerminal = false; } if (isTerminal) { clause = new TerminalClause<IN>(token); } else if (item == "[d]") { if (clauses.Last() is TerminalClause<IN> discardedTerminal) discardedTerminal.Discarded = true; } else { clause = new NonTerminalClause<IN>(item); } if (clause != null) clauses.Add(clause); } rule.Clauses = clauses; //rule.Key = ntAndRule.Item1 + "_" + ntAndRule.Item2.Replace(" ", "_"); return rule; } #endregion #region parser checking private BuildResult<Parser<IN, OUT>> CheckParser(BuildResult<Parser<IN, OUT>> result) { var checkers = new List<ParserChecker<IN, OUT>>(); checkers.Add(CheckUnreachable); checkers.Add(CheckNotFound); checkers.Add(CheckAlternates); checkers.Add(CheckVisitorsSignature); if (result.Result != null && !result.IsError) foreach (var checker in checkers) if (checker != null) result.Result.Configuration.NonTerminals.Values.ToList() .ForEach(nt => result = checker(result, nt)); return result; } private BuildResult<Parser<IN, OUT>> CheckUnreachable(BuildResult<Parser<IN, OUT>> result, NonTerminal<IN> nonTerminal) { var conf = result.Result.Configuration; var found = false; if (nonTerminal.Name != conf.StartingRule) { foreach (var nt in result.Result.Configuration.NonTerminals.Values.ToList()) if (nt.Name != nonTerminal.Name) { found = NonTerminalReferences(nt, nonTerminal.Name); if (found) break; } if (!found) result.AddError(new ParserInitializationError(ErrorLevel.WARN, I18N.Instance.GetText(I18n,Message.NonTerminalNeverUsed, nonTerminal.Name), ErrorCodes.NOT_AN_ERROR)); } return result; } private static bool NonTerminalReferences(NonTerminal<IN> nonTerminal, string referenceName) { var found = false; var iRule = 0; while (iRule < nonTerminal.Rules.Count && !found) { var rule = nonTerminal.Rules[iRule]; var iClause = 0; while (iClause < rule.Clauses.Count && !found) { var clause = rule.Clauses[iClause]; if (clause is NonTerminalClause<IN> ntClause) { found = ntClause.NonTerminalName == referenceName; } else if (clause is OptionClause<IN> option) { if (option.Clause is NonTerminalClause<IN> inner) found = inner.NonTerminalName == referenceName; } else if (clause is ZeroOrMoreClause<IN> zeroOrMore) { if (zeroOrMore.Clause is NonTerminalClause<IN> inner) found = inner.NonTerminalName == referenceName; } else if (clause is OneOrMoreClause<IN> oneOrMore) { if (oneOrMore.Clause is NonTerminalClause<IN> innerNonTerminal) found = innerNonTerminal.NonTerminalName == referenceName; if (oneOrMore.Clause is ChoiceClause<IN> innerChoice && innerChoice.IsNonTerminalChoice) found = innerChoice.Choices.Where(c => (c as NonTerminalClause<IN>).NonTerminalName == referenceName).Any(); } else if (clause is ChoiceClause<IN> choice) { int i = 0; while (i < choice.Choices.Count && !found) { if (choice.Choices[i] is NonTerminalClause<IN> nonTerm) { found = nonTerm.NonTerminalName == referenceName; } i++; } } iClause++; } iRule++; } return found; } private BuildResult<Parser<IN, OUT>> CheckNotFound(BuildResult<Parser<IN, OUT>> result, NonTerminal<IN> nonTerminal) { var conf = result.Result.Configuration; foreach (var rule in nonTerminal.Rules) foreach (var clause in rule.Clauses) if (clause is NonTerminalClause<IN> ntClause) if (!conf.NonTerminals.ContainsKey(ntClause.NonTerminalName)) result.AddError(new ParserInitializationError(ErrorLevel.ERROR, I18N.Instance.GetText(I18n,Message.ReferenceNotFound,ntClause.NonTerminalName,rule.RuleString), ErrorCodes.PARSER_REFERENCE_NOT_FOUND)); return result; } private BuildResult<Parser<IN, OUT>> CheckAlternates(BuildResult<Parser<IN, OUT>> result, NonTerminal<IN> nonTerminal) { var conf = result.Result.Configuration; foreach (var rule in nonTerminal.Rules) { foreach (var clause in rule.Clauses) { if (clause is ChoiceClause<IN> choice) { if (!choice.IsTerminalChoice && !choice.IsNonTerminalChoice) { result.AddError(new ParserInitializationError(ErrorLevel.ERROR, I18N.Instance.GetText(I18n,Message.MixedChoices,rule.RuleString,choice.ToString()), ErrorCodes.PARSER_MIXED_CHOICES)); } else if (choice.IsDiscarded && choice.IsNonTerminalChoice) { result.AddError(new ParserInitializationError(ErrorLevel.ERROR, I18N.Instance.GetText(I18n,Message.NonTerminalChoiceCannotBeDiscarded,rule.RuleString,choice.ToString()), ErrorCodes.PARSER_NON_TERMINAL_CHOICE_CANNOT_BE_DISCARDED)); } } } } return result; } private BuildResult<Parser<IN, OUT>> CheckVisitorsSignature(BuildResult<Parser<IN, OUT>> result, NonTerminal<IN> nonTerminal) { foreach (var rule in nonTerminal.Rules) { if (!rule.IsSubRule) { result = CheckVisitorSignature(result, rule); } } return result; } private BuildResult<Parser<IN, OUT>> CheckVisitorSignature(BuildResult<Parser<IN, OUT>> result, Rule<IN> rule) { if (!rule.IsExpressionRule) { var visitor = rule.GetVisitor(); if (visitor == null) { ; } var returnInfo = visitor.ReturnParameter; var expectedReturn = typeof(OUT); var foundReturn = returnInfo.ParameterType; if (!expectedReturn.IsAssignableFrom(foundReturn) && foundReturn != expectedReturn) { result.AddError(new InitializationError(ErrorLevel.FATAL, I18N.Instance.GetText(I18n,Message.IncorrectVisitorReturnType,visitor.Name,rule.RuleString,typeof(OUT).FullName,returnInfo.ParameterType.Name), ErrorCodes.PARSER_INCORRECT_VISITOR_RETURN_TYPE)); } var realClauses = rule.Clauses.Where(x => !(x is TerminalClause<IN> || x is ChoiceClause<IN>) || (x is TerminalClause<IN> t && !t.Discarded) || (x is ChoiceClause<IN> c && !c.IsDiscarded) ).ToList(); if (visitor.GetParameters().Length != realClauses.Count && visitor.GetParameters().Length != realClauses.Count +1) { result.AddError(new InitializationError(ErrorLevel.FATAL, I18N.Instance.GetText(I18n,Message.IncorrectVisitorParameterNumber,visitor.Name,rule.RuleString,realClauses.Count.ToString(),(realClauses.Count+1).ToString(),visitor.GetParameters().Length.ToString()), ErrorCodes.PARSER_INCORRECT_VISITOR_PARAMETER_NUMBER)); // do not go further : it will cause an out of bound error. return result; } int i = 0; foreach (var clause in realClauses) { var arg = visitor.GetParameters()[i]; switch (clause) { case TerminalClause<IN> terminal: { var expected = typeof(Token<IN>); var found = arg.ParameterType; result = CheckArgType(result, rule, expected, visitor, arg); break; } case NonTerminalClause<IN> nonTerminal: { Type expected = null; var found = arg.ParameterType; if (nonTerminal.IsGroup) { expected = typeof(Group<IN,OUT>); } else { expected = typeof(OUT); } CheckArgType(result, rule, expected, visitor, arg); break; } case ManyClause<IN> many: { Type expected = null; Type found = arg.ParameterType; var innerClause = many.Clause; switch (innerClause) { case TerminalClause<IN> term: { expected = typeof(List<Token<IN>>); break; } case NonTerminalClause<IN> nonTerm: { if (nonTerm.IsGroup) { expected = typeof(List<Group<IN, OUT>>); } else { expected = typeof(List<OUT>); } break; } case GroupClause<IN> group: { expected = typeof(Group<IN, OUT>); break; } case ChoiceClause<IN> choice: { if (choice.IsTerminalChoice) { expected = typeof(List<Token<IN>>); } else if (choice.IsNonTerminalChoice) { expected = typeof(List<OUT>); } break; } } result = CheckArgType(result, rule, expected, visitor, arg); break; } case GroupClause<IN> group: { Type expected = typeof(Group<IN,OUT>); Type found = arg.ParameterType; result = CheckArgType(result, rule, expected, visitor, arg); break; } case OptionClause<IN> option: { Type expected = null; Type found = arg.ParameterType; var innerClause = option.Clause; switch (innerClause) { case TerminalClause<IN> term: { expected = typeof(Token<IN>); break; } case NonTerminalClause<IN> nonTerm: { if (nonTerm.IsGroup) { expected = typeof(ValueOption<Group<IN, OUT>>); } else { expected = typeof(ValueOption<OUT>); } break; } case GroupClause<IN> group: { expected = typeof(ValueOption<Group<IN, OUT>>); break; } case ChoiceClause<IN> choice: { if (choice.IsTerminalChoice) { expected = typeof(Token<IN>); } else if (choice.IsNonTerminalChoice) { expected = typeof(ValueOption<OUT>); } break; } } result = CheckArgType(result, rule, expected, visitor, arg); break; } } i++; } } else { var operations = rule.GetOperations(); foreach (var operation in operations) { var visitor = operation.VisitorMethod; var returnInfo = visitor.ReturnParameter; var expectedReturn = typeof(OUT); var foundReturn = returnInfo?.ParameterType; if (!expectedReturn.IsAssignableFrom(foundReturn) && foundReturn != expectedReturn) { result.AddError(new InitializationError(ErrorLevel.FATAL, I18N.Instance.GetText(I18n,Message.IncorrectVisitorReturnType,visitor.Name,rule.RuleString,typeof(OUT).FullName,returnInfo.ParameterType.Name), ErrorCodes.PARSER_INCORRECT_VISITOR_RETURN_TYPE)); } if (operation.IsUnary) { var parameters = visitor.GetParameters(); if (parameters.Length != 2 && parameters.Length != 3) { result.AddError(new InitializationError(ErrorLevel.FATAL, $"visitor {visitor.Name} for rule {rule.RuleString} has incorrect argument number : 2 or 3, found {parameters.Length}", ErrorCodes.PARSER_INCORRECT_VISITOR_PARAMETER_NUMBER)); // do not go further : it will cause an out of bound error. return result; } if (operation.Affix == Affix.PreFix) { var token = parameters[0]; result = CheckArgType(result, rule, typeof(Token<IN>), visitor, token); var value = parameters[1]; result = CheckArgType(result, rule, typeof(OUT), visitor, value); } else { var token = parameters[1]; result = CheckArgType(result, rule, typeof(Token<IN>), visitor, token); var value = parameters[0]; result = CheckArgType(result, rule, typeof(OUT), visitor, value); } } else if (operation.IsBinary) { var parameters = visitor.GetParameters(); if (parameters.Length != 3 && parameters.Length != 4) { result.AddError(new InitializationError(ErrorLevel.FATAL,$"visitor {visitor.Name} for rule {rule.RuleString} has incorrect argument number : 3 or 4, found {parameters.Length}", ErrorCodes.PARSER_INCORRECT_VISITOR_PARAMETER_NUMBER)); // do not go further : it will cause an out of bound error. return result; } var left = parameters[0]; result = CheckArgType(result, rule, typeof(OUT), visitor, left); var op = parameters[1]; result = CheckArgType(result, rule, typeof(Token<IN>), visitor, op); var right = parameters[2]; result = CheckArgType(result, rule, typeof(OUT), visitor, right); } } } return result; } private BuildResult<Parser<IN, OUT>> CheckArgType(BuildResult<Parser<IN, OUT>> result, Rule<IN> rule, Type expected, MethodInfo visitor, ParameterInfo arg) { if (!expected.IsAssignableFrom(arg.ParameterType) && arg.ParameterType != expected) { result.AddError(new InitializationError(ErrorLevel.FATAL, I18N.Instance.GetText(I18n,Message.IncorrectVisitorParameterType,visitor.Name,rule.RuleString,arg.Name,expected.FullName,arg.ParameterType.FullName), ErrorCodes.PARSER_INCORRECT_VISITOR_PARAMETER_TYPE)); } return result; } #endregion } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime { using ArgumentNullException = System.ArgumentNullException; using ConditionalAttribute = System.Diagnostics.ConditionalAttribute; using IDebugEventListener = Antlr.Runtime.Debug.IDebugEventListener; #if !PORTABLE using Console = System.Console; #endif public delegate int SpecialStateTransitionHandler( DFA dfa, int s, IIntStream input ); /** <summary>A DFA implemented as a set of transition tables.</summary> * * <remarks> * Any state that has a semantic predicate edge is special; those states * are generated with if-then-else structures in a specialStateTransition() * which is generated by cyclicDFA template. * * There are at most 32767 states (16-bit signed short). * Could get away with byte sometimes but would have to generate different * types and the simulation code too. For a point of reference, the Java * lexer's Tokens rule DFA has 326 states roughly. * </remarks> */ public class DFA { protected short[] eot; protected short[] eof; protected char[] min; protected char[] max; protected short[] accept; protected short[] special; protected short[][] transition; protected int decisionNumber; /** <summary>Which recognizer encloses this DFA? Needed to check backtracking</summary> */ protected BaseRecognizer recognizer; public bool debug = false; public DFA() : this(SpecialStateTransitionDefault) { } public DFA( SpecialStateTransitionHandler specialStateTransition ) { this.SpecialStateTransition = specialStateTransition ?? SpecialStateTransitionDefault; } public virtual string Description { get { return "n/a"; } } /** <summary> * From the input stream, predict what alternative will succeed * using this DFA (representing the covering regular approximation * to the underlying CFL). Return an alternative number 1..n. Throw * an exception upon error. * </summary> */ public virtual int Predict( IIntStream input ) { if (input == null) throw new ArgumentNullException("input"); DfaDebugMessage("Enter DFA.Predict for decision {0}", decisionNumber); int mark = input.Mark(); // remember where decision started in input int s = 0; // we always start at s0 try { while (true) { DfaDebugMessage("DFA {0} state {1} LA(1)={2}({3}), index={4}", decisionNumber, s, (char)input.LA(1), input.LA(1), input.Index); int specialState = special[s]; if ( specialState >= 0 ) { DfaDebugMessage("DFA {0} state {1} is special state {2}", decisionNumber, s, specialState); s = SpecialStateTransition( this, specialState, input ); DfaDebugMessage("DFA {0} returns from special state {1} to {2}", decisionNumber, specialState, s); if ( s == -1 ) { NoViableAlt( s, input ); return 0; } input.Consume(); continue; } if ( accept[s] >= 1 ) { DfaDebugMessage("accept; predict {0} from state {1}", accept[s], s); return accept[s]; } // look for a normal char transition char c = (char)input.LA( 1 ); // -1 == \uFFFF, all tokens fit in 65000 space if ( c >= min[s] && c <= max[s] ) { int snext = transition[s][c - min[s]]; // move to next state if ( snext < 0 ) { // was in range but not a normal transition // must check EOT, which is like the else clause. // eot[s]>=0 indicates that an EOT edge goes to another // state. if ( eot[s] >= 0 ) { // EOT Transition to accept state? DfaDebugMessage("EOT transition"); s = eot[s]; input.Consume(); // TODO: I had this as return accept[eot[s]] // which assumed here that the EOT edge always // went to an accept...faster to do this, but // what about predicated edges coming from EOT // target? continue; } NoViableAlt( s, input ); return 0; } s = snext; input.Consume(); continue; } if ( eot[s] >= 0 ) { // EOT Transition? DfaDebugMessage("EOT transition"); s = eot[s]; input.Consume(); continue; } if ( c == unchecked( (char)TokenTypes.EndOfFile ) && eof[s] >= 0 ) { // EOF Transition to accept state? DfaDebugMessage("accept via EOF; predict {0} from {1}", accept[eof[s]], eof[s]); return accept[eof[s]]; } // not in range and not EOF/EOT, must be invalid symbol DfaDebugInvalidSymbol(s); NoViableAlt( s, input ); return 0; } } finally { input.Rewind( mark ); } } [Conditional("DEBUG_DFA")] private void DfaDebugMessage(string format, params object[] args) { #if !PORTABLE Console.Error.WriteLine(format, args); #endif } [Conditional("DEBUG_DFA")] private void DfaDebugInvalidSymbol(int s) { #if !PORTABLE Console.Error.WriteLine("min[{0}]={1}", s, min[s]); Console.Error.WriteLine("max[{0}]={1}", s, max[s]); Console.Error.WriteLine("eot[{0}]={1}", s, eot[s]); Console.Error.WriteLine("eof[{0}]={1}", s, eof[s]); for (int p = 0; p < transition[s].Length; p++) Console.Error.Write(transition[s][p] + " "); Console.Error.WriteLine(); #endif } protected virtual void NoViableAlt( int s, IIntStream input ) { if ( recognizer.state.backtracking > 0 ) { recognizer.state.failed = true; return; } NoViableAltException nvae = new NoViableAltException( Description, decisionNumber, s, input ); Error( nvae ); throw nvae; } /** <summary>A hook for debugging interface</summary> */ public virtual void Error( NoViableAltException nvae ) { } public SpecialStateTransitionHandler SpecialStateTransition { get; private set; } //public virtual int specialStateTransition( int s, IntStream input ) //{ // return -1; //} static int SpecialStateTransitionDefault( DFA dfa, int s, IIntStream input ) { return -1; } /** <summary> * Given a String that has a run-length-encoding of some unsigned shorts * like "\1\2\3\9", convert to short[] {2,9,9,9}. We do this to avoid * static short[] which generates so much init code that the class won't * compile. :( * </summary> */ public static short[] UnpackEncodedString( string encodedString ) { // walk first to find how big it is. int size = 0; for ( int i = 0; i < encodedString.Length; i += 2 ) { size += encodedString[i]; } short[] data = new short[size]; int di = 0; for ( int i = 0; i < encodedString.Length; i += 2 ) { char n = encodedString[i]; char v = encodedString[i + 1]; // add v n times to data for ( int j = 1; j <= n; j++ ) { data[di++] = (short)v; } } return data; } /** <summary>Hideous duplication of code, but I need different typed arrays out :(</summary> */ public static char[] UnpackEncodedStringToUnsignedChars( string encodedString ) { // walk first to find how big it is. int size = 0; for ( int i = 0; i < encodedString.Length; i += 2 ) { size += encodedString[i]; } char[] data = new char[size]; int di = 0; for ( int i = 0; i < encodedString.Length; i += 2 ) { char n = encodedString[i]; char v = encodedString[i + 1]; // add v n times to data for ( int j = 1; j <= n; j++ ) { data[di++] = v; } } return data; } [Conditional("ANTLR_DEBUG")] protected virtual void DebugRecognitionException(RecognitionException ex) { IDebugEventListener dbg = recognizer.DebugListener; if (dbg != null) dbg.RecognitionException(ex); } } }
/* * MindTouch Deki Wiki - a commercial grade open source wiki * Copyright (C) 2006, 2007 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using MindTouch.Dream; using log4net; namespace MindTouch.Deki.Services { using Yield = IEnumerator<IYield>; [DreamService("MindTouch LDAP Authentication Service", "MindTouch, Inc. 2007", Info = "http://doc.opengarden.org/Deki_API/Reference/LdapAuthentication", SID = new string[] { "sid://mindtouch.com/2007/05/BETA/ldap-authentication" } )] [DreamServiceConfig("hostname", "string", "hostname or ip of domain controller or ldap server. Port 389 used by default. Port 636 used by default with SSL enabled.")] [DreamServiceConfig("ssl", "bool?", "Use LDAPS mode. This requires your LDAP server to be running with SSL and for the certificate to be recognized on the machine running this LDAP service. (default: false)")] [DreamServiceConfig("ssl-ignore-cert-errors", "bool?", "Allows you to use self signed or expired certificates. This should only be used for testing. (default: false)")] [DreamServiceConfig("searchbase", "string", "The distinguished name (DN) of the domain. For example: 'DC=sd,DC=mindtouch,DC=com'")] [DreamServiceConfig("bindingdn", "string", "The DN to use for binding to LDAP. Use $1 to substitute with user name. ActiveDirectory example: $1@sd.mindtouch.com OpenLdap example: CN=$1,DC=sd,DC=mindtouch,DC=com")] [DreamServiceConfig("bindingpw", "string?", "Optional password for binding. Combined with a valid bindingdn account, queries to this service can be done without credentials")] [DreamServiceConfig("userquery", "string", "The search query to use for looking up users. Use $1 to substitute with user name. ActiveDirectory example: samAccountName=$1 OpenLdap example: cn=$1 Novell eDirectory example: uid=$1")] [DreamServiceConfig("timeout", "int?", "Timeout for directory operations in milliseconds")] [DreamServiceConfig("displayname-pattern", "string?", "Returns a friendlier name that can be customized by ldap attributes. Example: {sn}, {givenname}")] [DreamServiceConfig("groupquery", "string?", "LDAP query for group lookup by name. $1 is replaced by username. Default: (&(objectCategory=group)(cn=$1))")] [DreamServiceConfig("groupqueryall", "string?", "LDAP query for looking up all groups. Default: (objectCategory=group)")] [DreamServiceConfig("groupmembersattribute", "string?", "LDAP attribute for looking up members of a group. Default: memberof (works for AD). Use groupmembership for eDirectory")] [DreamServiceConfig("groupmembershipquery", "string?", "TODO")] [DreamServiceConfig("usernameattribute", "string?", "LDAP attribute for retrieving a users account name. Provide an attribute to always use rather then trying a series of common attributes. Default: attempts to use sAMAccountName -> uid -> name -> cn.")] [DreamServiceConfig("groupnameattribute", "string?", "LDAP attribute for retrieving a group name. Provide an attribute to always use rather then trying a series of common attributes. Default: attempts to use sAMAccountName -> uid -> name -> cn.")] [DreamServiceConfig("verboselogging", "bool?", "Will output more details to the log as TRACE level. Warning: usernames+passwords are included as well. Default: false")] [DreamServiceBlueprint("dekiwiki/service-type", "authentication")] public class LdapAuthenticationService : DreamService { //--- Constants --- public const int DEFAULT_TIMEOUT = 5000; public const int MIN_TIMEOUT = 500; //--- Types --- public class LdapConfig { //--- Fields --- public string LdapHostname = string.Empty; public bool SSL = false; public bool SSLIgnoreCertErrors = false; public string LdapSearchBase = string.Empty; public string BindingDn = string.Empty; public string BindingPw = string.Empty; public string UserQuery = string.Empty; public string GroupQuery = string.Empty; public string GroupQueryAll = string.Empty; public string GroupMembersAttribute = string.Empty; public string GroupMembershipQuery = string.Empty; public string UserNameAttribute = string.Empty; public string GroupNameAttribute = string.Empty; public string DisplayNamePattern = string.Empty; public int LdapTimeOut = 0; public bool VerboseLogging = false; } //--- Fields --- private LdapConfig _config; //--- Properties --- public override string AuthenticationRealm { get { return "LDAP: " + _config.LdapSearchBase; } } //--- Features --- [DreamFeature("GET:groups/{groupname}", "Retrieve verbose information about a given group.")] [DreamFeatureParam("output", "string?", "'verbose' will retrieve group member information. 'brief' will not. Default: 'brief'")] [DreamFeatureParam("timelimit", "int?", "Timelimit in milliseconds for lookup. Default = 5000")] public Yield GetGroupInfo(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string groupname = context.GetParam("groupname", null); string output = context.GetParam("output", "brief").Trim(); LdapClient ldap = GetLdapClient(context, request, false); XDoc groupXml = ldap.GetGroupInfo(StringUtil.EqualsInvariant(output, "verbose"), 3, groupname); if( groupXml == null) response.Return(DreamMessage.NotFound(string.Format("Group '{0}' not found", groupname))); else response.Return(DreamMessage.Ok(groupXml)); yield break; } [DreamFeature("GET:groups/", "Retrieve all groups found in the directory.")] [DreamFeatureParam("output", "string?", "'verbose' will retrieve group member information. 'brief' will not. Default: 'brief'")] [DreamFeatureParam("timelimit", "int?", "Timelimit in milliseconds for lookup. Default = 5000")] public Yield GetGroups(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string output = context.GetParam("output", "brief").Trim(); LdapClient ldap = GetLdapClient(context, request, false); XDoc groupXml = ldap.GetGroupInfo(StringUtil.EqualsInvariant(output, "verbose"), 3, null); if (groupXml == null) response.Return(DreamMessage.NotFound("No groups found")); else response.Return(DreamMessage.Ok(groupXml)); yield break; } [DreamFeature("GET:users/{username}", "Retrieve information about a given user.")] [DreamFeatureParam("timelimit", "int?", "Timelimit in milliseconds for lookup. Default = 5000")] public Yield GetUserInfo(DreamContext context, DreamMessage request, Result<DreamMessage> response) { string username = context.GetParam("username"); LdapClient ldap = GetLdapClient(context, request, false); XDoc userXml = ldap.GetUserInfo(true, 3, username); if (userXml == null) response.Return(DreamMessage.NotFound(string.Format("User '{0}' not found. Search query used: '{1}'", username, ldap.BuildUserSearchQuery(username)))); else response.Return(DreamMessage.Ok(userXml)); yield break; } [DreamFeature("GET:authenticate", "Authenticate a user with the directory.")] [DreamFeatureParam("timelimit", "int?", "Timelimit in milliseconds for lookup. Default = 5000")] public Yield UserLogin(DreamContext context, DreamMessage request, Result<DreamMessage> response) { //This will attempt to bind to ldap with credentials from http header. //Non authentication exceptions will be returned to user. //Authentication failure will result in a DreamMessage.AccessDenied response LdapClient ldapClient = GetLdapClient(context, request, true); XDoc userXml = ldapClient.GetUserInfo(true, 3, ldapClient.UserName); if (userXml == null) response.Return(DreamMessage.NotFound(string.Format("User '{0}' not found. Search query used: '{1}'", ldapClient.UserName, ldapClient.BuildUserSearchQuery(ldapClient.UserName)))); else response.Return(DreamMessage.Ok(userXml)); yield break; } //--- Methods --- public override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()).Catch(result); // TODO MaxM: Validate config. _config = new LdapConfig(); _config.LdapHostname = config["hostname"].AsText ?? config["ldaphostname"].AsText; _config.LdapSearchBase = config["searchbase"].AsText ?? config["ldapsearchbase"].AsText; _config.BindingDn = config["bindingdn"].AsText ?? config["ldapbindingdn"].AsText; _config.BindingPw = config["bindingpw"].AsText ?? config["ldapbindingpw"].AsText; _config.UserQuery = config["userquery"].AsText ?? config["ldapuserquery"].AsText; _config.DisplayNamePattern = config["displayname-pattern"].AsText; _config.GroupQuery = config["groupquery"].AsText ?? "(&(objectClass=group)(cn=$1))"; _config.GroupQueryAll = config["groupqueryall"].AsText ?? "(objectClass=group)"; _config.GroupMembersAttribute = config["groupmembersattribute"].AsText ?? "memberof"; _config.GroupMembershipQuery = config["groupmembershipquery"].AsText; _config.UserNameAttribute = config["usernameattribute"].AsText; _config.GroupNameAttribute = config["groupnameattribute"].AsText; _config.SSL = config["ssl"].AsBool ?? false; _config.SSLIgnoreCertErrors = config["ssl-ignore-cert-errors"].AsBool ?? false; _config.LdapTimeOut = Math.Max(MIN_TIMEOUT, config["timeout"].AsInt ?? config["ldaptimeout"].AsInt ?? DEFAULT_TIMEOUT); _config.VerboseLogging = config["verboselogging"].AsBool ?? false; try { string ARGERROR = "LDAP Service config parameter not provided"; // validate configuration if (string.IsNullOrEmpty(_config.LdapHostname)) { throw new ArgumentException(ARGERROR, "hostname"); } if (string.IsNullOrEmpty(_config.LdapSearchBase)) { throw new ArgumentException(ARGERROR, "searchbase"); } if (string.IsNullOrEmpty(_config.BindingDn)) { throw new ArgumentException(ARGERROR, "bindingdn"); } if (string.IsNullOrEmpty(_config.UserQuery)) { throw new ArgumentException(ARGERROR, "userquery"); } } catch (ArgumentException ae) { throw new DreamBadRequestException(ae.Message); } result.Return(); } /// <summary> /// Returns a connected/authenticated ldapclient. Authentication info either comes from /// the standard authentication header or from local configuration. /// Default scope and domain controller IP/Host must be in service configuration. /// </summary> /// <param name="requireHeaderAuth">Will only accept authenticate from request header</param> /// <returns></returns> private LdapClient GetLdapClient(DreamContext context, DreamMessage request, bool requireAuth) { string authuser = string.Empty; string authpassword = string.Empty; HttpUtil.GetAuthentication(context.Uri.ToUri(), request.Headers, out authuser, out authpassword); if (_config.VerboseLogging) { LogUtils.LogTrace(_log, context.Feature.VerbSignature, string.Format("Performing LDAP lookup uri: '{0}' username: '{1}' pw: '{2}'", context.Feature.VerbSignature, authuser, authpassword)); } if (string.IsNullOrEmpty(authuser) && requireAuth) throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, "Provide credentials to authenticate with ldap")); LdapClient ldap = new LdapClient(_config, authuser, authpassword, _log); ldap.TimeLimit = context.GetParam<int>("timelimit", _config.LdapTimeOut); if (requireAuth) { bool authenticated = ldap.Authenticate(); if (!authenticated) { string msg = string.Format("Invalid LDAP username or password. Login DN used: '{0}'", ldap.BuildBindDn(authuser)); throw new DreamAbortException(DreamMessage.AccessDenied(AuthenticationRealm, msg)); } } return ldap; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using OpenMetaverse; using OpenMetaverse.Packets; using OpenMetaverse.StructuredData; using OpenMetaverse.Messages.Linden; namespace OpenSim.Region.CoreModules.Framework.EventQueue { public class EventQueueHelper { private EventQueueHelper() {} // no construction possible, it's an utility class private static byte[] ulongToByteArray(ulong uLongValue) { // Reverse endianness of RegionHandle return new byte[] { (byte)((uLongValue >> 56) % 256), (byte)((uLongValue >> 48) % 256), (byte)((uLongValue >> 40) % 256), (byte)((uLongValue >> 32) % 256), (byte)((uLongValue >> 24) % 256), (byte)((uLongValue >> 16) % 256), (byte)((uLongValue >> 8) % 256), (byte)(uLongValue % 256) }; } // private static byte[] uintToByteArray(uint uIntValue) // { // byte[] result = new byte[4]; // Utils.UIntToBytesBig(uIntValue, result, 0); // return result; // } public static OSD buildEvent(string eventName, OSD eventBody) { OSDMap llsdEvent = new OSDMap(2); llsdEvent.Add("message", new OSDString(eventName)); llsdEvent.Add("body", eventBody); return llsdEvent; } public static OSD EnableSimulator(ulong handle, IPEndPoint endPoint) { OSDMap llsdSimInfo = new OSDMap(3); llsdSimInfo.Add("Handle", new OSDBinary(ulongToByteArray(handle))); llsdSimInfo.Add("IP", new OSDBinary(endPoint.Address.GetAddressBytes())); llsdSimInfo.Add("Port", new OSDInteger(endPoint.Port)); OSDArray arr = new OSDArray(1); arr.Add(llsdSimInfo); OSDMap llsdBody = new OSDMap(1); llsdBody.Add("SimulatorInfo", arr); return buildEvent("EnableSimulator", llsdBody); } public static OSD DisableSimulator(ulong handle) { //OSDMap llsdSimInfo = new OSDMap(1); //llsdSimInfo.Add("Handle", new OSDBinary(regionHandleToByteArray(handle))); //OSDArray arr = new OSDArray(1); //arr.Add(llsdSimInfo); OSDMap llsdBody = new OSDMap(0); //llsdBody.Add("SimulatorInfo", arr); return buildEvent("DisableSimulator", llsdBody); } public static OSD CrossRegion(ulong handle, Vector3 pos, Vector3 lookAt, IPEndPoint newRegionExternalEndPoint, string capsURL, UUID agentID, UUID sessionID) { OSDArray lookAtArr = new OSDArray(3); lookAtArr.Add(OSD.FromReal(lookAt.X)); lookAtArr.Add(OSD.FromReal(lookAt.Y)); lookAtArr.Add(OSD.FromReal(lookAt.Z)); OSDArray positionArr = new OSDArray(3); positionArr.Add(OSD.FromReal(pos.X)); positionArr.Add(OSD.FromReal(pos.Y)); positionArr.Add(OSD.FromReal(pos.Z)); OSDMap infoMap = new OSDMap(2); infoMap.Add("LookAt", lookAtArr); infoMap.Add("Position", positionArr); OSDArray infoArr = new OSDArray(1); infoArr.Add(infoMap); OSDMap agentDataMap = new OSDMap(2); agentDataMap.Add("AgentID", OSD.FromUUID(agentID)); agentDataMap.Add("SessionID", OSD.FromUUID(sessionID)); OSDArray agentDataArr = new OSDArray(1); agentDataArr.Add(agentDataMap); OSDMap regionDataMap = new OSDMap(4); regionDataMap.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(handle))); regionDataMap.Add("SeedCapability", OSD.FromString(capsURL)); regionDataMap.Add("SimIP", OSD.FromBinary(newRegionExternalEndPoint.Address.GetAddressBytes())); regionDataMap.Add("SimPort", OSD.FromInteger(newRegionExternalEndPoint.Port)); OSDArray regionDataArr = new OSDArray(1); regionDataArr.Add(regionDataMap); OSDMap llsdBody = new OSDMap(3); llsdBody.Add("Info", infoArr); llsdBody.Add("AgentData", agentDataArr); llsdBody.Add("RegionData", regionDataArr); return buildEvent("CrossedRegion", llsdBody); } public static OSD TeleportFinishEvent( ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, uint flags, string capsURL, UUID agentID) { OSDMap info = new OSDMap(); info.Add("AgentID", OSD.FromUUID(agentID)); info.Add("LocationID", OSD.FromInteger(4)); // TODO what is this? info.Add("RegionHandle", OSD.FromBinary(ulongToByteArray(regionHandle))); info.Add("SeedCapability", OSD.FromString(capsURL)); info.Add("SimAccess", OSD.FromInteger(simAccess)); info.Add("SimIP", OSD.FromBinary(regionExternalEndPoint.Address.GetAddressBytes())); info.Add("SimPort", OSD.FromInteger(regionExternalEndPoint.Port)); info.Add("TeleportFlags", OSD.FromULong(1L << 4)); // AgentManager.TeleportFlags.ViaLocation OSDArray infoArr = new OSDArray(); infoArr.Add(info); OSDMap body = new OSDMap(); body.Add("Info", infoArr); return buildEvent("TeleportFinish", body); } public static OSD ScriptRunningReplyEvent(UUID objectID, UUID itemID, bool running, bool mono) { OSDMap script = new OSDMap(); script.Add("ObjectID", OSD.FromUUID(objectID)); script.Add("ItemID", OSD.FromUUID(itemID)); script.Add("Running", OSD.FromBoolean(running)); script.Add("Mono", OSD.FromBoolean(mono)); OSDArray scriptArr = new OSDArray(); scriptArr.Add(script); OSDMap body = new OSDMap(); body.Add("Script", scriptArr); return buildEvent("ScriptRunningReply", body); } public static OSD EstablishAgentCommunication(UUID agentID, string simIpAndPort, string seedcap) { OSDMap body = new OSDMap(3); body.Add("agent-id", new OSDUUID(agentID)); body.Add("sim-ip-and-port", new OSDString(simIpAndPort)); body.Add("seed-capability", new OSDString(seedcap)); return buildEvent("EstablishAgentCommunication", body); } public static OSD KeepAliveEvent() { return buildEvent("FAKEEVENT", new OSDMap()); } public static OSD AgentParams(UUID agentID, bool checkEstate, int godLevel, bool limitedToEstate) { OSDMap body = new OSDMap(4); body.Add("agent_id", new OSDUUID(agentID)); body.Add("check_estate", new OSDInteger(checkEstate ? 1 : 0)); body.Add("god_level", new OSDInteger(godLevel)); body.Add("limited_to_estate", new OSDInteger(limitedToEstate ? 1 : 0)); return body; } public static OSD InstantMessageParams(UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket) { OSDMap messageParams = new OSDMap(15); messageParams.Add("type", new OSDInteger((int)dialog)); OSDArray positionArray = new OSDArray(3); positionArray.Add(OSD.FromReal(position.X)); positionArray.Add(OSD.FromReal(position.Y)); positionArray.Add(OSD.FromReal(position.Z)); messageParams.Add("position", positionArray); messageParams.Add("region_id", new OSDUUID(UUID.Zero)); messageParams.Add("to_id", new OSDUUID(toAgent)); messageParams.Add("source", new OSDInteger(0)); OSDMap data = new OSDMap(1); data.Add("binary_bucket", OSD.FromBinary(binaryBucket)); messageParams.Add("data", data); messageParams.Add("message", new OSDString(message)); messageParams.Add("id", new OSDUUID(transactionID)); messageParams.Add("from_name", new OSDString(fromName)); messageParams.Add("timestamp", new OSDInteger((int)timeStamp)); messageParams.Add("offline", new OSDInteger(offline ? 1 : 0)); messageParams.Add("parent_estate_id", new OSDInteger(parentEstateID)); messageParams.Add("ttl", new OSDInteger((int)ttl)); messageParams.Add("from_id", new OSDUUID(fromAgent)); messageParams.Add("from_group", new OSDInteger(fromGroup ? 1 : 0)); return messageParams; } public static OSD InstantMessage(UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket, bool checkEstate, int godLevel, bool limitedToEstate) { OSDMap im = new OSDMap(2); im.Add("message_params", InstantMessageParams(fromAgent, message, toAgent, fromName, dialog, timeStamp, offline, parentEstateID, position, ttl, transactionID, fromGroup, binaryBucket)); im.Add("agent_params", AgentParams(fromAgent, checkEstate, godLevel, limitedToEstate)); return im; } public static OSD ChatterboxInvitation(UUID sessionID, string sessionName, UUID fromAgent, string message, UUID toAgent, string fromName, byte dialog, uint timeStamp, bool offline, int parentEstateID, Vector3 position, uint ttl, UUID transactionID, bool fromGroup, byte[] binaryBucket) { OSDMap body = new OSDMap(5); body.Add("session_id", new OSDUUID(sessionID)); body.Add("from_name", new OSDString(fromName)); body.Add("session_name", new OSDString(sessionName)); body.Add("from_id", new OSDUUID(fromAgent)); body.Add("instantmessage", InstantMessage(fromAgent, message, toAgent, fromName, dialog, timeStamp, offline, parentEstateID, position, ttl, transactionID, fromGroup, binaryBucket, true, 0, true)); OSDMap chatterboxInvitation = new OSDMap(2); chatterboxInvitation.Add("message", new OSDString("ChatterBoxInvitation")); chatterboxInvitation.Add("body", body); return chatterboxInvitation; } public static OSD ChatterBoxSessionAgentListUpdates(UUID sessionID, UUID agentID, bool canVoiceChat, bool isModerator, bool textMute) { OSDMap body = new OSDMap(); OSDMap agentUpdates = new OSDMap(); OSDMap infoDetail = new OSDMap(); OSDMap mutes = new OSDMap(); mutes.Add("text", OSD.FromBoolean(textMute)); infoDetail.Add("can_voice_chat", OSD.FromBoolean(canVoiceChat)); infoDetail.Add("is_moderator", OSD.FromBoolean(isModerator)); infoDetail.Add("mutes", mutes); OSDMap info = new OSDMap(); info.Add("info", infoDetail); agentUpdates.Add(agentID.ToString(), info); body.Add("agent_updates", agentUpdates); body.Add("session_id", OSD.FromUUID(sessionID)); body.Add("updates", new OSD()); OSDMap chatterBoxSessionAgentListUpdates = new OSDMap(); chatterBoxSessionAgentListUpdates.Add("message", OSD.FromString("ChatterBoxSessionAgentListUpdates")); chatterBoxSessionAgentListUpdates.Add("body", body); return chatterBoxSessionAgentListUpdates; } public static OSD GroupMembership(AgentGroupDataUpdatePacket groupUpdatePacket) { OSDMap groupUpdate = new OSDMap(); groupUpdate.Add("message", OSD.FromString("AgentGroupDataUpdate")); OSDMap body = new OSDMap(); OSDArray agentData = new OSDArray(); OSDMap agentDataMap = new OSDMap(); agentDataMap.Add("AgentID", OSD.FromUUID(groupUpdatePacket.AgentData.AgentID)); agentData.Add(agentDataMap); body.Add("AgentData", agentData); OSDArray groupData = new OSDArray(); foreach (AgentGroupDataUpdatePacket.GroupDataBlock groupDataBlock in groupUpdatePacket.GroupData) { OSDMap groupDataMap = new OSDMap(); groupDataMap.Add("ListInProfile", OSD.FromBoolean(false)); groupDataMap.Add("GroupID", OSD.FromUUID(groupDataBlock.GroupID)); groupDataMap.Add("GroupInsigniaID", OSD.FromUUID(groupDataBlock.GroupInsigniaID)); groupDataMap.Add("Contribution", OSD.FromInteger(groupDataBlock.Contribution)); groupDataMap.Add("GroupPowers", OSD.FromBinary(ulongToByteArray(groupDataBlock.GroupPowers))); groupDataMap.Add("GroupName", OSD.FromString(Utils.BytesToString(groupDataBlock.GroupName))); groupDataMap.Add("AcceptNotices", OSD.FromBoolean(groupDataBlock.AcceptNotices)); groupData.Add(groupDataMap); } body.Add("GroupData", groupData); groupUpdate.Add("body", body); return groupUpdate; } public static OSD PlacesQuery(PlacesReplyPacket PlacesReply) { OSDMap placesReply = new OSDMap(); placesReply.Add("message", OSD.FromString("PlacesReplyMessage")); OSDMap body = new OSDMap(); OSDArray agentData = new OSDArray(); OSDMap agentDataMap = new OSDMap(); agentDataMap.Add("AgentID", OSD.FromUUID(PlacesReply.AgentData.AgentID)); agentDataMap.Add("QueryID", OSD.FromUUID(PlacesReply.AgentData.QueryID)); agentDataMap.Add("TransactionID", OSD.FromUUID(PlacesReply.TransactionData.TransactionID)); agentData.Add(agentDataMap); body.Add("AgentData", agentData); OSDArray QueryData = new OSDArray(); foreach (PlacesReplyPacket.QueryDataBlock groupDataBlock in PlacesReply.QueryData) { OSDMap QueryDataMap = new OSDMap(); QueryDataMap.Add("ActualArea", OSD.FromInteger(groupDataBlock.ActualArea)); QueryDataMap.Add("BillableArea", OSD.FromInteger(groupDataBlock.BillableArea)); QueryDataMap.Add("Description", OSD.FromBinary(groupDataBlock.Desc)); QueryDataMap.Add("Dwell", OSD.FromInteger((int)groupDataBlock.Dwell)); QueryDataMap.Add("Flags", OSD.FromString(Convert.ToString(groupDataBlock.Flags))); QueryDataMap.Add("GlobalX", OSD.FromInteger((int)groupDataBlock.GlobalX)); QueryDataMap.Add("GlobalY", OSD.FromInteger((int)groupDataBlock.GlobalY)); QueryDataMap.Add("GlobalZ", OSD.FromInteger((int)groupDataBlock.GlobalZ)); QueryDataMap.Add("Name", OSD.FromBinary(groupDataBlock.Name)); QueryDataMap.Add("OwnerID", OSD.FromUUID(groupDataBlock.OwnerID)); QueryDataMap.Add("SimName", OSD.FromBinary(groupDataBlock.SimName)); QueryDataMap.Add("SnapShotID", OSD.FromUUID(groupDataBlock.SnapshotID)); QueryDataMap.Add("ProductSku", OSD.FromInteger(0)); QueryDataMap.Add("Price", OSD.FromInteger(groupDataBlock.Price)); QueryData.Add(QueryDataMap); } body.Add("QueryData", QueryData); placesReply.Add("QueryData[]", body); return placesReply; } public static OSD ParcelProperties(ParcelPropertiesMessage parcelPropertiesMessage) { OSDMap message = new OSDMap(); message.Add("message", OSD.FromString("ParcelProperties")); OSD message_body = parcelPropertiesMessage.Serialize(); message.Add("body", message_body); return message; } } }
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Fungus { /** * Visual scripting controller for the Flowchart programming language. * Flowchart objects may be edited visually using the Flowchart editor window. */ [ExecuteInEditMode] public class Flowchart : MonoBehaviour { /** * Current version used to compare with the previous version so older versions can be custom-updated from previous versions. */ public const string CURRENT_VERSION = "1.0"; /** * The name of the initial block in a new flowchart. */ public const string DEFAULT_BLOCK_NAME = "New Block"; /** * Variable to track flowchart's version and if initial set up has completed. */ [HideInInspector] public string version; /** * Scroll position of Flowchart editor window. */ [HideInInspector] public Vector2 scrollPos; /** * Scroll position of Flowchart variables window. */ [HideInInspector] public Vector2 variablesScrollPos; /** * Show the variables pane. */ [HideInInspector] public bool variablesExpanded = true; /** * Height of command block view in inspector. */ [HideInInspector] public float blockViewHeight = 400; /** * Zoom level of Flowchart editor window */ [HideInInspector] public float zoom = 1f; /** * Scrollable area for Flowchart editor window. */ [HideInInspector] public Rect scrollViewRect; /** * Currently selected block in the Flowchart editor. */ [HideInInspector] [FormerlySerializedAs("selectedSequence")] public Block selectedBlock; /** * Currently selected command in the Flowchart editor. */ [HideInInspector] public List<Command> selectedCommands = new List<Command>(); /** * The list of variables that can be accessed by the Flowchart. */ [HideInInspector] public List<Variable> variables = new List<Variable>(); [TextArea(3, 5)] [Tooltip("Description text displayed in the Flowchart editor window")] public string description = ""; /** * Slow down execution in the editor to make it easier to visualise program flow. */ [Range(0f, 5f)] [Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")] public float stepPause = 0f; /** * Use command color when displaying the command list in the inspector. */ [Tooltip("Use command color when displaying the command list in the Fungus Editor window")] public bool colorCommands = true; /** * Hides the Flowchart block and command components in the inspector. * Deselect to inspect the block and command components that make up the Flowchart. */ [Tooltip("Hides the Flowchart block and command components in the inspector")] public bool hideComponents = true; /** * Saves the selected block and commands when saving the scene. * Helps avoid version control conflicts if you've only changed the active selection. */ [Tooltip("Saves the selected block and commands when saving the scene.")] public bool saveSelection = true; /** * Unique identifier for identifying this flowchart in localized string keys. */ [Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")] public string localizationId = ""; /** * Cached list of flowchart objects in the scene for fast lookup */ public static List<Flowchart> cachedFlowcharts = new List<Flowchart>(); protected static bool eventSystemPresent; /** * Returns the next id to assign to a new flowchart item. * Item ids increase monotically so they are guaranteed to * be unique within a Flowchart. */ public int NextItemId() { int maxId = -1; Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { maxId = Math.Max(maxId, block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { maxId = Math.Max(maxId, command.itemId); } return maxId + 1; } protected virtual void OnLevelWasLoaded(int level) { // Reset the flag for checking for an event system as there may not be one in the newly loaded scene. eventSystemPresent = false; } protected virtual void Start() { CheckEventSystem(); } // There must be an Event System in the scene for Say and Menu input to work. // This method will automatically instantiate one if none exists. protected virtual void CheckEventSystem() { if (eventSystemPresent) { return; } EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>(); if (eventSystem == null) { // Auto spawn an Event System from the prefab GameObject prefab = Resources.Load<GameObject>("EventSystem"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "EventSystem"; } } eventSystemPresent = true; } public virtual void OnEnable() { if (!cachedFlowcharts.Contains(this)) { cachedFlowcharts.Add(this); } CheckItemIds(); CleanupComponents(); UpdateVersion(); } public virtual void OnDisable() { cachedFlowcharts.Remove(this); } protected virtual void CheckItemIds() { // Make sure item ids are unique and monotonically increasing. // This should always be the case, but some legacy Flowcharts may have issues. List<int> usedIds = new List<int>(); Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.itemId == -1 || usedIds.Contains(block.itemId)) { block.itemId = NextItemId(); } usedIds.Add(block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { if (command.itemId == -1 || usedIds.Contains(command.itemId)) { command.itemId = NextItemId(); } usedIds.Add(command.itemId); } } protected virtual void CleanupComponents() { // Delete any unreferenced components which shouldn't exist any more // Unreferenced components don't have any effect on the flowchart behavior, but // they waste memory so should be cleared out periodically. Block[] blocks = GetComponentsInChildren<Block>(); foreach (Variable variable in GetComponents<Variable>()) { if (!variables.Contains(variable)) { DestroyImmediate(variable); } } foreach (Command command in GetComponents<Command>()) { bool found = false; foreach (Block block in blocks) { if (block.commandList.Contains(command)) { found = true; break; } } if (!found) { DestroyImmediate(command); } } foreach (EventHandler eventHandler in GetComponents<EventHandler>()) { bool found = false; foreach (Block block in blocks) { if (block.eventHandler == eventHandler) { found = true; break; } } if (!found) { DestroyImmediate(eventHandler); } } } private void UpdateVersion() { // If versions match, then we are already using the latest. if (version == CURRENT_VERSION) return; switch (version) { // Version never set, so we are initializing on first creation or this flowchart is pre-versioning. case null: case "": Initialize(); break; } version = CURRENT_VERSION; } protected virtual void Initialize() { // If there are other flowcharts in the scene and the selected block has the default name, then this is probably a new block. // Reset the event handler of the new flowchart's default block to avoid crashes. if (selectedBlock && cachedFlowcharts.Count > 1 && selectedBlock.blockName == DEFAULT_BLOCK_NAME) { selectedBlock.eventHandler = null; } } protected virtual Block CreateBlockComponent(GameObject parent) { Block block = parent.AddComponent<Block>(); return block; } /** * Create a new block node which you can then add commands to. */ public virtual Block CreateBlock(Vector2 position) { Block b = CreateBlockComponent(gameObject); b.nodeRect.x = position.x; b.nodeRect.y = position.y; b.blockName = GetUniqueBlockKey(b.blockName, b); b.itemId = NextItemId(); return b; } /** * Returns the named Block in the flowchart, or null if not found. */ public virtual Block FindBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { return block; } } return null; } /** * Start running another Flowchart by executing a specific child block. * The block must be in an idle state to be executed. * You can use this method in a UI event. e.g. to handle a button click. */ public virtual void ExecuteBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { ExecuteBlock(block); } } } /** * Sends a message to this Flowchart only. * Any block with a matching MessageReceived event handler will start executing. */ public virtual void SendFungusMessage(string messageName) { MessageReceived[] eventHandlers = GetComponentsInChildren<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Sends a message to all Flowchart objects in the current scene. * Any block with a matching MessageReceived event handler will start executing. */ public static void BroadcastFungusMessage(string messageName) { MessageReceived[] eventHandlers = GameObject.FindObjectsOfType<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Start executing a specific child block in the flowchart. * The block must be in an idle state to be executed. * Returns true if the Block started execution. */ public virtual bool ExecuteBlock(Block block, Action onComplete = null) { // Block must be a component of the Flowchart game object if (block == null || block.gameObject != gameObject) { return false; } // Can't restart a running block, have to wait until it's idle again if (block.IsExecuting()) { return false; } // Execute the first command in the command list block.Execute(onComplete); return true; } /** * Returns a new variable key that is guaranteed not to clash with any existing variable in the list. */ public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null) { int suffix = 0; string baseKey = originalKey; // Only letters and digits allowed char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray(); baseKey = new string(arr); // No leading digits allowed baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9'); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "Var"; } string key = baseKey; while (true) { bool collision = false; foreach(Variable variable in variables) { if (variable == null || variable == ignoreVariable || variable.key == null) { continue; } if (variable.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart. */ public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Block"; } Block[] blocks = GetComponentsInChildren<Block>(); string key = baseKey; while (true) { bool collision = false; foreach(Block block in blocks) { if (block == ignoreBlock || block.blockName == null) { continue; } if (block.blockName.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Label key that is guaranteed not to clash with any existing Label in the Block. */ public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Label"; } Block block = ignoreLabel.parentBlock; string key = baseKey; while (true) { bool collision = false; foreach(Command command in block.commandList) { Label label = command as Label; if (label == null || label == ignoreLabel) { continue; } if (label.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns the variable with the specified key, or null if the key is not found. * You can then access the variable's value using the Value property. e.g. * BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool"); * boolVar.Value = false; */ public T GetVariable<T>(string key) where T : Variable { foreach (Variable variable in variables) { if (variable.key == key) { return variable as T; } } return null; } /** * Gets a list of all variables with public scope in this Flowchart. */ public virtual List<Variable> GetPublicVariables() { List<Variable> publicVariables = new List<Variable>(); foreach (Variable v in variables) { if (v.scope == VariableScope.Public) { publicVariables.Add(v); } } return publicVariables; } /** * Gets the value of a boolean variable. * Returns false if the variable key does not exist. */ public virtual bool GetBooleanVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Boolean variable " + key + " not found."); return false; } /** * Sets the value of a boolean variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetBooleanVariable(string key, bool value) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Boolean variable " + key + " not found."); } /** * Gets the value of an integer variable. * Returns 0 if the variable key does not exist. */ public virtual int GetIntegerVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Integer variable " + key + " not found."); return 0; } /** * Sets the value of an integer variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetIntegerVariable(string key, int value) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Integer variable " + key + " not found."); } /** * Gets the value of a float variable. * Returns 0 if the variable key does not exist. */ public virtual float GetFloatVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Float variable " + key + " not found."); return 0f; } /** * Sets the value of a float variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetFloatVariable(string key, float value) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Float variable " + key + " not found."); } /** * Gets the value of a string variable. * Returns the empty string if the variable key does not exist. */ public virtual string GetStringVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("String variable " + key + " not found."); return ""; } /** * Sets the value of a string variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetStringVariable(string key, string value) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("String variable " + key + " not found."); } /** * Set the block objects to be hidden or visible depending on the hideComponents property. */ public virtual void UpdateHideFlags() { if (hideComponents) { Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { block.hideFlags = HideFlags.HideInInspector; if (block.gameObject != gameObject) { block.gameObject.hideFlags = HideFlags.HideInHierarchy; } } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.hideFlags = HideFlags.HideInInspector; } EventHandler[] eventHandlers = GetComponentsInChildren<EventHandler>(); foreach (EventHandler eventHandler in eventHandlers) { eventHandler.hideFlags = HideFlags.HideInInspector; } } else { MonoBehaviour[] monoBehaviours = GetComponentsInChildren<MonoBehaviour>(); foreach (MonoBehaviour monoBehaviour in monoBehaviours) { if (monoBehaviour == null) { continue; } monoBehaviour.hideFlags = HideFlags.None; monoBehaviour.gameObject.hideFlags = HideFlags.None; } } } public virtual void ClearSelectedCommands() { selectedCommands.Clear(); } public virtual void AddSelectedCommand(Command command) { if (!selectedCommands.Contains(command)) { selectedCommands.Add(command); } } public virtual void Reset(bool resetCommands, bool resetVariables) { if (resetCommands) { Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.OnReset(); } } if (resetVariables) { foreach (Variable variable in variables) { variable.OnReset(); } } } public virtual string SubstituteVariables(string text) { string subbedText = text; // Instantiate the regular expression object. Regex r = new Regex("{\\$.*?}"); // Match the regular expression pattern against a text string. var results = r.Matches(text); foreach (Match match in results) { string key = match.Value.Substring(2, match.Value.Length - 3); // Look for any matching variables in this Flowchart first (public or private) foreach (Variable variable in variables) { if (variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } // Now search all public variables in all scene Flowcharts in the scene foreach (Flowchart flowchart in cachedFlowcharts) { if (flowchart == this) { // We've already searched this flowchart continue; } foreach (Variable variable in flowchart.variables) { if (variable.scope == VariableScope.Public && variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } } // Next look for matching localized string string localizedString = Localization.GetLocalizedString(key); if (localizedString != null) { subbedText = subbedText.Replace(match.Value, localizedString); } } return subbedText; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Audio; using FlatRedBall.Math; using Microsoft.Xna.Framework.Media; using System.Reflection; using FlatRedBall.IO; using FlatRedBall.Instructions; namespace FlatRedBall.Audio { #region SoundEffectPlayingBehavior public enum SoundEffectPlayingBehavior { PlayAlways, OncePerFrame } #endregion public static partial class AudioManager { #region Fields private static List<SoundEffectPlayInfo> mSoundEffectPlayInfos = new List<SoundEffectPlayInfo>(); private static List<string> mSoundsPlayedThisFrame = new List<string>(); private static string mSettingsFile; private static bool mIsInitialized = false; private static Song mCurrentSong = null; private static Song mPreviousSong = null; private static bool mPreviousSongUsesGlobalContent = false; static Song mSongLastRequested; static string mLastSongNameRequested; static bool mAreSongsEnabled; static bool mAreSoundEffectsEnabled; static bool? mDoesUserWantCustomSoundtrack = null; #if MONODROID //This is for a performance issue with SoundPool private static SoundEffect _droidLoop; private static DateTime _lastPlay = DateTime.Now; #endif #endregion #region Properties public static bool IsCustomMusicPlaying { get { #if SILVERLIGHT return false; #else return Microsoft.Xna.Framework.Media.MediaPlayer.GameHasControl == false; #endif } } public static SoundEffectPlayingBehavior SoundEffectPlayingBehavior { get; set; } public static bool IsInitialized { get { return mIsInitialized; } } /// <summary> /// Controls whether the Play function will produce any audio when called. /// This defaults to true, and it can be set to false in response to a setting /// in the game's options screen. Setting this to false will not stop any currently-playing /// SoundEffects as this is an XNA limitation - SoundEffect is fire-and-forget. /// </summary> public static bool AreSoundEffectsEnabled { get { return mAreSoundEffectsEnabled; } set { mAreSoundEffectsEnabled = value; } } public static bool AreSongsEnabled { get { return mAreSongsEnabled; } set { mAreSongsEnabled = value; if (CurrentlyPlayingSong != null && !mAreSongsEnabled) { StopSong(); } } } public static string SettingsFile { get { return mSettingsFile; } } /// <summary> /// Represents the "active" song. This may or may not be actually playing. /// This may still be non-null when no song is playing if the code has stopped /// music from playing. The AudioManager remembers this to resume playing later. /// </summary> public static Song CurrentSong { get { return mCurrentSong; } } static bool mIsSongUsingGlobalContent; static Song mCurrentlyPlayingSongButUsePropertyPlease; /// <summary> /// Represents the song that is currently playing. If no song is playing this is null. /// </summary> public static Song CurrentlyPlayingSong { get { return mCurrentlyPlayingSongButUsePropertyPlease; } private set { if (value != mCurrentlyPlayingSongButUsePropertyPlease) { mCurrentlyPlayingSongButUsePropertyPlease = value; } } } #if DEBUG /// <summary> /// Reports the total number of sound effects that have been played by the AudioManager since the start of the program's execution. /// This can be used to count sound effect plays as a rough form of profiling. /// </summary> public static int NumberOfSoundEffectPlays { get; set; } #endif #endregion #region Event Handlers static void OnUnsuspending(object sender, EventArgs e) { if (mCurrentSong != null) { PlaySong(mCurrentSong, true, mIsSongUsingGlobalContent); } } static void OnSuspending(object sender, EventArgs e) { StopSong(); } #endregion #region Public Methods static AudioManager() { AreSoundEffectsEnabled = true; AreSongsEnabled = true; #if !MONOGAME SoundListener = new PositionedSoundListener(); PositionedSounds = new PositionedObjectList<PositionedSound>(); #endif Microsoft.Xna.Framework.Media.MediaPlayer.MediaStateChanged += HandleMediaStateChanged; } private static void HandleMediaStateChanged(object sender, EventArgs e) { if(CurrentlyPlayingSong != null && Microsoft.Xna.Framework.Media.MediaPlayer.State == MediaState.Stopped) { CurrentlyPlayingSong = null; } } /// <summary> /// Returns whether the argument SoundEffect is playing. If true, then the SoundEffect is already /// playing. If false, the SoundEffect is not playing. This will only check SoundEffects which were /// played through the AudioManager.Play method. /// </summary> /// <param name="soundEffect">The SoundEffect to test.</param> /// <returns>Whether the sound effect is playing.</returns> public static bool IsSoundEffectPlaying(SoundEffect soundEffect) { for (int i = 0; i < mSoundEffectPlayInfos.Count; i++) { if (mSoundEffectPlayInfos[i].SoundEffect == soundEffect) { return true; } } return false; } /// <summary> /// Plays the argument sound effect using a default Volume, pitch, and pan. /// </summary> /// <param name="soundEffect"></param> public static void Play(SoundEffect soundEffect) { Play(soundEffect, 1); } /// <summary> /// Plays the argument sound effect. /// </summary> /// <param name="soundEffect">The sound effect to play</param> /// <param name="volume">Volume, ranging from 0.0f (silence) to 1.0f (full volume). 1.0f is full volume</param> /// <param name="pitch">Pitch, ranging from -1.0f (one octave down) to 1.0f (one octave up). 0.0f means no change </param> /// <param name="pan">Volume, ranging from -1.0f (full left) to 1.0f (full right). 0.0f is centered </param> public static void Play(SoundEffect soundEffect, float volume, float pitch = 0, float pan = 0) { #if DEBUG && !MONOGAME if (soundEffect.IsDisposed) { throw new ArgumentException("Argument SoundEffect is disposed"); } #endif if (AreSoundEffectsEnabled) { bool shouldPlay = SoundEffectPlayingBehavior == Audio.SoundEffectPlayingBehavior.PlayAlways || mSoundsPlayedThisFrame.Contains(soundEffect.Name) == false; if (shouldPlay) { #if MONODROID _lastPlay = DateTime.Now; #endif #if ANDROID && !DEBUG try { if (volume < 1 || pitch != 0.0f || pan != 0.0f) { soundEffect.Play(volume, pitch, pan); } else { soundEffect.Play(); } } catch { // Sept 28, 2015 // Monogame 3.4 (and probably 3.5) does not support // playing Sounds on ARM 64 devices. It crashes. We will // catch it in release in case someone releases a FRB game // and doesn't test it on these devices - better to be quiet // than to crash. In debug it will crash like normal (see below) } #else if (volume < 1 || pitch != 0.0f || pan != 0.0f) { soundEffect.Play(volume, pitch, pan); } else { soundEffect.Play(); } #endif #if DEBUG NumberOfSoundEffectPlays++; #endif if (SoundEffectPlayingBehavior == Audio.SoundEffectPlayingBehavior.OncePerFrame) { mSoundsPlayedThisFrame.Add(soundEffect.Name); } SoundEffectPlayInfo sepi = new SoundEffectPlayInfo(); sepi.LastPlayTime = TimeManager.CurrentTime; sepi.SoundEffect = soundEffect; mSoundEffectPlayInfos.Add(sepi); } } } /// <summary> /// Checks if the argument sound effect if playing. If not, plays the sound effect. /// </summary> /// <param name="soundEffect">The sound effect to play.</param> public static void PlayIfNotPlaying(SoundEffect soundEffect) { if(!IsSoundEffectPlaying(soundEffect)) { Play(soundEffect); } } /// <summary> /// Plays the current song. PlaySong with an argument must /// be called before this can be called. This can be used to /// resume music when the game is unpaused or if audio options are /// being turned on/off /// </summary> public static void PlaySong() { PlaySong(mCurrentSong, false, mIsSongUsingGlobalContent); } /// <summary> /// Plays the argument song, optionally restarting it if it is already playing. /// </summary> /// <param name="toPlay">The song to play.</param> /// <param name="forceRestart">Whether the song should be restarted. If the toPlay parameter differs from the currently-playing song then it will /// restart regardless of the forceRestart value. This value only matters when the currently-playing song is passed.</param> /// <param name="isSongGlobalContent">Whether the song uses a Global content manager. This is important if StopAndDisposeCurrentSongIfNameDiffers is called. /// StopAndDisposeCurrentSongIfNameDiffers is called by Glue, so the isSongGlobalContent param matters even if your code is not directly calling this function.</param> public static void PlaySong(Song toPlay, bool forceRestart, bool isSongGlobalContent) { bool shouldPlay = true; shouldPlay = IsCustomMusicPlaying == false || (mDoesUserWantCustomSoundtrack.HasValue && mDoesUserWantCustomSoundtrack.Value == false); #if WINDOWS_PHONE if (!shouldPlay && !mDoesUserWantCustomSoundtrack.HasValue && AreSongsEnabled) { Guide.BeginShowMessageBox( "Stop music?", "Would you like to stop your current music and listen to the music for this game?", new string[] { "Yes", "No" }, 0, MessageBoxIcon.Alert, UserPermissionCallback, null); } #endif if (toPlay.Name != mLastSongNameRequested || forceRestart || CurrentlyPlayingSong == null) { mSongLastRequested = toPlay; mIsSongUsingGlobalContent = isSongGlobalContent; mLastSongNameRequested = toPlay.Name; } else { shouldPlay = false; } if (shouldPlay && AreSongsEnabled) { mCurrentSong = toPlay; CurrentlyPlayingSong = mCurrentSong; mIsSongUsingGlobalContent = isSongGlobalContent; #if ANDROID try { MediaPlayer.Play(toPlay); } // November 19, 2014 // For some reason the // automated test project // would always crash when // trying to play a song on // a certain screen. I was able // to avoid the crash by putting a // breakpoint and waiting a while before // continuing execution. I suppose it means // that the song needs a little bit of time before // it is played. So I just added a catch and put catch(Java.IO.IOException e) { string message = e.Message; if(message.Contains("0x64")) { // This needs a second before it starts up int msToWait = 100; System.Threading.Thread.Sleep(msToWait); MediaPlayer.Play(toPlay); } else { throw e; } } #else Microsoft.Xna.Framework.Media.MediaPlayer.Play(toPlay); #endif } } #if WINDOWS_PHONE private static void UserPermissionCallback(IAsyncResult r) { int? dialogResult = Guide.EndShowMessageBox(r); if (dialogResult == null || dialogResult == 1) { mDoesUserWantCustomSoundtrack = true; } else { mDoesUserWantCustomSoundtrack = false; PlaySong(mSongLastRequested, true, mIsSongUsingGlobalContent); } } #endif public static void StopSong() { Microsoft.Xna.Framework.Media.MediaPlayer.Stop(); CurrentlyPlayingSong = null; } public static bool StopAndDisposeCurrentSongIfNameDiffers(string nameToCompareAgainst) { bool wasDisposed = false; if (CurrentlyPlayingSong != null && nameToCompareAgainst != mLastSongNameRequested) { Song songToDispose = CurrentlyPlayingSong; StopSong(); if (!mIsSongUsingGlobalContent) { songToDispose.Dispose(); } wasDisposed = true; } return wasDisposed; } public static void PlaySongThenResumeCurrent(Song toPlay, bool songUsesGlobalContent) { mPreviousSong = mCurrentSong; mPreviousSongUsesGlobalContent = mIsSongUsingGlobalContent; mCurrentSong = toPlay; mIsSongUsingGlobalContent = songUsesGlobalContent; try { PlaySong(toPlay, false, songUsesGlobalContent); #if WINDOWS_8 || UWP MethodInfo playMethod = typeof(AudioManager).GetMethod("PlaySong", new Type[1] { typeof(Song) }); #else MethodInfo playMethod = typeof(AudioManager).GetMethod("PlaySong", BindingFlags.Public | BindingFlags.Static, null, new Type[1] { typeof(Song) }, null); #endif InstructionManager.Add(new StaticMethodInstruction(playMethod, new object[1] { mPreviousSong }, TimeManager.CurrentTime + toPlay.Duration.TotalSeconds)); } catch { // stupid DRM } } #endregion #region Internal Methods internal static void UpdateDependencies() { #if !WINDOWS_PHONE && !MONOGAME && !SILVERLIGHT SoundListener.UpdateDependencies(TimeManager.CurrentTime); SoundListener.UpdateAudio(); for (int i = 0; i < PositionedSounds.Count; i++) { PositionedSounds[i].UpdateDependencies(TimeManager.CurrentTime); PositionedSounds[i].UpdateAudio(); } if (mXnaAudioEngine != null) mXnaAudioEngine.Update(); #endif mSoundsPlayedThisFrame.Clear(); } public static void Update() { for (int i = mSoundEffectPlayInfos.Count - 1; i > -1; i--) { SoundEffectPlayInfo sepi = mSoundEffectPlayInfos[i]; if (TimeManager.SecondsSince(sepi.LastPlayTime + sepi.SoundEffect.Duration.TotalSeconds) > 0) { mSoundEffectPlayInfos.RemoveAt(i); } } // TODO: Execute instructions #if !WINDOWS_PHONE && !MONOGAME && !SILVERLIGHT for (int i = 0; i < PositionedSounds.Count; i++) { PositionedSounds[i].TimedActivity( TimeManager.SecondDifference, TimeManager.SecondDifferenceSquaredDividedByTwo, TimeManager.LastSecondDifference); } #endif // TODO [msmith] Get this working again once we add the data into the asset folder. /* TODO MDS_TEMP #if MONODROID if ((DateTime.Now - _lastPlay).Milliseconds > 200) { if (_droidLoop != null) { _droidLoop.Play(0, 0, 0); _lastPlay = DateTime.Now; }else { _droidLoop = FlatRedBallServices.Load<SoundEffect>(@"performanceloop"); } } #endif */ } #endregion } }
using System.Collections.Generic; using System.Diagnostics; using System.IO; using System; using System.Threading; using NAppUpdate.Framework.Common; using NAppUpdate.Framework.FeedReaders; using NAppUpdate.Framework.Sources; using NAppUpdate.Framework.Tasks; using NAppUpdate.Framework.Utils; namespace NAppUpdate.Framework { /// <summary> /// An UpdateManager class is a singleton class handling the update process from start to end for a consumer application /// </summary> public sealed class UpdateManager { #region Singleton Stuff /// <summary> /// Defaut ctor /// </summary> private UpdateManager() { IsWorking = false; State = UpdateProcessState.NotChecked; UpdatesToApply = new List<IUpdateTask>(); ApplicationPath = Process.GetCurrentProcess().MainModule.FileName; UpdateFeedReader = new NauXmlFeedReader(); Logger = new Logger(); Config = new NauConfigurations { TempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()), UpdateProcessName = "NAppUpdateProcess", UpdateExecutableName = "foo.exe", // Naming it updater.exe seem to trigger the UAC, and we don't want that }; // Need to do this manually here because the BackupFolder property is protected using the static instance, which we are // in the middle of creating string backupPath = Path.Combine(Path.GetDirectoryName(ApplicationPath) ?? string.Empty, "Backup" + DateTime.Now.Ticks); backupPath = backupPath.TrimEnd(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); Config._backupFolder = Path.IsPathRooted(backupPath) ? backupPath : Path.Combine(Config.TempFolder, backupPath); } static UpdateManager() { } /// <summary> /// The singleton update manager instance to used by consumer applications /// </summary> public static UpdateManager Instance { get { return instance; } } private static readonly UpdateManager instance = new UpdateManager(); // ReSharper disable NotAccessedField.Local private static Mutex _shutdownMutex; // ReSharper restore NotAccessedField.Local #endregion /// <summary> /// State of the update process /// </summary> [Serializable] public enum UpdateProcessState { NotChecked, Checked, Prepared, AfterRestart, AppliedSuccessfully, RollbackRequired, } internal readonly string ApplicationPath; public NauConfigurations Config { get; set; } public string BaseUrl { get; set; } internal IList<IUpdateTask> UpdatesToApply { get; private set; } public int UpdatesAvailable { get { return UpdatesToApply == null ? 0 : UpdatesToApply.Count; } } public UpdateProcessState State { get; private set; } public IUpdateSource UpdateSource { get; set; } public IUpdateFeedReader UpdateFeedReader { get; set; } public Logger Logger { get; private set; } public IEnumerable<IUpdateTask> Tasks { get { return UpdatesToApply; } } internal volatile bool ShouldStop; public bool IsWorking { get { return _isWorking; } private set { _isWorking = value; } } private volatile bool _isWorking; #region Progress reporting public event ReportProgressDelegate ReportProgress; private void TaskProgressCallback(UpdateProgressInfo currentStatus, IUpdateTask task) { if (ReportProgress == null) return; currentStatus.TaskDescription = task.Description; currentStatus.TaskId = UpdatesToApply.IndexOf(task) + 1; //This was an assumed int, which meant we never reached 100% with an odd number of tasks float taskPerc = 100F / UpdatesToApply.Count; currentStatus.Percentage = (int)Math.Round((currentStatus.Percentage * taskPerc / 100) + (currentStatus.TaskId - 1) * taskPerc); ReportProgress(currentStatus); } #endregion #region Step 1 - Check for updates /// <summary> /// Check for updates synchronously /// </summary> public void CheckForUpdates() { if (IsWorking) { throw new InvalidOperationException("Another update process is already in progress"); } else if (UpdateFeedReader == null) { throw new InvalidOperationException("UpdateFeedReader must be set before calling CheckForUpdates()"); } else if (UpdateSource == null) { throw new InvalidOperationException("UpdateSource must be set before calling CheckForUpdates()"); } using (WorkScope.New(isWorking => IsWorking = isWorking)) { if (State != UpdateProcessState.NotChecked) { throw new InvalidOperationException("Already checked for updates; to reset the current state call CleanUp()"); } lock (UpdatesToApply) { UpdatesToApply.Clear(); var tasks = UpdateFeedReader.Read(UpdateSource.GetUpdatesFeed()); foreach (var t in tasks) { if (ShouldStop) throw new UserAbortException(); if (t.UpdateConditions == null || t.UpdateConditions.IsMet(t)) // Only execute if all conditions are met UpdatesToApply.Add(t); } } State = UpdateProcessState.Checked; } } /// <summary> /// Check for updates asynchronously /// </summary> /// <param name="callback">Callback function to call when done; can be null</param> /// <param name="state">Allows the caller to preserve state; can be null</param> public IAsyncResult BeginCheckForUpdates(AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the // asynchronous operation var ar = new UpdateProcessAsyncResult(callback, state); // Use a thread pool thread to perform the operation ThreadPool.QueueUserWorkItem(o => { try { // Perform the operation; if sucessful set the result CheckForUpdates(); ar.SetAsCompleted(null, false); } catch (Exception e) { // If operation fails, set the exception ar.SetAsCompleted(e, false); } }, ar); return ar; // Return the IAsyncResult to the caller } /// <summary> /// Block until previously-called CheckForUpdates complete /// </summary> /// <param name="asyncResult"></param> public void EndCheckForUpdates(IAsyncResult asyncResult) { // Wait for operation to complete, then return or throw exception var ar = (UpdateProcessAsyncResult)asyncResult; ar.EndInvoke(); } #endregion #region Step 2 - Prepare to execute update tasks /// <summary> /// Prepare updates synchronously /// </summary> public void PrepareUpdates() { if (IsWorking) throw new InvalidOperationException("Another update process is already in progress"); using (WorkScope.New(isWorking => IsWorking = isWorking)) { lock (UpdatesToApply) { if (State != UpdateProcessState.Checked) throw new InvalidOperationException("Invalid state when calling PrepareUpdates(): " + State); if (UpdatesToApply.Count == 0) throw new InvalidOperationException("No updates to prepare"); if (!Directory.Exists(Config.TempFolder)) { Logger.Log("Creating Temp directory {0}", Config.TempFolder); Directory.CreateDirectory(Config.TempFolder); } else { Logger.Log("Using existing Temp directory {0}", Config.TempFolder); } foreach (var task in UpdatesToApply) { if (ShouldStop) throw new UserAbortException(); var t = task; task.ProgressDelegate += status => TaskProgressCallback(status, t); try { task.Prepare(UpdateSource); } catch (Exception ex) { task.ExecutionStatus = TaskExecutionStatus.FailedToPrepare; Logger.Log(ex); throw new UpdateProcessFailedException("Failed to prepare task: " + task.Description, ex); } task.ExecutionStatus = TaskExecutionStatus.Prepared; } State = UpdateProcessState.Prepared; } } } /// <summary> /// Prepare updates asynchronously /// </summary> /// <param name="callback">Callback function to call when done; can be null</param> /// <param name="state">Allows the caller to preserve state; can be null</param> public IAsyncResult BeginPrepareUpdates(AsyncCallback callback, Object state) { // Create IAsyncResult object identifying the // asynchronous operation var ar = new UpdateProcessAsyncResult(callback, state); // Use a thread pool thread to perform the operation ThreadPool.QueueUserWorkItem(o => { try { // Perform the operation; if sucessful set the result PrepareUpdates(); ar.SetAsCompleted(null, false); } catch (Exception e) { // If operation fails, set the exception ar.SetAsCompleted(e, false); } }, ar); return ar; // Return the IAsyncResult to the caller } /// <summary> /// Block until previously-called PrepareUpdates complete /// </summary> /// <param name="asyncResult"></param> public void EndPrepareUpdates(IAsyncResult asyncResult) { // Wait for operation to complete, then return or throw exception var ar = (UpdateProcessAsyncResult)asyncResult; ar.EndInvoke(); } #endregion #region Step 3 - Apply updates /// <summary> /// Starts the updater executable and sends update data to it, and relaunch the caller application as soon as its done /// </summary> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates() { ApplyUpdates(true); } /// <summary> /// Starts the updater executable and sends update data to it /// </summary> /// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates(bool relaunchApplication) { ApplyUpdates(relaunchApplication, false, false); } /// <summary> /// Starts the updater executable and sends update data to it /// </summary> /// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param> /// <param name="updaterDoLogging">true if the updater writes to a log file; false otherwise</param> /// <param name="updaterShowConsole">true if the updater shows the console window; false otherwise</param> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates(bool relaunchApplication, bool updaterDoLogging, bool updaterShowConsole) { if (IsWorking) throw new InvalidOperationException("Another update process is already in progress"); lock (UpdatesToApply) { using (WorkScope.New(isWorking => IsWorking = isWorking)) { bool revertToDefaultBackupPath = true; // Set current directory the the application directory // this prevents the updater from writing to e.g. c:\windows\system32 // if the process is started by autorun on windows logon. // ReSharper disable AssignNullToNotNullAttribute Environment.CurrentDirectory = Path.GetDirectoryName(ApplicationPath); // ReSharper restore AssignNullToNotNullAttribute // Make sure the current backup folder is accessible for writing from this process string backupParentPath = Path.GetDirectoryName(Config.BackupFolder) ?? string.Empty; if (Directory.Exists(backupParentPath) && PermissionsCheck.HaveWritePermissionsForFolder(backupParentPath)) { // Remove old backup folder, in case this same folder was used previously, // and it wasn't removed for some reason try { if (Directory.Exists(Config.BackupFolder)) FileSystem.DeleteDirectory(Config.BackupFolder); revertToDefaultBackupPath = false; } catch (UnauthorizedAccessException) { } // Attempt to (re-)create the backup folder try { Directory.CreateDirectory(Config.BackupFolder); if (!PermissionsCheck.HaveWritePermissionsForFolder(Config.BackupFolder)) revertToDefaultBackupPath = true; } catch (UnauthorizedAccessException) { // We're having permissions issues with this folder, so we'll attempt // using a backup in a default location revertToDefaultBackupPath = true; } } if (revertToDefaultBackupPath) { Config._backupFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Config.UpdateProcessName + "UpdateBackups" + DateTime.UtcNow.Ticks); try { Directory.CreateDirectory(Config.BackupFolder); } catch (UnauthorizedAccessException ex) { // We can't backup, so we abort throw new UpdateProcessFailedException("Could not create backup folder " + Config.BackupFolder, ex); } } bool runPrivileged = false, hasColdUpdates = false; State = UpdateProcessState.RollbackRequired; foreach (var task in UpdatesToApply) { IUpdateTask t = task; task.ProgressDelegate += status => TaskProgressCallback(status, t); try { // Execute the task task.ExecutionStatus = task.Execute(false); } catch (Exception ex) { task.ExecutionStatus = TaskExecutionStatus.Failed; // mark the failing task before rethrowing throw new UpdateProcessFailedException("Update task execution failed: " + task.Description, ex); } if (task.ExecutionStatus == TaskExecutionStatus.RequiresAppRestart || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart) { // Record that we have cold updates to run, and if required to run any of them privileged runPrivileged = runPrivileged || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart; hasColdUpdates = true; continue; } // We are being quite explicit here - only Successful return values are considered // to be Ok (cold updates are already handled above) if (task.ExecutionStatus != TaskExecutionStatus.Successful) throw new UpdateProcessFailedException("Update task execution failed: " + task.Description); } // If an application restart is required if (hasColdUpdates) { var dto = new NauIpc.NauDto { Configs = Instance.Config, Tasks = Instance.UpdatesToApply, AppPath = ApplicationPath, WorkingDirectory = Environment.CurrentDirectory, RelaunchApplication = relaunchApplication, LogItems = Logger.LogItems, }; NauIpc.ExtractUpdaterFromResource(Config.TempFolder, Instance.Config.UpdateExecutableName); var info = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = Path.Combine(Config.TempFolder, Instance.Config.UpdateExecutableName), Arguments = string.Format(@"""{0}"" {1} {2}", Config.UpdateProcessName, updaterShowConsole ? "-showConsole" : string.Empty, updaterDoLogging ? "-log" : string.Empty), }; if (!updaterShowConsole) { info.WindowStyle = ProcessWindowStyle.Hidden; info.CreateNoWindow = true; } // If we can't write to the destination folder, then lets try elevating priviledges. if (runPrivileged || !PermissionsCheck.HaveWritePermissionsForFolder(Environment.CurrentDirectory)) { info.Verb = "runas"; } bool createdNew; _shutdownMutex = new Mutex(true, Config.UpdateProcessName + "Mutex", out createdNew); try { NauIpc.LaunchProcessAndSendDto(dto, info, Config.UpdateProcessName); } catch (Exception ex) { throw new UpdateProcessFailedException("Could not launch cold update process", ex); } Environment.Exit(0); } State = UpdateProcessState.AppliedSuccessfully; UpdatesToApply.Clear(); } } } #endregion public void ReinstateIfRestarted() { if (!IsAfterRestart()) { return; } lock (UpdatesToApply) { NauIpc.NauDto dto = NauIpc.ReadDto(Config.UpdateProcessName); if (dto == null) { return; } Config = dto.Configs; UpdatesToApply = dto.Tasks; Logger = new Logger(dto.LogItems); State = UpdateProcessState.AfterRestart; } } /// <summary> /// Rollback executed updates in case of an update failure /// </summary> public void RollbackUpdates() { if (IsWorking) return; lock (UpdatesToApply) { foreach (var task in UpdatesToApply) { task.Rollback(); } State = UpdateProcessState.NotChecked; } } /// <summary> /// Abort update process, cancelling whatever background process currently taking place without waiting for it to complete /// </summary> public void Abort() { Abort(false); } /// <summary> /// Abort update process, cancelling whatever background process currently taking place /// </summary> /// <param name="waitForTermination">If true, blocks the calling thread until the current process terminates</param> public void Abort(bool waitForTermination) { ShouldStop = true; } /// <summary> /// Delete the temp folder as a whole and fail silently /// </summary> public void CleanUp() { Abort(true); lock (UpdatesToApply) { UpdatesToApply.Clear(); State = UpdateProcessState.NotChecked; try { if (Directory.Exists(Config.TempFolder)) FileSystem.DeleteDirectory(Config.TempFolder); } catch { } try { if (Directory.Exists(Config.BackupFolder)) FileSystem.DeleteDirectory(Config.BackupFolder); } catch { } ShouldStop = false; } } private bool IsAfterRestart() { foreach (string arg in Environment.GetCommandLineArgs()) { if (arg == "-nappupdate-afterrestart") { return true; } } return false; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using ParquetSharp.Column.Statistics; using ParquetSharp.External; using ParquetSharp.Hadoop.Metadata; using ParquetSharp.IO; using ParquetSharp.Schema; using static ParquetSharp.Schema.PrimitiveType; using static ParquetSharp.Util; using Repetition = ParquetSharp.Schema.Type.Repetition; namespace ParquetSharp.Format.Converter { // TODO: This file has become too long! // TODO: Lets split it up: https://issues.apache.org/jira/browse/PARQUET-310 public class ParquetMetadataConverter { internal static readonly MetadataFilter NO_FILTER = new NoFilter(); internal static readonly MetadataFilter SKIP_ROW_GROUPS = new SkipMetadataFilter(); private static readonly Log LOG = Log.getLog(typeof(ParquetMetadataConverter)); // NOTE: this cache is for memory savings, not cpu savings, and is used to de-duplicate // sets of encodings. It is important that all collections inserted to this cache be // immutable and have thread-safe read-only access. This can be achieved by wrapping // an unsynchronized collection in Collections.unmodifiable*(), and making sure to not // keep any references to the original collection. private static readonly ConcurrentDictionary<HashSet<Column.Encoding>, HashSet<Column.Encoding>> cachedEncodingSets = new ConcurrentDictionary<HashSet<Column.Encoding>, HashSet<Column.Encoding>>(); public FileMetaData toParquetMetadata(int currentVersion, ParquetMetadata parquetMetadata) { List<BlockMetaData> blocks = parquetMetadata.getBlocks(); List<RowGroup> rowGroups = new List<RowGroup>(); long numRows = 0; foreach (BlockMetaData block in blocks) { numRows += block.getRowCount(); addRowGroup(parquetMetadata, rowGroups, block); } FileMetaData fileMetaData = new FileMetaData( currentVersion, toParquetSchema(parquetMetadata.getFileMetaData().getSchema()), numRows, rowGroups); foreach (KeyValuePair<string, string> keyValue in parquetMetadata.getFileMetaData().getKeyValueMetaData()) { addKeyValue(fileMetaData, keyValue.Key, keyValue.Value); } fileMetaData.Created_by = parquetMetadata.getFileMetaData().getCreatedBy(); return fileMetaData; } // Visible for testing internal List<SchemaElement> toParquetSchema(MessageType schema) { List<SchemaElement> result = new List<SchemaElement>(); addToList(result, schema); return result; } private static void addToList(List<SchemaElement> result, ParquetSharp.Schema.Type field) { field.accept(new Visitor(result)); } private void addRowGroup(ParquetMetadata parquetMetadata, List<RowGroup> rowGroups, BlockMetaData block) { //rowGroup.total_byte_size = ; IReadOnlyCollection<ColumnChunkMetaData> columns = block.getColumns(); List<ColumnChunk> parquetColumns = new List<ColumnChunk>(); foreach (ColumnChunkMetaData columnMetaData in columns) { ColumnChunk columnChunk = new ColumnChunk(columnMetaData.getFirstDataPageOffset()); // verify this is the right offset columnChunk.File_path = block.getPath(); // they are in the same file for now columnChunk.Meta_data = new ColumnMetaData( getType(columnMetaData.getType()), toFormatEncodings(columnMetaData.getEncodings()), Arrays.asList(columnMetaData.getPath().toArray()), columnMetaData.getCodec().getParquetCompressionCodec(), columnMetaData.getValueCount(), columnMetaData.getTotalUncompressedSize(), columnMetaData.getTotalSize(), columnMetaData.getFirstDataPageOffset()); columnChunk.Meta_data.Dictionary_page_offset = columnMetaData.getDictionaryPageOffset(); if (!columnMetaData.getStatistics().isEmpty()) { columnChunk.Meta_data.Statistics = toParquetStatistics(columnMetaData.getStatistics()); } // columnChunk.meta_data.index_page_offset = ; // columnChunk.meta_data.key_value_metadata = ; // nothing yet parquetColumns.Add(columnChunk); } RowGroup rowGroup = new RowGroup(parquetColumns, block.getTotalByteSize(), block.getRowCount()); rowGroups.Add(rowGroup); } private List<Encoding> toFormatEncodings(HashSet<Column.Encoding> encodings) { List<Encoding> converted = new List<Encoding>(encodings.Count); foreach (Column.Encoding encoding in encodings) { converted.Add(getEncoding(encoding)); } return converted; } // Visible for testing HashSet<Column.Encoding> fromFormatEncodings(List<Encoding> encodings) { HashSet<Column.Encoding> converted = new HashSet<Column.Encoding>(); foreach (Encoding encoding in encodings) { converted.Add(getEncoding(encoding)); } // make converted unmodifiable, drop reference to modifiable copy converted = Collections.unmodifiableSet(converted); // atomically update the cache HashSet<Column.Encoding> cached = cachedEncodingSets.putIfAbsent(converted, converted); if (cached == null) { // cached == null signifies that converted was *not* in the cache previously // so we can return converted instead of throwing it away, it has now // been cached cached = converted; } return cached; } public Column.Encoding getEncoding(Encoding encoding) { return Column.Encoding.valueOf(encoding.name()); } public Encoding getEncoding(Column.Encoding encoding) { return Encoding.valueOf(encoding.name()); } public static Statistics toParquetStatistics(Column.Statistics.Statistics statistics) { Statistics stats = new Statistics(); if (!statistics.isEmpty()) { stats.Null_count = statistics.getNumNulls(); if (statistics.hasNonNullValue()) { stats.Max = statistics.getMaxBytes(); stats.Min = statistics.getMinBytes(); } } return stats; } /** * [Obsolete] Replaced by {@link #fromParquetStatistics( * String createdBy, Statistics statistics, PrimitiveTypeName type)} */ [Obsolete] public static Column.Statistics.Statistics fromParquetStatistics(Statistics statistics, PrimitiveTypeName type) { return fromParquetStatistics(null, statistics, type); } public static Column.Statistics.Statistics fromParquetStatistics (string createdBy, Format.Statistics statistics, PrimitiveTypeName type) { // create stats object based on the column type Column.Statistics.Statistics stats = Column.Statistics.Statistics.getStatsBasedOnType(type); // If there was no statistics written to the footer, create an empty Statistics object and return // NOTE: See docs in CorruptStatistics for explanation of why this check is needed if (statistics != null && !CorruptStatistics.shouldIgnoreStatistics(createdBy, type)) { if (statistics.__isset.max && statistics.__isset.min) { stats.setMinMaxFromBytes(statistics.Min, statistics.Max); } stats.setNumNulls(statistics.Null_count); } return stats; } static public PrimitiveTypeName getPrimitive(Type type) { switch (type) { case Type.BYTE_ARRAY: // TODO: rename BINARY and remove this switch return PrimitiveTypeName.BINARY; case Type.INT64: return PrimitiveTypeName.INT64; case Type.INT32: return PrimitiveTypeName.INT32; case Type.BOOLEAN: return PrimitiveTypeName.BOOLEAN; case Type.FLOAT: return PrimitiveTypeName.FLOAT; case Type.DOUBLE: return PrimitiveTypeName.DOUBLE; case Type.INT96: return PrimitiveTypeName.INT96; case Type.FIXED_LEN_BYTE_ARRAY: return PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY; default: throw new RuntimeException("Unknown type " + type); } } // Visible for testing static Type getType(PrimitiveTypeName type) { switch (type.Name) { case Name.INT64: return Format.Type.INT64; case Name.INT32: return Type.INT32; case Name.BOOLEAN: return Type.BOOLEAN; case Name.BINARY: return Type.BYTE_ARRAY; case Name.FLOAT: return Type.FLOAT; case Name.DOUBLE: return Type.DOUBLE; case Name.INT96: return Type.INT96; case Name.FIXED_LEN_BYTE_ARRAY: return Type.FIXED_LEN_BYTE_ARRAY; default: throw new RuntimeException("Unknown primitive type " + type); } } // Visible for testing OriginalType getOriginalType(ConvertedType type) { switch (type) { case ConvertedType.UTF8: return OriginalType.UTF8; case ConvertedType.MAP: return OriginalType.MAP; case ConvertedType.MAP_KEY_VALUE: return OriginalType.MAP_KEY_VALUE; case ConvertedType.LIST: return OriginalType.LIST; case ConvertedType.ENUM: return OriginalType.ENUM; case ConvertedType.DECIMAL: return OriginalType.DECIMAL; case ConvertedType.DATE: return OriginalType.DATE; case ConvertedType.TIME_MILLIS: return OriginalType.TIME_MILLIS; case ConvertedType.TIMESTAMP_MILLIS: return OriginalType.TIMESTAMP_MILLIS; case ConvertedType.INTERVAL: return OriginalType.INTERVAL; case ConvertedType.INT_8: return OriginalType.INT_8; case ConvertedType.INT_16: return OriginalType.INT_16; case ConvertedType.INT_32: return OriginalType.INT_32; case ConvertedType.INT_64: return OriginalType.INT_64; case ConvertedType.UINT_8: return OriginalType.UINT_8; case ConvertedType.UINT_16: return OriginalType.UINT_16; case ConvertedType.UINT_32: return OriginalType.UINT_32; case ConvertedType.UINT_64: return OriginalType.UINT_64; case ConvertedType.JSON: return OriginalType.JSON; case ConvertedType.BSON: return OriginalType.BSON; default: throw new RuntimeException("Unknown converted type " + type); } } // Visible for testing ConvertedType getConvertedType(OriginalType type) { switch (type) { case OriginalType.UTF8: return ConvertedType.UTF8; case OriginalType.MAP: return ConvertedType.MAP; case OriginalType.MAP_KEY_VALUE: return ConvertedType.MAP_KEY_VALUE; case OriginalType.LIST: return ConvertedType.LIST; case OriginalType.ENUM: return ConvertedType.ENUM; case OriginalType.DECIMAL: return ConvertedType.DECIMAL; case OriginalType.DATE: return ConvertedType.DATE; case OriginalType.TIME_MILLIS: return ConvertedType.TIME_MILLIS; case OriginalType.TIMESTAMP_MILLIS: return ConvertedType.TIMESTAMP_MILLIS; case OriginalType.INTERVAL: return ConvertedType.INTERVAL; case OriginalType.INT_8: return ConvertedType.INT_8; case OriginalType.INT_16: return ConvertedType.INT_16; case OriginalType.INT_32: return ConvertedType.INT_32; case OriginalType.INT_64: return ConvertedType.INT_64; case OriginalType.UINT_8: return ConvertedType.UINT_8; case OriginalType.UINT_16: return ConvertedType.UINT_16; case OriginalType.UINT_32: return ConvertedType.UINT_32; case OriginalType.UINT_64: return ConvertedType.UINT_64; case OriginalType.JSON: return ConvertedType.JSON; case OriginalType.BSON: return ConvertedType.BSON; default: throw new RuntimeException("Unknown original type " + type); } } private static void addKeyValue(FileMetaData fileMetaData, string key, string value) { KeyValue keyValue = new KeyValue(key); keyValue.Value = value; fileMetaData.Key_value_metadata.Add(keyValue); } internal interface MetadataFilterVisitor<T> { T visit(NoFilter filter); T visit(SkipMetadataFilter filter); T visit(RangeMetadataFilter filter); } internal abstract class MetadataFilter { protected MetadataFilter() { } internal abstract T accept<T>(MetadataFilterVisitor<T> visitor); } /** * [ startOffset, endOffset ) * @param startOffset * @param endOffset * @return the filter */ internal static MetadataFilter range(long startOffset, long endOffset) { return new RangeMetadataFilter(startOffset, endOffset); } internal sealed class NoFilter : MetadataFilter { public NoFilter() { } internal override T accept<T>(MetadataFilterVisitor<T> visitor) { return visitor.visit(this); } public override string ToString() { return "NO_FILTER"; } } internal sealed class SkipMetadataFilter : MetadataFilter { public SkipMetadataFilter() { } internal override T accept<T>(MetadataFilterVisitor<T> visitor) { return visitor.visit(this); } public override string ToString() { return "SKIP_ROW_GROUPS"; } } /** * [ startOffset, endOffset ) * @author Julien Le Dem */ // Visible for testing internal sealed class RangeMetadataFilter : MetadataFilter { readonly long startOffset; readonly long endOffset; public RangeMetadataFilter(long startOffset, long endOffset) { this.startOffset = startOffset; this.endOffset = endOffset; } internal override T accept<T>(MetadataFilterVisitor<T> visitor) { return visitor.visit(this); } internal bool contains(long offset) { return offset >= this.startOffset && offset < this.endOffset; } public override string ToString() { return "range(s:" + startOffset + ", e:" + endOffset + ")"; } } [Obsolete] public ParquetMetadata readParquetMetadata(InputStream from) { return readParquetMetadata(from, NO_FILTER); } // Visible for testing static FileMetaData filterFileMetaData(FileMetaData metaData, RangeMetadataFilter filter) { List<RowGroup> rowGroups = metaData.Row_groups; List<RowGroup> newRowGroups = new List<RowGroup>(); foreach (RowGroup rowGroup in rowGroups) { long totalSize = 0; long startIndex = getOffset(rowGroup.Columns[0]); foreach (ColumnChunk col in rowGroup.Columns) { totalSize += col.Meta_data.Total_compressed_size; } long midPoint = startIndex + totalSize / 2; if (filter.contains(midPoint)) { newRowGroups.Add(rowGroup); } } metaData.Row_groups = newRowGroups; return metaData; } // Visible for testing static long getOffset(RowGroup rowGroup) { return getOffset(rowGroup.Columns[0]); } // Visible for testing static long getOffset(ColumnChunk columnChunk) { ColumnMetaData md = columnChunk.Meta_data; long offset = md.Data_page_offset; if (md.__isset.dictionary_page_offset && offset > md.Dictionary_page_offset) { offset = md.Dictionary_page_offset; } return offset; } internal ParquetMetadata readParquetMetadata(InputStream from, MetadataFilter filter) { FileMetaData fileMetaData = filter.accept(new MyMetadataFilterVisitor(from)); if (Log.DEBUG) LOG.debug(fileMetaData); ParquetMetadata parquetMetadata = fromParquetMetadata(fileMetaData); if (Log.DEBUG) LOG.debug(ParquetMetadata.toPrettyJSON(parquetMetadata)); return parquetMetadata; } public ParquetMetadata fromParquetMetadata(FileMetaData parquetMetadata) { MessageType messageType = fromParquetSchema(parquetMetadata.Schema); List<BlockMetaData> blocks = new List<BlockMetaData>(); List<RowGroup> row_groups = parquetMetadata.Row_groups; if (row_groups != null) { foreach (RowGroup rowGroup in row_groups) { BlockMetaData blockMetaData = new BlockMetaData(); blockMetaData.setRowCount(rowGroup.Num_rows); blockMetaData.setTotalByteSize(rowGroup.Total_byte_size); List<ColumnChunk> columns = rowGroup.Columns; string filePath = columns[0].File_path; foreach (ColumnChunk columnChunk in columns) { if ((filePath == null && columnChunk.File_path != null) || (filePath != null && !filePath.Equals(columnChunk.File_path))) { throw new ParquetDecodingException("all column chunks of the same row group must be in the same file for now"); } ColumnMetaData metaData = columnChunk.Meta_data; ColumnPath path = getPath(metaData); ColumnChunkMetaData column = ColumnChunkMetaData.get( path, messageType.getType(path.toArray()).asPrimitiveType().getPrimitiveTypeName(), CompressionCodecName.fromParquet(metaData.Codec), fromFormatEncodings(metaData.Encodings), fromParquetStatistics( parquetMetadata.Created_by, metaData.Statistics, messageType.getType(path.toArray()).asPrimitiveType().getPrimitiveTypeName()), metaData.Data_page_offset, metaData.Dictionary_page_offset, metaData.Num_values, metaData.Total_compressed_size, metaData.Total_uncompressed_size); // TODO // index_page_offset // key_value_metadata blockMetaData.addColumn(column); } blockMetaData.setPath(filePath); blocks.Add(blockMetaData); } } Dictionary<string, string> keyValueMetaData = new Dictionary<string, string>(); List<KeyValue> key_value_metadata = parquetMetadata.Key_value_metadata; if (key_value_metadata != null) { foreach (KeyValue keyValue in key_value_metadata) { keyValueMetaData[keyValue.Key] = keyValue.Value; } } return new ParquetMetadata( new Hadoop.Metadata.FileMetaData(messageType, keyValueMetaData, parquetMetadata.Created_by), blocks); } private static ColumnPath getPath(ColumnMetaData metaData) { string[] path = metaData.Path_in_schema.ToArray(); return ColumnPath.get(path); } // Visible for testing internal MessageType fromParquetSchema(List<SchemaElement> schema) { IEnumerator<SchemaElement> iterator = schema.GetEnumerator(); iterator.MoveNext(); SchemaElement root = iterator.Current; Schema.Types.MessageTypeBuilder builder = Schema.Types.buildMessage(); buildChildren(builder, iterator, root.Num_children); return builder.named(root.Name); } private void buildChildren(Schema.Types.GroupBuilder builder, IEnumerator<SchemaElement> schema, int childrenCount) { for (int i = 0; i < childrenCount; i++) { schema.MoveNext(); SchemaElement schemaElement = schema.Current; // Create Parquet Type. Schema.Types.Builder childBuilder; if (schemaElement.Type != null) { Schema.Types.PrimitiveBuilder primitiveBuilder = builder.primitive( getPrimitive(schemaElement.Type), fromParquetRepetition(schemaElement.Repetition_type)); if (schemaElement.__isset.type_length) { primitiveBuilder.length(schemaElement.Type_length); } if (schemaElement.__isset.precision) { primitiveBuilder.precision(schemaElement.Precision); } if (schemaElement.__isset.scale) { primitiveBuilder.scale(schemaElement.Scale); } childBuilder = primitiveBuilder; } else { childBuilder = builder.group(fromParquetRepetition(schemaElement.Repetition_type)); buildChildren((Schema.Types.GroupBuilder)childBuilder, schema, schemaElement.Num_children); } if (schemaElement.__isset.converted_type) { childBuilder.@as(getOriginalType(schemaElement.Converted_type)); } if (schemaElement.__isset.field_id) { childBuilder.id(schemaElement.Field_id); } childBuilder.named(schemaElement.Name); } } // Visible for testing static FieldRepetitionType toParquetRepetition(Repetition repetition) { return FieldRepetitionType.valueOf(repetition.name()); } // Visible for testing static Repetition fromParquetRepetition(FieldRepetitionType repetition) { return Repetition.valueOf(repetition.name()); } [Obsolete] public void writeDataPageHeader( int uncompressedSize, int compressedSize, int valueCount, Column.Encoding rlEncoding, Column.Encoding dlEncoding, Column.Encoding valuesEncoding, OutputStream to) { writePageHeader(newDataPageHeader(uncompressedSize, compressedSize, valueCount, new BooleanStatistics(), rlEncoding, dlEncoding, valuesEncoding), to); } public void writeDataPageHeader( int uncompressedSize, int compressedSize, int valueCount, Column.Statistics.Statistics statistics, Column.Encoding rlEncoding, Column.Encoding dlEncoding, Column.Encoding valuesEncoding, OutputStream to) { writePageHeader( newDataPageHeader(uncompressedSize, compressedSize, valueCount, statistics, rlEncoding, dlEncoding, valuesEncoding), to); } private PageHeader newDataPageHeader( int uncompressedSize, int compressedSize, int valueCount, Column.Statistics.Statistics statistics, Column.Encoding rlEncoding, Column.Encoding dlEncoding, Column.Encoding valuesEncoding) { PageHeader pageHeader = new PageHeader(PageType.DATA_PAGE, uncompressedSize, compressedSize); // TODO: pageHeader.crc = ...; pageHeader.Data_page_header = new DataPageHeader( valueCount, getEncoding(valuesEncoding), getEncoding(dlEncoding), getEncoding(rlEncoding)); if (!statistics.isEmpty()) { pageHeader.Data_page_header.Statistics = toParquetStatistics(statistics); } return pageHeader; } public void writeDataPageV2Header( int uncompressedSize, int compressedSize, int valueCount, int nullCount, int rowCount, Column.Statistics.Statistics statistics, Column.Encoding dataEncoding, int rlByteLength, int dlByteLength, OutputStream to) { writePageHeader( newDataPageV2Header( uncompressedSize, compressedSize, valueCount, nullCount, rowCount, statistics, dataEncoding, rlByteLength, dlByteLength), to); } private PageHeader newDataPageV2Header( int uncompressedSize, int compressedSize, int valueCount, int nullCount, int rowCount, Column.Statistics.Statistics statistics, Column.Encoding dataEncoding, int rlByteLength, int dlByteLength) { // TODO: pageHeader.crc = ...; DataPageHeaderV2 dataPageHeaderV2 = new DataPageHeaderV2( valueCount, nullCount, rowCount, getEncoding(dataEncoding), dlByteLength, rlByteLength); if (!statistics.isEmpty()) { dataPageHeaderV2.Statistics = toParquetStatistics(statistics); } PageHeader pageHeader = new PageHeader(PageType.DATA_PAGE_V2, uncompressedSize, compressedSize); pageHeader.Data_page_header_v2 = dataPageHeaderV2; return pageHeader; } public void writeDictionaryPageHeader( int uncompressedSize, int compressedSize, int valueCount, Column.Encoding valuesEncoding, OutputStream to) { PageHeader pageHeader = new PageHeader(PageType.DICTIONARY_PAGE, uncompressedSize, compressedSize); pageHeader.Dictionary_page_header = new DictionaryPageHeader(valueCount, getEncoding(valuesEncoding)); writePageHeader(pageHeader, to); } class Visitor : TypeVisitor { readonly List<SchemaElement> result; public Visitor(List<SchemaElement> result) { this.result = result; } public void visit(PrimitiveType primitiveType) { SchemaElement element = new SchemaElement(primitiveType.getName()); element.Repetition_type = toParquetRepetition(primitiveType.getRepetition()); element.Type = getType(primitiveType.getPrimitiveTypeName()); if (primitiveType.getOriginalType() != null) { element.Converted_type = getConvertedType(primitiveType.getOriginalType()); } if (primitiveType.getDecimalMetadata() != null) { element.Precision = primitiveType.getDecimalMetadata().getPrecision(); element.Scale = primitiveType.getDecimalMetadata().getScale(); } if (primitiveType.getTypeLength() > 0) { element.Type_length = primitiveType.getTypeLength(); } result.Add(element); } public void visit(MessageType messageType) { SchemaElement element = new SchemaElement(messageType.getName()); visitChildren(result, messageType.asGroupType(), element); } public void visit(GroupType groupType) { SchemaElement element = new SchemaElement(groupType.getName()); element.Repetition_type = toParquetRepetition(groupType.getRepetition()); if (groupType.getOriginalType() != null) { element.Converted_type = getConvertedType(groupType.getOriginalType()); } visitChildren(result, groupType, element); } private void visitChildren(List<SchemaElement> result, GroupType groupType, SchemaElement element) { element.Num_children = groupType.getFieldCount(); result.Add(element); foreach (ParquetSharp.Schema.Type field in groupType.getFields()) { addToList(result, field); } } } class MyMetadataFilterVisitor : MetadataFilterVisitor<FileMetaData> { readonly InputStream from; public MyMetadataFilterVisitor(InputStream from) { this.from = from; } public FileMetaData visit(NoFilter filter) { return readFileMetaData(from); } public FileMetaData visit(SkipMetadataFilter filter) { return readFileMetaData(from, true); } public FileMetaData visit(RangeMetadataFilter filter) { return filterFileMetaData(readFileMetaData(from), filter); } } } }
// 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. // // C# translation of Whetstone Double Precision Benchmark using Microsoft.Xunit.Performance; using System; using System.Runtime.CompilerServices; using Xunit; [assembly: OptimizeForBenchmarks] namespace Benchstone.BenchF { public static class Whetsto { #if DEBUG public const int Iterations = 1; #else public const int Iterations = 50000; #endif private static int s_j, s_k, s_l; private static double s_t, s_t2; public static volatile int Volatile_out; private static void Escape(int n, int j, int k, double x1, double x2, double x3, double x4) { Volatile_out = n; Volatile_out = j; Volatile_out = k; Volatile_out = (int)x1; Volatile_out = (int)x2; Volatile_out = (int)x3; Volatile_out = (int)x4; } [MethodImpl(MethodImplOptions.NoInlining)] private static bool Bench() { double[] e1 = new double[4]; double x1, x2, x3, x4, x, y, z, t1; int i, n1, n2, n3, n4, n6, n7, n8, n9, n10, n11; s_t = 0.499975; t1 = 0.50025; s_t2 = 2.0; n1 = 0 * Iterations; n2 = 12 * Iterations; n3 = 14 * Iterations; n4 = 345 * Iterations; n6 = 210 * Iterations; n7 = 32 * Iterations; n8 = 899 * Iterations; n9 = 616 * Iterations; n10 = 0 * Iterations; n11 = 93 * Iterations; x1 = 1.0; x2 = x3 = x4 = -1.0; for (i = 1; i <= n1; i += 1) { x1 = (x1 + x2 + x3 - x4) * s_t; x2 = (x1 + x2 - x3 - x4) * s_t; x3 = (x1 - x2 + x3 + x4) * s_t; x4 = (-x1 + x2 + x3 + x4) * s_t; } Escape(n1, n1, n1, x1, x2, x3, x4); /* MODULE 2: array elements */ e1[0] = 1.0; e1[1] = e1[2] = e1[3] = -1.0; for (i = 1; i <= n2; i += 1) { e1[0] = (e1[0] + e1[1] + e1[2] - e1[3]) * s_t; e1[1] = (e1[0] + e1[1] - e1[2] + e1[3]) * s_t; e1[2] = (e1[0] - e1[1] + e1[2] + e1[3]) * s_t; e1[3] = (-e1[0] + e1[1] + e1[2] + e1[3]) * s_t; } Escape(n2, n3, n2, e1[0], e1[1], e1[2], e1[3]); /* MODULE 3: array as parameter */ for (i = 1; i <= n3; i += 1) { PA(e1); } Escape(n3, n2, n2, e1[0], e1[1], e1[2], e1[3]); /* MODULE 4: conditional jumps */ s_j = 1; for (i = 1; i <= n4; i += 1) { if (s_j == 1) { s_j = 2; } else { s_j = 3; } if (s_j > 2) { s_j = 0; } else { s_j = 1; } if (s_j < 1) { s_j = 1; } else { s_j = 0; } } Escape(n4, s_j, s_j, x1, x2, x3, x4); /* MODULE 5: omitted */ /* MODULE 6: integer Math */ s_j = 1; s_k = 2; s_l = 3; for (i = 1; i <= n6; i += 1) { s_j = s_j * (s_k - s_j) * (s_l - s_k); s_k = s_l * s_k - (s_l - s_j) * s_k; s_l = (s_l - s_k) * (s_k + s_j); e1[s_l - 2] = s_j + s_k + s_l; e1[s_k - 2] = s_j * s_k * s_l; } Escape(n6, s_j, s_k, e1[0], e1[1], e1[2], e1[3]); /* MODULE 7: trig. functions */ x = y = 0.5; for (i = 1; i <= n7; i += 1) { x = s_t * System.Math.Atan(s_t2 * System.Math.Sin(x) * System.Math.Cos(x) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0)); y = s_t * System.Math.Atan(s_t2 * System.Math.Sin(y) * System.Math.Cos(y) / (System.Math.Cos(x + y) + System.Math.Cos(x - y) - 1.0)); } Escape(n7, s_j, s_k, x, x, y, y); /* MODULE 8: procedure calls */ x = y = z = 1.0; for (i = 1; i <= n8; i += 1) { P3(x, y, out z); } Escape(n8, s_j, s_k, x, y, z, z); /* MODULE9: array references */ s_j = 1; s_k = 2; s_l = 3; e1[0] = 1.0; e1[1] = 2.0; e1[2] = 3.0; for (i = 1; i <= n9; i += 1) { P0(e1); } Escape(n9, s_j, s_k, e1[0], e1[1], e1[2], e1[3]); /* MODULE10: integer System.Math */ s_j = 2; s_k = 3; for (i = 1; i <= n10; i += 1) { s_j = s_j + s_k; s_k = s_j + s_k; s_j = s_k - s_j; s_k = s_k - s_j - s_j; } Escape(n10, s_j, s_k, x1, x2, x3, x4); /* MODULE11: standard functions */ x = 0.75; for (i = 1; i <= n11; i += 1) { x = System.Math.Sqrt(System.Math.Exp(System.Math.Log(x) / t1)); } Escape(n11, s_j, s_k, x, x, x, x); return true; } private static void PA(double[] e) { int j; j = 0; lab: e[0] = (e[0] + e[1] + e[2] - e[3]) * s_t; e[1] = (e[0] + e[1] - e[2] + e[3]) * s_t; e[2] = (e[0] - e[1] + e[2] + e[3]) * s_t; e[3] = (-e[0] + e[1] + e[2] + e[3]) / s_t2; j += 1; if (j < 6) { goto lab; } } private static void P3(double x, double y, out double z) { x = s_t * (x + y); y = s_t * (x + y); z = (x + y) / s_t2; } private static void P0(double[] e1) { e1[s_j] = e1[s_k]; e1[s_k] = e1[s_l]; e1[s_l] = e1[s_j]; } [Benchmark] public static void Test() { foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { Bench(); } } } private static bool TestBase() { bool result = Bench(); return result; } public static int Main() { bool result = TestBase(); return (result ? 100 : -1); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.ComponentModel; using System.Globalization; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using MahApps.Metro; using MetroDemo.Models; using System.Windows.Input; using MahApps.Metro.Controls; using MahApps.Metro.Controls.Dialogs; using MetroDemo.ExampleViews; using NHotkey; using NHotkey.Wpf; namespace MetroDemo { public class AccentColorMenuData { public string Name { get; set; } public Brush BorderColorBrush { get; set; } public Brush ColorBrush { get; set; } private ICommand changeAccentCommand; public ICommand ChangeAccentCommand { get { return this.changeAccentCommand ?? (changeAccentCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => this.DoChangeTheme(x) }); } } protected virtual void DoChangeTheme(object sender) { var theme = ThemeManager.DetectAppStyle(Application.Current); var accent = ThemeManager.GetAccent(this.Name); ThemeManager.ChangeAppStyle(Application.Current, accent, theme.Item1); } } public class AppThemeMenuData : AccentColorMenuData { protected override void DoChangeTheme(object sender) { var theme = ThemeManager.DetectAppStyle(Application.Current); var appTheme = ThemeManager.GetAppTheme(this.Name); ThemeManager.ChangeAppStyle(Application.Current, theme.Item2, appTheme); } } public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo, IDisposable { private readonly IDialogCoordinator _dialogCoordinator; int? _integerGreater10Property; private bool _animateOnPositionChange = true; public MainWindowViewModel(IDialogCoordinator dialogCoordinator) { this.Title = "Flyout Binding Test"; _dialogCoordinator = dialogCoordinator; SampleData.Seed(); // create accent color menu items for the demo this.AccentColors = ThemeManager.Accents .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush }) .ToList(); // create metro theme color menu items for the demo this.AppThemes = ThemeManager.AppThemes .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush }) .ToList(); Albums = SampleData.Albums; Artists = SampleData.Artists; FlipViewImages = new Uri[] { new Uri("http://www.public-domain-photos.com/free-stock-photos-4/landscapes/mountains/painted-desert.jpg", UriKind.Absolute), new Uri("http://www.public-domain-photos.com/free-stock-photos-3/landscapes/forest/breaking-the-clouds-on-winter-day.jpg", UriKind.Absolute), new Uri("http://www.public-domain-photos.com/free-stock-photos-4/travel/bodie/bodie-streets.jpg", UriKind.Absolute) }; BrushResources = FindBrushResources(); CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).OrderBy(c => c.DisplayName).ToList(); try { HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e)); } catch (HotkeyAlreadyRegisteredException exception) { System.Diagnostics.Trace.TraceWarning("Uups, the hotkey {0} is already registered!", exception.Name); } } public void Dispose() { HotkeyManager.Current.Remove("demo"); } public string Title { get; set; } public int SelectedIndex { get; set; } public List<Album> Albums { get; set; } public List<Artist> Artists { get; set; } public List<AccentColorMenuData> AccentColors { get; set; } public List<AppThemeMenuData> AppThemes { get; set; } public List<CultureInfo> CultureInfos { get; set; } public int? IntegerGreater10Property { get { return this._integerGreater10Property; } set { if (Equals(value, _integerGreater10Property)) { return; } _integerGreater10Property = value; RaisePropertyChanged("IntegerGreater10Property"); } } DateTime? _datePickerDate; [Display(Prompt = "Auto resolved Watermark")] public DateTime? DatePickerDate { get { return this._datePickerDate; } set { if (Equals(value, _datePickerDate)) { return; } _datePickerDate = value; RaisePropertyChanged("DatePickerDate"); } } bool _magicToggleButtonIsChecked = true; public bool MagicToggleButtonIsChecked { get { return this._magicToggleButtonIsChecked; } set { if (Equals(value, _magicToggleButtonIsChecked)) { return; } _magicToggleButtonIsChecked = value; RaisePropertyChanged("MagicToggleButtonIsChecked"); } } private bool _quitConfirmationEnabled; public bool QuitConfirmationEnabled { get { return _quitConfirmationEnabled; } set { if (value.Equals(_quitConfirmationEnabled)) return; _quitConfirmationEnabled = value; RaisePropertyChanged("QuitConfirmationEnabled"); } } private bool showMyTitleBar = true; public bool ShowMyTitleBar { get { return showMyTitleBar; } set { if (value.Equals(showMyTitleBar)) return; showMyTitleBar = value; RaisePropertyChanged("ShowMyTitleBar"); } } private bool canCloseFlyout = true; public bool CanCloseFlyout { get { return this.canCloseFlyout; } set { if (Equals(value, this.canCloseFlyout)) { return; } this.canCloseFlyout = value; this.RaisePropertyChanged("CanCloseFlyout"); } } private ICommand closeCmd; public ICommand CloseCmd { get { return this.closeCmd ?? (this.closeCmd = new SimpleCommand { CanExecuteDelegate = x => this.CanCloseFlyout, ExecuteDelegate = x => ((Flyout)x).IsOpen = false }); } } private bool canShowHamburgerAboutCommand = true; public bool CanShowHamburgerAboutCommand { get { return this.canShowHamburgerAboutCommand; } set { if (Equals(value, this.canShowHamburgerAboutCommand)) { return; } this.canShowHamburgerAboutCommand = value; this.RaisePropertyChanged("CanShowHamburgerAboutCommand"); } } private bool isHamburgerMenuPaneOpen; public bool IsHamburgerMenuPaneOpen { get { return this.isHamburgerMenuPaneOpen; } set { if (Equals(value, this.isHamburgerMenuPaneOpen)) { return; } this.isHamburgerMenuPaneOpen = value; this.RaisePropertyChanged("IsHamburgerMenuPaneOpen"); } } private ICommand textBoxButtonCmd; public ICommand TextBoxButtonCmd { get { return this.textBoxButtonCmd ?? (this.textBoxButtonCmd = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = async x => { if (x is string) { await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Wow, you typed Return and got", (string)x); } else if (x is TextBox) { await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button was clicked!", string.Format("Text: {0}", ((TextBox) x).Text)); } else if (x is PasswordBox) { await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("PasswordBox Button was clicked!", string.Format("Password: {0}", ((PasswordBox) x).Password)); } } }); } } private ICommand textBoxButtonCmdWithParameter; public ICommand TextBoxButtonCmdWithParameter { get { return this.textBoxButtonCmdWithParameter ?? (this.textBoxButtonCmdWithParameter = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = async x => { if (x is String) { await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("TextBox Button with parameter was clicked!", string.Format("Parameter: {0}", x)); } } }); } } public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event if needed. /// </summary> /// <param name="propertyName">The name of the property that changed.</param> protected virtual void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public string this[string columnName] { get { if (columnName == "IntegerGreater10Property" && this.IntegerGreater10Property < 10) { return "Number is not greater than 10!"; } if (columnName == "DatePickerDate" && this.DatePickerDate == null) { return "No date given!"; } if (columnName == "HotKey" && this.HotKey != null && this.HotKey.Key == Key.D && this.HotKey.ModifierKeys == ModifierKeys.Shift) { return "SHIFT-D is not allowed"; } return null; } } [Description("Test-Property")] public string Error { get { return string.Empty; } } private ICommand singleCloseTabCommand; public ICommand SingleCloseTabCommand { get { return this.singleCloseTabCommand ?? (this.singleCloseTabCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = async x => { await ((MetroWindow) Application.Current.MainWindow).ShowMessageAsync("Closing tab!", string.Format("You are now closing the '{0}' tab", x)); } }); } } private ICommand neverCloseTabCommand; public ICommand NeverCloseTabCommand { get { return this.neverCloseTabCommand ?? (this.neverCloseTabCommand = new SimpleCommand { CanExecuteDelegate = x => false }); } } private ICommand showInputDialogCommand; public ICommand ShowInputDialogCommand { get { return this.showInputDialogCommand ?? (this.showInputDialogCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = async x => { await _dialogCoordinator.ShowInputAsync(this, "From a VM", "This dialog was shown from a VM, without knowledge of Window").ContinueWith(t => Console.WriteLine(t.Result)); } }); } } private ICommand showLoginDialogCommand; public ICommand ShowLoginDialogCommand { get { return this.showLoginDialogCommand ?? (this.showLoginDialogCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = async x => { await _dialogCoordinator.ShowLoginAsync(this, "Login from a VM", "This login dialog was shown from a VM, so you can be all MVVM.").ContinueWith(t => Console.WriteLine(t.Result)); } }); } } private ICommand showMessageDialogCommand; public ICommand ShowMessageDialogCommand { get { return this.showMessageDialogCommand ?? (this.showMessageDialogCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => PerformDialogCoordinatorAction(this.ShowMessage((string)x), (string)x == "DISPATCHER_THREAD") }); } } private Action ShowMessage(string startingThread) { return () => { var message = $"MVVM based messages!\n\nThis dialog was created by {startingThread} Thread with ID=\"{Thread.CurrentThread.ManagedThreadId}\"\n" + $"The current DISPATCHER_THREAD Thread has the ID=\"{Application.Current.Dispatcher.Thread.ManagedThreadId}\""; this._dialogCoordinator.ShowMessageAsync(this, $"Message from VM created by {startingThread}", message).ContinueWith(t => Console.WriteLine(t.Result)); }; } private ICommand showProgressDialogCommand; public ICommand ShowProgressDialogCommand { get { return this.showProgressDialogCommand ?? (this.showProgressDialogCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => RunProgressFromVm() }); } } private async void RunProgressFromVm() { var controller = await _dialogCoordinator.ShowProgressAsync(this, "Progress from VM", "Progressing all the things, wait 3 seconds"); controller.SetIndeterminate(); await TaskEx.Delay(3000); await controller.CloseAsync(); } private static void PerformDialogCoordinatorAction(Action action, bool runInMainThread) { if (!runInMainThread) { Task.Factory.StartNew(action); } else { action(); } } private ICommand showCustomDialogCommand; public ICommand ShowCustomDialogCommand { get { return this.showCustomDialogCommand ?? (this.showCustomDialogCommand = new SimpleCommand { CanExecuteDelegate = x => true, ExecuteDelegate = x => RunCustomFromVm() }); } } private async void RunCustomFromVm() { var customDialog = new CustomDialog() { Title = "Custom Dialog" }; var dataContext = new CustomDialogExampleContent(instance => { _dialogCoordinator.HideMetroDialogAsync(this, customDialog); System.Diagnostics.Debug.WriteLine(instance.FirstName); }); customDialog.Content = new CustomDialogExample { DataContext = dataContext}; await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog); } public IEnumerable<string> BrushResources { get; private set; } public bool AnimateOnPositionChange { get { return _animateOnPositionChange; } set { if (Equals(_animateOnPositionChange, value)) return; _animateOnPositionChange = value; RaisePropertyChanged("AnimateOnPositionChange"); } } private IEnumerable<string> FindBrushResources() { var rd = new ResourceDictionary { Source = new Uri(@"/MahApps.Metro;component/Styles/Colors.xaml", UriKind.RelativeOrAbsolute) }; var resources = rd.Keys.Cast<object>() .Where(key => rd[key] is Brush) .Select(key => key.ToString()) .OrderBy(s => s) .ToList(); return resources; } public Uri[] FlipViewImages { get; set; } public class RandomDataTemplateSelector : DataTemplateSelector { public DataTemplate TemplateOne { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { return TemplateOne; } } private HotKey _hotKey = new HotKey(Key.Home, ModifierKeys.Control | ModifierKeys.Shift); public HotKey HotKey { get { return _hotKey; } set { if (_hotKey != value) { _hotKey = value; if (_hotKey != null && _hotKey.Key != Key.None) { HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e)); } else { HotkeyManager.Current.Remove("demo"); } RaisePropertyChanged("HotKey"); } } } private async Task OnHotKey(object sender, HotkeyEventArgs e) { await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync( "Hotkey pressed", "You pressed the hotkey '" + HotKey + "' registered with the name '" + e.Name + "'"); } private ICommand toggleIconScalingCommand; public ICommand ToggleIconScalingCommand { get { return toggleIconScalingCommand ?? (toggleIconScalingCommand = new SimpleCommand { ExecuteDelegate = ToggleIconScaling }); } } private void ToggleIconScaling(object obj) { var multiFrameImageMode = (MultiFrameImageMode)obj; ((MetroWindow)Application.Current.MainWindow).IconScalingMode = multiFrameImageMode; RaisePropertyChanged("IsScaleDownLargerFrame"); RaisePropertyChanged("IsNoScaleSmallerFrame"); } public bool IsScaleDownLargerFrame { get { return ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.ScaleDownLargerFrame; } } public bool IsNoScaleSmallerFrame { get { return ((MetroWindow)Application.Current.MainWindow).IconScalingMode == MultiFrameImageMode.NoScaleSmallerFrame; } } } }
#define TEST_DIRECT using System; using System.Diagnostics; using System.Collections.Generic; using ProtoCore; namespace ProtoAssociative.DependencyPass { //@TODO: Replace this whole structure with a DS-Hydrogen implementation public class AST { public AST () { } public DependencyPass.DependencyTracker GetDemoTracker2() { Associative.Scanner s = new Associative.Scanner(@"..\..\Scripts\expr.ds"); Associative.Parser p = new Associative.Parser(s); p.Parse(); CodeBlockNode code = p.codeblock; DependencyTracker tempTracker = new DependencyTracker(); Dictionary<string, List<Node>> names = new Dictionary<string, List<Node>>(); code.ConsolidateNames(ref(names)); tempTracker.GenerateDependencyGraph(code.Body); return tempTracker; } public DependencyPass.DependencyTracker GetDemoTracker3(out ProtoCore.DSASM.SymbolTable symbols, string pathFilename) { Associative.Scanner s = new Associative.Scanner(pathFilename); Associative.Parser p = new Associative.Parser(s); p.Parse(); CodeBlockNode code = p.codeblock; symbols = code.symbols; DependencyTracker tempTracker = new DependencyTracker(); #if TEST_DIRECT foreach (Node node in code.Body) { tempTracker.AllNodes.Add(node); } #else Dictionary<string, List<Node>> names = new Dictionary<string, List<Node>>(); code.ConsolidateNames(ref(names)); tempTracker.GenerateDependencyGraph(code.Body); #endif return tempTracker; } /* public DependencyPass.DependencyTracker generateAST(ProtoCore.CodeBlock codeblock) { DependencyTracker tempTracker = new DependencyTracker(); foreach (Object obj in codeblock.Body) { Debug.Assert(obj is ProtoAssociative.DependencyPass.Node); Node node = obj as ProtoAssociative.DependencyPass.Node; tempTracker.AllNodes.Add(node); } return tempTracker; } * */ public DependencyPass.DependencyTracker GetDemoTracker() { TerminalNode a = new TerminalNode(); a.Value = "1..1000..+1"; FunctionCallNode b = new FunctionCallNode(); b.Function = new TerminalNode() { Value = "SQRT" }; b.FormalArguments.Add(a); BinaryExpressionNode c = new BinaryExpressionNode(); c.LeftNode = a; c.Operator = Operator.Mult; TerminalNode _2Node = new TerminalNode() { Value = "2" }; c.RightNode = _2Node; BinaryExpressionNode d = new BinaryExpressionNode(); d.LeftNode = c; d.RightNode = c; d.Operator = Operator.Mult; FunctionCallNode e = new FunctionCallNode(); e.Function = new TerminalNode() { Value = "LineFromPoint" }; e.FormalArguments.Add(a); e.FormalArguments.Add(b); e.FormalArguments.Add(d); Node f = new FunctionCallNode() { Function = new TerminalNode() { Value = "Trim" } }; Node g = new FunctionCallNode() { Function = new TerminalNode() { Value = "Rotate" } }; DependencyPass.DependencyTracker tracker = new DependencyPass.DependencyTracker(); tracker.AllNodes.Add(a); tracker.AllNodes.Add(b); tracker.AllNodes.Add(c); tracker.AllNodes.Add(_2Node); tracker.AllNodes.Add(d); tracker.AllNodes.Add(e); tracker.AllNodes.Add(f); tracker.AllNodes.Add(g); tracker.DirectContingents.Add(a, new List<Node>() { }); tracker.DirectContingents.Add(_2Node, new List<Node>() { }); tracker.DirectContingents.Add(b, new List<Node>() { a }); tracker.DirectContingents.Add(c, new List<Node>() { a, _2Node }); tracker.DirectContingents.Add(d, new List<Node>() { c }); tracker.DirectContingents.Add(e, new List<Node>() { a, b, d }); tracker.DirectContingents.Add(f, new List<Node>() { e }); tracker.DirectContingents.Add(g, new List<Node>() { f }); tracker.DirectDependents.Add(a, new List<Node>() {b, c, e}); tracker.DirectDependents.Add(b, new List<Node>() {e}); tracker.DirectDependents.Add(c, new List<Node>() {d}); tracker.DirectDependents.Add(d, new List<Node>() {e}); tracker.DirectDependents.Add(e, new List<Node>() {f}); tracker.DirectDependents.Add(f, new List<Node>() {g}); tracker.DirectDependents.Add(g, new List<Node>() {}); tracker.DirectDependents.Add(_2Node, new List<Node>() {c}); return tracker; } // a = 25 // b = 4 + 20 / 5 // c = a - 20 * 5 public DependencyPass.DependencyTracker GetDemoTrackerJun() { DependencyPass.DependencyTracker tracker = new DependencyPass.DependencyTracker(); string varIdent = null; const int functionIndex = (int)ProtoCore.DSASM.Constants.kGlobalScope; //======================================================== // a = 25 BinaryExpressionNode i1 = new BinaryExpressionNode(); varIdent = "a"; TerminalNode fAssignLeft = new TerminalNode() { Value = varIdent, type = /*SDD*/(int)ProtoCore.PrimitiveType.kTypeVar }; // SDD - automatic allocation //tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize); i1.LeftNode = fAssignLeft; i1.Operator = Operator.Assign; TerminalNode fAssignRight = new TerminalNode() { Value = "25", type = (int)ProtoCore.PrimitiveType.kTypeInt }; i1.RightNode = fAssignRight; //======================================================== // b = 4 + 20 / 5 // 20 / 5 BinaryExpressionNode sDiv = new BinaryExpressionNode(); TerminalNode sDivLeft = new TerminalNode() { Value = "20", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt }; sDiv.LeftNode = sDivLeft; sDiv.Operator = Operator.Divide; TerminalNode sDivRight = new TerminalNode() { Value = "5", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt }; sDiv.RightNode = sDivRight; // 4 + ( 20 / 5 ) BinaryExpressionNode sAdd = new BinaryExpressionNode(); TerminalNode sAddLeft = new TerminalNode() { Value = "4", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt }; sAdd.LeftNode = sAddLeft; sAdd.Operator = Operator.Add; BinaryExpressionNode sAddRight = new BinaryExpressionNode(); sAddRight = sDiv; sAdd.RightNode = sAddRight; // b = 4 + 20 / 5 BinaryExpressionNode i2 = new BinaryExpressionNode(); varIdent = "b"; TerminalNode sAssignLeft = new TerminalNode() { Value = varIdent, /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar }; // SDD - automatic allocation //tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize); i2.LeftNode = sAssignLeft; i2.Operator = Operator.Assign; BinaryExpressionNode sAssignRight = new BinaryExpressionNode(); sAssignRight = sAdd; i2.RightNode = sAssignRight; // c = a - 20 * 5 // 20 * 5 BinaryExpressionNode sMul = new BinaryExpressionNode(); TerminalNode sMulLeft = new TerminalNode() { Value = "20", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt }; sMul.LeftNode = sMulLeft; sMul.Operator = Operator.Mult; TerminalNode sMulRight = new TerminalNode() { Value = "5", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeInt }; sMul.RightNode = sMulRight; // a - ( 20 * 5 ) BinaryExpressionNode sSub = new BinaryExpressionNode(); TerminalNode sSubLeft = new TerminalNode() { Value = "a", /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar }; sSub.LeftNode = sSubLeft; sSub.Operator = Operator.Subtract; BinaryExpressionNode sSubRight = new BinaryExpressionNode(); sSubRight = sMul; sSub.RightNode = sSubRight; // c = a - 20 * 5 BinaryExpressionNode i3 = new BinaryExpressionNode(); varIdent = "c"; TerminalNode si3Left = new TerminalNode() { Value = varIdent, /*SDD*/type = (int)ProtoCore.PrimitiveType.kTypeVar }; // SDD - automatic allocation //tracker.Allocate(varIdent, (int)FusionCore.DSASM.Constants.kGlobalScope, (int)FusionCore.DSASM.Constants.kPrimitiveSize); i3.LeftNode = si3Left; i3.Operator = Operator.Assign; BinaryExpressionNode si3Right = new BinaryExpressionNode(); si3Right = sSub; i3.RightNode = si3Right; tracker.AllNodes.Add(i1); tracker.AllNodes.Add(i2); tracker.AllNodes.Add(i3); return tracker; } } public abstract class Node { private static int sID = 0; //allow the assignment node to be part of dependency struture? //this lead to entiely different set of results in optimization protected static bool AssignNodeDependencyEnabled = true; //even if the '=' is not a link between LHS and RHS, can we keep it in dependency graph? //protected static bool AssignNodeDependencyEnabledLame = true; public int ID { get; private set; } public Node() { ID = ++sID; } /// <summary> /// Optional name for the node /// </summary> public string Name { get; set; } public virtual void GenerateDependencyGraph(DependencyTracker tracker) { tracker.AddNode(this);//get rid of this later IEnumerable<Node> contingents = getContingents(); foreach (Node node in contingents) { tracker.AddNode(node); if (node == null) continue; tracker.AddDirectContingent(this, node); tracker.AddDirectDependent(node, this); node.GenerateDependencyGraph(tracker); } } public virtual IEnumerable<Node> getContingents() { return new List<Node>(); } public virtual void ConsolidateNames(ref Dictionary<string, List<Node>> names) { } protected static void Consolidate(ref Dictionary<string, List<Node>> names, ref TerminalNode node) { if (null != node.Name) { if (names.ContainsKey(node.Name)) { List<Node> candidates = names[node.Name]; node = candidates[candidates.Count - 1] as TerminalNode; } else { //symbol not defined. //should we ignore this until somebody else defines a symbol? //or add the symbol? //throw new KeyNotFoundException(); List<Node> candidates = new List<Node>(); candidates.Add(node); names.Add(node.Name, candidates); } } } } public class LanguageBlockNode : Node { public LanguageBlockNode() { codeblock = new ProtoCore.CodeBlock(); } public ProtoCore.CodeBlock codeblock { get; set; } } /// <summary> /// This node will be used by the optimiser /// </summary> public class MergeNode : Node { public List<Node> MergedNodes { get; private set; } public MergeNode () { MergedNodes = new List<Node>(); } public override IEnumerable<Node> getContingents() { return MergedNodes; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { foreach (Node node in MergedNodes) node.ConsolidateNames(ref(names)); } } public class TerminalNode : Node { public TerminalNode() { type = (int)ProtoCore.PrimitiveType.kInvalidType; } public int type { get; set; } public ProtoCore.PrimitiveType datatype { get; set; } public string Value { get; set; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { throw new NotImplementedException(); //we should not be here at all. the parent node should take care. //disabling execption as functioncalls will still need to add the nodes to } } public class FunctionCallNode : Node { public Node Function { get; set; } public List<Node> FormalArguments { get; set; } public FunctionCallNode () { FormalArguments = new List<Node>(); } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(FormalArguments) ; contingents.Add(Function); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { List<Node> newFormalArguments = new List<Node>(); //replace the names in arguments by current names in calling context foreach(Node argument in FormalArguments) { Node newArgument = argument; TerminalNode terminalNode = newArgument as TerminalNode; if (terminalNode != null) { Consolidate(ref(names), ref(terminalNode)); newArgument = terminalNode; } else { argument.ConsolidateNames(ref(names)); } newFormalArguments.Add(newArgument); } FormalArguments = newFormalArguments; } } public class Pattern : Node { public Node Expression { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(1); contingents.Add(Expression); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { Expression.ConsolidateNames(ref(names)); } }; public class QualifiedNode : Node { public Node Value { get; set; } public List<Node> ReplicationGuides { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(ReplicationGuides); contingents.Add(Value); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { Value.ConsolidateNames(ref(names)); } } public class ArgumentNode : Node { public ProtoCore.Type ArgumentType { get; set; } public Pattern Pattern { get; set; } public TerminalNode NameNode { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(1); contingents.Add(Pattern); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { if (names.ContainsKey(NameNode.Name)) throw new Exception(); List<Node> records = new List<Node>(); records.Add(NameNode); names.Add(NameNode.Name, records); Dictionary<string, List<Node>> localnames = new Dictionary<string, List<Node>>(); localnames.Add(NameNode.Name, records); Pattern.ConsolidateNames(ref(localnames)); } } public class ArgumentSignatureNode : Node { public ArgumentSignatureNode() { Arguments = new List<ArgumentNode>(); } public List<ArgumentNode> Arguments { get; set; } public void AddArgument(ArgumentNode arg) { Arguments.Add(arg); } public List<KeyValuePair<ProtoCore.Type, Pattern>> ArgumentStructure { get { List<KeyValuePair<ProtoCore.Type, Pattern>> argStructure = new List<KeyValuePair<ProtoCore.Type, Pattern>>(); foreach(ArgumentNode i in Arguments) { argStructure.Add(new KeyValuePair<ProtoCore.Type, Pattern>(i.ArgumentType, i.Pattern)); } return argStructure; } } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(Arguments); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { foreach (Node node in Arguments) node.ConsolidateNames(ref(names)); } } public class CodeBlockNode : Node { public ProtoCore.DSASM.SymbolTable symbols { get; set; } public ProtoCore.DSASM.FunctionTable functions { get; set; } public CodeBlockNode() { Body = new List<Node>(); symbols = new ProtoCore.DSASM.SymbolTable(); functions = new ProtoCore.DSASM.FunctionTable(); } public List<Node> Body { get; set; } public override IEnumerable<Node> getContingents() { return new List<Node>(Body); } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { //todo make a decision whether to pass out the local names. foreach (Node node in Body) { node.ConsolidateNames(ref(names)); } } } public class ConstructorDefinitionNode : Node { public int localVars { get; set; } public ArgumentSignatureNode Signature { get; set; } public CodeBlockNode FunctionBody { get; set; } } public class FunctionDefinitionNode : Node { public CodeBlockNode FunctionBody { get; set; } public ProtoCore.Type ReturnType { get; set; } public ArgumentSignatureNode Singnature { get; set; } public Pattern Pattern { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(); contingents.Add(FunctionBody); contingents.Add(Singnature); contingents.Add(Pattern); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { Dictionary<string, List<Node>> localNames = new Dictionary<string, List<Node>>(); Singnature.ConsolidateNames(ref(localNames)); Pattern.ConsolidateNames(ref(localNames)); FunctionBody.ConsolidateNames(ref(localNames)); if (names.ContainsKey(Name)) { throw new Exception(); } List<Node> namelist = new List<Node>(); namelist.Add(this); names.Add(Name, namelist); } } public class BinaryExpressionNode : Node { public Node LeftNode { get; set; } public Operator Operator { get; set; } public Node RightNode { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(); if (Operator != Operator.Assign) { contingents.Add(LeftNode); } //if we have enabled the '=' node to be a part of depencency, then we return RHS, no matter what if (AssignNodeDependencyEnabled || Operator != Operator.Assign) { contingents.Add(RightNode); } return contingents; } public override void GenerateDependencyGraph(DependencyTracker tracker) { base.GenerateDependencyGraph(tracker); if (Operator == Operator.Assign) { //so do we set dependency between LeftNode and '=' or LeftNode and RightNode : may be later is better if (AssignNodeDependencyEnabled) { //if we have enabled the '=' node to be a part of depencency, then we already handled RHS as a contingent //so skip it tracker.AddNode(LeftNode); tracker.AddDirectContingent(LeftNode, this); tracker.AddDirectDependent(this, LeftNode); } else { //if(AssignNodeDependencyEnabledLame) //{ // tracker.AddDirectContingent(this, RightNode); //? still keep in dependency? // tracker.AddDirectContingent(LeftNode, RightNode); //} tracker.AddNode(RightNode); tracker.AddNode(LeftNode); tracker.AddDirectContingent(LeftNode, RightNode); tracker.AddDirectDependent(RightNode, LeftNode); RightNode.GenerateDependencyGraph(tracker); } } } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { TerminalNode rightTerminalNode = RightNode as TerminalNode; if (rightTerminalNode != null) { if (Operator != Operator.Dot) { //replace RHS Consolidate(ref(names), ref(rightTerminalNode)); RightNode = rightTerminalNode; } } else { RightNode.ConsolidateNames(ref(names)); } //left has to be done 2nd, because in case of modifiers, we dont want to //replace the node on RHS by a node on LHS. So a modifier stack name is not unique. TerminalNode leftTerminalNode = LeftNode as TerminalNode; if (leftTerminalNode != null) { if (Operator != Operator.Assign) { //replace LHS Consolidate(ref(names), ref(leftTerminalNode)); LeftNode = leftTerminalNode; } else { if (leftTerminalNode.Name != null) { if (names.ContainsKey(leftTerminalNode.Name)) { List<Node> candidates = names[leftTerminalNode.Name]; candidates.Add(leftTerminalNode); } else { //append LHS List<Node> candidates = new List<Node>(); candidates.Add(leftTerminalNode); names.Add(leftTerminalNode.Name, candidates); } } } } else { LeftNode.ConsolidateNames(ref(names)); } } } public class UnaryExpressionNode : Node { public UnaryOperator Operator { get; set; } public Node Expression { get; set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(1); contingents.Add(Expression); return contingents; } public override void ConsolidateNames(ref Dictionary<string, List<Node>> names) { Expression.ConsolidateNames(ref(names)); } } public enum UnaryOperator { None, Not, Negate } public enum Operator { Assign, LessThan, GreaterThan, LessThanEqual, GreaterThanEqual, Equals, NotEquals, Add, Subtract, Mult, Divide, Modulo, And, Or, Dot } public class ModifierStackNode : Node { public ModifierStackNode () { ElementNodes = new List<Node>(); AtNames = new Dictionary<string, Node>(); } public List<Node> ElementNodes { get; private set; } public Node ReturnNode { get; set; } public Dictionary<string, Node> AtNames { get; private set; } public override IEnumerable<Node> getContingents() { List<Node> contingents = new List<Node>(ElementNodes); contingents.Add(ReturnNode); return contingents; } } }
using System; using Bitmap = System.Drawing.Bitmap; using System.ComponentModel; using System.Collections.Generic; using Cairo; using Gtk; using LynnaLib; using Util; namespace LynnaLab { public enum MouseButton { Any, LeftClick, RightClick } [Flags] public enum MouseModifier { // Exact combination of keys must be pressed, but "Any" allows any combination. Any = 1, None = 2, Ctrl = 4 | None, Shift = 8 | None, // Mouse can be dragged during the operation. Drag = 16, } public enum GridAction { Select, // Set the selected tile (bound to button "Any" with modifier "None" by default) SelectRange, // [PLANNED] Select a range of tiles Callback // Invoke a callback whenever the tile is clicked, or the drag changes } /* Represents any kind of tile-based grid. It can be hovered over with the mouse, and optionally * allows one to select tiles by clicking, or define actions to occur with other mouse buttons. */ public abstract class TileGridViewer : Gtk.DrawingArea { public static readonly Cairo.Color DefaultHoverColor = new Cairo.Color(1.0, 0, 0); public static readonly Cairo.Color DefaultSelectionColor = new Cairo.Color(1.0, 1.0, 1.0); public Cairo.Color HoverColor { get; set; } = DefaultHoverColor; public Cairo.Color SelectionColor { get; set; } = DefaultSelectionColor; public int Width { get; set; } public int Height { get; set; } public int TileWidth { get; set; } public int TileHeight { get; set; } public int Scale { get; set; } // Pixel offset where grid starts. // This is updated with the "OnSizeAllocated" function. Don't directly set this otherwise. public int XOffset { get; protected set; } public int YOffset { get; protected set; } // Padding on each side of each tile on the grid, before scaling (default = 0) public int TilePaddingX { get; set; } public int TilePaddingY { get; set; } public bool Hoverable { get { return _hoverable; } set { if (_hoverable != value && HoveringIndex != -1) { Cairo.Rectangle rect = GetTileRectWithPadding(HoveringX, HoveringY); QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); } _hoverable = value; } } public bool Selectable { get { return _selectable; } set { if (_selectable == value) return; _selectable = value; CanFocus = value; if (value) AddMouseAction(MouseButton.Any, MouseModifier.Any, GridAction.Select); else RemoveMouseAction(MouseButton.Any, MouseModifier.Any); } } public int HoveringIndex { get { return hoveringIndex; } } public int HoveringX { get { if (Width == 0) return 0; return hoveringIndex%Width; } } public int HoveringY { get { if (Height == 0) return 0; return hoveringIndex/Width; } } // This can be set to -1 for "nothing selected". public int SelectedIndex { get { return selectedIndex; } set { if (selectedIndex != value) { var rect = GetTileRectSansPadding(SelectedX, SelectedY); QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); selectedIndex = value; rect = GetTileRectSansPadding(SelectedX, SelectedY); QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); } tileSelectedEvent.Invoke(this, SelectedIndex); } } public int SelectedX { get { if (Width == 0) return 0; return selectedIndex%Width; } } public int SelectedY { get { if (Height == 0) return 0; return selectedIndex/Width; } } // Size of tile (not including spacing) public int ScaledTileWidth { get { return TileWidth*Scale; } } public int ScaledTileHeight { get { return TileHeight*Scale; } } public int MaxIndex { get { return Math.Min(_maxIndex, Width * Height - 1); } set { _maxIndex = value; hoveringIndex = Math.Min(hoveringIndex, MaxIndex); } } // Subclasses can either override "Image" to set the image, or override the "TileDrawer" property // to set the image using a per-tile draw function. protected virtual Bitmap Image { get { return null; } } // TODO: Replace "Image" property above in favor of this protected virtual Cairo.Surface Surface { get { return null; } } public Cairo.Color BackgroundColor { get; set; } // Event triggered when the hovering tile changes public event EventHandler<int> HoverChangedEvent; public delegate void TileGridEventHandler(object sender, int tileIndex); // Protected variables protected LockableEvent<int> tileSelectedEvent = new LockableEvent<int>(); // Private variables int hoveringIndex = -1, selectedIndex = -1; int _maxIndex = int.MaxValue; bool _selectable = false, _hoverable = true; bool keyDown = false; IList<TileGridAction> actionList = new List<TileGridAction>(); TileGridAction activeAction = null; // Constructors public TileGridViewer() : base() { this.ButtonPressEvent += new ButtonPressEventHandler(OnButtonPressEvent); this.ButtonReleaseEvent += new ButtonReleaseEventHandler(OnButtonReleaseEvent); this.MotionNotifyEvent += new MotionNotifyEventHandler(OnMoveMouse); this.LeaveNotifyEvent += new LeaveNotifyEventHandler(OnMouseLeave); this.KeyPressEvent += new KeyPressEventHandler(OnKeyPressEvent); this.KeyReleaseEvent += new KeyReleaseEventHandler(OnKeyReleaseEvent); this.Events = Gdk.EventMask.PointerMotionMask | Gdk.EventMask.LeaveNotifyMask | Gdk.EventMask.ButtonPressMask | Gdk.EventMask.ButtonReleaseMask | Gdk.EventMask.KeyPressMask | Gdk.EventMask.KeyReleaseMask; // This doesn't work by itself? //base.FocusOnClick = true; // Really stupid hack to prevent focus from being lost when arrow keys are used. // This isn't ideal because it will still attempt to focus on other widgets, with // visible effects (ie. spin button contents are highlighted). this.FocusOutEvent += (a, b) => { if (keyDown) GrabFocus(); }; Scale = 1; } // Methods // Check if the given "real" position (in pixels) is in bounds. This ALSO checks that the // index that it's hovering over does not exceed MaxIndex. public bool IsInBounds(int x, int y, bool scale = true, bool offset = true) { Cairo.Rectangle p = GetTotalBounds(scale:scale, offset:offset); if (!(x >= p.X && y >= p.Y && x < p.X + p.Width && y < p.Y + p.Height)) return false; return GetGridIndex(x, y) <= MaxIndex; } // Convert a "real" position (in pixels) into a grid position (in tiles). public Cairo.Point GetGridPosition(int x, int y, bool scale = true, bool offset = true) { int s = Scale; int xoffset = XOffset; int yoffset = YOffset; if (!scale) s = 1; if (!offset) { xoffset = 0; yoffset = 0; } int x2 = (x - xoffset) / ((TileWidth * s) + (TilePaddingX * s * 2)); int y2 = (y - yoffset) / ((TileHeight * s) + (TilePaddingY * s * 2)); return new Cairo.Point(x2, y2); } // Convert a "real" position (in pixels) to an index. public int GetGridIndex(int x, int y) { Cairo.Point p = GetGridPosition(x, y); return p.X + p.Y * Width; } public void AddMouseAction(MouseButton button, MouseModifier mod, GridAction action, TileGridEventHandler callback = null) { TileGridAction act; if (action == GridAction.Callback) { if (callback == null) throw new Exception("Need to specify a callback."); act = new TileGridAction(button, mod, action, callback); } else { if (callback != null) throw new Exception("This action doesn't take a callback."); act = new TileGridAction(button, mod, action); } actionList.Add(act); } public void RemoveMouseAction(MouseButton button, MouseModifier mod) { for (int i=0; i<actionList.Count; i++) { var act = actionList[i]; if (act.button == button && act.mod == mod) { actionList.Remove(act); i--; } } } public void AddTileSelectedHandler(EventHandler<int> handler) { tileSelectedEvent += handler; } public void RemoveTileSelectedHandler(EventHandler<int> handler) { tileSelectedEvent -= handler; } // May need to call this after updating Width, Height, TileWidth, TileHeight public void UpdateSizeRequest() { Cairo.Rectangle r = GetTotalBounds(scale:true, offset:false); SetSizeRequest((int)r.Width, (int)r.Height); } // Protected methods protected void OnButtonPressEvent(object o, ButtonPressEventArgs args) { int x,y; Gdk.ModifierType state; args.Event.Window.GetPointer(out x, out y, out state); if (activeAction == null && IsInBounds(x, y)) { foreach (TileGridAction act in actionList) { if (act.MatchesState(state)) { HandleTileGridAction(act, GetGridIndex(x, y)); if (act.mod.HasFlag(MouseModifier.Drag)) activeAction = act; } } if (Selectable) GrabFocus(); } } protected void OnButtonReleaseEvent(object o, ButtonReleaseEventArgs args) { int x,y; Gdk.ModifierType state; args.Event.Window.GetPointer(out x, out y, out state); if (activeAction != null && !activeAction.ButtonMatchesState(state)) { if (activeAction.mod.HasFlag(MouseModifier.Drag)) { // Probably will add a "button release" callback here later activeAction = null; } } } protected void OnMoveMouse(object o, MotionNotifyEventArgs args) { int x,y; Gdk.ModifierType state; args.Event.Window.GetPointer(out x, out y, out state); int nextHoveringIndex; if (IsInBounds(x,y)) { Cairo.Point p = GetGridPosition(x, y); nextHoveringIndex = p.X + p.Y * Width; } else { nextHoveringIndex = -1; } if (nextHoveringIndex != hoveringIndex) { // Update hovering cursor Cairo.Rectangle rect = GetTileRectWithPadding(HoveringX, HoveringY); this.QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); hoveringIndex = nextHoveringIndex; rect = GetTileRectWithPadding(HoveringX, HoveringY); this.QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); if (HoverChangedEvent != null) HoverChangedEvent(this, hoveringIndex); // Drag actions if (activeAction != null && activeAction.mod.HasFlag(MouseModifier.Drag) && IsInBounds(x, y)) { HandleTileGridAction(activeAction, nextHoveringIndex); } } } protected void OnMouseLeave(object o, LeaveNotifyEventArgs args) { bool changed = false; if (hoveringIndex != -1) { Cairo.Rectangle rect = GetTileRectWithPadding(HoveringX, HoveringY); this.QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); changed = true; } hoveringIndex = -1; if (changed && HoverChangedEvent != null) HoverChangedEvent(this, hoveringIndex); // Don't check for drag actions because we'll ignore out-of-bounds events? } protected void OnKeyPressEvent(object o, KeyPressEventArgs args) { if (Selectable) { int newIndex = -1; if (args.Event.Key == Gdk.Key.Up) { newIndex = SelectedIndex - Width; } else if (args.Event.Key == Gdk.Key.Down) { newIndex = SelectedIndex + Width; } else if (args.Event.Key == Gdk.Key.Left) { newIndex = SelectedIndex - 1; } else if (args.Event.Key == Gdk.Key.Right) { newIndex = SelectedIndex + 1; } if (newIndex >= 0 && newIndex <= MaxIndex) SelectedIndex = newIndex; } if (args.Event.Key != Gdk.Key.Tab) keyDown = true; } protected void OnKeyReleaseEvent(object o, KeyReleaseEventArgs args) { keyDown = false; } void HandleTileGridAction(TileGridAction act, int index) { if (act.action == GridAction.Select) { SelectedIndex = index; } else if (act.action == GridAction.Callback) { act.callback(this, index); } } protected override void OnSizeAllocated(Gdk.Rectangle allocation) { base.OnSizeAllocated(allocation); Cairo.Rectangle desiredRect = GetTotalBounds(); if (Halign == Gtk.Align.Center || Halign == Gtk.Align.Fill) XOffset = (int)(((allocation.Width) - desiredRect.Width) / 2); else if (Halign == Gtk.Align.Start) XOffset = 0; else throw new NotImplementedException(); if (Valign == Gtk.Align.Center || Valign == Gtk.Align.Fill) YOffset = (int)(((allocation.Height) - desiredRect.Height) / 2); else if (Valign == Gtk.Align.Start) YOffset = 0; else throw new NotImplementedException(); } protected override bool OnDrawn(Cairo.Context cr) { DrawBackground(cr); DrawHoverAndSelection(cr); return true; } protected void DrawBackground(Cairo.Context cr) { var totalRect = GetTotalBounds(); cr.SetSourceColor(BackgroundColor); cr.Rectangle(totalRect.X, totalRect.Y, totalRect.Width, totalRect.Height); cr.Fill(); cr.Save(); cr.Translate(XOffset, YOffset); cr.Scale(Scale, Scale); if (Surface != null) { cr.SetSource(Surface, 0, 0); using (SurfacePattern pattern = (SurfacePattern)cr.GetSource()) { pattern.Filter = Filter.Nearest; } cr.Paint(); } else if (Image != null) { using (Surface source = new BitmapSurface(Image)) { cr.SetSource(source, 0, 0); using (SurfacePattern pattern = (SurfacePattern)cr.GetSource()) { pattern.Filter = Filter.Nearest; } cr.Paint(); } } else { Cairo.Rectangle extents = cr.ClipExtents(); for (int i=0; i<Width*Height; i++) { int tileX = i%Width; int tileY = i/Width; Cairo.Rectangle rect = GetTileRectWithPadding(tileX, tileY, scale:false, offset:false); if (!CairoHelper.RectsOverlap(extents, rect)) continue; cr.Save(); cr.Translate(rect.X + TilePaddingX, rect.Y + TilePaddingY); cr.Rectangle(0, 0, TileWidth, TileHeight); cr.Clip(); TileDrawer(i, cr); cr.Restore(); } } cr.Restore(); // Undo scale, offset } protected void DrawHoverAndSelection(Cairo.Context cr) { cr.Save(); cr.Translate(XOffset, YOffset); cr.Scale(Scale, Scale); if (Hoverable && hoveringIndex != -1) { Cairo.Rectangle rect = GetTileRectSansPadding(HoveringX, HoveringY, scale:false, offset:false); cr.NewPath(); cr.SetSourceColor(HoverColor); cr.Rectangle(new Cairo.Rectangle(rect.X + 0.5, rect.Y + 0.5, rect.Width-1, rect.Height-1)); cr.LineWidth = 1; cr.LineJoin = LineJoin.Bevel; cr.Stroke(); } if (Selectable) { var rect = GetTileRectSansPadding(SelectedX, SelectedY, scale:false, offset:false); if (IsInBounds((int)rect.X, (int)rect.Y, scale:false, offset:false)) { cr.NewPath(); cr.SetSourceColor(SelectionColor); cr.Rectangle(rect.X + 0.5, rect.Y + 0.5, rect.Width-1, rect.Height-1); cr.LineWidth = 1; cr.Stroke(); } } cr.Restore(); } protected override void OnGetPreferredWidth(out int minimum_width, out int natural_width) { var rect = GetTotalBounds(); minimum_width = (int)rect.Width; natural_width = (int)rect.Width; } protected override void OnGetPreferredHeight(out int minimum_height, out int natural_height) { var rect = GetTotalBounds(); minimum_height = (int)rect.Height; natural_height = (int)rect.Height; } protected Cairo.Rectangle GetTileRectWithPadding(int x, int y, bool scale = true, bool offset = true) { int s = Scale; int xoffset = XOffset; int yoffset = YOffset; if (!scale) s = 1; if (!offset) { xoffset = 0; yoffset = 0; } return new Cairo.Rectangle( xoffset + x * (TilePaddingX * 2 + TileWidth) * s, yoffset + y * (TilePaddingY * 2 + TileHeight) * s, TileWidth * s + TilePaddingX * s * 2, TileHeight * s + TilePaddingY * s * 2); } protected Cairo.Rectangle GetTileRectSansPadding(int x, int y, bool scale = true, bool offset = true) { int s = Scale; int xoffset = XOffset; int yoffset = YOffset; if (!scale) s = 1; if (!offset) { xoffset = 0; yoffset = 0; } return new Cairo.Rectangle( xoffset + x * (TilePaddingX * 2 + TileWidth) * s + TilePaddingX * s, yoffset + y * (TilePaddingY * 2 + TileHeight) * s + TilePaddingY * s, TileWidth * s, TileHeight * s); } protected Cairo.Rectangle GetTotalBounds(bool scale = true, bool offset = true) { int s = Scale; int xoffset = XOffset; int yoffset = YOffset; if (!scale) s = 1; if (!offset) { xoffset = 0; yoffset = 0; } return new Cairo.Rectangle( xoffset, yoffset, Width * (TilePaddingX * 2 + TileWidth) * s, Height * (TilePaddingY * 2 + TileHeight) * s); } protected void QueueDrawTile(int x, int y) { Cairo.Rectangle rect = GetTileRectSansPadding(x, y); QueueDrawArea((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height); } protected virtual void TileDrawer(int index, Cairo.Context cr) {} // Nested class class TileGridAction { public readonly MouseButton button; public readonly MouseModifier mod; public readonly GridAction action; public readonly TileGridEventHandler callback; public int lastIndex = -1; public TileGridAction(MouseButton button, MouseModifier mod, GridAction action, TileGridEventHandler callback=null) { this.button = button; this.mod = mod; this.action = action; this.callback = callback; } public bool MatchesState(Gdk.ModifierType state) { return ButtonMatchesState(state) && ModifierMatchesState(state); } public bool ButtonMatchesState(Gdk.ModifierType state) { bool left = state.HasFlag(Gdk.ModifierType.Button1Mask); bool right = state.HasFlag(Gdk.ModifierType.Button3Mask); if (button == MouseButton.Any && (left || right)) return true; if (button == MouseButton.LeftClick && left) return true; if (button == MouseButton.RightClick && right) return true; return false; } public bool ModifierMatchesState(Gdk.ModifierType state) { if (mod.HasFlag(MouseModifier.Any)) return true; MouseModifier flags = MouseModifier.None; if (state.HasFlag(Gdk.ModifierType.ControlMask)) flags |= MouseModifier.Ctrl; if (state.HasFlag(Gdk.ModifierType.ShiftMask)) flags |= MouseModifier.Shift; return mod == flags; } } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.List<T>.CopyTo(int32,T,Int32,Int32) /// </summary> public class CopyTo3 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; retVal = NegTest5() && retVal; retVal = NegTest6() && retVal; retVal = NegTest7() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The list is type of int and get a random index"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[100]; int t = this.GetInt32(0, 90); listObject.CopyTo(0, result, t, 10); for (int i = 0; i < 10; i++) { if (listObject[i] != result[i + t]) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is: " + i); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The list is type of string and copy the date to the array whose beginning index is zero"); try { string[] strArray = { "Tom", "Jack", "Mike" }; List<string> listObject = new List<string>(strArray); string[] result = new string[3]; listObject.CopyTo(2, result, 0, 1); if (result[0] != "Mike") { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The generic type is a custom type"); try { MyClass myclass1 = new MyClass(); MyClass myclass2 = new MyClass(); MyClass myclass3 = new MyClass(); List<MyClass> listObject = new List<MyClass>(); listObject.Add(myclass1); listObject.Add(myclass2); listObject.Add(myclass3); MyClass[] mc = new MyClass[3]; listObject.CopyTo(0, mc, 0, 3); if ((mc[0] != myclass1) || (mc[1] != myclass2) || (mc[2] != myclass3)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Copy an empty list to the end of an array,the three int32 arguments are zero all"); try { List<MyClass> listObject = new List<MyClass>(); MyClass[] mc = new MyClass[3]; listObject.CopyTo(0, mc, 0, 0); for (int i = 0; i < 3; i++) { if (mc[i] != null) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The array is a null reference"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); listObject.CopyTo(0, null, 0, 10); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The number of elements in the source List is greater than the number of elements that the destination array can contain"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[1]; listObject.CopyTo(0, result, 0, 2); TestLibrary.TestFramework.LogError("103", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: arrayIndex is equal to the length of array"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[20]; listObject.CopyTo(0, result, 20, 2); TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: arrayIndex is greater than the length of array"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[20]; listObject.CopyTo(3, result, 300, 6); TestLibrary.TestFramework.LogError("107", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("108", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest5: arrayIndex is less than 0"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[20]; listObject.CopyTo(result, -1); TestLibrary.TestFramework.LogError("109", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("110", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest6: The index of list is less than 0"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[20]; listObject.CopyTo(-1, result, 10, 5); TestLibrary.TestFramework.LogError("111", "The ArgumentOutOfRangeException was not thrown as expected"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("112", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest7: The index of list is greater than the Count of the source"); try { int[] iArray = { 1, 9, 3, 6, 5, 8, 7, 2, 4, 0 }; List<int> listObject = new List<int>(iArray); int[] result = new int[20]; listObject.CopyTo(11, result, 10, 5); TestLibrary.TestFramework.LogError("113", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("114", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { CopyTo3 test = new CopyTo3(); TestLibrary.TestFramework.BeginTestCase("CopyTo3"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } } public class MyClass { }
// 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.Data.Common; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; namespace System.Data.ProviderBase { internal sealed class DbConnectionPool { private enum State { Initializing, Running, ShuttingDown, } private sealed class PendingGetConnection { public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource<DbConnectionInternal> completion, DbConnectionOptions userOptions) { DueTime = dueTime; Owner = owner; Completion = completion; } public long DueTime { get; private set; } public DbConnection Owner { get; private set; } public TaskCompletionSource<DbConnectionInternal> Completion { get; private set; } public DbConnectionOptions UserOptions { get; private set; } } private sealed class PoolWaitHandles { private readonly Semaphore _poolSemaphore; private readonly ManualResetEvent _errorEvent; // Using a Mutex requires ThreadAffinity because SQL CLR can swap // the underlying Win32 thread associated with a managed thread in preemptive mode. // Using an AutoResetEvent does not have that complication. private readonly Semaphore _creationSemaphore; private readonly WaitHandle[] _handlesWithCreate; private readonly WaitHandle[] _handlesWithoutCreate; internal PoolWaitHandles() { _poolSemaphore = new Semaphore(0, MAX_Q_SIZE); _errorEvent = new ManualResetEvent(false); _creationSemaphore = new Semaphore(1, 1); _handlesWithCreate = new WaitHandle[] { _poolSemaphore, _errorEvent, _creationSemaphore }; _handlesWithoutCreate = new WaitHandle[] { _poolSemaphore, _errorEvent }; } internal Semaphore CreationSemaphore { get { return _creationSemaphore; } } internal ManualResetEvent ErrorEvent { get { return _errorEvent; } } internal Semaphore PoolSemaphore { get { return _poolSemaphore; } } internal WaitHandle[] GetHandles(bool withCreate) { return withCreate ? _handlesWithCreate : _handlesWithoutCreate; } } private const int MAX_Q_SIZE = (int)0x00100000; // The order of these is important; we want the WaitAny call to be signaled // for a free object before a creation signal. Only the index first signaled // object is returned from the WaitAny call. private const int SEMAPHORE_HANDLE = (int)0x0; private const int ERROR_HANDLE = (int)0x1; private const int CREATION_HANDLE = (int)0x2; private const int BOGUS_HANDLE = (int)0x3; private const int ERROR_WAIT_DEFAULT = 5 * 1000; // 5 seconds // we do want a testable, repeatable set of generated random numbers private static readonly Random s_random = new Random(5101977); // Value obtained from Dave Driver private readonly int _cleanupWait; private readonly DbConnectionPoolIdentity _identity; private readonly DbConnectionFactory _connectionFactory; private readonly DbConnectionPoolGroup _connectionPoolGroup; private readonly DbConnectionPoolGroupOptions _connectionPoolGroupOptions; private DbConnectionPoolProviderInfo _connectionPoolProviderInfo; private State _state; private readonly ConcurrentStack<DbConnectionInternal> _stackOld = new ConcurrentStack<DbConnectionInternal>(); private readonly ConcurrentStack<DbConnectionInternal> _stackNew = new ConcurrentStack<DbConnectionInternal>(); private readonly ConcurrentQueue<PendingGetConnection> _pendingOpens = new ConcurrentQueue<PendingGetConnection>(); private int _pendingOpensWaiting = 0; private readonly WaitCallback _poolCreateRequest; private int _waitCount; private readonly PoolWaitHandles _waitHandles; private Exception _resError; private volatile bool _errorOccurred; private int _errorWait; private Timer _errorTimer; private Timer _cleanupTimer; private readonly List<DbConnectionInternal> _objectList; private int _totalObjects; // only created by DbConnectionPoolGroup.GetConnectionPool internal DbConnectionPool( DbConnectionFactory connectionFactory, DbConnectionPoolGroup connectionPoolGroup, DbConnectionPoolIdentity identity, DbConnectionPoolProviderInfo connectionPoolProviderInfo) { Debug.Assert(null != connectionPoolGroup, "null connectionPoolGroup"); if ((null != identity) && identity.IsRestricted) { throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToPoolOnRestrictedToken); } _state = State.Initializing; lock (s_random) { // Random.Next is not thread-safe _cleanupWait = s_random.Next(12, 24) * 10 * 1000; // 2-4 minutes in 10 sec intervals } _connectionFactory = connectionFactory; _connectionPoolGroup = connectionPoolGroup; _connectionPoolGroupOptions = connectionPoolGroup.PoolGroupOptions; _connectionPoolProviderInfo = connectionPoolProviderInfo; _identity = identity; _waitHandles = new PoolWaitHandles(); _errorWait = ERROR_WAIT_DEFAULT; _errorTimer = null; // No error yet. _objectList = new List<DbConnectionInternal>(MaxPoolSize); _poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback _state = State.Running; //_cleanupTimer & QueuePoolCreateRequest is delayed until DbConnectionPoolGroup calls // StartBackgroundCallbacks after pool is actually in the collection } private int CreationTimeout { get { return PoolGroupOptions.CreationTimeout; } } internal int Count { get { return _totalObjects; } } internal DbConnectionFactory ConnectionFactory { get { return _connectionFactory; } } internal bool ErrorOccurred { get { return _errorOccurred; } } internal TimeSpan LoadBalanceTimeout { get { return PoolGroupOptions.LoadBalanceTimeout; } } private bool NeedToReplenish { get { if (State.Running != _state) // Don't allow connection create when not running. return false; int totalObjects = Count; if (totalObjects >= MaxPoolSize) return false; if (totalObjects < MinPoolSize) return true; int freeObjects = (_stackNew.Count + _stackOld.Count); int waitingRequests = _waitCount; bool needToReplenish = (freeObjects < waitingRequests) || ((freeObjects == waitingRequests) && (totalObjects > 1)); return needToReplenish; } } internal DbConnectionPoolIdentity Identity { get { return _identity; } } internal bool IsRunning { get { return State.Running == _state; } } private int MaxPoolSize { get { return PoolGroupOptions.MaxPoolSize; } } private int MinPoolSize { get { return PoolGroupOptions.MinPoolSize; } } internal DbConnectionPoolGroup PoolGroup { get { return _connectionPoolGroup; } } internal DbConnectionPoolGroupOptions PoolGroupOptions { get { return _connectionPoolGroupOptions; } } internal DbConnectionPoolProviderInfo ProviderInfo { get { return _connectionPoolProviderInfo; } } internal bool UseLoadBalancing { get { return PoolGroupOptions.UseLoadBalancing; } } private bool UsingIntegrateSecurity { get { return (null != _identity && DbConnectionPoolIdentity.NoIdentity != _identity); } } private void CleanupCallback(object state) { // Called when the cleanup-timer ticks over. // This is the automatic pruning method. Every period, we will // perform a two-step process: // // First, for each free object above MinPoolSize, we will obtain a // semaphore representing one object and destroy one from old stack. // We will continue this until we either reach MinPoolSize, we are // unable to obtain a free object, or we have exhausted all the // objects on the old stack. // // Second we move all free objects on the new stack to the old stack. // So, every period the objects on the old stack are destroyed and // the objects on the new stack are pushed to the old stack. All // objects that are currently out and in use are not on either stack. // // With this logic, objects are pruned from the pool if unused for // at least one period but not more than two periods. // Destroy free objects that put us above MinPoolSize from old stack. while (Count > MinPoolSize) { // While above MinPoolSize... if (_waitHandles.PoolSemaphore.WaitOne(0)) { // We obtained a objects from the semaphore. DbConnectionInternal obj; if (_stackOld.TryPop(out obj)) { Debug.Assert(obj != null, "null connection is not expected"); // If we obtained one from the old stack, destroy it. DestroyObject(obj); } else { // Else we exhausted the old stack (the object the // semaphore represents is on the new stack), so break. _waitHandles.PoolSemaphore.Release(1); break; } } else { break; } } // Push to the old-stack. For each free object, move object from // new stack to old stack. if (_waitHandles.PoolSemaphore.WaitOne(0)) { for (;;) { DbConnectionInternal obj; if (!_stackNew.TryPop(out obj)) break; Debug.Assert(obj != null, "null connection is not expected"); Debug.Assert(!obj.IsEmancipated, "pooled object not in pool"); Debug.Assert(obj.CanBePooled, "pooled object is not poolable"); _stackOld.Push(obj); } _waitHandles.PoolSemaphore.Release(1); } // Queue up a request to bring us up to MinPoolSize QueuePoolCreateRequest(); } internal void Clear() { DbConnectionInternal obj; // First, quickly doom everything. lock (_objectList) { int count = _objectList.Count; for (int i = 0; i < count; ++i) { obj = _objectList[i]; if (null != obj) { obj.DoNotPoolThisConnection(); } } } // Second, dispose of all the free connections. while (_stackNew.TryPop(out obj)) { Debug.Assert(obj != null, "null connection is not expected"); DestroyObject(obj); } while (_stackOld.TryPop(out obj)) { Debug.Assert(obj != null, "null connection is not expected"); DestroyObject(obj); } // Finally, reclaim everything that's emancipated (which, because // it's been doomed, will cause it to be disposed of as well) ReclaimEmancipatedObjects(); } private Timer CreateCleanupTimer() => ADP.UnsafeCreateTimer( new TimerCallback(CleanupCallback), null, _cleanupWait, _cleanupWait); private DbConnectionInternal CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { DbConnectionInternal newObj = null; try { newObj = _connectionFactory.CreatePooledConnection(this, owningObject, _connectionPoolGroup.ConnectionOptions, _connectionPoolGroup.PoolKey, userOptions); if (null == newObj) { throw ADP.InternalError(ADP.InternalErrorCode.CreateObjectReturnedNull); // CreateObject succeeded, but null object } if (!newObj.CanBePooled) { throw ADP.InternalError(ADP.InternalErrorCode.NewObjectCannotBePooled); // CreateObject succeeded, but non-poolable object } newObj.PrePush(null); lock (_objectList) { if ((oldConnection != null) && (oldConnection.Pool == this)) { _objectList.Remove(oldConnection); } _objectList.Add(newObj); _totalObjects = _objectList.Count; } // If the old connection belonged to another pool, we need to remove it from that if (oldConnection != null) { var oldConnectionPool = oldConnection.Pool; if (oldConnectionPool != null && oldConnectionPool != this) { Debug.Assert(oldConnectionPool._state == State.ShuttingDown, "Old connections pool should be shutting down"); lock (oldConnectionPool._objectList) { oldConnectionPool._objectList.Remove(oldConnection); oldConnectionPool._totalObjects = oldConnectionPool._objectList.Count; } } } // Reset the error wait: _errorWait = ERROR_WAIT_DEFAULT; } catch (Exception e) { if (!ADP.IsCatchableExceptionType(e)) { throw; } newObj = null; // set to null, so we do not return bad new object // Failed to create instance _resError = e; // Make sure the timer starts even if ThreadAbort occurs after setting the ErrorEvent. // timer allocation has to be done out of CER block Timer t = new Timer(new TimerCallback(this.ErrorCallback), null, Timeout.Infinite, Timeout.Infinite); bool timerIsNotDisposed; try { } finally { _waitHandles.ErrorEvent.Set(); _errorOccurred = true; // Enable the timer. // Note that the timer is created to allow periodic invocation. If ThreadAbort occurs in the middle of ErrorCallback, // the timer will restart. Otherwise, the timer callback (ErrorCallback) destroys the timer after resetting the error to avoid second callback. _errorTimer = t; timerIsNotDisposed = t.Change(_errorWait, _errorWait); } Debug.Assert(timerIsNotDisposed, "ErrorCallback timer has been disposed"); if (30000 < _errorWait) { _errorWait = 60000; } else { _errorWait *= 2; } throw; } return newObj; } private void DeactivateObject(DbConnectionInternal obj) { obj.DeactivateConnection(); bool returnToGeneralPool = false; bool destroyObject = false; if (obj.IsConnectionDoomed) { // the object is not fit for reuse -- just dispose of it. destroyObject = true; } else { // NOTE: constructor should ensure that current state cannot be State.Initializing, so it can only // be State.Running or State.ShuttingDown Debug.Assert(_state == State.Running || _state == State.ShuttingDown); lock (obj) { // A connection with a delegated transaction cannot currently // be returned to a different customer until the transaction // actually completes, so we send it into Stasis -- the SysTx // transaction object will ensure that it is owned (not lost), // and it will be certain to put it back into the pool. if (_state == State.ShuttingDown) { // connection is being closed and the pool has been marked as shutting // down, so destroy this object. destroyObject = true; } else { if (obj.CanBePooled) { // We must put this connection into the transacted pool // while inside a lock to prevent a race condition with // the transaction asynchronously completing on a second // thread. // return to general pool returnToGeneralPool = true; } else { // object is not fit for reuse -- just dispose of it destroyObject = true; } } } } if (returnToGeneralPool) { // Only push the connection into the general pool if we didn't // already push it onto the transacted pool, put it into stasis, // or want to destroy it. Debug.Assert(destroyObject == false); PutNewObject(obj); } else if (destroyObject) { DestroyObject(obj); QueuePoolCreateRequest(); } //------------------------------------------------------------------------------------- // postcondition // ensure that the connection was processed Debug.Assert( returnToGeneralPool == true || destroyObject == true); } internal void DestroyObject(DbConnectionInternal obj) { // A connection with a delegated transaction cannot be disposed of // until the delegated transaction has actually completed. Instead, // we simply leave it alone; when the transaction completes, it will // come back through PutObjectFromTransactedPool, which will call us // again. bool removed = false; lock (_objectList) { removed = _objectList.Remove(obj); Debug.Assert(removed, "attempt to DestroyObject not in list"); _totalObjects = _objectList.Count; } if (removed) { } obj.Dispose(); } private void ErrorCallback(object state) { _errorOccurred = false; _waitHandles.ErrorEvent.Reset(); // the error state is cleaned, destroy the timer to avoid periodic invocation Timer t = _errorTimer; _errorTimer = null; if (t != null) { t.Dispose(); // Cancel timer request. } } // TODO: move this to src/Common and integrate with SqlClient // Note: Odbc connections are not passing through this code private Exception TryCloneCachedException() { return _resError; } private void WaitForPendingOpen() { PendingGetConnection next; do { bool started = false; try { try { } finally { started = Interlocked.CompareExchange(ref _pendingOpensWaiting, 1, 0) == 0; } if (!started) { return; } while (_pendingOpens.TryDequeue(out next)) { if (next.Completion.Task.IsCompleted) { continue; } uint delay; if (next.DueTime == Timeout.Infinite) { delay = unchecked((uint)Timeout.Infinite); } else { delay = (uint)Math.Max(ADP.TimerRemainingMilliseconds(next.DueTime), 0); } DbConnectionInternal connection = null; bool timeout = false; Exception caughtException = null; try { bool allowCreate = true; bool onlyOneCheckConnection = false; timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection); } catch (Exception e) { caughtException = e; } if (caughtException != null) { next.Completion.TrySetException(caughtException); } else if (timeout) { next.Completion.TrySetException(ADP.ExceptionWithStackTrace(ADP.PooledOpenTimeout())); } else { Debug.Assert(connection != null, "connection should never be null in success case"); if (!next.Completion.TrySetResult(connection)) { // if the completion was cancelled, lets try and get this connection back for the next try PutObject(connection, next.Owner); } } } } finally { if (started) { Interlocked.Exchange(ref _pendingOpensWaiting, 0); } } } while (_pendingOpens.TryPeek(out next)); } internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions, out DbConnectionInternal connection) { uint waitForMultipleObjectsTimeout = 0; bool allowCreate = false; if (retry == null) { waitForMultipleObjectsTimeout = (uint)CreationTimeout; // Set the wait timeout to INFINITE (-1) if the SQL connection timeout is 0 (== infinite) if (waitForMultipleObjectsTimeout == 0) waitForMultipleObjectsTimeout = unchecked((uint)Timeout.Infinite); allowCreate = true; } if (_state != State.Running) { connection = null; return true; } bool onlyOneCheckConnection = true; if (TryGetConnection(owningObject, waitForMultipleObjectsTimeout, allowCreate, onlyOneCheckConnection, userOptions, out connection)) { return true; } else if (retry == null) { // timed out on a sync call return true; } var pendingGetConnection = new PendingGetConnection( CreationTimeout == 0 ? Timeout.Infinite : ADP.TimerCurrent() + ADP.TimerFromSeconds(CreationTimeout / 1000), owningObject, retry, userOptions); _pendingOpens.Enqueue(pendingGetConnection); // it is better to StartNew too many times than not enough if (_pendingOpensWaiting == 0) { Thread waitOpenThread = new Thread(WaitForPendingOpen); waitOpenThread.IsBackground = true; waitOpenThread.Start(); } connection = null; return false; } private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection) { DbConnectionInternal obj = null; if (null == obj) { Interlocked.Increment(ref _waitCount); do { int waitResult = BOGUS_HANDLE; try { try { } finally { waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(allowCreate), unchecked((int)waitForMultipleObjectsTimeout)); } // From the WaitAny docs: "If more than one object became signaled during // the call, this is the array index of the signaled object with the // smallest index value of all the signaled objects." This is important // so that the free object signal will be returned before a creation // signal. switch (waitResult) { case WaitHandle.WaitTimeout: Interlocked.Decrement(ref _waitCount); connection = null; return false; case ERROR_HANDLE: // Throw the error that PoolCreateRequest stashed. Interlocked.Decrement(ref _waitCount); throw TryCloneCachedException(); case CREATION_HANDLE: try { obj = UserCreateRequest(owningObject, userOptions); } catch { if (null == obj) { Interlocked.Decrement(ref _waitCount); } throw; } finally { // Ensure that we release this waiter, regardless // of any exceptions that may be thrown. if (null != obj) { Interlocked.Decrement(ref _waitCount); } } if (null == obj) { // If we were not able to create an object, check to see if // we reached MaxPoolSize. If so, we will no longer wait on // the CreationHandle, but instead wait for a free object or // the timeout. if (Count >= MaxPoolSize && 0 != MaxPoolSize) { if (!ReclaimEmancipatedObjects()) { // modify handle array not to wait on creation mutex anymore Debug.Assert(2 == CREATION_HANDLE, "creation handle changed value"); allowCreate = false; } } } break; case SEMAPHORE_HANDLE: // // guaranteed available inventory // Interlocked.Decrement(ref _waitCount); obj = GetFromGeneralPool(); if ((obj != null) && (!obj.IsConnectionAlive())) { DestroyObject(obj); obj = null; // Setting to null in case creating a new object fails if (onlyOneCheckConnection) { if (_waitHandles.CreationSemaphore.WaitOne(unchecked((int)waitForMultipleObjectsTimeout))) { try { obj = UserCreateRequest(owningObject, userOptions); } finally { _waitHandles.CreationSemaphore.Release(1); } } else { // Timeout waiting for creation semaphore - return null connection = null; return false; } } } break; default: Interlocked.Decrement(ref _waitCount); throw ADP.InternalError(ADP.InternalErrorCode.UnexpectedWaitAnyResult); } } finally { if (CREATION_HANDLE == waitResult) { _waitHandles.CreationSemaphore.Release(1); } } } while (null == obj); } if (null != obj) { PrepareConnection(owningObject, obj); } connection = obj; return true; } private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj) { lock (obj) { // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop obj.PostPop(owningObject); } try { obj.ActivateConnection(); } catch { // if Activate throws an exception // put it back in the pool or have it properly disposed of this.PutObject(obj, owningObject); throw; } } /// <summary> /// Creates a new connection to replace an existing connection /// </summary> /// <param name="owningObject">Outer connection that currently owns <paramref name="oldConnection"/></param> /// <param name="userOptions">Options used to create the new connection</param> /// <param name="oldConnection">Inner connection that will be replaced</param> /// <returns>A new inner connection that is attached to the <paramref name="owningObject"/></returns> internal DbConnectionInternal ReplaceConnection(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) { DbConnectionInternal newConnection = UserCreateRequest(owningObject, userOptions, oldConnection); if (newConnection != null) { PrepareConnection(owningObject, newConnection); oldConnection.PrepareForReplaceConnection(); oldConnection.DeactivateConnection(); oldConnection.Dispose(); } return newConnection; } private DbConnectionInternal GetFromGeneralPool() { DbConnectionInternal obj = null; if (!_stackNew.TryPop(out obj)) { if (!_stackOld.TryPop(out obj)) { obj = null; } else { Debug.Assert(obj != null, "null connection is not expected"); } } else { Debug.Assert(obj != null, "null connection is not expected"); } // When another thread is clearing this pool, // it will remove all connections in this pool which causes the // following assert to fire, which really mucks up stress against // checked bits. if (null != obj) { } return (obj); } private void PoolCreateRequest(object state) { // called by pooler to ensure pool requests are currently being satisfied - // creation mutex has not been obtained if (State.Running == _state) { // in case WaitForPendingOpen ever failed with no subsequent OpenAsync calls, // start it back up again if (!_pendingOpens.IsEmpty && _pendingOpensWaiting == 0) { Thread waitOpenThread = new Thread(WaitForPendingOpen); waitOpenThread.IsBackground = true; waitOpenThread.Start(); } // Before creating any new objects, reclaim any released objects that were // not closed. ReclaimEmancipatedObjects(); if (!ErrorOccurred) { if (NeedToReplenish) { // Check to see if pool was created using integrated security and if so, make // sure the identity of current user matches that of user that created pool. // If it doesn't match, do not create any objects on the ThreadPool thread, // since either Open will fail or we will open a object for this pool that does // not belong in this pool. The side effect of this is that if using integrated // security min pool size cannot be guaranteed. if (UsingIntegrateSecurity && !_identity.Equals(DbConnectionPoolIdentity.GetCurrent())) { return; } int waitResult = BOGUS_HANDLE; try { try { } finally { waitResult = WaitHandle.WaitAny(_waitHandles.GetHandles(withCreate: true), CreationTimeout); } if (CREATION_HANDLE == waitResult) { DbConnectionInternal newObj; // Check ErrorOccurred again after obtaining mutex if (!ErrorOccurred) { while (NeedToReplenish) { // Don't specify any user options because there is no outer connection associated with the new connection newObj = CreateObject(owningObject: null, userOptions: null, oldConnection: null); // We do not need to check error flag here, since we know if // CreateObject returned null, we are in error case. if (null != newObj) { PutNewObject(newObj); } else { break; } } } } else if (WaitHandle.WaitTimeout == waitResult) { // do not wait forever and potential block this worker thread // instead wait for a period of time and just requeue to try again QueuePoolCreateRequest(); } } finally { if (CREATION_HANDLE == waitResult) { // reuse waitResult and ignore its value _waitHandles.CreationSemaphore.Release(1); } } } } } } internal void PutNewObject(DbConnectionInternal obj) { Debug.Assert(null != obj, "why are we adding a null object to the pool?"); // Debug.Assert(obj.CanBePooled, "non-poolable object in pool"); _stackNew.Push(obj); _waitHandles.PoolSemaphore.Release(1); } internal void PutObject(DbConnectionInternal obj, object owningObject) { Debug.Assert(null != obj, "null obj?"); // Once a connection is closing (which is the state that we're in at // this point in time) you cannot delegate a transaction to or enlist // a transaction in it, so we can correctly presume that if there was // not a delegated or enlisted transaction to start with, that there // will not be a delegated or enlisted transaction once we leave the // lock. lock (obj) { // Calling PrePush prevents the object from being reclaimed // once we leave the lock, because it sets _pooledCount such // that it won't appear to be out of the pool. What that // means, is that we're now responsible for this connection: // it won't get reclaimed if we drop the ball somewhere. obj.PrePush(owningObject); } DeactivateObject(obj); } private void QueuePoolCreateRequest() { if (State.Running == _state) { // Make sure we're at quota by posting a callback to the threadpool. ThreadPool.QueueUserWorkItem(_poolCreateRequest); } } private bool ReclaimEmancipatedObjects() { bool emancipatedObjectFound = false; List<DbConnectionInternal> reclaimedObjects = new List<DbConnectionInternal>(); int count; lock (_objectList) { count = _objectList.Count; for (int i = 0; i < count; ++i) { DbConnectionInternal obj = _objectList[i]; if (null != obj) { bool locked = false; try { Monitor.TryEnter(obj, ref locked); if (locked) { // avoid race condition with PrePush/PostPop and IsEmancipated if (obj.IsEmancipated) { // Inside the lock, we want to do as little // as possible, so we simply mark the object // as being in the pool, but hand it off to // an out of pool list to be deactivated, // etc. obj.PrePush(null); reclaimedObjects.Add(obj); } } } finally { if (locked) Monitor.Exit(obj); } } } } // NOTE: we don't want to call DeactivateObject while we're locked, // because it can make roundtrips to the server and this will block // object creation in the pooler. Instead, we queue things we need // to do up, and process them outside the lock. count = reclaimedObjects.Count; for (int i = 0; i < count; ++i) { DbConnectionInternal obj = reclaimedObjects[i]; emancipatedObjectFound = true; DeactivateObject(obj); } return emancipatedObjectFound; } internal void Startup() { _cleanupTimer = CreateCleanupTimer(); if (NeedToReplenish) { QueuePoolCreateRequest(); } } internal void Shutdown() { _state = State.ShuttingDown; // deactivate timer callbacks Timer t = _cleanupTimer; _cleanupTimer = null; if (null != t) { t.Dispose(); } } private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null) { // called by user when they were not able to obtain a free object but // instead obtained creation mutex DbConnectionInternal obj = null; if (ErrorOccurred) { throw TryCloneCachedException(); } else { if ((oldConnection != null) || (Count < MaxPoolSize) || (0 == MaxPoolSize)) { // If we have an odd number of total objects, reclaim any dead objects. // If we did not find any objects to reclaim, create a new one. if ((oldConnection != null) || (Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects()) obj = CreateObject(owningObject, userOptions, oldConnection); } return obj; } } } }
namespace zlib { using System; internal static class InfTree { static InfTree() { InfTree.fixed_tl = new int[] { 0x60, 7, 0x100, 0, 8, 80, 0, 8, 0x10, 0x54, 8, 0x73, 0x52, 7, 0x1f, 0, 8, 0x70, 0, 8, 0x30, 0, 9, 0xc0, 80, 7, 10, 0, 8, 0x60, 0, 8, 0x20, 0, 9, 160, 0, 8, 0, 0, 8, 0x80, 0, 8, 0x40, 0, 9, 0xe0, 80, 7, 6, 0, 8, 0x58, 0, 8, 0x18, 0, 9, 0x90, 0x53, 7, 0x3b, 0, 8, 120, 0, 8, 0x38, 0, 9, 0xd0, 0x51, 7, 0x11, 0, 8, 0x68, 0, 8, 40, 0, 9, 0xb0, 0, 8, 8, 0, 8, 0x88, 0, 8, 0x48, 0, 9, 240, 80, 7, 4, 0, 8, 0x54, 0, 8, 20, 0x55, 8, 0xe3, 0x53, 7, 0x2b, 0, 8, 0x74, 0, 8, 0x34, 0, 9, 200, 0x51, 7, 13, 0, 8, 100, 0, 8, 0x24, 0, 9, 0xa8, 0, 8, 4, 0, 8, 0x84, 0, 8, 0x44, 0, 9, 0xe8, 80, 7, 8, 0, 8, 0x5c, 0, 8, 0x1c, 0, 9, 0x98, 0x54, 7, 0x53, 0, 8, 0x7c, 0, 8, 60, 0, 9, 0xd8, 0x52, 7, 0x17, 0, 8, 0x6c, 0, 8, 0x2c, 0, 9, 0xb8, 0, 8, 12, 0, 8, 140, 0, 8, 0x4c, 0, 9, 0xf8, 80, 7, 3, 0, 8, 0x52, 0, 8, 0x12, 0x55, 8, 0xa3, 0x53, 7, 0x23, 0, 8, 0x72, 0, 8, 50, 0, 9, 0xc4, 0x51, 7, 11, 0, 8, 0x62, 0, 8, 0x22, 0, 9, 0xa4, 0, 8, 2, 0, 8, 130, 0, 8, 0x42, 0, 9, 0xe4, 80, 7, 7, 0, 8, 90, 0, 8, 0x1a, 0, 9, 0x94, 0x54, 7, 0x43, 0, 8, 0x7a, 0, 8, 0x3a, 0, 9, 0xd4, 0x52, 7, 0x13, 0, 8, 0x6a, 0, 8, 0x2a, 0, 9, 180, 0, 8, 10, 0, 8, 0x8a, 0, 8, 0x4a, 0, 9, 0xf4, 80, 7, 5, 0, 8, 0x56, 0, 8, 0x16, 0xc0, 8, 0, 0x53, 7, 0x33, 0, 8, 0x76, 0, 8, 0x36, 0, 9, 0xcc, 0x51, 7, 15, 0, 8, 0x66, 0, 8, 0x26, 0, 9, 0xac, 0, 8, 6, 0, 8, 0x86, 0, 8, 70, 0, 9, 0xec, 80, 7, 9, 0, 8, 0x5e, 0, 8, 30, 0, 9, 0x9c, 0x54, 7, 0x63, 0, 8, 0x7e, 0, 8, 0x3e, 0, 9, 220, 0x52, 7, 0x1b, 0, 8, 110, 0, 8, 0x2e, 0, 9, 0xbc, 0, 8, 14, 0, 8, 0x8e, 0, 8, 0x4e, 0, 9, 0xfc, 0x60, 7, 0x100, 0, 8, 0x51, 0, 8, 0x11, 0x55, 8, 0x83, 0x52, 7, 0x1f, 0, 8, 0x71, 0, 8, 0x31, 0, 9, 0xc2, 80, 7, 10, 0, 8, 0x61, 0, 8, 0x21, 0, 9, 0xa2, 0, 8, 1, 0, 8, 0x81, 0, 8, 0x41, 0, 9, 0xe2, 80, 7, 6, 0, 8, 0x59, 0, 8, 0x19, 0, 9, 0x92, 0x53, 7, 0x3b, 0, 8, 0x79, 0, 8, 0x39, 0, 9, 210, 0x51, 7, 0x11, 0, 8, 0x69, 0, 8, 0x29, 0, 9, 0xb2, 0, 8, 9, 0, 8, 0x89, 0, 8, 0x49, 0, 9, 0xf2, 80, 7, 4, 0, 8, 0x55, 0, 8, 0x15, 80, 8, 0x102, 0x53, 7, 0x2b, 0, 8, 0x75, 0, 8, 0x35, 0, 9, 0xca, 0x51, 7, 13, 0, 8, 0x65, 0, 8, 0x25, 0, 9, 170, 0, 8, 5, 0, 8, 0x85, 0, 8, 0x45, 0, 9, 0xea, 80, 7, 8, 0, 8, 0x5d, 0, 8, 0x1d, 0, 9, 0x9a, 0x54, 7, 0x53, 0, 8, 0x7d, 0, 8, 0x3d, 0, 9, 0xda, 0x52, 7, 0x17, 0, 8, 0x6d, 0, 8, 0x2d, 0, 9, 0xba, 0, 8, 13, 0, 8, 0x8d, 0, 8, 0x4d, 0, 9, 250, 80, 7, 3, 0, 8, 0x53, 0, 8, 0x13, 0x55, 8, 0xc3, 0x53, 7, 0x23, 0, 8, 0x73, 0, 8, 0x33, 0, 9, 0xc6, 0x51, 7, 11, 0, 8, 0x63, 0, 8, 0x23, 0, 9, 0xa6, 0, 8, 3, 0, 8, 0x83, 0, 8, 0x43, 0, 9, 230, 80, 7, 7, 0, 8, 0x5b, 0, 8, 0x1b, 0, 9, 150, 0x54, 7, 0x43, 0, 8, 0x7b, 0, 8, 0x3b, 0, 9, 0xd6, 0x52, 7, 0x13, 0, 8, 0x6b, 0, 8, 0x2b, 0, 9, 0xb6, 0, 8, 11, 0, 8, 0x8b, 0, 8, 0x4b, 0, 9, 0xf6, 80, 7, 5, 0, 8, 0x57, 0, 8, 0x17, 0xc0, 8, 0, 0x53, 7, 0x33, 0, 8, 0x77, 0, 8, 0x37, 0, 9, 0xce, 0x51, 7, 15, 0, 8, 0x67, 0, 8, 0x27, 0, 9, 0xae, 0, 8, 7, 0, 8, 0x87, 0, 8, 0x47, 0, 9, 0xee, 80, 7, 9, 0, 8, 0x5f, 0, 8, 0x1f, 0, 9, 0x9e, 0x54, 7, 0x63, 0, 8, 0x7f, 0, 8, 0x3f, 0, 9, 0xde, 0x52, 7, 0x1b, 0, 8, 0x6f, 0, 8, 0x2f, 0, 9, 190, 0, 8, 15, 0, 8, 0x8f, 0, 8, 0x4f, 0, 9, 0xfe, 0x60, 7, 0x100, 0, 8, 80, 0, 8, 0x10, 0x54, 8, 0x73, 0x52, 7, 0x1f, 0, 8, 0x70, 0, 8, 0x30, 0, 9, 0xc1, 80, 7, 10, 0, 8, 0x60, 0, 8, 0x20, 0, 9, 0xa1, 0, 8, 0, 0, 8, 0x80, 0, 8, 0x40, 0, 9, 0xe1, 80, 7, 6, 0, 8, 0x58, 0, 8, 0x18, 0, 9, 0x91, 0x53, 7, 0x3b, 0, 8, 120, 0, 8, 0x38, 0, 9, 0xd1, 0x51, 7, 0x11, 0, 8, 0x68, 0, 8, 40, 0, 9, 0xb1, 0, 8, 8, 0, 8, 0x88, 0, 8, 0x48, 0, 9, 0xf1, 80, 7, 4, 0, 8, 0x54, 0, 8, 20, 0x55, 8, 0xe3, 0x53, 7, 0x2b, 0, 8, 0x74, 0, 8, 0x34, 0, 9, 0xc9, 0x51, 7, 13, 0, 8, 100, 0, 8, 0x24, 0, 9, 0xa9, 0, 8, 4, 0, 8, 0x84, 0, 8, 0x44, 0, 9, 0xe9, 80, 7, 8, 0, 8, 0x5c, 0, 8, 0x1c, 0, 9, 0x99, 0x54, 7, 0x53, 0, 8, 0x7c, 0, 8, 60, 0, 9, 0xd9, 0x52, 7, 0x17, 0, 8, 0x6c, 0, 8, 0x2c, 0, 9, 0xb9, 0, 8, 12, 0, 8, 140, 0, 8, 0x4c, 0, 9, 0xf9, 80, 7, 3, 0, 8, 0x52, 0, 8, 0x12, 0x55, 8, 0xa3, 0x53, 7, 0x23, 0, 8, 0x72, 0, 8, 50, 0, 9, 0xc5, 0x51, 7, 11, 0, 8, 0x62, 0, 8, 0x22, 0, 9, 0xa5, 0, 8, 2, 0, 8, 130, 0, 8, 0x42, 0, 9, 0xe5, 80, 7, 7, 0, 8, 90, 0, 8, 0x1a, 0, 9, 0x95, 0x54, 7, 0x43, 0, 8, 0x7a, 0, 8, 0x3a, 0, 9, 0xd5, 0x52, 7, 0x13, 0, 8, 0x6a, 0, 8, 0x2a, 0, 9, 0xb5, 0, 8, 10, 0, 8, 0x8a, 0, 8, 0x4a, 0, 9, 0xf5, 80, 7, 5, 0, 8, 0x56, 0, 8, 0x16, 0xc0, 8, 0, 0x53, 7, 0x33, 0, 8, 0x76, 0, 8, 0x36, 0, 9, 0xcd, 0x51, 7, 15, 0, 8, 0x66, 0, 8, 0x26, 0, 9, 0xad, 0, 8, 6, 0, 8, 0x86, 0, 8, 70, 0, 9, 0xed, 80, 7, 9, 0, 8, 0x5e, 0, 8, 30, 0, 9, 0x9d, 0x54, 7, 0x63, 0, 8, 0x7e, 0, 8, 0x3e, 0, 9, 0xdd, 0x52, 7, 0x1b, 0, 8, 110, 0, 8, 0x2e, 0, 9, 0xbd, 0, 8, 14, 0, 8, 0x8e, 0, 8, 0x4e, 0, 9, 0xfd, 0x60, 7, 0x100, 0, 8, 0x51, 0, 8, 0x11, 0x55, 8, 0x83, 0x52, 7, 0x1f, 0, 8, 0x71, 0, 8, 0x31, 0, 9, 0xc3, 80, 7, 10, 0, 8, 0x61, 0, 8, 0x21, 0, 9, 0xa3, 0, 8, 1, 0, 8, 0x81, 0, 8, 0x41, 0, 9, 0xe3, 80, 7, 6, 0, 8, 0x59, 0, 8, 0x19, 0, 9, 0x93, 0x53, 7, 0x3b, 0, 8, 0x79, 0, 8, 0x39, 0, 9, 0xd3, 0x51, 7, 0x11, 0, 8, 0x69, 0, 8, 0x29, 0, 9, 0xb3, 0, 8, 9, 0, 8, 0x89, 0, 8, 0x49, 0, 9, 0xf3, 80, 7, 4, 0, 8, 0x55, 0, 8, 0x15, 80, 8, 0x102, 0x53, 7, 0x2b, 0, 8, 0x75, 0, 8, 0x35, 0, 9, 0xcb, 0x51, 7, 13, 0, 8, 0x65, 0, 8, 0x25, 0, 9, 0xab, 0, 8, 5, 0, 8, 0x85, 0, 8, 0x45, 0, 9, 0xeb, 80, 7, 8, 0, 8, 0x5d, 0, 8, 0x1d, 0, 9, 0x9b, 0x54, 7, 0x53, 0, 8, 0x7d, 0, 8, 0x3d, 0, 9, 0xdb, 0x52, 7, 0x17, 0, 8, 0x6d, 0, 8, 0x2d, 0, 9, 0xbb, 0, 8, 13, 0, 8, 0x8d, 0, 8, 0x4d, 0, 9, 0xfb, 80, 7, 3, 0, 8, 0x53, 0, 8, 0x13, 0x55, 8, 0xc3, 0x53, 7, 0x23, 0, 8, 0x73, 0, 8, 0x33, 0, 9, 0xc7, 0x51, 7, 11, 0, 8, 0x63, 0, 8, 0x23, 0, 9, 0xa7, 0, 8, 3, 0, 8, 0x83, 0, 8, 0x43, 0, 9, 0xe7, 80, 7, 7, 0, 8, 0x5b, 0, 8, 0x1b, 0, 9, 0x97, 0x54, 7, 0x43, 0, 8, 0x7b, 0, 8, 0x3b, 0, 9, 0xd7, 0x52, 7, 0x13, 0, 8, 0x6b, 0, 8, 0x2b, 0, 9, 0xb7, 0, 8, 11, 0, 8, 0x8b, 0, 8, 0x4b, 0, 9, 0xf7, 80, 7, 5, 0, 8, 0x57, 0, 8, 0x17, 0xc0, 8, 0, 0x53, 7, 0x33, 0, 8, 0x77, 0, 8, 0x37, 0, 9, 0xcf, 0x51, 7, 15, 0, 8, 0x67, 0, 8, 0x27, 0, 9, 0xaf, 0, 8, 7, 0, 8, 0x87, 0, 8, 0x47, 0, 9, 0xef, 80, 7, 9, 0, 8, 0x5f, 0, 8, 0x1f, 0, 9, 0x9f, 0x54, 7, 0x63, 0, 8, 0x7f, 0, 8, 0x3f, 0, 9, 0xdf, 0x52, 7, 0x1b, 0, 8, 0x6f, 0, 8, 0x2f, 0, 9, 0xbf, 0, 8, 15, 0, 8, 0x8f, 0, 8, 0x4f, 0, 9, 0xff }; InfTree.fixed_td = new int[] { 80, 5, 1, 0x57, 5, 0x101, 0x53, 5, 0x11, 0x5b, 5, 0x1001, 0x51, 5, 5, 0x59, 5, 0x401, 0x55, 5, 0x41, 0x5d, 5, 0x4001, 80, 5, 3, 0x58, 5, 0x201, 0x54, 5, 0x21, 0x5c, 5, 0x2001, 0x52, 5, 9, 90, 5, 0x801, 0x56, 5, 0x81, 0xc0, 5, 0x6001, 80, 5, 2, 0x57, 5, 0x181, 0x53, 5, 0x19, 0x5b, 5, 0x1801, 0x51, 5, 7, 0x59, 5, 0x601, 0x55, 5, 0x61, 0x5d, 5, 0x6001, 80, 5, 4, 0x58, 5, 0x301, 0x54, 5, 0x31, 0x5c, 5, 0x3001, 0x52, 5, 13, 90, 5, 0xc01, 0x56, 5, 0xc1, 0xc0, 5, 0x6001 }; InfTree.cplens = new int[] { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 0x11, 0x13, 0x17, 0x1b, 0x1f, 0x23, 0x2b, 0x33, 0x3b, 0x43, 0x53, 0x63, 0x73, 0x83, 0xa3, 0xc3, 0xe3, 0x102, 0, 0 }; InfTree.cplext = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0x70, 0x70 }; InfTree.cpdist = new int[] { 1, 2, 3, 4, 5, 7, 9, 13, 0x11, 0x19, 0x21, 0x31, 0x41, 0x61, 0x81, 0xc1, 0x101, 0x181, 0x201, 0x301, 0x401, 0x601, 0x801, 0xc01, 0x1001, 0x1801, 0x2001, 0x3001, 0x4001, 0x6001 }; InfTree.cpdext = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; } internal static int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) { int[] numArray1 = new int[0x10]; int[] numArray2 = new int[3]; int[] numArray3 = new int[15]; int[] numArray4 = new int[0x10]; int num10 = 0; int num5 = n; do { numArray1[b[bindex + num10]]++; num10++; num5--; } while (num5 != 0); if (numArray1[0] == n) { t[0] = -1; m[0] = 0; return 0; } int num8 = m[0]; int num6 = 1; while (num6 <= 15) { if (numArray1[num6] != 0) { break; } num6++; } int num7 = num6; if (num8 < num6) { num8 = num6; } num5 = 15; while (num5 != 0) { if (numArray1[num5] != 0) { break; } num5--; } int num3 = num5; if (num8 > num5) { num8 = num5; } m[0] = num8; int num14 = 1 << (num6 & 0x1f); while (num6 < num5) { num14 -= numArray1[num6]; if (num14 < 0) { return -3; } num6++; num14 = num14 << 1; } num14 -= numArray1[num5]; if (num14 < 0) { return -3; } numArray1[num5] += num14; numArray4[1] = num6 = 0; num10 = 1; int num13 = 2; while (--num5 != 0) { numArray4[num13] = num6 += numArray1[num10]; num13++; num10++; } num5 = 0; num10 = 0; do { num6 = b[bindex + num10]; if (num6 != 0) { v[numArray4[num6]++] = num5; } num10++; } while (++num5 < n); n = numArray4[num3]; numArray4[0] = num5 = 0; num10 = 0; int num4 = -1; int num12 = -num8; numArray3[0] = 0; int num11 = 0; int num15 = 0; while (num7 <= num3) { int num2; int num1 = numArray1[num7]; goto Label_03BD; Label_01B2: num4++; num12 += num8; num15 = num3 - num12; num15 = (num15 > num8) ? num8 : num15; if ((num2 = 1 << ((num6 = num7 - num12) & 0x1f)) > (num1 + 1)) { num2 -= num1 + 1; num13 = num7; if (num6 < num15) { while (++num6 < num15) { if ((num2 = num2 << 1) <= numArray1[++num13]) { break; } num2 -= numArray1[num13]; } } } num15 = 1 << (num6 & 0x1f); if ((hn[0] + num15) > 0x5a0) { return -3; } numArray3[num4] = num11 = hn[0]; hn[0] += num15; if (num4 != 0) { numArray4[num4] = num5; numArray2[0] = (byte) num6; numArray2[1] = (byte) num8; num6 = SupportClass.URShift(num5, num12 - num8); numArray2[2] = (num11 - numArray3[num4 - 1]) - num6; Array.Copy(numArray2, 0, hp, (numArray3[num4 - 1] + num6) * 3, 3); } else { t[0] = num11; } Label_02AE: if (num7 > (num12 + num8)) { goto Label_01B2; } numArray2[1] = (byte) (num7 - num12); if (num10 >= n) { numArray2[0] = 0xc0; } else if (v[num10] < s) { numArray2[0] = (v[num10] < 0x100) ? ((byte) 0) : ((byte) 0x60); numArray2[2] = v[num10++]; } else { numArray2[0] = (byte) ((e[v[num10] - s] + 0x10) + 0x40); numArray2[2] = d[v[num10++] - s]; } num2 = 1 << ((num7 - num12) & 0x1f); num6 = SupportClass.URShift(num5, num12); while (num6 < num15) { Array.Copy(numArray2, 0, hp, (num11 + num6) * 3, 3); num6 += num2; } num6 = 1 << ((num7 - 1) & 0x1f); while ((num5 & num6) != 0) { num5 ^= num6; num6 = SupportClass.URShift(num6, 1); } num5 ^= num6; for (int num9 = (1 << (num12 & 0x1f)) - 1; (num5 & num9) != numArray4[num4]; num9 = (1 << (num12 & 0x1f)) - 1) { num4--; num12 -= num8; } Label_03BD: if (num1-- != 0) { goto Label_02AE; } num7++; } if ((num14 != 0) && (num3 != 1)) { return -5; } return 0; } internal static int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZStream z) { int[] numArray1 = new int[1]; int[] numArray2 = new int[0x13]; int num1 = InfTree.huft_build(c, 0, 0x13, 0x13, null, null, tb, bb, hp, numArray1, numArray2); if (num1 == -3) { z.msg = "oversubscribed dynamic bit lengths tree"; return num1; } if ((num1 != -5) && (bb[0] != 0)) { return num1; } z.msg = "incomplete dynamic bit lengths tree"; return -3; } internal static int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int[] tl, int[] td, int[] hp, ZStream z) { int[] numArray1 = new int[1]; int[] numArray2 = new int[0x120]; int num1 = InfTree.huft_build(c, 0, nl, 0x101, InfTree.cplens, InfTree.cplext, tl, bl, hp, numArray1, numArray2); if ((num1 != 0) || (bl[0] == 0)) { if (num1 == -3) { z.msg = "oversubscribed literal/length tree"; return num1; } if (num1 != -4) { z.msg = "incomplete literal/length tree"; num1 = -3; } return num1; } num1 = InfTree.huft_build(c, nl, nd, 0, InfTree.cpdist, InfTree.cpdext, td, bd, hp, numArray1, numArray2); if ((num1 == 0) && ((bd[0] != 0) || (nl <= 0x101))) { return 0; } if (num1 == -3) { z.msg = "oversubscribed distance tree"; return num1; } if (num1 == -5) { z.msg = "incomplete distance tree"; return -3; } if (num1 != -4) { z.msg = "empty distance tree with lengths"; num1 = -3; } return num1; } internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZStream z) { bl[0] = 9; bd[0] = 5; tl[0] = InfTree.fixed_tl; td[0] = InfTree.fixed_td; return 0; } internal const int BMAX = 15; internal static readonly int[] cpdext; internal static readonly int[] cpdist; internal static readonly int[] cplens; internal static readonly int[] cplext; internal const int fixed_bd = 5; internal const int fixed_bl = 9; internal static readonly int[] fixed_td; internal static readonly int[] fixed_tl; private const int MANY = 0x5a0; private const int Z_BUF_ERROR = -5; private const int Z_DATA_ERROR = -3; private const int Z_ERRNO = -1; private const int Z_MEM_ERROR = -4; private const int Z_NEED_DICT = 2; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_STREAM_ERROR = -2; private const int Z_VERSION_ERROR = -6; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using GoldenEye.Events; using GoldenEye.Registration; using GoldenEye.Tests.External.Contracts; using GoldenEye.Tests.External.Handlers; using MediatR; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace GoldenEye.Tests.Registration; public class EventHandlerRegistrationTests { public class UserCreated: IEvent { public UserCreated(Guid userId) { UserId = userId; } public Guid UserId { get; } public Guid StreamId => UserId; } public class UsersCountHandler: IEventHandler<UserCreated> { public int UserCount { get; private set; } public Task Handle(UserCreated @event, CancellationToken cancellationToken) { UserCount++; return Unit.Task; } } public class UsersIdsHandler: IEventHandler<UserCreated> { public List<Guid> UserIds { get; } = new List<Guid>(); public Task Handle(UserCreated @event, CancellationToken cancellationToken) { UserIds.Add(@event.StreamId); return Unit.Task; } } [Fact] public async Task GivenTwoEventHandlers_WhenEventIsPublished_ThenBothHandles() { //Given var services = new ServiceCollection(); services.AddDDD(); services.AddEventHandler<UserCreated, UsersCountHandler>(ServiceLifetime.Singleton); services.AddEventHandler<UserCreated, UsersIdsHandler>(ServiceLifetime.Singleton); var sp = services.BuildServiceProvider(); var eventBus = sp.GetService<IEventBus>(); var @event = new UserCreated(Guid.NewGuid()); //When await eventBus.Publish(@event); //Then var usersCountHandler = sp.GetService<UsersCountHandler>(); usersCountHandler.UserCount.Should().Be(1); var usersIdsHandler = sp.GetService<UsersIdsHandler>(); usersIdsHandler.UserIds.Should().HaveCount(1); usersIdsHandler.UserIds.Should().Contain(@event.UserId); } } public class EventHandlerAllRegistrationTests { public EventHandlerAllRegistrationTests() { services.AddAllEventHandlers(ServiceLifetime.Scoped); } public class UserAdded: IEvent { public Guid StreamId => Guid.Empty; } public class UserUpdated: IEvent { public Guid StreamId => Guid.Empty; } public class AccountAdded: IEvent { public Guid StreamId => Guid.Empty; } public class AccountUpdated: IEvent { public Guid StreamId => Guid.Empty; } public class AccountDeleted: IEvent { public Guid StreamId => Guid.Empty; } public class UserEventHandler: IEventHandler<UserAdded>, IEventHandler<UserUpdated> { public Task Handle(UserAdded request, CancellationToken cancellationToken) { return Unit.Task; } public Task Handle(UserUpdated request, CancellationToken cancellationToken) { return Unit.Task; } } public abstract class BaseAccountEventHandler: IEventHandler<AccountAdded>, IEventHandler<AccountUpdated> { public abstract Task Handle(AccountAdded request, CancellationToken cancellationToken); public Task Handle(AccountUpdated request, CancellationToken cancellationToken) { return Unit.Task; } } public class AccountEventHandler: BaseAccountEventHandler, IEventHandler<AccountDeleted> { public Task Handle(AccountDeleted request, CancellationToken cancellationToken) { return Unit.Task; } public override Task Handle(AccountAdded request, CancellationToken cancellationToken) { return Unit.Task; } } public class DuplicatedDeleteAccountEventHandler: IEventHandler<AccountDeleted> { public Task Handle(AccountDeleted request, CancellationToken cancellationToken) { return Unit.Task; } } public abstract class AbstractEventHandler: IEventHandler<AccountDeleted> { public Task Handle(AccountDeleted request, CancellationToken cancellationToken) { return Unit.Task; } } public class GenericEventHandler<TEvent>: IEventHandler<TEvent> where TEvent : IEvent { public Task Handle(TEvent notification, CancellationToken cancellationToken) { throw new NotImplementedException(); } } private readonly ServiceCollection services = new ServiceCollection(); [Fact] public void GivenAbstractEventHandler_WhenAddAllEventHandlerCalled_ThenIsNotRegistered() { using (var sp = services.BuildServiceProvider()) { var deleteAccountHandlers = sp.GetServices<INotificationHandler<AccountDeleted>>() .Union(sp.GetServices<IEventHandler<AccountDeleted>>()); deleteAccountHandlers.Should().NotContain(x => x is AbstractEventHandler); } } [Fact] public void GivenBaseEventHandler_WhenAddAllEventHandlerCalled_ThenOnlyDerivedClassIsRegistered() { using (var sp = services.BuildServiceProvider()) { var accountAddedHandlers = sp.GetServices<INotificationHandler<AccountAdded>>() .Union(sp.GetServices<IEventHandler<AccountAdded>>()); var accountUpdatedHandlers = sp.GetServices<INotificationHandler<AccountUpdated>>() .Union(sp.GetServices<IEventHandler<AccountUpdated>>()); accountAddedHandlers.Should().ContainSingle(); accountAddedHandlers.Should().AllBeOfType<AccountEventHandler>(); accountUpdatedHandlers.Should().ContainSingle(); accountUpdatedHandlers.Should().AllBeOfType<AccountEventHandler>(); } } [Fact] public void GivenDuplicatedEventHandler_WhenAddAllEventHandlerCalled_ThenBothAreRegistered() { using (var sp = services.BuildServiceProvider()) { var deleteAccountHandlers = sp.GetServices<INotificationHandler<AccountDeleted>>() .Union(sp.GetServices<IEventHandler<AccountDeleted>>()); deleteAccountHandlers.Should().HaveCount(2); deleteAccountHandlers.Should().Contain(x => x is AccountEventHandler); deleteAccountHandlers.Should().Contain(x => x is DuplicatedDeleteAccountEventHandler); } } [Fact] public void GivenGenericEventHandler_WhenAddAllEventHandlerCalled_ThenIsNotRegistered() { using (var sp = services.BuildServiceProvider()) { var genericHandler = sp.GetService<GenericEventHandler<BankAccountCreated>>(); genericHandler.Should().BeNull(); } } [Fact] public void GivenMultipleEventHandler_WhenAddAllEventHandlerCalled_ThenAllEventHandlersAreRegistered() { using (var sp = services.BuildServiceProvider()) { var userAddedHandlers = sp.GetServices<INotificationHandler<UserAdded>>() .Union(sp.GetServices<IEventHandler<UserAdded>>()).ToList(); var userUpdatedHandlers = sp.GetServices<INotificationHandler<UserUpdated>>() .Union(sp.GetServices<IEventHandler<UserUpdated>>()).ToList(); userAddedHandlers.Should().ContainSingle(); userAddedHandlers.Should().AllBeOfType<UserEventHandler>(); userUpdatedHandlers.Should().ContainSingle(); userUpdatedHandlers.Should().AllBeOfType<UserEventHandler>(); } } [Fact] public void GivenMultipleEventHandlersFromApplicationDependencies_WhenAddAllEventHandlerCalled_ThenBothAreRegistered() { using (var sp = services.BuildServiceProvider()) { var bankAccountCreatedHandlers = sp.GetServices<INotificationHandler<BankAccountCreated>>() .Union(sp.GetServices<IEventHandler<BankAccountCreated>>()).ToList(); var moneyWasWithdrawnHandlers = sp.GetServices<INotificationHandler<MoneyWasWithdrawn>>() .Union(sp.GetServices<IEventHandler<MoneyWasWithdrawn>>()).ToList(); bankAccountCreatedHandlers.Should().HaveCount(2); bankAccountCreatedHandlers.Should().Contain(x => x is FirstEventHandler); bankAccountCreatedHandlers.Should().Contain(x => x is SecondEventHandler); moneyWasWithdrawnHandlers.Should().ContainSingle(); moneyWasWithdrawnHandlers.Should().AllBeOfType<FirstEventHandler>(); } } }
// *********************************************************************** // Copyright (c) 2010 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework.Attributes { [TestFixture] public class ApplyToTestTests { Test test; [SetUp] public void SetUp() { test = new TestDummy(); test.RunState = RunState.Runnable; } #region CategoryAttribute [Test] public void CategoryAttributeSetsCategory() { new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsCategoryOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsMultipleCategories() { new CategoryAttribute("group1").ApplyToTest(test); new CategoryAttribute("group2").ApplyToTest(test); Assert.That(test.Properties[PropertyNames.Category], Is.EquivalentTo( new string[] { "group1", "group2" } )); } #endregion #region DescriptionAttribute [Test] public void DescriptionAttributeSetsDescription() { new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } [Test] public void DescriptionAttributeSetsDescriptionOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } #endregion #region IgnoreAttribute [Test] public void IgnoreAttributeIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeSetsIgnoreReason() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void IgnoreAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; test.Properties.Set(PropertyNames.SkipReason, "UNCHANGED"); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void IgnoreAttributeIgnoresTestUntilDateSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeIgnoresTestUntilDateTimeSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01 12:00:00Z"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeMarksTestAsRunnableAfterUntilDatePasses() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1492-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [TestCase("4242-01-01")] [TestCase("4242-01-01 00:00:00Z")] [TestCase("4242-01-01 00:00:00")] public void IgnoreAttributeUntilSetsTheReason(string date) { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = date; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Ignoring until 4242-01-01 00:00:00Z. BECAUSE")); } [Test] public void IgnoreAttributeWithInvalidDateThrowsException() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); Assert.Throws<FormatException>(() => ignoreAttribute.Until = "Thursday the twenty fifth of December"); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDateProperty() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("4242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDatePropertyPastUntilDate() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("1242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithExplicitIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region ExplicitAttribute [Test] public void ExplicitAttributeMakesTestExplicit() { new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); } [Test] public void ExplicitAttributeSetsIgnoreReason() { new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void ExplicitAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; test.Properties.Set(PropertyNames.SkipReason, "UNCHANGED"); new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void ExplicitAttributeWithIgnoreIgnoresTest() { new ExplicitAttribute().ApplyToTest(test); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttributeSetsJoinType() { new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } [Test] public void CombinatorialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } #endregion #region CultureAttribute [Test] public void CultureAttributeIncludingCurrentCultureRunsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void CultureAttributeExcludingCurrentCultureSkipsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; CultureAttribute attr = new CultureAttribute(name); attr.Exclude = name; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Not supported under culture " + name)); } [Test] public void CultureAttributeIncludingOtherCultureSkipsTest() { string name = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == name) name = "en-US"; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Only supported under culture " + name)); } [Test] public void CultureAttributeExcludingOtherCultureRunsTest() { string other = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == other) other = "en-US"; CultureAttribute attr = new CultureAttribute(); attr.Exclude = other; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeWithMultipleCulturesIncluded() { string current = System.Globalization.CultureInfo.CurrentCulture.Name; string other = current == "fr-FR" ? "en-US" : "fr-FR"; string cultures = current + "," + other; new CultureAttribute(cultures).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region MaxTimeAttribute [Test] public void MaxTimeAttributeSetsMaxTime() { new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } [Test] public void MaxTimeAttributeSetsMaxTimeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttributeSetsJoinType() { new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } [Test] public void PairwiseAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } #endregion #region PlatformAttribute #if !PORTABLE [Test] public void PlatformAttributeRunsTest() { string myPlatform = System.IO.Path.DirectorySeparatorChar == '/' ? "Linux" : "Win"; new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void PlatformAttributeSkipsTest() { string notMyPlatform = System.IO.Path.DirectorySeparatorChar == '/' ? "Win" : "Linux"; new PlatformAttribute(notMyPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); } [Test] public void PlatformAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string myPlatform = System.IO.Path.DirectorySeparatorChar == '/' ? "Linux" : "Win"; new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endif #endregion #region RepeatAttribute [Test] public void RepeatAttributeSetsRepeatCount() { new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } [Test] public void RepeatAttributeSetsRepeatCountOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } #endregion #if !SILVERLIGHT && !NETCF && !PORTABLE #region RequiresMTAAttribute [Test] public void RequiresMTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } [Test] public void RequiresMTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } #endregion #region RequiresSTAAttribute [Test] public void RequiresSTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } [Test] public void RequiresSTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endregion #endif #region RequiresThreadAttribute #if !SILVERLIGHT && !PORTABLE [Test] public void RequiresThreadAttributeSetsRequiresThread() { new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } [Test] public void RequiresThreadAttributeSetsRequiresThreadOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } #endif #if !SILVERLIGHT && !NETCF && !PORTABLE [Test] public void RequiresThreadAttributeMaySetApartmentState() { new RequiresThreadAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endif #endregion #region SequentialAttribute [Test] public void SequentialAttributeSetsJoinType() { new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } [Test] public void SequentialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } #endregion #if !NETCF #region SetCultureAttribute public void SetCultureAttributeSetsSetCultureProperty() { new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } public void SetCultureAttributeSetsSetCulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } #endregion #region SetUICultureAttribute public void SetUICultureAttributeSetsSetUICultureProperty() { new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } public void SetUICultureAttributeSetsSetUICulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } #endregion #endif } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows.Input; using Microsoft.PythonTools.Editor.Core; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.IncrementalSearch; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.TextManager.Interop; using IServiceProvider = System.IServiceProvider; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.PythonTools.Intellisense { internal sealed class IntellisenseController : IIntellisenseController, IOleCommandTarget { private readonly ITextView _textView; private readonly IntellisenseControllerProvider _provider; private readonly IIncrementalSearch _incSearch; private readonly ExpansionClient _expansionClient; private readonly IServiceProvider _serviceProvider; private readonly IVsExpansionManager _expansionMgr; private ICompletionSession _activeSession; private ISignatureHelpSession _sigHelpSession; private IQuickInfoSession _quickInfoSession; internal IOleCommandTarget _oldTarget; private IEditorOperations _editOps; private readonly HashSet<ITextBuffer> _subjectBuffers = new HashSet<ITextBuffer>(); private static string[] _allStandardSnippetTypes = { ExpansionClient.Expansion, ExpansionClient.SurroundsWith }; private static string[] _surroundsWithSnippetTypes = { ExpansionClient.SurroundsWith, ExpansionClient.SurroundsWithStatement }; /// <summary> /// Attaches events for invoking Statement completion /// </summary> public IntellisenseController(IntellisenseControllerProvider provider, ITextView textView, IServiceProvider serviceProvider) { _textView = textView; _provider = provider; _editOps = provider._EditOperationsFactory.GetEditorOperations(textView); _incSearch = provider._IncrementalSearch.GetIncrementalSearch(textView); _textView.MouseHover += TextViewMouseHover; _serviceProvider = serviceProvider; if (textView.TextBuffer.IsPythonContent()) { try { _expansionClient = new ExpansionClient(textView, provider._adaptersFactory, provider._ServiceProvider); var textMgr = (IVsTextManager2)_serviceProvider.GetService(typeof(SVsTextManager)); textMgr.GetExpansionManager(out _expansionMgr); } catch (ArgumentException) { // No expansion client for this buffer, but we can continue without it } } textView.Properties.AddProperty(typeof(IntellisenseController), this); // added so our key processors can get back to us _textView.Closed += TextView_Closed; } private void TextView_Closed(object sender, EventArgs e) { Close(); } internal void Close() { _textView.MouseHover -= TextViewMouseHover; _textView.Closed -= TextView_Closed; _textView.Properties.RemoveProperty(typeof(IntellisenseController)); foreach (var buffer in _subjectBuffers.ToArray()) { DisconnectSubjectBuffer(buffer); } } private async void TextViewMouseHover(object sender, MouseHoverEventArgs e) { if (_quickInfoSession != null && !_quickInfoSession.IsDismissed) { _quickInfoSession.Dismiss(); } var pt = e.TextPosition.GetPoint(EditorExtensions.IsPythonContent, PositionAffinity.Successor); if (pt != null) { if (_textView.TextBuffer.GetInteractiveWindow() != null && pt.Value.Snapshot.Length > 1 && pt.Value.Snapshot[0] == '$') { // don't provide quick info on help, the content type doesn't switch until we have // a complete command otherwise we shouldn't need to do this. return; } var quickInfo = await VsProjectAnalyzer.GetQuickInfoAsync( _serviceProvider, _textView, pt.Value ); QuickInfoSource.AddQuickInfo(_textView, quickInfo); var viewPoint = _textView.BufferGraph.MapUpToBuffer( pt.Value, PointTrackingMode.Positive, PositionAffinity.Successor, _textView.TextBuffer ); if (viewPoint != null) { _quickInfoSession = _provider._QuickInfoBroker.TriggerQuickInfo( _textView, viewPoint.Value.Snapshot.CreateTrackingPoint(viewPoint.Value, PointTrackingMode.Positive), true ); } } } internal void TriggerQuickInfo() { if (_quickInfoSession != null && !_quickInfoSession.IsDismissed) { _quickInfoSession.Dismiss(); } _quickInfoSession = _provider._QuickInfoBroker.TriggerQuickInfo(_textView); } private static object _intellisenseAnalysisEntry = new object(); public void ConnectSubjectBuffer(ITextBuffer subjectBuffer) { _subjectBuffers.Add(subjectBuffer); var analyzer = _textView.GetAnalysisEntry(subjectBuffer, _serviceProvider)?.Analyzer; bool isTemporaryFile = false; if (analyzer == null) { // there's no analyzer for this file, but we can analyze it against either // the default analyzer or some other analyzer (e.g. if it's a diff view, we want // to analyze against the project we're diffing from). But in either case this // is just a temporary file which should be closed when the view is closed. analyzer = _textView.GetBestAnalyzer(_serviceProvider); isTemporaryFile = true; } if (analyzer != null) { analyzer.MonitorTextBufferAsync(subjectBuffer, isTemporaryFile).ContinueWith(task => { var newParser = task.Result; if (newParser != null) { // store the analysis entry so that we can detach it (the file path is lost // when we close the view) subjectBuffer.Properties[_intellisenseAnalysisEntry] = newParser.AnalysisEntry; lock(newParser) { newParser.AttachedViews++; } } }); } } public void DisconnectSubjectBuffer(ITextBuffer subjectBuffer) { if (_subjectBuffers.Remove(subjectBuffer)) { AnalysisEntry analysis; if (subjectBuffer.Properties.TryGetProperty(_intellisenseAnalysisEntry, out analysis)) { analysis.Analyzer.BufferDetached(analysis, subjectBuffer); subjectBuffer.Properties.RemoveProperty(_intellisenseAnalysisEntry); } } } /// <summary> /// Detaches the events /// </summary> /// <param name="textView"></param> public void Detach(ITextView textView) { if (_textView == null) { throw new InvalidOperationException("Already detached from text view"); } if (textView != _textView) { throw new ArgumentException("Not attached to specified text view", "textView"); } _textView.MouseHover -= TextViewMouseHover; _textView.Properties.RemoveProperty(typeof(IntellisenseController)); DetachKeyboardFilter(); } /// <summary> /// Triggers Statement completion when appropriate keys are pressed /// The key combination is CTRL-J or "." /// The intellisense window is dismissed when one presses ESC key /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPreprocessKeyDown(object sender, TextCompositionEventArgs e) { // We should only receive pre-process events from our text view Debug.Assert(sender == _textView); string text = e.Text; if (text.Length == 1) { HandleChar(text[0]); } } private string GetTextBeforeCaret(int includeCharsAfter = 0) { var maybePt = _textView.Caret.Position.Point.GetPoint(_textView.TextBuffer, PositionAffinity.Predecessor); if (!maybePt.HasValue) { return string.Empty; } var pt = maybePt.Value + includeCharsAfter; var span = new SnapshotSpan(pt.GetContainingLine().Start, pt); return span.GetText(); } private void HandleChar(char ch) { // We trigger completions when the user types . or space. Called via our IOleCommandTarget filter // on the text view. // // We trigger signature help when we receive a "(". We update our current sig when // we receive a "," and we close sig help when we receive a ")". if (!_incSearch.IsActive) { switch (ch) { case '@': if (!string.IsNullOrWhiteSpace(GetTextBeforeCaret(-1))) { break; } goto case '.'; case '.': case ' ': if (_provider.PythonService.LangPrefs.AutoListMembers) { TriggerCompletionSession(false); } break; case '(': if (_provider.PythonService.LangPrefs.AutoListParams) { OpenParenStartSignatureSession(); } break; case ')': if (_sigHelpSession != null) { _sigHelpSession.Dismiss(); _sigHelpSession = null; } if (_provider.PythonService.LangPrefs.AutoListParams) { // trigger help for outer call if there is one TriggerSignatureHelp(); } break; case '=': case ',': if (_sigHelpSession == null) { if (_provider.PythonService.LangPrefs.AutoListParams) { CommaStartSignatureSession(); } } else { UpdateCurrentParameter(); } break; default: if (IsIdentifierFirstChar(ch) && (_activeSession == null || _activeSession.CompletionSets.Count == 0)) { bool commitByDefault; if (ShouldTriggerIdentifierCompletionSession(out commitByDefault)) { TriggerCompletionSession(false, commitByDefault); } } break; } } } private bool ShouldTriggerIdentifierCompletionSession(out bool commitByDefault) { commitByDefault = true; if (!_provider.PythonService.AdvancedOptions.AutoListIdentifiers || !_provider.PythonService.AdvancedOptions.AutoListMembers) { return false; } SnapshotPoint? caretPoint = _textView.BufferGraph.MapDownToFirstMatch( _textView.Caret.Position.BufferPosition, PointTrackingMode.Positive, EditorExtensions.IsPythonContent, PositionAffinity.Predecessor ); if (!caretPoint.HasValue) { return false; } var snapshot = caretPoint.Value.Snapshot; var statement = new ReverseExpressionParser( snapshot, snapshot.TextBuffer, snapshot.CreateTrackingSpan(caretPoint.Value.Position, 0, SpanTrackingMode.EdgeNegative) ).GetStatementRange(); if (!statement.HasValue || caretPoint.Value <= statement.Value.Start) { return false; } var text = new SnapshotSpan(statement.Value.Start, caretPoint.Value).GetText(); if (string.IsNullOrEmpty(text)) { return false; } var analysis = _textView.GetAnalysisEntry(snapshot.TextBuffer, _serviceProvider); if (analysis == null) { return false; } var languageVersion = analysis.Analyzer.InterpreterFactory.Configuration.Version.ToLanguageVersion(); PythonAst ast; using (var parser = Parser.CreateParser(new StringReader(text), languageVersion, new ParserOptions())) { ast = parser.ParseSingleStatement(); } var walker = new ExpressionCompletionWalker(caretPoint.Value.Position - statement.Value.Start.Position); ast.Walk(walker); commitByDefault = walker.CommitByDefault; return walker.CanComplete; } private class ExpressionCompletionWalker : PythonWalker { public bool CanComplete = false; public bool CommitByDefault = true; private readonly int _caretIndex; public ExpressionCompletionWalker(int caretIndex) { _caretIndex = caretIndex; } private static bool IsActualExpression(Expression node) { return node != null && !(node is ErrorExpression); } private static bool IsActualExpression(IList<NameExpression> expressions) { return expressions != null && expressions.Count > 0; } private static bool IsActualExpression(IList<Expression> expressions) { return expressions != null && expressions.Count > 0 && !(expressions[0] is ErrorExpression); } private bool HasCaret(Node node) { return node.StartIndex <= _caretIndex && _caretIndex <= node.EndIndex; } public override bool Walk(ErrorExpression node) { return false; } public override bool Walk(AssignmentStatement node) { CanComplete = true; CommitByDefault = true; if (node.Right != null) { node.Right.Walk(this); } return false; } public override bool Walk(Arg node) { CanComplete = true; CommitByDefault = true; return base.Walk(node); } public override bool Walk(ClassDefinition node) { CanComplete = false; return base.Walk(node); } public override bool Walk(FunctionDefinition node) { CommitByDefault = true; if (node.Parameters != null) { CanComplete = false; foreach (var p in node.Parameters) { p.Walk(this); } } if (node.Decorators != null) { node.Decorators.Walk(this); } if (node.ReturnAnnotation != null) { CanComplete = true; node.ReturnAnnotation.Walk(this); } if (node.Body != null && !(node.Body is ErrorStatement)) { CanComplete = node.IsLambda; node.Body.Walk(this); } return false; } public override bool Walk(Parameter node) { CommitByDefault = true; var afterName = node.Annotation ?? node.DefaultValue; CanComplete = afterName != null && afterName.StartIndex <= _caretIndex; return base.Walk(node); } public override bool Walk(ComprehensionFor node) { if (!IsActualExpression(node.Left) || HasCaret(node.Left)) { CanComplete = false; CommitByDefault = false; } else if (IsActualExpression(node.List)) { CanComplete = true; CommitByDefault = true; node.List.Walk(this); } return false; } public override bool Walk(ComprehensionIf node) { CanComplete = true; CommitByDefault = true; return base.Walk(node); } private bool WalkCollection(Expression node, IEnumerable<Expression> items) { CanComplete = HasCaret(node); int count = 0; Expression last = null; foreach (var e in items) { count += 1; last = e; } if (count == 0) { CommitByDefault = false; } else if (count == 1) { last.Walk(this); CommitByDefault = false; } else { CommitByDefault = true; last.Walk(this); } return false; } public override bool Walk(ListExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(DictionaryExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(SetExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(TupleExpression node) { return WalkCollection(node, node.Items); } public override bool Walk(ParenthesisExpression node) { CanComplete = HasCaret(node); CommitByDefault = false; return base.Walk(node); } public override bool Walk(AssertStatement node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(AugmentedAssignStatement node) { CanComplete = IsActualExpression(node.Right); CommitByDefault = true; return base.Walk(node); } public override bool Walk(AwaitExpression node) { CanComplete = IsActualExpression(node.Expression); CommitByDefault = true; return base.Walk(node); } public override bool Walk(DelStatement node) { CanComplete = IsActualExpression(node.Expressions); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ExecStatement node) { CanComplete = IsActualExpression(node.Code); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ExpressionStatement node) { if (node.Expression is TupleExpression) { node.Expression.Walk(this); CommitByDefault = false; return false; } return base.Walk(node); } public override bool Walk(ForStatement node) { if (!IsActualExpression(node.Left) || HasCaret(node.Left)) { CanComplete = false; CommitByDefault = false; } else if (IsActualExpression(node.List)) { CanComplete = true; CommitByDefault = true; node.List.Walk(this); } return false; } public override bool Walk(IfStatementTest node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(GlobalStatement node) { CanComplete = IsActualExpression(node.Names); CommitByDefault = true; return base.Walk(node); } public override bool Walk(NonlocalStatement node) { CanComplete = IsActualExpression(node.Names); CommitByDefault = true; return base.Walk(node); } public override bool Walk(PrintStatement node) { CanComplete = IsActualExpression(node.Expressions); CommitByDefault = true; return base.Walk(node); } public override bool Walk(ReturnStatement node) { CanComplete = IsActualExpression(node.Expression); CommitByDefault = true; return base.Walk(node); } public override bool Walk(WhileStatement node) { CanComplete = IsActualExpression(node.Test); CommitByDefault = true; return base.Walk(node); } public override bool Walk(WithStatement node) { CanComplete = true; CommitByDefault = true; if (node.Items != null) { var item = node.Items.LastOrDefault(); if (item != null) { if (item.Variable != null) { CanComplete = false; } else { item.Walk(this); } } } if (node.Body != null) { node.Body.Walk(this); } return false; } public override bool Walk(YieldExpression node) { CommitByDefault = true; if (IsActualExpression(node.Expression)) { // "yield" is valid and has implied None following it var ce = node.Expression as ConstantExpression; CanComplete = ce == null || ce.Value != null; } return base.Walk(node); } } private bool Backspace() { if (_sigHelpSession != null) { if (_textView.Selection.IsActive && !_textView.Selection.IsEmpty) { // when deleting a selection don't do anything to pop up signature help again _sigHelpSession.Dismiss(); return false; } SnapshotPoint? caretPoint = _textView.BufferGraph.MapDownToFirstMatch( _textView.Caret.Position.BufferPosition, PointTrackingMode.Positive, EditorExtensions.IsPythonContent, PositionAffinity.Predecessor ); if (caretPoint != null && caretPoint.Value.Position != 0) { var deleting = caretPoint.Value.Snapshot[caretPoint.Value.Position - 1]; if (deleting == ',') { caretPoint.Value.Snapshot.TextBuffer.Delete(new Span(caretPoint.Value.Position - 1, 1)); UpdateCurrentParameter(); return true; } else if (deleting == '(' || deleting == ')') { _sigHelpSession.Dismiss(); // delete the ( before triggering help again caretPoint.Value.Snapshot.TextBuffer.Delete(new Span(caretPoint.Value.Position - 1, 1)); // Pop to an outer nesting of signature help if (_provider.PythonService.LangPrefs.AutoListParams) { TriggerSignatureHelp(); } return true; } } } return false; } private void OpenParenStartSignatureSession() { if (_activeSession != null) { _activeSession.Dismiss(); } if (_sigHelpSession != null) { _sigHelpSession.Dismiss(); } TriggerSignatureHelp(); } private void CommaStartSignatureSession() { TriggerSignatureHelp(); } /// <summary> /// Updates the current parameter for the caret's current position. /// /// This will analyze the buffer for where we are currently located, find the current /// parameter that we're entering, and then update the signature. If our current /// signature does not have enough parameters we'll find a signature which does. /// </summary> private void UpdateCurrentParameter() { if (_sigHelpSession == null) { // we moved out of the original span for sig help, re-trigger based upon the position TriggerSignatureHelp(); return; } int position = _textView.Caret.Position.BufferPosition.Position; // we advance to the next parameter // TODO: Take into account params arrays // TODO: need to parse and see if we have keyword arguments entered into the current signature yet PythonSignature sig = _sigHelpSession.SelectedSignature as PythonSignature; if (sig != null) { var prevBuffer = sig.ApplicableToSpan.TextBuffer; var textBuffer = _textView.TextBuffer; var targetPt = _textView.BufferGraph.MapDownToFirstMatch( new SnapshotPoint(_textView.TextBuffer.CurrentSnapshot, position), PointTrackingMode.Positive, EditorExtensions.IsPythonContent, PositionAffinity.Successor ); if (targetPt == null) { return; } var span = targetPt.Value.Snapshot.CreateTrackingSpan(targetPt.Value.Position, 0, SpanTrackingMode.EdgeInclusive); var sigs = _provider.PythonService.GetSignatures(_textView, targetPt.Value.Snapshot, span); bool retrigger = false; if (sigs.Signatures.Count == _sigHelpSession.Signatures.Count) { for (int i = 0; i < sigs.Signatures.Count && !retrigger; i++) { var leftSig = sigs.Signatures[i]; var rightSig = _sigHelpSession.Signatures[i]; if (leftSig.Parameters.Count == rightSig.Parameters.Count) { for (int j = 0; j < leftSig.Parameters.Count; j++) { var leftParam = leftSig.Parameters[j]; var rightParam = rightSig.Parameters[j]; if (leftParam.Name != rightParam.Name || leftParam.Documentation != rightParam.Documentation) { retrigger = true; break; } } } if (leftSig.Content != rightSig.Content || leftSig.Documentation != rightSig.Documentation) { retrigger = true; } } } else { retrigger = true; } if (retrigger) { _sigHelpSession.Dismiss(); TriggerSignatureHelp(); } else { CommaFindBestSignature(sigs.ParameterIndex, sigs.LastKeywordArgument); } } } private void CommaFindBestSignature(int curParam, string lastKeywordArg) { // see if we have a signature which accomodates this... // TODO: We should also get the types of the arguments and use that to // pick the best signature when the signature includes types. var bestSig = _sigHelpSession.SelectedSignature as PythonSignature; if (bestSig != null) { for (int i = 0; i < bestSig.Parameters.Count; ++i) { if (bestSig.Parameters[i].Name == lastKeywordArg || lastKeywordArg == null && (i == curParam || PythonSignature.IsParamArray(bestSig.Parameters[i].Name)) ) { bestSig.SetCurrentParameter(bestSig.Parameters[i]); _sigHelpSession.SelectedSignature = bestSig; return; } } } PythonSignature fallback = null; foreach (var sig in _sigHelpSession.Signatures.OfType<PythonSignature>().OrderBy(s => s.Parameters.Count)) { fallback = sig; for (int i = 0; i < sig.Parameters.Count; ++i) { if (sig.Parameters[i].Name == lastKeywordArg || lastKeywordArg == null && (i == curParam || PythonSignature.IsParamArray(sig.Parameters[i].Name)) ) { sig.SetCurrentParameter(sig.Parameters[i]); _sigHelpSession.SelectedSignature = sig; return; } } } if (fallback != null) { fallback.SetCurrentParameter(null); _sigHelpSession.SelectedSignature = fallback; } else { _sigHelpSession.Dismiss(); } } [ThreadStatic] internal static bool ForceCompletions; private bool SelectSingleBestCompletion(ICompletionSession session) { if (session.CompletionSets.Count != 1) { return false; } var set = session.CompletionSets[0] as FuzzyCompletionSet; if (set == null) { return false; } set.Filter(); if (set.SelectSingleBest()) { session.Commit(); return true; } return false; } internal void TriggerCompletionSession(bool completeWord, bool? commitByDefault = null) { Dismiss(); var session = CompletionBroker.TriggerCompletion(_textView); if (session == null) { _activeSession = null; } else if (completeWord && SelectSingleBestCompletion(session)) { session.Commit(); } else { if (commitByDefault.HasValue) { foreach (var s in session.CompletionSets.OfType<FuzzyCompletionSet>()) { s.CommitByDefault = commitByDefault.GetValueOrDefault(); } } session.Filter(); session.Dismissed += OnCompletionSessionDismissedOrCommitted; session.Committed += OnCompletionSessionDismissedOrCommitted; _activeSession = session; } } internal void TriggerSignatureHelp() { if (_sigHelpSession != null) { _sigHelpSession.Dismiss(); } _sigHelpSession = SignatureBroker.TriggerSignatureHelp(_textView); if (_sigHelpSession != null) { _sigHelpSession.Dismissed += OnSignatureSessionDismissed; ISignature sig; if (_sigHelpSession.Properties.TryGetProperty(typeof(PythonSignature), out sig)) { _sigHelpSession.SelectedSignature = sig; IParameter param; if (_sigHelpSession.Properties.TryGetProperty(typeof(PythonParameter), out param)) { ((PythonSignature)sig).SetCurrentParameter(param); } } } } private void OnCompletionSessionDismissedOrCommitted(object sender, EventArgs e) { // We've just been told that our active session was dismissed. We should remove all references to it. _activeSession.Committed -= OnCompletionSessionDismissedOrCommitted; _activeSession.Dismissed -= OnCompletionSessionDismissedOrCommitted; _activeSession = null; } private void OnSignatureSessionDismissed(object sender, EventArgs e) { // We've just been told that our active session was dismissed. We should remove all references to it. _sigHelpSession.Dismissed -= OnSignatureSessionDismissed; _sigHelpSession = null; } private void DeleteSelectedSpans() { if (!_textView.Selection.IsEmpty) { _editOps.Delete(); } } private void Dismiss() { if (_activeSession != null) { _activeSession.Dismiss(); } } internal ICompletionBroker CompletionBroker { get { return _provider._CompletionBroker; } } internal IVsEditorAdaptersFactoryService AdaptersFactory { get { return _provider._adaptersFactory; } } internal ISignatureHelpBroker SignatureBroker { get { return _provider._SigBroker; } } #region IOleCommandTarget Members // we need this because VS won't give us certain keyboard events as they're handled before our key processor. These // include enter and tab both of which we want to complete. internal void AttachKeyboardFilter() { if (_oldTarget == null) { var viewAdapter = AdaptersFactory.GetViewAdapter(_textView); if (viewAdapter != null) { ErrorHandler.ThrowOnFailure(viewAdapter.AddCommandFilter(this, out _oldTarget)); } } } private void DetachKeyboardFilter() { if (_oldTarget != null) { ErrorHandler.ThrowOnFailure(AdaptersFactory.GetViewAdapter(_textView).RemoveCommandFilter(this)); _oldTarget = null; } } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { if (pguidCmdGroup == VSConstants.VSStd2K && nCmdID == (int)VSConstants.VSStd2KCmdID.TYPECHAR) { var ch = (char)(ushort)System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(pvaIn); if (_activeSession != null && !_activeSession.IsDismissed) { if (_activeSession.SelectedCompletionSet != null && _activeSession.SelectedCompletionSet.SelectionStatus.IsSelected && _provider.PythonService.AdvancedOptions.CompletionCommittedBy.IndexOf(ch) != -1) { _activeSession.Commit(); } else if (!IsIdentifierChar(ch)) { _activeSession.Dismiss(); } } int res = _oldTarget != null ? _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut) : VSConstants.S_OK; HandleChar((char)(ushort)System.Runtime.InteropServices.Marshal.GetObjectForNativeVariant(pvaIn)); if (_activeSession != null && !_activeSession.IsDismissed) { _activeSession.Filter(); } return res; } if (_activeSession != null) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: if (_provider.PythonService.AdvancedOptions.EnterCommitsIntellisense && !_activeSession.IsDismissed && _activeSession.SelectedCompletionSet.SelectionStatus.IsSelected) { // If the user has typed all of the characters as the completion and presses // enter we should dismiss & let the text editor receive the enter. For example // when typing "import sys[ENTER]" completion starts after the space. After typing // sys the user wants a new line and doesn't want to type enter twice. bool enterOnComplete = _provider.PythonService.AdvancedOptions.AddNewLineAtEndOfFullyTypedWord && EnterOnCompleteText(); _activeSession.Commit(); if (!enterOnComplete) { return VSConstants.S_OK; } } else { _activeSession.Dismiss(); } break; case VSConstants.VSStd2KCmdID.TAB: if (!_activeSession.IsDismissed) { _activeSession.Commit(); return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.BACKSPACE: case VSConstants.VSStd2KCmdID.DELETE: case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: case VSConstants.VSStd2KCmdID.DELETEWORDRIGHT: int res = _oldTarget != null ? _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut) : VSConstants.S_OK; if (_activeSession != null && !_activeSession.IsDismissed) { _activeSession.Filter(); } return res; } } } else if (_sigHelpSession != null) { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.BACKSPACE: bool fDeleted = Backspace(); if (fDeleted) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.LEFT: _editOps.MoveToPreviousCharacter(false); UpdateCurrentParameter(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.RIGHT: _editOps.MoveToNextCharacter(false); UpdateCurrentParameter(); return VSConstants.S_OK; case VSConstants.VSStd2KCmdID.HOME: case VSConstants.VSStd2KCmdID.BOL: case VSConstants.VSStd2KCmdID.BOL_EXT: case VSConstants.VSStd2KCmdID.EOL: case VSConstants.VSStd2KCmdID.EOL_EXT: case VSConstants.VSStd2KCmdID.END: case VSConstants.VSStd2KCmdID.WORDPREV: case VSConstants.VSStd2KCmdID.WORDPREV_EXT: case VSConstants.VSStd2KCmdID.DELETEWORDLEFT: _sigHelpSession.Dismiss(); _sigHelpSession = null; break; } } } else { if (pguidCmdGroup == VSConstants.VSStd2K) { switch ((VSConstants.VSStd2KCmdID)nCmdID) { case VSConstants.VSStd2KCmdID.RETURN: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.EndCurrentExpansion(false))) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.TAB: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.NextField())) { return VSConstants.S_OK; } if (_textView.Selection.IsEmpty && _textView.Caret.Position.BufferPosition > 0) { if (TryTriggerExpansion()) { return VSConstants.S_OK; } } break; case VSConstants.VSStd2KCmdID.BACKTAB: if (_expansionMgr != null && _expansionClient.InSession && ErrorHandler.Succeeded(_expansionClient.PreviousField())) { return VSConstants.S_OK; } break; case VSConstants.VSStd2KCmdID.SURROUNDWITH: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: TriggerSnippet(nCmdID); return VSConstants.S_OK; } } } if (_oldTarget != null) { return _oldTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } return (int)Constants.OLECMDERR_E_UNKNOWNGROUP; } private void TriggerSnippet(uint nCmdID) { if (_expansionMgr != null) { string prompt; string[] snippetTypes; if ((VSConstants.VSStd2KCmdID)nCmdID == VSConstants.VSStd2KCmdID.SURROUNDWITH) { prompt = Strings.SurroundWith; snippetTypes = _surroundsWithSnippetTypes; } else { prompt = Strings.InsertSnippet; snippetTypes = _allStandardSnippetTypes; } _expansionMgr.InvokeInsertionUI( GetViewAdapter(), _expansionClient, GuidList.guidPythonLanguageServiceGuid, snippetTypes, snippetTypes.Length, 0, null, 0, 0, prompt, ">" ); } } private bool TryTriggerExpansion() { if (_expansionMgr != null) { var snapshot = _textView.TextBuffer.CurrentSnapshot; var span = new SnapshotSpan(snapshot, new Span(_textView.Caret.Position.BufferPosition.Position - 1, 1)); var classification = _textView.TextBuffer.GetPythonClassifier().GetClassificationSpans(span); if (classification.Count == 1) { var clsSpan = classification.First().Span; var text = classification.First().Span.GetText(); TextSpan[] textSpan = new TextSpan[1]; textSpan[0].iStartLine = clsSpan.Start.GetContainingLine().LineNumber; textSpan[0].iStartIndex = clsSpan.Start.Position - clsSpan.Start.GetContainingLine().Start; textSpan[0].iEndLine = clsSpan.End.GetContainingLine().LineNumber; textSpan[0].iEndIndex = clsSpan.End.Position - clsSpan.End.GetContainingLine().Start; string expansionPath, title; int hr = _expansionMgr.GetExpansionByShortcut( _expansionClient, GuidList.guidPythonLanguageServiceGuid, text, GetViewAdapter(), textSpan, 1, out expansionPath, out title ); if (ErrorHandler.Succeeded(hr)) { // hr may be S_FALSE if there are multiple expansions, // so we don't want to InsertNamedExpansion yet. VS will // pop up a selection dialog in this case. if (hr == VSConstants.S_OK) { return ErrorHandler.Succeeded(_expansionClient.InsertNamedExpansion(title, expansionPath, textSpan[0])); } return true; } } } return false; } private IVsTextView GetViewAdapter() { return _provider._adaptersFactory.GetViewAdapter(_textView); } private static bool IsIdentifierFirstChar(char ch) { return ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } private static bool IsIdentifierChar(char ch) { return IsIdentifierFirstChar(ch) || (ch >= '0' && ch <= '9'); } private bool EnterOnCompleteText() { SnapshotPoint? point = _activeSession.GetTriggerPoint(_textView.TextBuffer.CurrentSnapshot); if (point.HasValue) { int chars = _textView.Caret.Position.BufferPosition.Position - point.Value.Position; var selectionStatus = _activeSession.SelectedCompletionSet.SelectionStatus; if (chars == selectionStatus.Completion.InsertionText.Length) { string text = _textView.TextSnapshot.GetText(point.Value.Position, chars); if (String.Compare(text, selectionStatus.Completion.InsertionText, true) == 0) { return true; } } } return false; } public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { if (pguidCmdGroup == VSConstants.VSStd2K) { for (int i = 0; i < cCmds; i++) { switch ((VSConstants.VSStd2KCmdID)prgCmds[i].cmdID) { case VSConstants.VSStd2KCmdID.SURROUNDWITH: case VSConstants.VSStd2KCmdID.INSERTSNIPPET: if (_expansionMgr != null) { prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); return VSConstants.S_OK; } break; } } } if (_oldTarget != null) { return _oldTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } return (int)Constants.OLECMDERR_E_UNKNOWNGROUP; } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.TestModels.Inheritance; using Xunit; using Xunit.Abstractions; // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore.Query { public class InheritanceMySqlTest : InheritanceRelationalTestBase<InheritanceMySqlFixture> { public InheritanceMySqlTest(InheritanceMySqlFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } [Fact] public virtual void Common_property_shares_column() { using (var context = CreateContext()) { var liltType = context.Model.FindEntityType(typeof(Lilt)); var cokeType = context.Model.FindEntityType(typeof(Coke)); var teaType = context.Model.FindEntityType(typeof(Tea)); Assert.Equal("SugarGrams", cokeType.FindProperty("SugarGrams").Relational().ColumnName); Assert.Equal("CaffeineGrams", cokeType.FindProperty("CaffeineGrams").Relational().ColumnName); Assert.Equal("CokeCO2", cokeType.FindProperty("Carbination").Relational().ColumnName); Assert.Equal("SugarGrams", liltType.FindProperty("SugarGrams").Relational().ColumnName); Assert.Equal("LiltCO2", liltType.FindProperty("Carbination").Relational().ColumnName); Assert.Equal("CaffeineGrams", teaType.FindProperty("CaffeineGrams").Relational().ColumnName); Assert.Equal("HasMilk", teaType.FindProperty("HasMilk").Relational().ColumnName); } } public override void Can_query_when_shared_column() { base.Can_query_when_shared_column(); AssertSql( @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[CokeCO2], [d].[SugarGrams] FROM [Drink] AS [d] WHERE [d].[Discriminator] = N'Coke'", // @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[LiltCO2], [d].[SugarGrams] FROM [Drink] AS [d] WHERE [d].[Discriminator] = N'Lilt'", // @"SELECT TOP(2) [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[HasMilk] FROM [Drink] AS [d] WHERE [d].[Discriminator] = N'Tea'"); } public override void FromSql_on_root() { base.FromSql_on_root(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM ( select * from ""Animal"" ) AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle')"); } public override void FromSql_on_derived() { base.FromSql_on_derived(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group] FROM ( select * from ""Animal"" ) AS [a] WHERE [a].[Discriminator] = N'Eagle'"); } public override void Can_query_all_types_when_shared_column() { base.Can_query_all_types_when_shared_column(); AssertSql( @"SELECT [d].[Id], [d].[Discriminator], [d].[CaffeineGrams], [d].[CokeCO2], [d].[SugarGrams], [d].[LiltCO2], [d].[HasMilk] FROM [Drink] AS [d] WHERE [d].[Discriminator] IN (N'Tea', N'Lilt', N'Coke', N'Drink')"); } public override void Can_use_of_type_animal() { base.Can_use_of_type_animal(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [a].[Species]"); } public override void Can_use_is_kiwi() { base.Can_use_is_kiwi(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') AND ([a].[Discriminator] = N'Kiwi')"); } public override void Can_use_is_kiwi_with_other_predicate() { base.Can_use_is_kiwi_with_other_predicate(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') AND (([a].[Discriminator] = N'Kiwi') AND ([a].[CountryId] = 1))"); } public override void Can_use_is_kiwi_in_projection() { base.Can_use_is_kiwi_in_projection(); AssertSql( @"SELECT CASE WHEN [a].[Discriminator] = N'Kiwi' THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle')"); } public override void Can_use_of_type_bird() { base.Can_use_of_type_bird(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [a].[Species]"); } public override void Can_use_of_type_bird_predicate() { base.Can_use_of_type_bird_predicate(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') AND ([a].[CountryId] = 1) ORDER BY [a].[Species]"); } public override void Can_use_of_type_bird_with_projection() { base.Can_use_of_type_bird_with_projection(); AssertSql( @"SELECT [b].[EagleId] FROM [Animal] AS [b] WHERE [b].[Discriminator] IN (N'Kiwi', N'Eagle')"); } public override void Can_use_of_type_bird_first() { base.Can_use_of_type_bird_first(); AssertSql( @"SELECT TOP(1) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [a].[Species]"); } public override void Can_use_of_type_kiwi() { base.Can_use_of_type_kiwi(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] = N'Kiwi'"); } public override void Can_use_of_type_rose() { base.Can_use_of_type_rose(); AssertSql( @"SELECT [p].[Species], [p].[CountryId], [p].[Genus], [p].[Name], [p].[HasThorns] FROM [Plant] AS [p] WHERE [p].[Genus] = 0"); } public override void Can_query_all_animals() { base.Can_query_all_animals(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [a].[Species]"); } public override void Can_query_all_animal_views() { base.Can_query_all_animal_views(); AssertSql( @"SELECT [av].[CountryId], [av].[Discriminator], [av].[Name], [av].[EagleId], [av].[IsFlightless], [av].[Group], [av].[FoundOn] FROM [Animal] AS [av] WHERE [av].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [av].[CountryId]"); } public override void Can_query_all_plants() { base.Can_query_all_plants(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Genus], [a].[Name], [a].[HasThorns] FROM [Plant] AS [a] WHERE [a].[Genus] IN (0, 1) ORDER BY [a].[Species]"); } public override void Can_filter_all_animals() { base.Can_filter_all_animals(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') AND ([a].[Name] = N'Great spotted kiwi') ORDER BY [a].[Species]"); } public override void Can_query_all_birds() { base.Can_query_all_birds(); AssertSql( @"SELECT [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[Group], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [a].[Species]"); } public override void Can_query_just_kiwis() { base.Can_query_just_kiwis(); AssertSql( @"SELECT TOP(2) [a].[Species], [a].[CountryId], [a].[Discriminator], [a].[Name], [a].[EagleId], [a].[IsFlightless], [a].[FoundOn] FROM [Animal] AS [a] WHERE [a].[Discriminator] = N'Kiwi'"); } public override void Can_query_just_roses() { base.Can_query_just_roses(); AssertSql( @"SELECT TOP(2) [p].[Species], [p].[CountryId], [p].[Genus], [p].[Name], [p].[HasThorns] FROM [Plant] AS [p] WHERE [p].[Genus] = 0" ); } public override void Can_include_prey() { base.Can_include_prey(); AssertSql( @"SELECT TOP(2) [e].[Species], [e].[CountryId], [e].[Discriminator], [e].[Name], [e].[EagleId], [e].[IsFlightless], [e].[Group] FROM [Animal] AS [e] WHERE [e].[Discriminator] = N'Eagle' ORDER BY [e].[Species]", // @"SELECT [e.Prey].[Species], [e.Prey].[CountryId], [e.Prey].[Discriminator], [e.Prey].[Name], [e.Prey].[EagleId], [e.Prey].[IsFlightless], [e.Prey].[Group], [e.Prey].[FoundOn] FROM [Animal] AS [e.Prey] INNER JOIN ( SELECT TOP(1) [e0].[Species] FROM [Animal] AS [e0] WHERE [e0].[Discriminator] = N'Eagle' ORDER BY [e0].[Species] ) AS [t] ON [e.Prey].[EagleId] = [t].[Species] WHERE [e.Prey].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [t].[Species]"); } public override void Can_include_animals() { base.Can_include_animals(); AssertSql( @"SELECT [c].[Id], [c].[Name] FROM [Country] AS [c] ORDER BY [c].[Name], [c].[Id]", // @"SELECT [c.Animals].[Species], [c.Animals].[CountryId], [c.Animals].[Discriminator], [c.Animals].[Name], [c.Animals].[EagleId], [c.Animals].[IsFlightless], [c.Animals].[Group], [c.Animals].[FoundOn] FROM [Animal] AS [c.Animals] INNER JOIN ( SELECT [c0].[Id], [c0].[Name] FROM [Country] AS [c0] ) AS [t] ON [c.Animals].[CountryId] = [t].[Id] WHERE [c.Animals].[Discriminator] IN (N'Kiwi', N'Eagle') ORDER BY [t].[Name], [t].[Id]"); } public override void Can_use_of_type_kiwi_where_north_on_derived_property() { base.Can_use_of_type_kiwi_where_north_on_derived_property(); AssertSql( @"SELECT [x].[Species], [x].[CountryId], [x].[Discriminator], [x].[Name], [x].[EagleId], [x].[IsFlightless], [x].[FoundOn] FROM [Animal] AS [x] WHERE ([x].[Discriminator] = N'Kiwi') AND ([x].[FoundOn] = CAST(0 AS tinyint))"); } public override void Can_use_of_type_kiwi_where_south_on_derived_property() { base.Can_use_of_type_kiwi_where_south_on_derived_property(); AssertSql( @"SELECT [x].[Species], [x].[CountryId], [x].[Discriminator], [x].[Name], [x].[EagleId], [x].[IsFlightless], [x].[FoundOn] FROM [Animal] AS [x] WHERE ([x].[Discriminator] = N'Kiwi') AND ([x].[FoundOn] = CAST(1 AS tinyint))"); } public override void Discriminator_used_when_projection_over_derived_type() { base.Discriminator_used_when_projection_over_derived_type(); AssertSql( @"SELECT [k].[FoundOn] FROM [Animal] AS [k] WHERE [k].[Discriminator] = N'Kiwi'"); } public override void Discriminator_used_when_projection_over_derived_type2() { base.Discriminator_used_when_projection_over_derived_type2(); AssertSql( @"SELECT [b].[IsFlightless], [b].[Discriminator] FROM [Animal] AS [b] WHERE [b].[Discriminator] IN (N'Kiwi', N'Eagle')"); } public override void Discriminator_used_when_projection_over_of_type() { base.Discriminator_used_when_projection_over_of_type(); AssertSql( @"SELECT [k].[FoundOn] FROM [Animal] AS [k] WHERE [k].[Discriminator] = N'Kiwi'"); } public override void Can_insert_update_delete() { base.Can_insert_update_delete(); AssertSql( @"SELECT TOP(2) [c].[Id], [c].[Name] FROM [Country] AS [c] WHERE [c].[Id] = 1", // @"@p0='Apteryx owenii' (Nullable = false) (Size = 100) @p1='1' @p2='Kiwi' (Nullable = false) (Size = 4000) @p3='Little spotted kiwi' (Size = 4000) @p4='' (Size = 100) @p5='True' @p6='0' (Size = 1) SET NOCOUNT ON; INSERT INTO [Animal] ([Species], [CountryId], [Discriminator], [Name], [EagleId], [IsFlightless], [FoundOn]) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6);", // @"SELECT TOP(2) [k].[Species], [k].[CountryId], [k].[Discriminator], [k].[Name], [k].[EagleId], [k].[IsFlightless], [k].[FoundOn] FROM [Animal] AS [k] WHERE ([k].[Discriminator] = N'Kiwi') AND (RIGHT([k].[Species], LEN(N'owenii')) = N'owenii')", // @"@p1='Apteryx owenii' (Nullable = false) (Size = 100) @p0='Aquila chrysaetos canadensis' (Size = 100) SET NOCOUNT ON; UPDATE [Animal] SET [EagleId] = @p0 WHERE [Species] = @p1; SELECT @@ROWCOUNT;", // @"SELECT TOP(2) [k].[Species], [k].[CountryId], [k].[Discriminator], [k].[Name], [k].[EagleId], [k].[IsFlightless], [k].[FoundOn] FROM [Animal] AS [k] WHERE ([k].[Discriminator] = N'Kiwi') AND (RIGHT([k].[Species], LEN(N'owenii')) = N'owenii')", // @"@p0='Apteryx owenii' (Nullable = false) (Size = 100) SET NOCOUNT ON; DELETE FROM [Animal] WHERE [Species] = @p0; SELECT @@ROWCOUNT;", // @"SELECT COUNT(*) FROM [Animal] AS [k] WHERE ([k].[Discriminator] = N'Kiwi') AND (RIGHT([k].[Species], LEN(N'owenii')) = N'owenii')"); } public override void Byte_enum_value_constant_used_in_projection() { base.Byte_enum_value_constant_used_in_projection(); AssertSql( @"SELECT CASE WHEN [k].[IsFlightless] = 1 THEN CAST(0 AS tinyint) ELSE CAST(1 AS tinyint) END FROM [Animal] AS [k] WHERE [k].[Discriminator] = N'Kiwi'"); } protected override void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction) => facade.UseTransaction(transaction.GetDbTransaction()); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); } }
/* 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.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { /// <summary> /// This interface is for use with the Orleans timers. /// </summary> internal interface ITimebound { /// <summary> /// This method is called by the timer when the time out is reached. /// </summary> void OnTimeout(); TimeSpan RequestedTimeout(); } internal class CallbackData : ITimebound, IDisposable { private readonly Action<Message, TaskCompletionSource<object>> callback; private readonly Func<Message, bool> resendFunc; private readonly Action unregister; private readonly TaskCompletionSource<object> context; private bool alreadyFired; private TimeSpan timeout; private readonly Action<CallbackData> onTimeout; private SafeTimer timer; private ITimeInterval timeSinceIssued; private static readonly TraceLogger logger = TraceLogger.GetLogger("CallbackData"); internal static IMessagingConfiguration Config; public Message Message { get; set; } // might hold metadata used by response pipeline public CallbackData(Action<Message, TaskCompletionSource<object>> callback, Func<Message, bool> resendFunc, TaskCompletionSource<object> ctx, Message msg, Action unregisterDelegate, Action<CallbackData> onTimeout = null) { // We are never called without a callback func, but best to double check. if (callback == null) throw new ArgumentNullException("callback"); // We are never called without a resend func, but best to double check. if (resendFunc == null) throw new ArgumentNullException("resendFunc"); this.callback = callback; this.resendFunc = resendFunc; this.context = ctx; this.Message = msg; this.unregister = unregisterDelegate; this.alreadyFired = false; this.onTimeout = onTimeout; } /// <summary> /// Start this callback timer /// </summary> /// <param name="time">Timeout time</param> public void StartTimer(TimeSpan time) { if (time < TimeSpan.Zero) throw new ArgumentOutOfRangeException("time", "The timeout parameter is negative."); timeout = time; if (StatisticsCollector.CollectApplicationRequestsStats) { timeSinceIssued = TimeIntervalFactory.CreateTimeInterval(true); timeSinceIssued.Start(); } TimeSpan firstPeriod = timeout; TimeSpan repeatPeriod = Constants.INFINITE_TIMESPAN; // Single timeout period --> No repeat if (Config.ResendOnTimeout && Config.MaxResendCount > 0) { firstPeriod = repeatPeriod = timeout.Divide(Config.MaxResendCount + 1); } // Start time running DisposeTimer(); timer = new SafeTimer(TimeoutCallback, null, firstPeriod, repeatPeriod); } private void TimeoutCallback(object obj) { if (onTimeout != null) { onTimeout(this); } else { OnTimeout(); } } public void OnTimeout() { if (alreadyFired) return; var msg = this.Message; // Local working copy lock (this) { if (alreadyFired) return; if (Config.ResendOnTimeout && resendFunc(msg)) { if(logger.IsVerbose) logger.Verbose("OnTimeout - Resend {0} for {1}", msg.ResendCount, msg); return; } alreadyFired = true; DisposeTimer(); if (StatisticsCollector.CollectApplicationRequestsStats) { timeSinceIssued.Stop(); } if (unregister != null) { unregister(); } } string messageHistory = msg.GetTargetHistory(); string errorMsg = String.Format("Response did not arrive on time in {0} for message: {1}. Target History is: {2}", timeout, msg, messageHistory); logger.Warn(ErrorCode.Runtime_Error_100157, "{0}. About to break its promise.", errorMsg); var error = new Message(Message.Categories.Application, Message.Directions.Response) { Result = Message.ResponseTypes.Error, BodyObject = Response.ExceptionResponse(new TimeoutException(errorMsg)) }; if (StatisticsCollector.CollectApplicationRequestsStats) { ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed); ApplicationRequestsStatisticsGroup.OnAppRequestsTimedOut(); } callback(error, context); } public void DoCallback(Message response) { if (alreadyFired) return; lock (this) { if (alreadyFired) return; if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.Transient) { if (resendFunc(Message)) { return; } } alreadyFired = true; DisposeTimer(); if (StatisticsCollector.CollectApplicationRequestsStats) { timeSinceIssued.Stop(); } if (unregister != null) { unregister(); } } if (Message.WriteMessagingTraces) response.AddTimestamp(Message.LifecycleTag.InvokeIncoming); if (logger.IsVerbose2) logger.Verbose2("Message {0} timestamps: {1}", response, response.GetTimestampString()); if (StatisticsCollector.CollectApplicationRequestsStats) { ApplicationRequestsStatisticsGroup.OnAppRequestsEnd(timeSinceIssued.Elapsed); } // do callback outside the CallbackData lock. Just not a good practice to hold a lock for this unrelated operation. callback(response, context); } public void Dispose() { DisposeTimer(); GC.SuppressFinalize(this); } private void DisposeTimer() { try { if (timer != null) { var tmp = timer; timer = null; tmp.Dispose(); } } catch (Exception) { } // Ignore any problems with Dispose } public TimeSpan RequestedTimeout() { return timeout; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.ServiceBus.UnitTests { using System; using System.Text; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Core; using Xunit; public class SenderReceiverTests : SenderReceiverClientTestBase { private static TimeSpan TwoSeconds = TimeSpan.FromSeconds(2); public static IEnumerable<object[]> TestPermutations => new object[][] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, new object[] { true, false } }; [Theory] [MemberData(nameof(TestPermutations))] [LiveTest] [DisplayTestMethodName] public async Task MessageReceiverAndMessageSenderCreationWorksAsExpected(bool partitioned, bool sessionEnabled, int messageCount = 10) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.PeekLock); try { await this.PeekLockTestCase(sender, receiver, messageCount); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Theory] [MemberData(nameof(TestPermutations))] [LiveTest] [DisplayTestMethodName] public async Task TopicClientPeekLockDeferTestCase(bool partitioned, bool sessionEnabled, int messageCount = 10) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.PeekLock); try { await this.PeekLockDeferTestCase(sender, receiver, messageCount); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Theory] [MemberData(nameof(TestPermutations))] [LiveTest] [DisplayTestMethodName] public async Task PeekAsyncTest(bool partitioned, bool sessionEnabled, int messageCount = 10) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { await this.PeekAsyncTestCase(sender, receiver, messageCount); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Theory] [MemberData(nameof(TestPermutations))] [LiveTest] [DisplayTestMethodName] public async Task ReceiveShouldReturnNoLaterThanServerWaitTimeTest(bool partitioned, bool sessionEnabled, int messageCount = 1) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { await this.ReceiveShouldReturnNoLaterThanServerWaitTimeTestCase(sender, receiver, messageCount); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Theory] [MemberData(nameof(TestPermutations))] [LiveTest] [DisplayTestMethodName] public async Task ReceiveShouldThrowForServerTimeoutZeroTest(bool partitioned, bool sessionEnabled) { await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName => { var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { await this.ReceiveShouldThrowForServerTimeoutZero(receiver); } finally { await receiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task ReceiverShouldUseTheLatestPrefetchCount() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver1 = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); var receiver2 = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete, prefetchCount: 1); Assert.Equal(0, receiver1.PrefetchCount); Assert.Equal(1, receiver2.PrefetchCount); try { for (var i = 0; i < 9; i++) { var message = new Message(Encoding.UTF8.GetBytes("test" + i)) { Label = "prefetch" + i }; await sender.SendAsync(message).ConfigureAwait(false); } // Default prefetch count should be 0 for receiver 1. Assert.Equal("prefetch0", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); // The first ReceiveAsync() would initialize the link and block prefetch2 for receiver2 Assert.Equal("prefetch1", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); await Task.Delay(TwoSeconds); // Updating prefetch count on receiver1. receiver1.PrefetchCount = 2; await Task.Delay(TwoSeconds); // The next operation should fetch prefetch3 and prefetch4. Assert.Equal("prefetch3", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); await Task.Delay(TwoSeconds); Assert.Equal("prefetch2", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); await Task.Delay(TwoSeconds); // The next operation should block prefetch6 for receiver2. Assert.Equal("prefetch5", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); await Task.Delay(TwoSeconds); // Updates in prefetch count of receiver1 should not affect receiver2. // Receiver2 should continue with 1 prefetch. Assert.Equal("prefetch4", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); Assert.Equal("prefetch7", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); Assert.Equal("prefetch8", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); } catch (Exception) { // Cleanup Message message; do { message = await receiver1.ReceiveAsync(TimeSpan.FromSeconds(3)).ConfigureAwait(false); } while (message != null); } finally { await sender.CloseAsync(); await receiver1.CloseAsync(); await receiver2.CloseAsync(); } }); } [Fact(Skip = "Flaky Test in Appveyor, fix and enable back")] [LiveTest] [DisplayTestMethodName] public async Task WaitingReceiveShouldReturnImmediatelyWhenReceiverIsClosed() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); TestUtility.Log("Begin to receive from an empty queue."); Task quickTask; try { quickTask = Task.Run(async () => { try { await receiver.ReceiveAsync(TimeSpan.FromSeconds(40)); } catch (Exception e) { TestUtility.Log("Unexpected exception: " + e); } }); await Task.Delay(2000); TestUtility.Log("Waited for 2 Seconds for the ReceiveAsync to establish connection."); } finally { await receiver.CloseAsync(); TestUtility.Log("Closed Receiver"); } TestUtility.Log("Waiting for maximum 10 Secs"); bool receiverReturnedInTime = false; using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { var completedTask = await Task.WhenAny(quickTask, Task.Delay(10000, timeoutCancellationTokenSource.Token)); if (completedTask == quickTask) { timeoutCancellationTokenSource.Cancel(); receiverReturnedInTime = true; TestUtility.Log("The Receiver closed in time."); } else { TestUtility.Log("The Receiver did not close in time."); } } Assert.True(receiverReturnedInTime); }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task DeadLetterReasonShouldPropagateToTheReceivedMessage() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName); var dlqReceiver = new MessageReceiver(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatDeadLetterPath(queueName), ReceiveMode.ReceiveAndDelete); try { await sender.SendAsync(new Message(Encoding.UTF8.GetBytes("deadLetterTest2"))); var message = await receiver.ReceiveAsync(); Assert.NotNull(message); await receiver.DeadLetterAsync( message.SystemProperties.LockToken, "deadLetterReason", "deadLetterDescription"); var dlqMessage = await dlqReceiver.ReceiveAsync(); Assert.NotNull(dlqMessage); Assert.True(dlqMessage.UserProperties.ContainsKey(Message.DeadLetterReasonHeader)); Assert.True(dlqMessage.UserProperties.ContainsKey(Message.DeadLetterErrorDescriptionHeader)); Assert.Equal("deadLetterReason", dlqMessage.UserProperties[Message.DeadLetterReasonHeader]); Assert.Equal("deadLetterDescription", dlqMessage.UserProperties[Message.DeadLetterErrorDescriptionHeader]); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); await dlqReceiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task DispositionWithUpdatedPropertiesShouldPropagateToReceivedMessage() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName); try { await sender.SendAsync(new Message(Encoding.UTF8.GetBytes("propertiesToUpdate"))); var message = await receiver.ReceiveAsync(); Assert.NotNull(message); await receiver.AbandonAsync(message.SystemProperties.LockToken, new Dictionary<string, object> { {"key", "value1"} }); message = await receiver.ReceiveAsync(); Assert.NotNull(message); Assert.True(message.UserProperties.ContainsKey("key")); Assert.Equal("value1", message.UserProperties["key"]); long sequenceNumber = message.SystemProperties.SequenceNumber; await receiver.DeferAsync(message.SystemProperties.LockToken, new Dictionary<string, object> { {"key", "value2"} }); message = await receiver.ReceiveDeferredMessageAsync(sequenceNumber); Assert.NotNull(message); Assert.True(message.UserProperties.ContainsKey("key")); Assert.Equal("value2", message.UserProperties["key"]); await receiver.CompleteAsync(message.SystemProperties.LockToken); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task CancelScheduledMessageShouldThrowMessageNotFoundException() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); try { long nonExistingSequenceNumber = 1000; await Assert.ThrowsAsync<MessageNotFoundException>( async () => await sender.CancelScheduledMessageAsync(nonExistingSequenceNumber)); } finally { await sender.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task ClientThrowsUnauthorizedExceptionWhenUserDoesntHaveAccess() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString); csb.SasKeyName = "nonExistingKey"; csb.EntityPath = queueName; var sender = new MessageSender(csb); try { await Assert.ThrowsAsync<UnauthorizedException>( async () => await sender.SendAsync(new Message())); long nonExistingSequenceNumber = 1000; await Assert.ThrowsAsync<UnauthorizedException>( async () => await sender.CancelScheduledMessageAsync(nonExistingSequenceNumber)); } finally { await sender.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task ClientThrowsObjectDisposedExceptionWhenUserCloseConnectionAndWouldUseOldSeviceBusConnection() { await ServiceBusScope.UsingQueueAsync(partitioned: true, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { var messageBody = Encoding.UTF8.GetBytes("Message"); var message = new Message(messageBody); await sender.SendAsync(message); await sender.CloseAsync(); var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); var connection = sender.ServiceBusConnection; Assert.Throws<ObjectDisposedException>(() => new MessageSender(connection, queueName)); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task SendMesageCloseConnectionCreateAnotherConnectionSendAgainMessage() { await ServiceBusScope.UsingQueueAsync(partitioned: true, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { var messageBody = Encoding.UTF8.GetBytes("Message"); var message = new Message(messageBody); await sender.SendAsync(message); await sender.CloseAsync(); var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString) { EntityPath = queueName }; ServiceBusConnection connection = new ServiceBusConnection(csb); sender = new MessageSender(connection, queueName); messageBody = Encoding.UTF8.GetBytes("Message 2"); message = new Message(messageBody); await sender.SendAsync(message); recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task ClientsUseGlobalConnectionCloseFirstClientSecoundClientShouldSendMessage() { await ServiceBusScope.UsingQueueAsync(partitioned: true, sessionEnabled: false, async queueName => { var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString); var connection = new ServiceBusConnection(csb); var sender = new MessageSender(connection, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete); try { var messageBody = Encoding.UTF8.GetBytes("Message"); var message = new Message(messageBody); await sender.SendAsync(message); await sender.CloseAsync(); var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); connection = sender.ServiceBusConnection; sender = new MessageSender(connection, queueName); messageBody = Encoding.UTF8.GetBytes("Message 2"); message = new Message(messageBody); await sender.SendAsync(message); recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false); Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody)); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } [Fact] [LiveTest] [DisplayTestMethodName] public async Task MessageSenderShouldNotThrowWhenSendingEmptyCollection() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { await sender.SendAsync(new List<Message>()); var message = await receiver.ReceiveAsync(TimeSpan.FromSeconds(3)); Assert.True(message == null, "Expected not to find any messages, but a message was received."); } finally { await sender.CloseAsync(); await receiver.CloseAsync(); } }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /*============================================================ ** ** ** Purpose: ** This public class exposes all the metadata for a specific ** Provider. An instance of this class is obtained from ** EventLogManagement and is scoped to a single Locale. ** ============================================================*/ using System.Globalization; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// Exposes all the metadata for a specific event Provider. An instance /// of this class is obtained from EventLogManagement and is scoped to a /// single Locale. /// </summary> public class ProviderMetadata : IDisposable { // // access to the data member reference is safe, while // invoking methods on it is marked SecurityCritical as appropriate. // private EventLogHandle _handle = EventLogHandle.Zero; private EventLogHandle _defaultProviderHandle = EventLogHandle.Zero; private EventLogSession _session = null; private string _providerName; private CultureInfo _cultureInfo; private string _logFilePath; // caching of the IEnumerable<EventLevel>, <EventTask>, <EventKeyword>, <EventOpcode> on the ProviderMetadata // they do not change with every call. private IList<EventLevel> _levels = null; private IList<EventOpcode> _opcodes = null; private IList<EventTask> _tasks = null; private IList<EventKeyword> _keywords = null; private IList<EventLevel> _standardLevels = null; private IList<EventOpcode> _standardOpcodes = null; private IList<EventTask> _standardTasks = null; private IList<EventKeyword> _standardKeywords = null; private IList<EventLogLink> _channelReferences = null; private object _syncObject; public ProviderMetadata(string providerName) : this(providerName, null, null, null) { } public ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo) : this(providerName, session, targetCultureInfo, null) { } // SecurityCritical since it allocates SafeHandles. // Marked TreatAsSafe since we perform the Demand check. [System.Security.SecuritySafeCritical] internal ProviderMetadata(string providerName, EventLogSession session, CultureInfo targetCultureInfo, string logFilePath) { if (targetCultureInfo == null) targetCultureInfo = CultureInfo.CurrentCulture; if (session == null) session = EventLogSession.GlobalSession; _session = session; _providerName = providerName; _cultureInfo = targetCultureInfo; _logFilePath = logFilePath; _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0); _syncObject = new object(); } internal EventLogHandle Handle { get { return _handle; } } public string Name { get { return _providerName; } } public Guid Id { get { return (Guid)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherGuid); } } public string MessageFilePath { get { return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataMessageFilePath); } } public string ResourceFilePath { get { return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataResourceFilePath); } } public string ParameterFilePath { get { return (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataParameterFilePath); } } public Uri HelpLink { get { string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); if (helpLinkStr == null || helpLinkStr.Length == 0) return null; return new Uri(helpLinkStr); } } private uint ProviderMessageID { get { return (uint)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataPublisherMessageID); } } public string DisplayName { [System.Security.SecurityCritical] get { uint msgId = (uint)this.ProviderMessageID; if (msgId == 0xffffffff) return null; return NativeWrapper.EvtFormatMessage(_handle, msgId); } } public IList<EventLogLink> LogLinks { [System.Security.SecurityCritical] get { EventLogHandle elHandle = EventLogHandle.Zero; try { lock (_syncObject) { if (_channelReferences != null) return _channelReferences; elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferences); int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle); List<EventLogLink> channelList = new List<EventLogLink>(arraySize); for (int index = 0; index < arraySize; index++) { string channelName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferencePath); uint channelId = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceID); uint flag = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceFlags); bool isImported; if (flag == (int)UnsafeNativeMethods.EvtChannelReferenceFlags.EvtChannelReferenceImported) isImported = true; else isImported = false; int channelRefMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataChannelReferenceMessageID))); string channelRefDisplayName; // if channelRefMessageId == -1, we do not have anything in the message table. if (channelRefMessageId == -1) { channelRefDisplayName = null; } else { channelRefDisplayName = NativeWrapper.EvtFormatMessage(_handle, unchecked((uint)channelRefMessageId)); } if (channelRefDisplayName == null && isImported) { if (string.Compare(channelName, "Application", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 256; else if (string.Compare(channelName, "System", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 258; else if (string.Compare(channelName, "Security", StringComparison.OrdinalIgnoreCase) == 0) channelRefMessageId = 257; else channelRefMessageId = -1; if (channelRefMessageId != -1) { if (_defaultProviderHandle.IsInvalid) { _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); } channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId)); } } channelList.Add(new EventLogLink(channelName, isImported, channelRefDisplayName, channelId)); } _channelReferences = channelList.AsReadOnly(); } return _channelReferences; } finally { elHandle.Dispose(); } } } internal enum ObjectTypeName { Level = 0, Opcode = 1, Task = 2, Keyword = 3 } internal string FindStandardLevelDisplayName(string name, uint value) { if (_standardLevels == null) _standardLevels = (List<EventLevel>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); foreach (EventLevel standardLevel in _standardLevels) { if (standardLevel.Name == name && standardLevel.Value == value) return standardLevel.DisplayName; } return null; } internal string FindStandardOpcodeDisplayName(string name, uint value) { if (_standardOpcodes == null) _standardOpcodes = (List<EventOpcode>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); foreach (EventOpcode standardOpcode in _standardOpcodes) { if (standardOpcode.Name == name && standardOpcode.Value == value) return standardOpcode.DisplayName; } return null; } internal string FindStandardKeywordDisplayName(string name, long value) { if (_standardKeywords == null) _standardKeywords = (List<EventKeyword>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); foreach (EventKeyword standardKeyword in _standardKeywords) { if (standardKeyword.Name == name && standardKeyword.Value == value) return standardKeyword.DisplayName; } return null; } internal string FindStandardTaskDisplayName(string name, uint value) { if (_standardTasks == null) _standardTasks = (List<EventTask>)GetProviderListProperty(_defaultProviderHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); foreach (EventTask standardTask in _standardTasks) { if (standardTask.Name == name && standardTask.Value == value) return standardTask.DisplayName; } return null; } [System.Security.SecuritySafeCritical] internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId metadataProperty) { EventLogHandle elHandle = EventLogHandle.Zero; try { UnsafeNativeMethods.EvtPublisherMetadataPropertyId propName; UnsafeNativeMethods.EvtPublisherMetadataPropertyId propValue; UnsafeNativeMethods.EvtPublisherMetadataPropertyId propMessageId; ObjectTypeName objectTypeName; List<EventLevel> levelList = null; List<EventOpcode> opcodeList = null; List<EventKeyword> keywordList = null; List<EventTask> taskList = null; elHandle = NativeWrapper.EvtGetPublisherMetadataPropertyHandle(providerHandle, metadataProperty); int arraySize = NativeWrapper.EvtGetObjectArraySize(elHandle); switch (metadataProperty) { case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels: propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelName; propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelValue; propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevelMessageID; objectTypeName = ObjectTypeName.Level; levelList = new List<EventLevel>(arraySize); break; case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes: propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeName; propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeValue; propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodeMessageID; objectTypeName = ObjectTypeName.Opcode; opcodeList = new List<EventOpcode>(arraySize); break; case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords: propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordName; propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordValue; propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywordMessageID; objectTypeName = ObjectTypeName.Keyword; keywordList = new List<EventKeyword>(arraySize); break; case UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks: propName = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskName; propValue = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskValue; propMessageId = UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskMessageID; objectTypeName = ObjectTypeName.Task; taskList = new List<EventTask>(arraySize); break; default: return null; } for (int index = 0; index < arraySize; index++) { string generalName = (string)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propName); uint generalValue = 0; long generalValueKeyword = 0; if (objectTypeName != ObjectTypeName.Keyword) { generalValue = (uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue); } else { generalValueKeyword = unchecked((long)((ulong)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propValue))); } int generalMessageId = unchecked((int)((uint)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)propMessageId))); string generalDisplayName = null; if (generalMessageId == -1) { if (providerHandle != _defaultProviderHandle) { if (_defaultProviderHandle.IsInvalid) { _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); } switch (objectTypeName) { case ObjectTypeName.Level: generalDisplayName = FindStandardLevelDisplayName(generalName, generalValue); break; case ObjectTypeName.Opcode: generalDisplayName = FindStandardOpcodeDisplayName(generalName, generalValue >> 16); break; case ObjectTypeName.Keyword: generalDisplayName = FindStandardKeywordDisplayName(generalName, generalValueKeyword); break; case ObjectTypeName.Task: generalDisplayName = FindStandardTaskDisplayName(generalName, generalValue); break; default: generalDisplayName = null; break; } } } else { generalDisplayName = NativeWrapper.EvtFormatMessage(providerHandle, unchecked((uint)generalMessageId)); } switch (objectTypeName) { case ObjectTypeName.Level: levelList.Add(new EventLevel(generalName, (int)generalValue, generalDisplayName)); break; case ObjectTypeName.Opcode: opcodeList.Add(new EventOpcode(generalName, (int)(generalValue >> 16), generalDisplayName)); break; case ObjectTypeName.Keyword: keywordList.Add(new EventKeyword(generalName, (long)generalValueKeyword, generalDisplayName)); break; case ObjectTypeName.Task: Guid taskGuid = (Guid)NativeWrapper.EvtGetObjectArrayProperty(elHandle, index, (int)UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTaskEventGuid); taskList.Add(new EventTask(generalName, (int)generalValue, generalDisplayName, taskGuid)); break; default: return null; } } switch (objectTypeName) { case ObjectTypeName.Level: return levelList; case ObjectTypeName.Opcode: return opcodeList; case ObjectTypeName.Keyword: return keywordList; case ObjectTypeName.Task: return taskList; } return null; } finally { elHandle.Dispose(); } } public IList<EventLevel> Levels { get { List<EventLevel> el; lock (_syncObject) { if (_levels != null) return _levels; el = (List<EventLevel>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataLevels); _levels = el.AsReadOnly(); } return _levels; } } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Opcodes", Justification = "matell: Shipped public in 3.5, breaking change to fix now.")] public IList<EventOpcode> Opcodes { get { List<EventOpcode> eo; lock (_syncObject) { if (_opcodes != null) return _opcodes; eo = (List<EventOpcode>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataOpcodes); _opcodes = eo.AsReadOnly(); } return _opcodes; } } public IList<EventKeyword> Keywords { get { List<EventKeyword> ek; lock (_syncObject) { if (_keywords != null) return _keywords; ek = (List<EventKeyword>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataKeywords); _keywords = ek.AsReadOnly(); } return _keywords; } } public IList<EventTask> Tasks { get { List<EventTask> et; lock (_syncObject) { if (_tasks != null) return _tasks; et = (List<EventTask>)this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); _tasks = et.AsReadOnly(); } return _tasks; } } public IEnumerable<EventMetadata> Events { [System.Security.SecurityCritical] get { List<EventMetadata> emList = new List<EventMetadata>(); EventLogHandle emEnumHandle = NativeWrapper.EvtOpenEventMetadataEnum(_handle, 0); using (emEnumHandle) { while (true) { EventLogHandle emHandle = emHandle = NativeWrapper.EvtNextEventMetadata(emEnumHandle, 0); if (emHandle == null) break; using (emHandle) { unchecked { uint emId = (uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventID); byte emVersion = (byte)((uint)(NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventVersion))); byte emChannelId = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventChannel)); byte emLevel = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventLevel)); byte emOpcode = (byte)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventOpcode)); short emTask = (short)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTask)); long emKeywords = (long)(ulong)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventKeyword); string emTemplate = (string)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventTemplate); int messageId = (int)((uint)NativeWrapper.EvtGetEventMetadataProperty(emHandle, UnsafeNativeMethods.EvtEventMetadataPropertyId.EventMetadataEventMessageID)); string emMessage = (messageId == -1) ? null : NativeWrapper.EvtFormatMessage(_handle, (uint)messageId); EventMetadata em = new EventMetadata(emId, emVersion, emChannelId, emLevel, emOpcode, emTask, emKeywords, emTemplate, emMessage, this); emList.Add(em); } } } return emList.AsReadOnly(); } } } // throws if Provider metadata has been uninstalled since this object was created. internal void CheckReleased() { lock (_syncObject) { this.GetProviderListProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataTasks); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { if (_handle != null && !_handle.IsInvalid) _handle.Dispose(); } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using RazorDBx.C5; using NUnit.Framework; namespace C5UnitTests.wrappers { namespace events { [TestFixture] public class IList_ { private ArrayList<int> list; ICollectionValue<int> guarded; CollectionEventList<int> seen; [SetUp] public void Init () { list = new ArrayList<int> (TenEqualityComparer.Default); guarded = new GuardedList<int> (list); seen = new CollectionEventList<int> (System.Collections.Generic.EqualityComparer<int>.Default); } private void listen () { seen.Listen (guarded, EventTypeEnum.All); } [Test] public void Listenable () { Assert.AreEqual (EventTypeEnum.All, guarded.ListenableEvents); Assert.AreEqual (EventTypeEnum.None, guarded.ActiveEvents); listen (); Assert.AreEqual (EventTypeEnum.All, guarded.ActiveEvents); } [Test] public void SetThis () { list.Add (4); list.Add (56); list.Add (8); listen (); list [1] = 45; seen.Check (new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(56,1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); } [Test] public void Insert () { list.Add (4); list.Add (56); list.Add (8); listen (); list.Insert (1, 45); seen.Check (new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); } [Test] public void InsertAll () { list.Add (4); list.Add (56); list.Add (8); listen (); list.InsertAll (1, new int[] { 666, 777, 888 }); //seen.Print(Console.Error); seen.Check (new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(666,1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(666, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(777,2), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(777, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(888,3), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(888, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.InsertAll (1, new int[] { }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void InsertFirstLast() { list.Add(4); list.Add(56); list.Add(8); listen(); list.InsertFirst(45); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(45,0), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.InsertLast(88); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(88,4), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(88, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); } [Test] public void Remove() { list.Add(4); list.Add(56); list.Add(8); listen(); list.Remove(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(8, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void RemoveFirst() { list.Add(4); list.Add(56); list.Add(8); listen(); list.RemoveFirst(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(4,0), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(4, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void RemoveLast() { list.Add(4); list.Add(56); list.Add(8); listen(); list.RemoveLast(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(8,2), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(8, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void Reverse() { list.Add(4); list.Add(56); list.Add(8); listen(); list.Reverse(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.View(1, 0).Reverse(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Sort() { list.Add(4); list.Add(56); list.Add(8); listen(); list.Sort(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.View(1, 0).Sort(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Shuffle() { list.Add(4); list.Add(56); list.Add(8); listen(); list.Shuffle(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.View(1, 0).Shuffle(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RemoveAt() { list.Add(4); list.Add(56); list.Add(8); listen(); list.RemoveAt(1); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(56,1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void RemoveInterval() { list.Add(4); list.Add(56); list.Add(8); listen(); list.RemoveInterval(1, 2); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,2,1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.RemoveInterval(1, 0); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Update() { list.Add(4); list.Add(56); list.Add(8); listen(); list.Update(53); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.Update(67); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void FindOrAdd() { list.Add(4); list.Add(56); list.Add(8); listen(); int val = 53; list.FindOrAdd(ref val); seen.Check(new CollectionEvent<int>[] { }); val = 67; list.FindOrAdd(ref val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); } [Test] public void UpdateOrAdd() { list.Add(4); list.Add(56); list.Add(8); listen(); int val = 53; list.UpdateOrAdd(val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(53, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); val = 67; list.UpdateOrAdd(val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.UpdateOrAdd(51, out val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(53, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(51, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); val = 67; list.UpdateOrAdd(81, out val); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(81, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); } [Test] public void RemoveItem() { list.Add(4); list.Add(56); list.Add(18); listen(); list.Remove(53); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Remove(11); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(18, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void RemoveAll() { for (int i = 0; i < 10; i++) { list.Add(10 * i + 5); } listen(); list.RemoveAll(new int[] { 32, 187, 45 }); //TODO: the order depends on internals of the HashSet seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(35, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(45, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.RemoveAll(new int[] { 200, 300 }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Clear() { list.Add(4); list.Add(56); list.Add(8); listen(); list.View(1, 1).Clear(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(false,1,1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.Clear(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,2,0), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.Clear(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void ListDispose() { list.Add(4); list.Add(56); list.Add(8); listen(); list.View(1, 1).Dispose(); seen.Check(new CollectionEvent<int>[] { }); list.Dispose(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Cleared, new ClearedRangeEventArgs(true,3,0), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded) }); list.Dispose(); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RetainAll() { for (int i = 0; i < 10; i++) { list.Add(10 * i + 5); } listen(); list.RetainAll(new int[] { 32, 187, 45, 62, 82, 95, 2 }); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(15, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(25, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(55, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(75, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.RetainAll(new int[] { 32, 187, 45, 62, 82, 95, 2 }); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void RemoveAllCopies() { for (int i = 0; i < 10; i++) { list.Add(3 * i + 5); } listen(); list.RemoveAllCopies(14); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(11, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(14, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(17, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.RemoveAllCopies(14); seen.Check(new CollectionEvent<int>[] { }); } [Test] public void Add() { listen(); seen.Check(new CollectionEvent<int>[0]); list.Add(23); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(23, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void AddAll() { for (int i = 0; i < 10; i++) { list.Add(10 * i + 5); } listen(); list.AddAll(new int[] { 45, 56, 67 }); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(45, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(56, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.AddAll(new int[] { }); seen.Check(new CollectionEvent<int>[] { }); } [TearDown] public void Dispose() { list = null; seen = null; } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewChanged() { IList<int> w = list.View(0, 0); w.CollectionChanged += new CollectionChangedHandler<int>(w_CollectionChanged); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewCleared() { IList<int> w = list.View(0, 0); w.CollectionCleared += new CollectionClearedHandler<int>(w_CollectionCleared); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewAdded() { IList<int> w = list.View(0, 0); w.ItemsAdded += new ItemsAddedHandler<int>(w_ItemAdded); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewInserted() { IList<int> w = list.View(0, 0); w.ItemInserted += new ItemInsertedHandler<int>(w_ItemInserted); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewRemoved() { IList<int> w = list.View(0, 0); w.ItemsRemoved += new ItemsRemovedHandler<int>(w_ItemRemoved); } [Test] [ExpectedException(typeof(UnlistenableEventException))] public void ViewRemovedAt() { IList<int> w = list.View(0, 0); w.ItemRemovedAt += new ItemRemovedAtHandler<int>(w_ItemRemovedAt); } void w_CollectionChanged(object sender) { throw new NotImplementedException(); } void w_CollectionCleared(object sender, ClearedEventArgs eventArgs) { throw new NotImplementedException(); } void w_ItemAdded(object sender, ItemCountEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemInserted(object sender, ItemAtEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemRemoved(object sender, ItemCountEventArgs<int> eventArgs) { throw new NotImplementedException(); } void w_ItemRemovedAt(object sender, ItemAtEventArgs<int> eventArgs) { throw new NotImplementedException(); } } [TestFixture] public class StackQueue { private ArrayList<int> list; ICollectionValue<int> guarded; CollectionEventList<int> seen; [SetUp] public void Init() { list = new ArrayList<int>(TenEqualityComparer.Default); guarded = new GuardedList<int>(list); seen = new CollectionEventList<int>(System.Collections.Generic.EqualityComparer<int>.Default); } private void listen() { seen.Listen(guarded, EventTypeEnum.All); } [Test] public void EnqueueDequeue() { listen(); list.Enqueue(67); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(67,0), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(67, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Enqueue(2); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(2,1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(2, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Dequeue(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(67,0), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(67, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Dequeue(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(2,0), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(2, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [Test] public void PushPop() { listen(); seen.Check(new CollectionEvent<int>[0]); list.Push(23); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(23,0), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(23, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Push(-12); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.Inserted, new ItemAtEventArgs<int>(-12,1), guarded), new CollectionEvent<int>(EventTypeEnum.Added, new ItemCountEventArgs<int>(-12, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Pop(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(-12,1), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(-12, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); list.Pop(); seen.Check(new CollectionEvent<int>[] { new CollectionEvent<int>(EventTypeEnum.RemovedAt, new ItemAtEventArgs<int>(23,0), guarded), new CollectionEvent<int>(EventTypeEnum.Removed, new ItemCountEventArgs<int>(23, 1), guarded), new CollectionEvent<int>(EventTypeEnum.Changed, new EventArgs(), guarded)}); } [TearDown] public void Dispose() { list = null; seen = null; } } } namespace wrappedarray { [TestFixture] public class Basic { [SetUp] public void Init() { } [TearDown] public void Dispose() { } [Test] public void NoExc() { WrappedArray<int> wrapped = new WrappedArray<int>(new int[] { 4, 6, 5 }); Assert.AreEqual(6, wrapped[1]); Assert.IsTrue(IC.eq(wrapped[1, 2], 6, 5)); // Func<int, bool> is4 = delegate(int i) { return i == 4; }; Assert.AreEqual(EventTypeEnum.None, wrapped.ActiveEvents); Assert.AreEqual(false, wrapped.All(is4)); Assert.AreEqual(true, wrapped.AllowsDuplicates); wrapped.Apply(delegate(int i) { }); Assert.AreEqual("{ 5, 6, 4 }", wrapped.Backwards().ToString()); Assert.AreEqual(true, wrapped.Check()); wrapped.Choose(); Assert.AreEqual(true, wrapped.Contains(4)); Assert.AreEqual(true, wrapped.ContainsAll(new ArrayList<int>())); Assert.AreEqual(1, wrapped.ContainsCount(4)); Assert.AreEqual(Speed.Linear, wrapped.ContainsSpeed); int[] extarray = new int[5]; wrapped.CopyTo(extarray, 1); Assert.IsTrue(IC.eq(extarray, 0, 4, 6, 5, 0)); Assert.AreEqual(3, wrapped.Count); Assert.AreEqual(Speed.Constant, wrapped.CountSpeed); Assert.AreEqual(EnumerationDirection.Forwards, wrapped.Direction); Assert.AreEqual(false, wrapped.DuplicatesByCounting); Assert.AreEqual(System.Collections.Generic.EqualityComparer<int>.Default, wrapped.EqualityComparer); Assert.AreEqual(true, wrapped.Exists(is4)); Assert.IsTrue(IC.eq(wrapped.Filter(is4), 4)); int j = 5; Assert.AreEqual(true, wrapped.Find(ref j)); Assert.AreEqual(true, wrapped.Find(is4, out j)); Assert.AreEqual("[ 0:4 ]", wrapped.FindAll(is4).ToString()); Assert.AreEqual(0, wrapped.FindIndex(is4)); Assert.AreEqual(true, wrapped.FindLast(is4, out j)); Assert.AreEqual(0, wrapped.FindLastIndex(is4)); Assert.AreEqual(4, wrapped.First); wrapped.GetEnumerator(); Assert.AreEqual(CHC.sequencedhashcode(4, 6, 5), wrapped.GetSequencedHashCode()); Assert.AreEqual(CHC.unsequencedhashcode(4, 6, 5), wrapped.GetUnsequencedHashCode()); Assert.AreEqual(Speed.Constant, wrapped.IndexingSpeed); Assert.AreEqual(2, wrapped.IndexOf(5)); Assert.AreEqual(false, wrapped.IsEmpty); Assert.AreEqual(true, wrapped.IsReadOnly); Assert.AreEqual(false, wrapped.IsSorted()); Assert.AreEqual(true, wrapped.IsValid); Assert.AreEqual(5, wrapped.Last); Assert.AreEqual(2, wrapped.LastIndexOf(5)); Assert.AreEqual(EventTypeEnum.None, wrapped.ListenableEvents); Func<int, string> i2s = delegate(int i) { return string.Format("T{0}", i); }; Assert.AreEqual("[ 0:T4, 1:T6, 2:T5 ]", wrapped.Map<string>(i2s).ToString()); Assert.AreEqual(0, wrapped.Offset); wrapped.Reverse(); Assert.AreEqual("[ 0:5, 1:6, 2:4 ]", wrapped.ToString()); IList<int> other = new ArrayList<int>(); other.AddAll(new int[] { 4, 5, 6 }); Assert.IsFalse(wrapped.SequencedEquals(other)); j = 30; Assert.AreEqual(true, wrapped.Show(new System.Text.StringBuilder(), ref j, null)); wrapped.Sort(); Assert.AreEqual("[ 0:4, 1:5, 2:6 ]", wrapped.ToString()); Assert.IsTrue(IC.eq(wrapped.ToArray(), 4, 5, 6)); Assert.AreEqual("[ ... ]", wrapped.ToString("L4", null)); Assert.AreEqual(null, wrapped.Underlying); Assert.IsTrue(IC.seteq(wrapped.UniqueItems(), 4, 5, 6)); Assert.IsTrue(wrapped.UnsequencedEquals(other)); wrapped.Shuffle(); Assert.IsTrue(IC.seteq(wrapped.UniqueItems(), 4, 5, 6)); } [Test] public void WithExc() { WrappedArray<int> wrapped = new WrappedArray<int>(new int[] { 3, 4, 6, 5, 7 }); // try { wrapped.Add(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.AddAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Clear(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Dispose(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } int j = 1; try { wrapped.FindOrAdd(ref j); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Insert(1, 1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Insert(wrapped.View(0, 0), 1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertAll(1, null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertFirst(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertLast(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Remove(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Remove(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAllCopies(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAt(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveFirst(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveInterval(0, 0); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveLast(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RetainAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Update(1, out j); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.UpdateOrAdd(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } } [Test] public void View() { int[] inner = new int[] { 3, 4, 6, 5, 7 }; WrappedArray<int> outerwrapped = new WrappedArray<int>(inner); WrappedArray<int> wrapped = (WrappedArray<int>)outerwrapped.View(1, 3); // Assert.AreEqual(6, wrapped[1]); Assert.IsTrue(IC.eq(wrapped[1, 2], 6, 5)); // Func<int, bool> is4 = delegate(int i) { return i == 4; }; Assert.AreEqual(EventTypeEnum.None, wrapped.ActiveEvents); Assert.AreEqual(false, wrapped.All(is4)); Assert.AreEqual(true, wrapped.AllowsDuplicates); wrapped.Apply(delegate(int i) { }); Assert.AreEqual("{ 5, 6, 4 }", wrapped.Backwards().ToString()); Assert.AreEqual(true, wrapped.Check()); wrapped.Choose(); Assert.AreEqual(true, wrapped.Contains(4)); Assert.AreEqual(true, wrapped.ContainsAll(new ArrayList<int>())); Assert.AreEqual(1, wrapped.ContainsCount(4)); Assert.AreEqual(Speed.Linear, wrapped.ContainsSpeed); int[] extarray = new int[5]; wrapped.CopyTo(extarray, 1); Assert.IsTrue(IC.eq(extarray, 0, 4, 6, 5, 0)); Assert.AreEqual(3, wrapped.Count); Assert.AreEqual(Speed.Constant, wrapped.CountSpeed); Assert.AreEqual(EnumerationDirection.Forwards, wrapped.Direction); Assert.AreEqual(false, wrapped.DuplicatesByCounting); Assert.AreEqual(System.Collections.Generic.EqualityComparer<int>.Default, wrapped.EqualityComparer); Assert.AreEqual(true, wrapped.Exists(is4)); Assert.IsTrue(IC.eq(wrapped.Filter(is4), 4)); int j = 5; Assert.AreEqual(true, wrapped.Find(ref j)); Assert.AreEqual(true, wrapped.Find(is4, out j)); Assert.AreEqual("[ 0:4 ]", wrapped.FindAll(is4).ToString()); Assert.AreEqual(0, wrapped.FindIndex(is4)); Assert.AreEqual(true, wrapped.FindLast(is4, out j)); Assert.AreEqual(0, wrapped.FindLastIndex(is4)); Assert.AreEqual(4, wrapped.First); wrapped.GetEnumerator(); Assert.AreEqual(CHC.sequencedhashcode(4, 6, 5), wrapped.GetSequencedHashCode()); Assert.AreEqual(CHC.unsequencedhashcode(4, 6, 5), wrapped.GetUnsequencedHashCode()); Assert.AreEqual(Speed.Constant, wrapped.IndexingSpeed); Assert.AreEqual(2, wrapped.IndexOf(5)); Assert.AreEqual(false, wrapped.IsEmpty); Assert.AreEqual(true, wrapped.IsReadOnly); Assert.AreEqual(false, wrapped.IsSorted()); Assert.AreEqual(true, wrapped.IsValid); Assert.AreEqual(5, wrapped.Last); Assert.AreEqual(2, wrapped.LastIndexOf(5)); Assert.AreEqual(EventTypeEnum.None, wrapped.ListenableEvents); Func<int, string> i2s = delegate(int i) { return string.Format("T{0}", i); }; Assert.AreEqual("[ 0:T4, 1:T6, 2:T5 ]", wrapped.Map<string>(i2s).ToString()); Assert.AreEqual(1, wrapped.Offset); wrapped.Reverse(); Assert.AreEqual("[ 0:5, 1:6, 2:4 ]", wrapped.ToString()); IList<int> other = new ArrayList<int>(); other.AddAll(new int[] { 4, 5, 6 }); Assert.IsFalse(wrapped.SequencedEquals(other)); j = 30; Assert.AreEqual(true, wrapped.Show(new System.Text.StringBuilder(), ref j, null)); wrapped.Sort(); Assert.AreEqual("[ 0:4, 1:5, 2:6 ]", wrapped.ToString()); Assert.IsTrue(IC.eq(wrapped.ToArray(), 4, 5, 6)); Assert.AreEqual("[ ... ]", wrapped.ToString("L4", null)); Assert.AreEqual(outerwrapped, wrapped.Underlying); Assert.IsTrue(IC.seteq(wrapped.UniqueItems(), 4, 5, 6)); Assert.IsTrue(wrapped.UnsequencedEquals(other)); // Assert.IsTrue(wrapped.TrySlide(1)); Assert.IsTrue(IC.eq(wrapped, 5, 6, 7)); Assert.IsTrue(wrapped.TrySlide(-1, 2)); Assert.IsTrue(IC.eq(wrapped, 4, 5)); Assert.IsFalse(wrapped.TrySlide(-2)); Assert.IsTrue(IC.eq(wrapped.Span(outerwrapped.ViewOf(7)), 4, 5, 6, 7)); // wrapped.Shuffle(); Assert.IsTrue(IC.seteq(wrapped.UniqueItems(), 4, 5)); Assert.IsTrue(wrapped.IsValid); wrapped.Dispose(); Assert.IsFalse(wrapped.IsValid); } [Test] public void ViewWithExc() { int[] inner = new int[] { 3, 4, 6, 5, 7 }; WrappedArray<int> outerwrapped = new WrappedArray<int>(inner); WrappedArray<int> wrapped = (WrappedArray<int>)outerwrapped.View(1, 3); // try { wrapped.Add(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.AddAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Clear(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } //Should not throw //try { wrapped.Dispose(); Assert.Fail("No throw"); } //catch (FixedSizeCollectionException) { } int j = 1; try { wrapped.FindOrAdd(ref j); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Insert(1, 1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Insert(wrapped.View(0, 0), 1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertAll(1, null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertFirst(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.InsertLast(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Remove(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Remove(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAllCopies(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveAt(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveFirst(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveInterval(0, 0); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RemoveLast(); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.RetainAll(null); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.Update(1, out j); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } try { wrapped.UpdateOrAdd(1); Assert.Fail("No throw"); } catch (FixedSizeCollectionException) { } } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Glass.Mapper.Sc.Dynamic; using Sitecore.Data; using NUnit.Framework; using Sitecore.Data.Items; using Sitecore.Links; namespace Glass.Mapper.Sc.Integration.Dynamic { public class DynamicCollectionFixture { Database _db; private const string TargetPath = "/sitecore/content/Tests/Dynamic/DynamicCollection/Target"; [SetUp] public void Setup() { _db = global::Sitecore.Configuration.Factory.GetDatabase("master"); global::Sitecore.Context.Site = global::Sitecore.Sites.SiteContext.GetSite("website"); } #region METHOD - SELECT [Test] public void First() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.First(); //Assert Assert.AreEqual(TargetPath+"/Child1", child.Path); } [Test] public void First_WithPredicate() { //Assign Item item = _db.GetItem(TargetPath); string name = "Child2"; dynamic d = new DynamicItem(item); //Act var child = d.Children.First(Dy.Fc(x => x.Name == "Child2")); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void FirstOrDefault() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.FirstOrDefault(); //Assert Assert.AreEqual(TargetPath+"/Child1", child.Path); } [Test] public void FirstOrDefault_WithPredicate() { //Assign Item item = _db.GetItem(TargetPath); string name = "Child2"; dynamic d = new DynamicItem(item); //Act var func = Dy.Fc(x => x.Name == "Child2"); var child = d.Children.First(func); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void Last() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.Last(); //Assert Assert.AreEqual(TargetPath+"/Child3", child.Path); } [Test] public void Last_WithPredicate() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.Last(Dy.Fc(x=>x.Name == "Child2")); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void LastOrDefault() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.LastOrDefault(); //Assert Assert.AreEqual(TargetPath+"/Child3", child.Path); } [Test] public void LastOrDefault_WithPredicate() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.LastOrDefault(Dy.Fc(x => x.Name == "Child2")); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void ElementAt() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.ElementAt(1); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void Where() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.Where(Dy.Fc(x => x.Name == "Child2")).First(); //Assert Assert.AreEqual(TargetPath+"/Child2", child.Path); } [Test] public void Any() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result1 = d.Children.Any(Dy.Fc(x => x.Name == "Child2")); var result2 = d.Children.Any(Dy.Fc(x => x.Name == "NotThere")); //Assert Assert.AreEqual(true, result1); Assert.AreEqual(false, result2); } [Test] public void All() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var result1 = d.Children.All(Dy.Fc(x => x.Name.StartsWith("Child"))); var result2 = d.Children.All(Dy.Fc(x => x.Name.StartsWith("Child2"))); //Assert Assert.AreEqual(true, result1); Assert.AreEqual(false, result2); } [Test] public void Select_ToKnown() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var children = d.Children.Select(Dy.FcT<Known>(x => new Known { Name = x.Name })) as IEnumerable<Known>; var child = children.First(); //Assert Assert.AreEqual("Child1", child.Name); } [Test] public void Select_ToDynamic() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var children = d.Children.Select(Dy.FcT(x => new { Name = x.Name })) as IEnumerable<dynamic>; var child = children.First(); //Assert Assert.AreEqual("Child1", child.Name); } [Test] public void Where_Select_First_DyamicsTypes() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var child = d.Children.Where(Dy.Fc(x=> x.Name == "Child2")).Select(Dy.FcT(x => new { NewPath = x.Path, NewName = x.Name })).First(); //Assert Assert.AreEqual(TargetPath+"/Child2", child.NewPath); Assert.AreEqual("Child2", child.NewName); } [Test] public void Count() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var count = d.Children.Count(); //Assert Assert.AreEqual(3, count); } [Test] public void ForEach() { //Assign Item item = _db.GetItem(TargetPath); dynamic d = new DynamicItem(item); //Act var children = d.Children; //Assert int total = 0; foreach (var child in children) { total++; switch (total) { case 1: Assert.AreEqual(TargetPath+"/Child1", child.Path); break; case 2: Assert.AreEqual(TargetPath + "/Child2", child.Path); break; case 3: Assert.AreEqual(TargetPath + "/Child3", child.Path); break; } } Assert.AreEqual(3, total); } #endregion public class Known { public string Name { get; set; } public string Path { get; set; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; #if !netstandard using Internal.Runtime.CompilerServices; #endif namespace System { internal static partial class SpanHelpers // .T { public static int IndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return 0; // A zero-length sequence is always treated as "found" at the start of the search space. T valueHead = value; ref T valueTail = ref Unsafe.Add(ref value, 1); int valueTailLength = valueLength - 1; int index = 0; while (true) { Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength". int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength; if (remainingSearchSpaceLength <= 0) break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there. // Do a quick search for the first element of "value". int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, index), valueHead, remainingSearchSpaceLength); if (relativeIndex == -1) break; index += relativeIndex; // Found the first element of "value". See if the tail matches. if (SequenceEqual(ref Unsafe.Add(ref searchSpace, index + 1), ref valueTail, valueTailLength)) return index; // The tail matched. Return a successful find. index++; } return -1; } // Adapted from IndexOf(...) public static unsafe bool Contains<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || value.Equals(Unsafe.Add(ref searchSpace, index + 3)) || value.Equals(Unsafe.Add(ref searchSpace, index + 4)) || value.Equals(Unsafe.Add(ref searchSpace, index + 5)) || value.Equals(Unsafe.Add(ref searchSpace, index + 6)) || value.Equals(Unsafe.Add(ref searchSpace, index + 7))) { goto Found; } index += 8; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, index + 0)) || value.Equals(Unsafe.Add(ref searchSpace, index + 1)) || value.Equals(Unsafe.Add(ref searchSpace, index + 2)) || value.Equals(Unsafe.Add(ref searchSpace, index + 3))) { goto Found; } index += 4; } while (length > 0) { length--; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; index += 1; } } else { byte* len = (byte*)length; for (index = (IntPtr)0; index.ToPointer() < len; index += 1) { if ((object)Unsafe.Add(ref searchSpace, index) is null) { goto Found; } } } return false; Found: return true; } public static unsafe int IndexOf<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; if (value.Equals(Unsafe.Add(ref searchSpace, index + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, index + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, index + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, index + 4))) goto Found4; if (value.Equals(Unsafe.Add(ref searchSpace, index + 5))) goto Found5; if (value.Equals(Unsafe.Add(ref searchSpace, index + 6))) goto Found6; if (value.Equals(Unsafe.Add(ref searchSpace, index + 7))) goto Found7; index += 8; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; if (value.Equals(Unsafe.Add(ref searchSpace, index + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, index + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, index + 3))) goto Found3; index += 4; } while (length > 0) { if (value.Equals(Unsafe.Add(ref searchSpace, index))) goto Found; index += 1; length--; } } else { byte* len = (byte*)length; for (index = (IntPtr)0; index.ToPointer() < len; index += 1) { if ((object)Unsafe.Add(ref searchSpace, index) is null) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return (int)(byte*)index; Found1: return (int)(byte*)(index + 1); Found2: return (int)(byte*)(index + 2); Found3: return (int)(byte*)(index + 3); Found4: return (int)(byte*)(index + 4); Found5: return (int)(byte*)(index + 5); Found6: return (int)(byte*)(index + 6); Found7: return (int)(byte*)(index + 7); } public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; int index = 0; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while ((length - index) >= 8) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, index + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, index + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, index + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, index + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found7; index += 8; } if ((length - index) >= 4) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; index += 4; } while (index < length) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; index++; } } else { for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; Found1: return index + 1; Found2: return index + 2; Found3: return index + 3; Found4: return index + 4; Found5: return index + 5; Found6: return index + 6; Found7: return index + 7; } public static int IndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; int index = 0; if (default(T)! != null || ((object)value0 != null && (object)value1 != null && (object)value2 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while ((length - index) >= 8) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, index + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, index + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, index + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, index + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found7; index += 8; } if ((length - index) >= 4) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; lookUp = Unsafe.Add(ref searchSpace, index + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, index + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, index + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; index += 4; } while (index < length) { lookUp = Unsafe.Add(ref searchSpace, index); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; index++; } } else { for (index = 0; index < length; index++) { lookUp = Unsafe.Add(ref searchSpace, index); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return index; Found1: return index + 1; Found2: return index + 2; Found3: return index + 3; Found4: return index + 4; Found5: return index + 5; Found6: return index + 6; Found7: return index + 7; } public static int IndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return -1; // A zero-length set of values is always treated as "not found". int index = -1; for (int i = 0; i < valueLength; i++) { int tempIndex = IndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if ((uint)tempIndex < (uint)index) { index = tempIndex; // Reduce space for search, cause we don't care if we find the search value after the index of a previously found value searchSpaceLength = tempIndex; if (index == 0) break; } } return index; } public static int LastIndexOf<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return 0; // A zero-length sequence is always treated as "found" at the start of the search space. T valueHead = value; ref T valueTail = ref Unsafe.Add(ref value, 1); int valueTailLength = valueLength - 1; int index = 0; while (true) { Debug.Assert(0 <= index && index <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength". int remainingSearchSpaceLength = searchSpaceLength - index - valueTailLength; if (remainingSearchSpaceLength <= 0) break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there. // Do a quick search for the first element of "value". int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength); if (relativeIndex == -1) break; // Found the first element of "value". See if the tail matches. if (SequenceEqual(ref Unsafe.Add(ref searchSpace, relativeIndex + 1), ref valueTail, valueTailLength)) return relativeIndex; // The tail matched. Return a successful find. index += remainingSearchSpaceLength - relativeIndex; } return -1; } public static int LastIndexOf<T>(ref T searchSpace, T value, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); if (default(T)! != null || (object)value != null) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, length + 7))) goto Found7; if (value.Equals(Unsafe.Add(ref searchSpace, length + 6))) goto Found6; if (value.Equals(Unsafe.Add(ref searchSpace, length + 5))) goto Found5; if (value.Equals(Unsafe.Add(ref searchSpace, length + 4))) goto Found4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) goto Found3; if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) goto Found2; if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) goto Found1; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } while (length > 0) { length--; if (value.Equals(Unsafe.Add(ref searchSpace, length))) goto Found; } } else { for (length--; length >= 0; length--) { if ((object)Unsafe.Add(ref searchSpace, length) is null) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; lookUp = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found7; lookUp = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } if (length >= 4) { length -= 4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } while (length > 0) { length--; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp)) goto Found; } } else { for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, T value0, T value1, T value2, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); T lookUp; if (default(T)! != null || ((object)value0 != null && (object)value1 != null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) { while (length >= 8) { length -= 8; lookUp = Unsafe.Add(ref searchSpace, length + 7); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found7; lookUp = Unsafe.Add(ref searchSpace, length + 6); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found6; lookUp = Unsafe.Add(ref searchSpace, length + 5); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found5; lookUp = Unsafe.Add(ref searchSpace, length + 4); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } if (length >= 4) { length -= 4; lookUp = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found3; lookUp = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found2; lookUp = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found1; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } while (length > 0) { length--; lookUp = Unsafe.Add(ref searchSpace, length); if (value0.Equals(lookUp) || value1.Equals(lookUp) || value2.Equals(lookUp)) goto Found; } } else { for (length--; length >= 0; length--) { lookUp = Unsafe.Add(ref searchSpace, length); if ((object?)lookUp is null) { if ((object?)value0 is null || (object?)value1 is null || (object?)value2 is null) { goto Found; } } else if (lookUp.Equals(value0) || lookUp.Equals(value1) || lookUp.Equals(value2)) { goto Found; } } } return -1; Found: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return length; Found1: return length + 1; Found2: return length + 2; Found3: return length + 3; Found4: return length + 4; Found5: return length + 5; Found6: return length + 6; Found7: return length + 7; } public static int LastIndexOfAny<T>(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(searchSpaceLength >= 0); Debug.Assert(valueLength >= 0); if (valueLength == 0) return -1; // A zero-length set of values is always treated as "not found". int index = -1; for (int i = 0; i < valueLength; i++) { int tempIndex = LastIndexOf(ref searchSpace, Unsafe.Add(ref value, i), searchSpaceLength); if (tempIndex > index) index = tempIndex; } return index; } public static bool SequenceEqual<T>(ref T first, ref T second, int length) #nullable disable // to enable use with both T and T? for reference types due to IEquatable<T> being invariant where T : IEquatable<T> #nullable restore { Debug.Assert(length >= 0); if (Unsafe.AreSame(ref first, ref second)) goto Equal; IntPtr index = (IntPtr)0; // Use IntPtr for arithmetic to avoid unnecessary 64->32->64 truncations T lookUp0; T lookUp1; while (length >= 8) { length -= 8; lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 4); lookUp1 = Unsafe.Add(ref second, index + 4); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 5); lookUp1 = Unsafe.Add(ref second, index + 5); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 6); lookUp1 = Unsafe.Add(ref second, index + 6); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 7); lookUp1 = Unsafe.Add(ref second, index + 7); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 8; } if (length >= 4) { length -= 4; lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 1); lookUp1 = Unsafe.Add(ref second, index + 1); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 2); lookUp1 = Unsafe.Add(ref second, index + 2); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; lookUp0 = Unsafe.Add(ref first, index + 3); lookUp1 = Unsafe.Add(ref second, index + 3); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 4; } while (length > 0) { lookUp0 = Unsafe.Add(ref first, index); lookUp1 = Unsafe.Add(ref second, index); if (!(lookUp0?.Equals(lookUp1) ?? (object?)lookUp1 is null)) goto NotEqual; index += 1; length--; } Equal: return true; NotEqual: // Workaround for https://github.com/dotnet/coreclr/issues/13549 return false; } public static int SequenceCompareTo<T>(ref T first, int firstLength, ref T second, int secondLength) where T : IComparable<T> { Debug.Assert(firstLength >= 0); Debug.Assert(secondLength >= 0); int minLength = firstLength; if (minLength > secondLength) minLength = secondLength; for (int i = 0; i < minLength; i++) { T lookUp = Unsafe.Add(ref second, i); int result = (Unsafe.Add(ref first, i)?.CompareTo(lookUp) ?? (((object?)lookUp is null) ? 0 : -1)); if (result != 0) return result; } return firstLength.CompareTo(secondLength); } } }
//#define ASTARDEBUG //"BBTree Debug" If enables, some queries to the tree will show debug lines. Turn off multithreading when using this since DrawLine calls cannot be called from a different thread //#define ASTAR_OLD_BBTREE // Use class based BBTree implementation instead of struct based. Struct based is better for runtime performance and memory, but class based scans slightly faster. using System; using UnityEngine; using Pathfinding; using System.Collections.Generic; namespace Pathfinding { /** Axis Aligned Bounding Box Tree. * Holds a bounding box tree of triangles.\n * \b Performance: Insertion - Practically O(1) - About 0.003 ms * \astarpro */ public class BBTree { #if !ASTAR_OLD_BBTREE /** Holds an Axis Aligned Bounding Box Tree used for faster node lookups. * \astarpro */ BBTreeBox[] arr = new BBTreeBox[6]; int count = 0; public INavmeshHolder graph; public BBTree (INavmeshHolder graph) { this.graph = graph; } public Rect Size { get { return count != 0 ? arr[0].rect : new Rect (0,0,0,0); } } /** Clear the tree. * Note that references to old nodes will still be intact so the GC cannot immediately collect them. */ public void Clear () { count = 0; } void EnsureCapacity ( int c ) { if ( arr.Length < c ) { var narr = new BBTreeBox[System.Math.Max ( c , (int)(arr.Length*1.5f))]; for ( int i = 0; i < count; i++ ) { narr[i] = arr[i]; } arr = narr; } } int GetBox ( MeshNode node ) { if ( count >= arr.Length ) EnsureCapacity ( count+1 ); arr[count] = new BBTreeBox ( this, node ); count++; return count-1; } /** Inserts a mesh node in the tree */ public void Insert (MeshNode node) { int boxi = GetBox (node); // Was set to root if (boxi == 0) { return; } BBTreeBox box = arr[boxi]; //int depth = 0; int c = 0; while (true) { BBTreeBox cb = arr[c]; cb.rect = ExpandToContain (cb.rect,box.rect); if (cb.node != null) { //Is Leaf cb.left = boxi; int box2 = GetBox (cb.node); //BBTreeBox box2 = new BBTreeBox (this,c.node); //Console.WriteLine ("Inserted "+box.node+", rect "+box.rect.ToString ()); cb.right = box2; cb.node = null; //cb.depth++; //c.rect = c.rect. arr[c] = cb; //Debug.Log (depth); return; } else { //depth++; //cb.depth++; arr[c] = cb; float e1 = ExpansionRequired (arr[cb.left].rect,box.rect);// * arr[cb.left].depth; float e2 = ExpansionRequired (arr[cb.right].rect,box.rect);// * arr[cb.left].depth; //Choose the rect requiring the least expansion to contain box.rect if (e1 < e2) { c = cb.left; } else if (e2 < e1) { c = cb.right; } else { //Equal, Choose the one with the smallest area c = RectArea (arr[cb.left].rect) < RectArea (arr[cb.right].rect) ? cb.left : cb.right; } } } } public NNInfo Query (Vector3 p, NNConstraint constraint) { if ( count == 0 ) return new NNInfo(null); NNInfo nnInfo = new NNInfo (); SearchBox (0,p, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } /** Queries the tree for the best node, searching within a circle around \a p with the specified radius. * Will fill in both the constrained node and the not constrained node in the NNInfo. * * \see QueryClosest */ public NNInfo QueryCircle (Vector3 p, float radius, NNConstraint constraint) { if ( count == 0 ) return new NNInfo(null); NNInfo nnInfo = new NNInfo (null); SearchBoxCircle (0,p, radius, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } /** Queries the tree for the closest node to \a p constrained by the NNConstraint. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * \see QueryCircle */ public NNInfo QueryClosest (Vector3 p, NNConstraint constraint, out float distance) { distance = float.PositiveInfinity; return QueryClosest (p, constraint, ref distance, new NNInfo (null)); } /** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * This search will start from the \a previous NNInfo and improve it if possible. * Even if the search fails on this call, the solution will never be worse than \a previous. * * This method will completely ignore any Y-axis differences in positions. * * \param distance The best distance for the \a previous solution. Will be updated with the best distance * after this search. Will be positive infinity if no node could be found. * Set to positive infinity if there was no previous solution. * * * \see QueryCircle */ public NNInfo QueryClosestXZ (Vector3 p, NNConstraint constraint, ref float distance, NNInfo previous) { if (count == 0) { return previous; } SearchBoxClosestXZ (0,p, ref distance, constraint, ref previous); return previous; } void SearchBoxClosestXZ (int boxi, Vector3 p, ref float closestDist, NNConstraint constraint, ref NNInfo nnInfo) { BBTreeBox box = arr[boxi]; if (box.node != null) { //Leaf node //if (NodeIntersectsCircle (box.node,p,closestDist)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif Vector3 closest = box.node.ClosestPointOnNodeXZ (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); // XZ distance float dist = (closest.x-p.x)*(closest.x-p.x)+(closest.z-p.z)*(closest.z-p.z); if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } else if (dist < closestDist*closestDist) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } } //} else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif //} } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (arr[box.left].rect,p,closestDist)) { SearchBoxClosestXZ (box.left,p, ref closestDist, constraint, ref nnInfo); } if (RectIntersectsCircle (arr[box.right].rect,p,closestDist)) { SearchBoxClosestXZ (box.right,p, ref closestDist, constraint, ref nnInfo); } } } /** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * This search will start from the \a previous NNInfo and improve it if possible. * Even if the search fails on this call, the solution will never be worse than \a previous. * * * \param distance The best distance for the \a previous solution. Will be updated with the best distance * after this search. Will be positive infinity if no node could be found. * Set to positive infinity if there was no previous solution. * * * \see QueryCircle */ public NNInfo QueryClosest (Vector3 p, NNConstraint constraint, ref float distance, NNInfo previous) { if ( count == 0 ) return previous; SearchBoxClosest (0,p, ref distance, constraint, ref previous); return previous; } void SearchBoxClosest (int boxi, Vector3 p, ref float closestDist, NNConstraint constraint, ref NNInfo nnInfo) { BBTreeBox box = arr[boxi]; if (box.node != null) { //Leaf node if (NodeIntersectsCircle (box.node,p,closestDist)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif Vector3 closest = box.node.ClosestPointOnNode (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); float dist = (closest-p).sqrMagnitude; if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } else if (dist < closestDist*closestDist) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (arr[box.left].rect,p,closestDist)) { SearchBoxClosest (box.left,p, ref closestDist, constraint, ref nnInfo); } if (RectIntersectsCircle (arr[box.right].rect,p,closestDist)) { SearchBoxClosest (box.right,p, ref closestDist, constraint, ref nnInfo); } } } public MeshNode QueryInside (Vector3 p, NNConstraint constraint) { if ( count == 0 ) return null; return SearchBoxInside (0,p, constraint); } MeshNode SearchBoxInside (int boxi, Vector3 p, NNConstraint constraint) { BBTreeBox box = arr[boxi]; if (box.node != null) { if (box.node.ContainsPoint ((Int3)p)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif if (constraint == null || constraint.Suitable (box.node)) { return box.node; } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children MeshNode g; if (arr[box.left].rect.Contains (new Vector2(p.x,p.z))) { g = SearchBoxInside (box.left,p, constraint); if (g != null) return g; } if (arr[box.right].rect.Contains (new Vector2(p.x,p.z))) { g = SearchBoxInside (box.right, p, constraint); if (g != null) return g; } } return null; } void SearchBoxCircle (int boxi, Vector3 p, float radius, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { BBTreeBox box = arr[boxi]; if (box.node != null) { //Leaf node if (NodeIntersectsCircle (box.node,p,radius)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.red); #endif Vector3 closest = box.node.ClosestPointOnNode (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); float dist = (closest-p).sqrMagnitude; if (nnInfo.node == null) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } else if (dist < (nnInfo.clampedPosition - p).sqrMagnitude) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } else if (dist < (nnInfo.constClampedPosition - p).sqrMagnitude) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } return; } #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (arr[box.left].rect,p,radius)) { SearchBoxCircle (box.left,p, radius, constraint, ref nnInfo); } if (RectIntersectsCircle (arr[box.right].rect,p,radius)) { SearchBoxCircle (box.right,p, radius, constraint, ref nnInfo); } } void SearchBox (int boxi, Vector3 p, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { BBTreeBox box = arr[boxi]; if (box.node != null) { //Leaf node if (box.node.ContainsPoint ((Int3)p)) { //Update the NNInfo if (nnInfo.node == null) { nnInfo.node = box.node; } else if (Mathf.Abs(((Vector3)box.node.position).y - p.y) < Mathf.Abs (((Vector3)nnInfo.node.position).y - p.y)) { nnInfo.node = box.node; } if (constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; } else if (Mathf.Abs(box.node.position.y - p.y) < Mathf.Abs (nnInfo.constrainedNode.position.y - p.y)) { nnInfo.constrainedNode = box.node; } } } return; } //Search children if (RectContains (arr[box.left].rect,p)) { SearchBox (box.left,p, constraint, ref nnInfo); } if (RectContains (arr[box.right].rect,p)) { SearchBox (box.right,p, constraint, ref nnInfo); } } //[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)] struct BBTreeBox { public Rect rect; public MeshNode node; public int left, right; //public short depth; public bool IsLeaf { get { return node != null; } } public BBTreeBox (BBTree tree, MeshNode node) { this.node = node; //depth = 0; Vector3 first = (Vector3)node.GetVertex(0); Vector2 min = new Vector2(first.x,first.z); Vector2 max = min; for (int i=1;i<node.GetVertexCount();i++) { Vector3 p = (Vector3)node.GetVertex(i); min.x = System.Math.Min (min.x,p.x); min.y = System.Math.Min (min.y,p.z); max.x = System.Math.Max (max.x,p.x); max.y = System.Math.Max (max.y,p.z); } rect = Rect.MinMaxRect (min.x,min.y,max.x,max.y); left = right = -1; } public bool Contains (Vector3 p) { return rect.Contains (new Vector2(p.x,p.z)); } } public void OnDrawGizmos () { Gizmos.color = new Color (1,1,1,0.5F); if ( count == 0 ) return; //OnDrawGizmos (0, 0); //Debug.Log ("Size " + arr.Length + " actual count " + count ); } void OnDrawGizmos ( int boxi, int depth ) { BBTreeBox box = arr[boxi]; Vector3 min = new Vector3 (box.rect.xMin,0,box.rect.yMin); Vector3 max = new Vector3 (box.rect.xMax,0,box.rect.yMax); Vector3 center = (min+max)*0.5F; Vector3 size = (max-center)*2; center.y += depth * 0.2f; //Gizmos.color = new Color (1,1,1,0.5F); //Gizmos.DrawWireCube (center,size); Gizmos.color = AstarMath.IntToColor (depth, 0.05f);//new Color (0,0,0,0.2F); Gizmos.DrawCube (center,size); if ( box.node != null ) { } else { OnDrawGizmos ( box.left, depth + 1 ); OnDrawGizmos ( box.right, depth + 1 ); } } #else /** Holds an Axis Aligned Bounding Box Tree used for faster node lookups. * \astarpro */ BBTreeBox root; public INavmeshHolder graph; public BBTree (INavmeshHolder graph) { this.graph = graph; } public Rect Size { get { return root != null ? root.rect : new Rect (0,0,0,0); } } public void Clear () { root = null; } public NNInfo Query (Vector3 p, NNConstraint constraint) { BBTreeBox c = root; if (c == null) { return new NNInfo(); } NNInfo nnInfo = new NNInfo (); SearchBox (c,p, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } /** Queries the tree for the best node, searching within a circle around \a p with the specified radius. * Will fill in both the constrained node and the not constrained node in the NNInfo. * * \see QueryClosest */ public NNInfo QueryCircle (Vector3 p, float radius, NNConstraint constraint) { BBTreeBox c = root; if (c == null) { return new NNInfo(); } #if ASTARDEBUG Vector3 prev = new Vector3 (1,0,0)*radius+p; for (double i=0;i< Math.PI*2; i += Math.PI/50.0) { Vector3 cpos = new Vector3 ((float)Math.Cos (i),0,(float)Math.Sin (i))*radius+p; Debug.DrawLine (prev,cpos,Color.yellow); prev = cpos; } #endif NNInfo nnInfo = new NNInfo (null); SearchBoxCircle (c,p, radius, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } /** Queries the tree for the closest node to \a p constrained by the NNConstraint. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * \see QueryCircle */ public NNInfo QueryClosest (Vector3 p, NNConstraint constraint, out float distance) { distance = float.PositiveInfinity; return QueryClosest (p, constraint, ref distance, new NNInfo (null)); } /** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * This search will start from the \a previous NNInfo and improve it if possible. * Even if the search fails on this call, the solution will never be worse than \a previous. * * This method will completely ignore any Y-axis differences in positions. * * \param distance The best distance for the \a previous solution. Will be updated with the best distance * after this search. Will be positive infinity if no node could be found. * Set to positive infinity if there was no previous solution. * * * \see QueryCircle */ public NNInfo QueryClosestXZ (Vector3 p, NNConstraint constraint, ref float distance, NNInfo previous) { BBTreeBox c = root; if (c == null) { return previous; } SearchBoxClosestXZ (c,p, ref distance, constraint, ref previous); return previous; } /** Queries the tree for the closest node to \a p constrained by the NNConstraint trying to improve an existing solution. * Note that this function will, unlike QueryCircle, only fill in the constrained node. * If you want a node not constrained by any NNConstraint, do an additional search with constraint = NNConstraint.None * * This search will start from the \a previous NNInfo and improve it if possible. * Even if the search fails on this call, the solution will never be worse than \a previous. * * * \param distance The best distance for the \a previous solution. Will be updated with the best distance * after this search. Will be positive infinity if no node could be found. * Set to positive infinity if there was no previous solution. * * * \see QueryCircle */ public NNInfo QueryClosest (Vector3 p, NNConstraint constraint, ref float distance, NNInfo previous) { BBTreeBox c = root; if (c == null) { return previous; } SearchBoxClosest (c,p, ref distance, constraint, ref previous); return previous; } void SearchBoxClosest (BBTreeBox box, Vector3 p, ref float closestDist, NNConstraint constraint, ref NNInfo nnInfo) { if (box.node != null) { //Leaf node if (NodeIntersectsCircle (box.node,p,closestDist)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif Vector3 closest = box.node.ClosestPointOnNode (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); float dist = (closest-p).sqrMagnitude; if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } else if (dist < closestDist*closestDist) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (box.c1.rect,p,closestDist)) { SearchBoxClosest (box.c1,p, ref closestDist, constraint, ref nnInfo); } if (RectIntersectsCircle (box.c2.rect,p,closestDist)) { SearchBoxClosest (box.c2,p, ref closestDist, constraint, ref nnInfo); } } } public MeshNode QueryInside (Vector3 p, NNConstraint constraint) { BBTreeBox c = root; if (c == null) { return null; } return SearchBoxInside (c,p, constraint); } MeshNode SearchBoxInside (BBTreeBox box, Vector3 p, NNConstraint constraint) { if (box.node != null) { if (box.node.ContainsPoint ((Int3)p)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif if (constraint == null || constraint.Suitable (box.node)) { return box.node; } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children MeshNode g; if (box.c1.rect.Contains (new Vector2(p.x,p.z))) { g = SearchBoxInside (box.c1,p, constraint); if (g != null) return g; } if (box.c2.rect.Contains (new Vector2(p.x,p.z))) { g = SearchBoxInside (box.c2, p, constraint); if (g != null) return g; } } return null; } void SearchBoxClosestXZ (BBTreeBox box, Vector3 p, ref float closestDist, NNConstraint constraint, ref NNInfo nnInfo) { if (box.node != null) { //Leaf node //if (NodeIntersectsCircle (box.node,p,closestDist)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(1) + Vector3.up*0.2f,Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2) + Vector3.up*0.2f,(Vector3)box.node.GetVertex(0) + Vector3.up*0.2f,Color.red); #endif Vector3 closest = box.node.ClosestPointOnNodeXZ (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); // XZ distance float dist = (closest.x-p.x)*(closest.x-p.x)+(closest.z-p.z)*(closest.z-p.z); if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } else if (dist < closestDist*closestDist) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; closestDist = (float)System.Math.Sqrt (dist); } } //} else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif //} } else { #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (box.c1.rect,p,closestDist)) { SearchBoxClosestXZ (box.c1,p, ref closestDist, constraint, ref nnInfo); } if (RectIntersectsCircle (box.c2.rect,p,closestDist)) { SearchBoxClosestXZ (box.c2,p, ref closestDist, constraint, ref nnInfo); } } } void SearchBoxCircle (BBTreeBox box, Vector3 p, float radius, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { if (box.node != null) { //Leaf node if (NodeIntersectsCircle (box.node,p,radius)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.red); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.red); #endif Vector3 closest = box.node.ClosestPointOnNode (p);//NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); float dist = (closest-p).sqrMagnitude; if (nnInfo.node == null) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } else if (dist < (nnInfo.clampedPosition - p).sqrMagnitude) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } if (constraint == null || constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } else if (dist < (nnInfo.constClampedPosition - p).sqrMagnitude) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)box.node.GetVertex(0),(Vector3)box.node.GetVertex(1),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(1),(Vector3)box.node.GetVertex(2),Color.blue); Debug.DrawLine ((Vector3)box.node.GetVertex(2),(Vector3)box.node.GetVertex(0),Color.blue); #endif } return; } #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (box.c1.rect,p,radius)) { SearchBoxCircle (box.c1,p, radius, constraint, ref nnInfo); } if (RectIntersectsCircle (box.c2.rect,p,radius)) { SearchBoxCircle (box.c2,p, radius, constraint, ref nnInfo); } } void SearchBox (BBTreeBox box, Vector3 p, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { if (box.node != null) { //Leaf node if (box.node.ContainsPoint ((Int3)p)) { //Update the NNInfo if (nnInfo.node == null) { nnInfo.node = box.node; } else if (Mathf.Abs(((Vector3)box.node.position).y - p.y) < Mathf.Abs (((Vector3)nnInfo.node.position).y - p.y)) { nnInfo.node = box.node; } if (constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; } else if (Mathf.Abs(box.node.position.y - p.y) < Mathf.Abs (nnInfo.constrainedNode.position.y - p.y)) { nnInfo.constrainedNode = box.node; } } } return; } //Search children if (RectContains (box.c1.rect,p)) { SearchBox (box.c1,p, constraint, ref nnInfo); } if (RectContains (box.c2.rect,p)) { SearchBox (box.c2,p, constraint, ref nnInfo); } } /** Inserts a mesh node in the tree */ public void Insert (MeshNode node) { BBTreeBox box = new BBTreeBox (this,node); if (root == null) { root = box; return; } BBTreeBox c = root; while (true) { c.rect = ExpandToContain (c.rect,box.rect); if (c.node != null) { //Is Leaf c.c1 = box; BBTreeBox box2 = new BBTreeBox (this,c.node); //Console.WriteLine ("Inserted "+box.node+", rect "+box.rect.ToString ()); c.c2 = box2; c.node = null; //c.rect = c.rect. return; } else { float e1 = ExpansionRequired (c.c1.rect,box.rect); float e2 = ExpansionRequired (c.c2.rect,box.rect); //Choose the rect requiring the least expansion to contain box.rect if (e1 < e2) { c = c.c1; } else if (e2 < e1) { c = c.c2; } else { //Equal, Choose the one with the smallest area c = RectArea (c.c1.rect) < RectArea (c.c2.rect) ? c.c1 : c.c2; } } } } void OnDrawGizmos (BBTreeBox box) { if (box == null) { return; } Vector3 min = new Vector3 (box.rect.xMin,0,box.rect.yMin); Vector3 max = new Vector3 (box.rect.xMax,0,box.rect.yMax); Vector3 center = (min+max)*0.5F; Vector3 size = (max-center)*2; Gizmos.DrawCube (center,size); OnDrawGizmos (box.c1); OnDrawGizmos (box.c2); } public void OnDrawGizmos () { //Gizmos.color = new Color (1,1,1,0.01F); //OnDrawGizmos (root); } #endif /*static void TestIntersections (BBTreeBox box, Vector3 p, float radius) { if (box == null) { return; } RectIntersectsCircle (box.rect,p,radius); TestIntersections (box.c1,p,radius); TestIntersections (box.c2,p,radius); }*/ static bool NodeIntersectsCircle (MeshNode node, Vector3 p, float radius) { if (float.IsPositiveInfinity(radius)) return true; /** \bug Is not correct on the Y axis */ /*if (node.ContainsPoint ((Int3)p)) { return true; }*/ return (p - node.ClosestPointOnNode (p)).sqrMagnitude < radius*radius; /*Int3[] vertices = graph.vertices; Vector3 p1 = (Vector3)vertices[node[0]], p2 = (Vector3)vertices[node[1]], p3 = (Vector3)vertices[node[2]]; float r2 = radius*radius; p1.y = p.y; p2.y = p.y; p3.y = p.y; return Mathfx.DistancePointSegmentStrict (p1,p2,p) < r2 || Mathfx.DistancePointSegmentStrict (p2,p3,p) < r2 || Mathfx.DistancePointSegmentStrict (p3,p1,p) < r2;*/ } /** Returns true if \a p is within \a radius from \a r. * Correctly handles cases where \a radius is positive infinity. */ static bool RectIntersectsCircle (Rect r, Vector3 p, float radius) { if (float.IsPositiveInfinity(radius)) return true; Vector3 po = p; p.x = System.Math.Max (p.x, r.xMin); p.x = System.Math.Min (p.x, r.xMax); p.z = System.Math.Max (p.z, r.yMin); p.z = System.Math.Min (p.z, r.yMax); // XZ squared magnitude comparison return (p.x-po.x)*(p.x-po.x) + (p.z-po.z)*(p.z-po.z) < radius*radius; } /** Returns if a rect contains the 3D point in XZ space */ static bool RectContains (Rect r, Vector3 p) { return p.x >= r.xMin && p.x <= r.xMax && p.z >= r.yMin && p.z <= r.yMax; } /** Returns the difference in area between \a r and \a r expanded to contain \a r2 */ static float ExpansionRequired (Rect r, Rect r2) { float xMin = System.Math.Min (r.xMin,r2.xMin); float xMax = System.Math.Max (r.xMax,r2.xMax); float yMin = System.Math.Min (r.yMin,r2.yMin); float yMax = System.Math.Max (r.yMax,r2.yMax); return (xMax-xMin)*(yMax-yMin)-RectArea (r); } /** Returns a new rect which contains both \a r and \a r2 */ static Rect ExpandToContain (Rect r, Rect r2) { float xMin = System.Math.Min (r.xMin,r2.xMin); float xMax = System.Math.Max (r.xMax,r2.xMax); float yMin = System.Math.Min (r.yMin,r2.yMin); float yMax = System.Math.Max (r.yMax,r2.yMax); return Rect.MinMaxRect (xMin,yMin,xMax,yMax); } /** Returns the area of a rect */ static float RectArea (Rect r) { return r.width*r.height; } #if ASTAR_OLD_BBTREE public new void ToString () { Console.WriteLine ("Root "+(root.node != null ? root.node.ToString () : "")); BBTreeBox c = root; Stack<BBTreeBox> stack = new Stack<BBTreeBox>(); stack.Push (c); c.WriteChildren (0); } #else #endif } #if ASTAR_OLD_BBTREE class BBTreeBox { public Rect rect; public MeshNode node; public BBTreeBox c1; public BBTreeBox c2; public BBTreeBox (BBTree tree, MeshNode node) { this.node = node; Vector3 first = (Vector3)node.GetVertex(0); Vector2 min = new Vector2(first.x,first.z); Vector2 max = min; for (int i=1;i<node.GetVertexCount();i++) { Vector3 p = (Vector3)node.GetVertex(i); min.x = Mathf.Min (min.x,p.x); min.y = Mathf.Min (min.y,p.z); max.x = Mathf.Max (max.x,p.x); max.y = Mathf.Max (max.y,p.z); } rect = Rect.MinMaxRect (min.x,min.y,max.x,max.y); } public bool Contains (Vector3 p) { return rect.Contains (p); } public void WriteChildren (int level) { for (int i=0;i<level;i++) { Console.Write (" "); } if (node != null) { Console.WriteLine ("Leaf ");//+triangle.ToString ()); } else { Console.WriteLine ("Box ");//+rect.ToString ()); c1.WriteChildren (level+1); c2.WriteChildren (level+1); } } } #endif }
//----------------------------------------------------------------------- // <copyright file="Timed.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using static Akka.Streams.Extra.Timed; namespace Akka.Streams.Extra { /// <summary> /// INTERNAL API /// /// Provides operations needed to implement the <see cref="TimedFlowDsl"/> and <see cref="TimedSourceDsl"/> /// </summary> internal static class TimedOps { /// <summary> /// INTERNAL API /// /// Measures time from receiving the first element and completion events - one for each subscriber of this <see cref="IFlow{TOut,TMat}"/>. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <typeparam name="TMat2">TBD</typeparam> /// <param name="source">TBD</param> /// <param name="measuredOps">TBD</param> /// <param name="onComplete">TBD</param> /// <returns>TBD</returns> public static Source<TOut, TMat2> Timed<TIn, TOut, TMat, TMat2>(Source<TIn, TMat> source, Func<Source<TIn, TMat>, Source<TOut, TMat2>> measuredOps, Action<TimeSpan> onComplete) { var ctx = new TimedFlowContext(); var startTimed = Flow.Create<TIn>().Via(new StartTimed<TIn>(ctx)).Named("startTimed"); var stopTimed = Flow.Create<TOut>().Via(new StopTime<TOut>(ctx, onComplete)).Named("stopTimed"); return measuredOps(source.Via(startTimed)).Via(stopTimed); } /// <summary> /// INTERNAL API /// /// Measures time from receiving the first element and completion events - one for each subscriber of this <see cref="IFlow{TOut,TMat}"/>. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> /// <typeparam name="TOut2">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <typeparam name="TMat2">TBD</typeparam> /// <param name="flow">TBD</param> /// <param name="measuredOps">TBD</param> /// <param name="onComplete">TBD</param> /// <returns>TBD</returns> public static Flow<TIn, TOut2, TMat2> Timed<TIn, TOut, TOut2, TMat, TMat2>(Flow<TIn, TOut, TMat> flow, Func<Flow<TIn, TOut, TMat>, Flow<TIn, TOut2, TMat2>> measuredOps, Action<TimeSpan> onComplete) { // todo is there any other way to provide this for Flow, without duplicating impl? // they do share a super-type (FlowOps), but all operations of FlowOps return path dependant type var ctx = new TimedFlowContext(); var startTimed = Flow.Create<TOut>().Via(new StartTimed<TOut>(ctx)).Named("startTimed"); var stopTimed = Flow.Create<TOut2>().Via(new StopTime<TOut2>(ctx, onComplete)).Named("stopTimed"); return measuredOps(flow.Via(startTimed)).Via(stopTimed); } } /// <summary> /// INTERNAL API /// /// Provides operations needed to implement the <see cref="TimedFlowDsl"/> and <see cref="TimedSourceDsl"/> /// </summary> internal static class TimedIntervalBetweenOps { /// <summary> /// INTERNAL API /// /// Measures rolling interval between immediately subsequent `matching(o: O)` elements. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <param name="flow">TBD</param> /// <param name="matching">TBD</param> /// <param name="onInterval">TBD</param> /// <returns>TBD</returns> public static IFlow<TIn, TMat> TimedIntervalBetween<TIn, TMat>(IFlow<TIn, TMat> flow, Func<TIn, bool> matching, Action<TimeSpan> onInterval) { var timedInterval = Flow.Create<TIn>() .Via(new TimedInterval<TIn>(matching, onInterval)) .Named("timedInterval"); return flow.Via(timedInterval); } } /// <summary> /// TBD /// </summary> internal static class Timed { /// <summary> /// TBD /// </summary> internal sealed class TimedFlowContext { private readonly Stopwatch _stopwatch = new Stopwatch(); /// <summary> /// TBD /// </summary> public void Start() => _stopwatch.Start(); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public TimeSpan Stop() { _stopwatch.Stop(); return _stopwatch.Elapsed; } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class StartTimed<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly StartTimed<T> _stage; private bool _started; public Logic(StartTimed<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() { if (!_started) { _stage._timedContext.Start(); _started = true; } Push(_stage.Outlet, Grab(_stage.Inlet)); } public override void OnPull() => Pull(_stage.Inlet); } #endregion private readonly TimedFlowContext _timedContext; /// <summary> /// TBD /// </summary> /// <param name="timedContext">TBD</param> public StartTimed(TimedFlowContext timedContext) { _timedContext = timedContext; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class StopTime<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly StopTime<T> _stage; public Logic(StopTime<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet)); public override void OnUpstreamFinish() { StopTime(); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { StopTime(); FailStage(e); } public override void OnPull() => Pull(_stage.Inlet); private void StopTime() { var d = _stage._timedContext.Stop(); _stage._onComplete(d); } } #endregion private readonly TimedFlowContext _timedContext; private readonly Action<TimeSpan> _onComplete; /// <summary> /// TBD /// </summary> /// <param name="timedContext">TBD</param> /// <param name="onComplete">TBD</param> public StopTime(TimedFlowContext timedContext, Action<TimeSpan> onComplete) { _timedContext = timedContext; _onComplete = onComplete; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class TimedInterval<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly TimedInterval<T> _stage; private long _previousTicks; private long _matched; public Logic(TimedInterval<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() { var element = Grab(_stage.Inlet); if (_stage._matching(element)) { var d = UpdateInterval(); if (_matched > 1) _stage._onInterval(d); } Push(_stage.Outlet, element); } public override void OnPull() => Pull(_stage.Inlet); private TimeSpan UpdateInterval() { _matched += 1; var nowTicks = DateTime.Now.Ticks; var d = nowTicks - _previousTicks; _previousTicks = nowTicks; return TimeSpan.FromTicks(d); } } #endregion private readonly Func<T, bool> _matching; private readonly Action<TimeSpan> _onInterval; /// <summary> /// TBD /// </summary> /// <param name="matching">TBD</param> /// <param name="onInterval">TBD</param> public TimedInterval(Func<T, bool> matching, Action<TimeSpan> onInterval) { _matching = matching; _onInterval = onInterval; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Codecs.Lucene45 { /* * 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 BlockPackedWriter = YAF.Lucene.Net.Util.Packed.BlockPackedWriter; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FieldInfo = YAF.Lucene.Net.Index.FieldInfo; using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames; using IndexOutput = YAF.Lucene.Net.Store.IndexOutput; using IOUtils = YAF.Lucene.Net.Util.IOUtils; using MathUtil = YAF.Lucene.Net.Util.MathUtil; using MonotonicBlockPackedWriter = YAF.Lucene.Net.Util.Packed.MonotonicBlockPackedWriter; using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s; using RAMOutputStream = YAF.Lucene.Net.Store.RAMOutputStream; using SegmentWriteState = YAF.Lucene.Net.Index.SegmentWriteState; using StringHelper = YAF.Lucene.Net.Util.StringHelper; /// <summary> /// Writer for <see cref="Lucene45DocValuesFormat"/> </summary> public class Lucene45DocValuesConsumer : DocValuesConsumer, IDisposable { internal static readonly int BLOCK_SIZE = 16384; internal static readonly int ADDRESS_INTERVAL = 16; internal static readonly long MISSING_ORD = -1L; /// <summary> /// Compressed using packed blocks of <see cref="int"/>s. </summary> public const int DELTA_COMPRESSED = 0; /// <summary> /// Compressed by computing the GCD. </summary> public const int GCD_COMPRESSED = 1; /// <summary> /// Compressed by giving IDs to unique values. </summary> public const int TABLE_COMPRESSED = 2; /// <summary> /// Uncompressed binary, written directly (fixed length). </summary> public const int BINARY_FIXED_UNCOMPRESSED = 0; /// <summary> /// Uncompressed binary, written directly (variable length). </summary> public const int BINARY_VARIABLE_UNCOMPRESSED = 1; /// <summary> /// Compressed binary with shared prefixes </summary> public const int BINARY_PREFIX_COMPRESSED = 2; /// <summary> /// Standard storage for sorted set values with 1 level of indirection: /// docId -> address -> ord. /// </summary> public static readonly int SORTED_SET_WITH_ADDRESSES = 0; /// <summary> /// Single-valued sorted set values, encoded as sorted values, so no level /// of indirection: docId -> ord. /// </summary> public static readonly int SORTED_SET_SINGLE_VALUED_SORTED = 1; internal IndexOutput data, meta; internal readonly int maxDoc; /// <summary> /// Expert: Creates a new writer. </summary> public Lucene45DocValuesConsumer(SegmentWriteState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension) { bool success = false; try { string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension); data = state.Directory.CreateOutput(dataName, state.Context); CodecUtil.WriteHeader(data, dataCodec, Lucene45DocValuesFormat.VERSION_CURRENT); string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension); meta = state.Directory.CreateOutput(metaName, state.Context); CodecUtil.WriteHeader(meta, metaCodec, Lucene45DocValuesFormat.VERSION_CURRENT); maxDoc = state.SegmentInfo.DocCount; success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(this); } } } public override void AddNumericField(FieldInfo field, IEnumerable<long?> values) { AddNumericField(field, values, true); } internal virtual void AddNumericField(FieldInfo field, IEnumerable<long?> values, bool optimizeStorage) { long count = 0; long minValue = long.MaxValue; long maxValue = long.MinValue; long gcd = 0; bool missing = false; // TODO: more efficient? JCG.HashSet<long> uniqueValues = null; if (optimizeStorage) { uniqueValues = new JCG.HashSet<long>(); foreach (long? nv in values) { long v; if (nv == null) { v = 0; missing = true; } else { v = nv.Value; } if (gcd != 1) { if (v < long.MinValue / 2 || v > long.MaxValue / 2) { // in that case v - minValue might overflow and make the GCD computation return // wrong results. Since these extreme values are unlikely, we just discard // GCD computation for them gcd = 1; } // minValue needs to be set first else if (count != 0) { gcd = MathUtil.Gcd(gcd, v - minValue); } } minValue = Math.Min(minValue, v); maxValue = Math.Max(maxValue, v); if (uniqueValues != null) { if (uniqueValues.Add(v)) { if (uniqueValues.Count > 256) { uniqueValues = null; } } } ++count; } } else { foreach (var nv in values) { ++count; } } long delta = maxValue - minValue; int format; if (uniqueValues != null && (delta < 0L || PackedInt32s.BitsRequired(uniqueValues.Count - 1) < PackedInt32s.BitsRequired(delta)) && count <= int.MaxValue) { format = TABLE_COMPRESSED; } else if (gcd != 0 && gcd != 1) { format = GCD_COMPRESSED; } else { format = DELTA_COMPRESSED; } meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.NUMERIC); meta.WriteVInt32(format); if (missing) { meta.WriteInt64(data.GetFilePointer()); WriteMissingBitset(values); } else { meta.WriteInt64(-1L); } meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); meta.WriteInt64(data.GetFilePointer()); meta.WriteVInt64(count); meta.WriteVInt32(BLOCK_SIZE); switch (format) { case GCD_COMPRESSED: meta.WriteInt64(minValue); meta.WriteInt64(gcd); BlockPackedWriter quotientWriter = new BlockPackedWriter(data, BLOCK_SIZE); foreach (long? nv in values) { quotientWriter.Add((nv.GetValueOrDefault() - minValue) / gcd); } quotientWriter.Finish(); break; case DELTA_COMPRESSED: BlockPackedWriter writer = new BlockPackedWriter(data, BLOCK_SIZE); foreach (long? nv in values) { writer.Add(nv.GetValueOrDefault()); } writer.Finish(); break; case TABLE_COMPRESSED: // LUCENENET NOTE: diming an array and then using .CopyTo() for better efficiency than LINQ .ToArray() long[] decode = new long[uniqueValues.Count]; uniqueValues.CopyTo(decode, 0); Dictionary<long, int> encode = new Dictionary<long, int>(); meta.WriteVInt32(decode.Length); for (int i = 0; i < decode.Length; i++) { meta.WriteInt64(decode[i]); encode[decode[i]] = i; } int bitsRequired = PackedInt32s.BitsRequired(uniqueValues.Count - 1); PackedInt32s.Writer ordsWriter = PackedInt32s.GetWriterNoHeader(data, PackedInt32s.Format.PACKED, (int)count, bitsRequired, PackedInt32s.DEFAULT_BUFFER_SIZE); foreach (long? nv in values) { ordsWriter.Add(encode[nv.GetValueOrDefault()]); } ordsWriter.Finish(); break; default: throw new InvalidOperationException(); } } // TODO: in some cases representing missing with minValue-1 wouldn't take up additional space and so on, // but this is very simple, and algorithms only check this for values of 0 anyway (doesnt slow down normal decode) internal virtual void WriteMissingBitset(IEnumerable values) { sbyte bits = 0; int count = 0; foreach (object v in values) { if (count == 8) { data.WriteByte((byte)bits); count = 0; bits = 0; } if (v != null) { bits |= (sbyte)(1 << (count & 7)); } count++; } if (count > 0) { data.WriteByte((byte)bits); } } public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values) { // write the byte[] data meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.BINARY); int minLength = int.MaxValue; int maxLength = int.MinValue; long startFP = data.GetFilePointer(); long count = 0; bool missing = false; foreach (BytesRef v in values) { int length; if (v == null) { length = 0; missing = true; } else { length = v.Length; } minLength = Math.Min(minLength, length); maxLength = Math.Max(maxLength, length); if (v != null) { data.WriteBytes(v.Bytes, v.Offset, v.Length); } count++; } meta.WriteVInt32(minLength == maxLength ? BINARY_FIXED_UNCOMPRESSED : BINARY_VARIABLE_UNCOMPRESSED); if (missing) { meta.WriteInt64(data.GetFilePointer()); WriteMissingBitset(values); } else { meta.WriteInt64(-1L); } meta.WriteVInt32(minLength); meta.WriteVInt32(maxLength); meta.WriteVInt64(count); meta.WriteInt64(startFP); // if minLength == maxLength, its a fixed-length byte[], we are done (the addresses are implicit) // otherwise, we need to record the length fields... if (minLength != maxLength) { meta.WriteInt64(data.GetFilePointer()); meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); meta.WriteVInt32(BLOCK_SIZE); MonotonicBlockPackedWriter writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE); long addr = 0; foreach (BytesRef v in values) { if (v != null) { addr += v.Length; } writer.Add(addr); } writer.Finish(); } } /// <summary> /// Expert: writes a value dictionary for a sorted/sortedset field. </summary> protected virtual void AddTermsDict(FieldInfo field, IEnumerable<BytesRef> values) { // first check if its a "fixed-length" terms dict int minLength = int.MaxValue; int maxLength = int.MinValue; foreach (BytesRef v in values) { minLength = Math.Min(minLength, v.Length); maxLength = Math.Max(maxLength, v.Length); } if (minLength == maxLength) { // no index needed: direct addressing by mult AddBinaryField(field, values); } else { // header meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.BINARY); meta.WriteVInt32(BINARY_PREFIX_COMPRESSED); meta.WriteInt64(-1L); // now write the bytes: sharing prefixes within a block long startFP = data.GetFilePointer(); // currently, we have to store the delta from expected for every 1/nth term // we could avoid this, but its not much and less overall RAM than the previous approach! RAMOutputStream addressBuffer = new RAMOutputStream(); MonotonicBlockPackedWriter termAddresses = new MonotonicBlockPackedWriter(addressBuffer, BLOCK_SIZE); BytesRef lastTerm = new BytesRef(); long count = 0; foreach (BytesRef v in values) { if (count % ADDRESS_INTERVAL == 0) { termAddresses.Add(data.GetFilePointer() - startFP); // force the first term in a block to be abs-encoded lastTerm.Length = 0; } // prefix-code int sharedPrefix = StringHelper.BytesDifference(lastTerm, v); data.WriteVInt32(sharedPrefix); data.WriteVInt32(v.Length - sharedPrefix); data.WriteBytes(v.Bytes, v.Offset + sharedPrefix, v.Length - sharedPrefix); lastTerm.CopyBytes(v); count++; } long indexStartFP = data.GetFilePointer(); // write addresses of indexed terms termAddresses.Finish(); addressBuffer.WriteTo(data); addressBuffer = null; termAddresses = null; meta.WriteVInt32(minLength); meta.WriteVInt32(maxLength); meta.WriteVInt64(count); meta.WriteInt64(startFP); meta.WriteVInt32(ADDRESS_INTERVAL); meta.WriteInt64(indexStartFP); meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); meta.WriteVInt32(BLOCK_SIZE); } } public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd) { meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.SORTED); AddTermsDict(field, values); AddNumericField(field, docToOrd, false); } private static bool IsSingleValued(IEnumerable<long?> docToOrdCount) { return docToOrdCount.All(ordCount => ordCount <= 1); } public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords) { meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.SORTED_SET); if (IsSingleValued(docToOrdCount)) { meta.WriteVInt32(SORTED_SET_SINGLE_VALUED_SORTED); // The field is single-valued, we can encode it as SORTED AddSortedField(field, values, GetSortedSetEnumerable(docToOrdCount, ords)); return; } meta.WriteVInt32(SORTED_SET_WITH_ADDRESSES); // write the ord -> byte[] as a binary field AddTermsDict(field, values); // write the stream of ords as a numeric field // NOTE: we could return an iterator that delta-encodes these within a doc AddNumericField(field, ords, false); // write the doc -> ord count as a absolute index to the stream meta.WriteVInt32(field.Number); meta.WriteByte((byte)Lucene45DocValuesFormat.NUMERIC); meta.WriteVInt32(DELTA_COMPRESSED); meta.WriteInt64(-1L); meta.WriteVInt32(PackedInt32s.VERSION_CURRENT); meta.WriteInt64(data.GetFilePointer()); meta.WriteVInt64(maxDoc); meta.WriteVInt32(BLOCK_SIZE); var writer = new MonotonicBlockPackedWriter(data, BLOCK_SIZE); long addr = 0; foreach (long? v in docToOrdCount) { addr += v.Value; writer.Add(addr); } writer.Finish(); } private IEnumerable<long?> GetSortedSetEnumerable(IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords) { IEnumerator<long?> docToOrdCountIter = docToOrdCount.GetEnumerator(); IEnumerator<long?> ordsIter = ords.GetEnumerator(); const long MISSING_ORD = -1; while (docToOrdCountIter.MoveNext()) { long current = docToOrdCountIter.Current.Value; if (current == 0) { yield return MISSING_ORD; } else { Debug.Assert(current == 1); ordsIter.MoveNext(); yield return ordsIter.Current; } } Debug.Assert(!ordsIter.MoveNext()); } protected override void Dispose(bool disposing) { if (disposing) { bool success = false; try { if (meta != null) { meta.WriteVInt32(-1); // write EOF marker CodecUtil.WriteFooter(meta); // write checksum } if (data != null) { CodecUtil.WriteFooter(data); // write checksum } success = true; } finally { if (success) { IOUtils.Dispose(data, meta); } else { IOUtils.DisposeWhileHandlingException(data, meta); } meta = data = null; } } } } }
using System; using System.Collections; using T = GuruComponents.CodeEditor.CodeEditor.Syntax.Pattern; namespace GuruComponents.CodeEditor.CodeEditor.Syntax { /// <summary> /// /// </summary> public sealed class PatternCollection : ICollection, IList, IEnumerable, ICloneable { private const int DefaultMinimumCapacity = 16; private T[] m_array = new T[DefaultMinimumCapacity]; private int m_count = 0; private int m_version = 0; // Construction /// <summary> /// /// </summary> public PatternCollection() { } /// <summary> /// /// </summary> /// <param name="collection"></param> public PatternCollection(PatternCollection collection) { AddRange(collection); } /// <summary> /// /// </summary> /// <param name="array"></param> public PatternCollection(T[] array) { AddRange(array); } // Operations (type-safe ICollection) /// <summary> /// /// </summary> public int Count { get { return m_count; } } /// <summary> /// /// </summary> /// <param name="array"></param> public void CopyTo(T[] array) { this.CopyTo(array, 0); } /// <summary> /// /// </summary> /// <param name="array"></param> /// <param name="start"></param> public void CopyTo(T[] array, int start) { if (m_count > array.GetUpperBound(0) + 1 - start) throw new ArgumentException("Destination array was not long enough."); // for (int i=0; i < m_count; ++i) array[start+i] = m_array[i]; Array.Copy(m_array, 0, array, start, m_count); } // Operations (type-safe IList) /// <summary> /// /// </summary> public T this[int index] { get { ValidateIndex(index); // throws return m_array[index]; } set { ValidateIndex(index); // throws ++m_version; m_array[index] = value; } } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public int Add(T item) { if (NeedsGrowth()) Grow(); ++m_version; m_array[m_count] = item; return m_count++; } /// <summary> /// /// </summary> public void Clear() { ++m_version; m_array = new T[DefaultMinimumCapacity]; m_count = 0; } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(T item) { return ((IndexOf(item) == -1) ? false : true); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <returns></returns> public int IndexOf(T item) { for (int i = 0; i < m_count; ++i) if (m_array[i] == (item)) return i; return -1; } /// <summary> /// /// </summary> /// <param name="position"></param> /// <param name="item"></param> public void Insert(int position, T item) { ValidateIndex(position, true); // throws if (NeedsGrowth()) Grow(); ++m_version; // for (int i=m_count; i > position; --i) m_array[i] = m_array[i-1]; Array.Copy(m_array, position, m_array, position + 1, m_count - position); m_array[position] = item; m_count++; } /// <summary> /// /// </summary> /// <param name="item"></param> public void Remove(T item) { int index = IndexOf(item); if (index < 0) throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection."); RemoveAt(index); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { ValidateIndex(index); // throws ++m_version; m_count--; // for (int i=index; i < m_count; ++i) m_array[i] = m_array[i+1]; Array.Copy(m_array, index + 1, m_array, index, m_count - index); if (NeedsTrimming()) Trim(); } // Operations (type-safe IEnumerable) /// <summary> /// /// </summary> /// <returns></returns> public Enumerator GetEnumerator() { return new Enumerator(this); } // Operations (type-safe ICloneable) /// <summary> /// /// </summary> /// <returns></returns> public PatternCollection Clone() { PatternCollection tc = new PatternCollection(); tc.AddRange(this); tc.Capacity = this.m_array.Length; tc.m_version = this.m_version; return tc; } // Public helpers (just to mimic some nice features of ArrayList) /// <summary> /// /// </summary> public int Capacity { get { return m_array.Length; } set { if (value < m_count) value = m_count; if (value < DefaultMinimumCapacity) value = DefaultMinimumCapacity; if (m_array.Length == value) return; ++m_version; T[] temp = new T[value]; // for (int i=0; i < m_count; ++i) temp[i] = m_array[i]; Array.Copy(m_array, 0, temp, 0, m_count); m_array = temp; } } /// <summary> /// /// </summary> /// <param name="collection"></param> public void AddRange(PatternCollection collection) { // for (int i=0; i < collection.Count; ++i) Add(collection[i]); ++m_version; Capacity += collection.Count; Array.Copy(collection.m_array, 0, this.m_array, m_count, collection.m_count); m_count += collection.Count; } /// <summary> /// /// </summary> /// <param name="array"></param> public void AddRange(T[] array) { // for (int i=0; i < array.Length; ++i) Add(array[i]); ++m_version; Capacity += array.Length; Array.Copy(array, 0, this.m_array, m_count, array.Length); m_count += array.Length; } // Implementation (helpers) private void ValidateIndex(int index) { ValidateIndex(index, false); } private void ValidateIndex(int index, bool allowEqualEnd) { int max = (allowEqualEnd) ? (m_count) : (m_count - 1); if (index < 0 || index > max) throw new ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection.", (object) index, "Specified argument was out of the range of valid values."); } private bool NeedsGrowth() { return (m_count >= Capacity); } private void Grow() { if (NeedsGrowth()) Capacity = m_count*2; } private bool NeedsTrimming() { return (m_count <= Capacity/2); } private void Trim() { if (NeedsTrimming()) Capacity = m_count; } // Implementation (ICollection) /* redundant w/ type-safe method int ICollection.Count { get { return m_count; } } */ bool ICollection.IsSynchronized { get { return m_array.IsSynchronized; } } object ICollection.SyncRoot { get { return m_array.SyncRoot; } } void ICollection.CopyTo(Array array, int start) { this.CopyTo((T[]) array, start); } // Implementation (IList) bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this[int index] { get { return (object) this[index]; } set { this[index] = (T) value; } } int IList.Add(object item) { return this.Add((T) item); } /* redundant w/ type-safe method void IList.Clear() { this.Clear(); } */ bool IList.Contains(object item) { return this.Contains((T) item); } int IList.IndexOf(object item) { return this.IndexOf((T) item); } void IList.Insert(int position, object item) { this.Insert(position, (T) item); } void IList.Remove(object item) { this.Remove((T) item); } /* redundant w/ type-safe method void IList.RemoveAt(int index) { this.RemoveAt(index); } */ // Implementation (IEnumerable) IEnumerator IEnumerable.GetEnumerator() { return (IEnumerator) (this.GetEnumerator()); } // Implementation (ICloneable) object ICloneable.Clone() { return (object) (this.Clone()); } // Nested enumerator class /// <summary> /// /// </summary> public class Enumerator : IEnumerator { private PatternCollection m_collection; private int m_index; private int m_version; // Construction public Enumerator(PatternCollection tc) { m_collection = tc; m_index = -1; m_version = tc.m_version; } // Operations (type-safe IEnumerator) /// <summary> /// /// </summary> public T Current { get { return m_collection[m_index]; } } /// <summary> /// /// </summary> /// <returns></returns> public bool MoveNext() { if (m_version != m_collection.m_version) throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); ++m_index; return (m_index < m_collection.Count) ? true : false; } /// <summary> /// /// </summary> public void Reset() { if (m_version != m_collection.m_version) throw new InvalidOperationException("Collection was modified; enumeration operation may not execute."); m_index = -1; } // Implementation (IEnumerator) object IEnumerator.Current { get { return (object) (this.Current); } } /* redundant w/ type-safe method bool IEnumerator.MoveNext() { return this.MoveNext(); } */ /* redundant w/ type-safe method void IEnumerator.Reset() { this.Reset(); } */ } } }
using System; using NTumbleBit.BouncyCastle.Security; namespace NTumbleBit.BouncyCastle.Crypto.Paddings { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion with padding. The PaddedBufferedBlockCipher * outputs a block only when the buffer is full and more data is being added, * or on a doFinal (unless the current block in the buffer is a pad block). * The default padding mechanism used is the one outlined in Pkcs5/Pkcs7. */ internal class PaddedBufferedBlockCipher : BufferedBlockCipher { private readonly IBlockCipherPadding padding; /** * Create a buffered block cipher with the desired padding. * * @param cipher the underlying block cipher this buffering object wraps. * @param padding the padding type. */ public PaddedBufferedBlockCipher( IBlockCipher cipher, IBlockCipherPadding padding) { this.cipher = cipher; this.padding = padding; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } /** * Create a buffered block cipher Pkcs7 padding * * @param cipher the underlying block cipher this buffering object wraps. */ public PaddedBufferedBlockCipher( IBlockCipher cipher) : this(cipher, new Pkcs7Padding()) { } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; Reset(); padding.Init(); cipher.Init(forEncryption, parameters); } /** * return the minimum size of the output buffer required for an update * plus a doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if(leftOver == 0) { if(forEncryption) { return total + buf.Length; } return total; } return total - leftOver + buf.Length; } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; if(leftOver == 0) { return total - buf.Length; } return total - leftOver; } /** * process a single byte, producing an output block if necessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { int resultLen = 0; if(bufOff == buf.Length) { resultLen = cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; } buf[bufOff++] = input; return resultLen; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if(length < 0) { throw new ArgumentException("Can't have a negative input length!"); } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if(outLength > 0) { Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; int gapLen = buf.Length - bufOff; if(length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while(length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; return resultLen; } /** * Process the last block in the buffer. If the buffer is currently * full and padding needs to be added a call to doFinal will produce * 2 * GetBlockSize() bytes. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output or we are decrypting and the input is not block size aligned. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. */ public override int DoFinal( byte[] output, int outOff) { int blockSize = cipher.GetBlockSize(); int resultLen = 0; if(forEncryption) { if(bufOff == blockSize) { if((outOff + 2 * blockSize) > output.Length) { Reset(); throw new OutputLengthException("output buffer too short"); } resultLen = cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; } padding.AddPadding(buf, bufOff); resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); Reset(); } else { if(bufOff == blockSize) { resultLen = cipher.ProcessBlock(buf, 0, buf, 0); bufOff = 0; } else { Reset(); throw new DataLengthException("last block incomplete in decryption"); } try { resultLen -= padding.PadCount(buf); Array.Copy(buf, 0, output, outOff, resultLen); } finally { Reset(); } } return resultLen; } } }
// // 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 Encog.ML.Data; using Encog.Util; namespace Encog.Neural.Networks.Training.Propagation.Resilient { /// <summary> /// One problem with the backpropagation algorithm is that the magnitude of the /// partial derivative is usually too large or too small. Further, the learning /// rate is a single value for the entire neural network. The resilient /// propagation learning algorithm uses a special update value(similar to the /// learning rate) for every neuron connection. Further these update values are /// automatically determined, unlike the learning rate of the backpropagation /// algorithm. /// For most training situations, we suggest that the resilient propagation /// algorithm (this class) be used for training. /// There are a total of three parameters that must be provided to the resilient /// training algorithm. Defaults are provided for each, and in nearly all cases, /// these defaults are acceptable. This makes the resilient propagation algorithm /// one of the easiest and most efficient training algorithms available. /// The optional parameters are: /// zeroTolerance - How close to zero can a number be to be considered zero. The /// default is 0.00000000000000001. /// initialUpdate - What are the initial update values for each matrix value. The /// default is 0.1. /// maxStep - What is the largest amount that the update values can step. The /// default is 50. /// Usually you will not need to use these, and you should use the constructor /// that does not require them. /// </summary> /// public class ResilientPropagation : Propagation { /// <summary> /// Continuation tag for the last gradients. /// </summary> /// public const String LastGradientsConst = "LAST_GRADIENTS"; /// <summary> /// Continuation tag for the last values. /// </summary> /// public const String UpdateValuesConst = "UPDATE_VALUES"; /// <summary> /// The last deltas. /// </summary> private readonly double[] _lastDelta; /// <summary> /// The last weight changed. /// </summary> private readonly double[] _lastWeightChanged; /// <summary> /// The maximum step value for rprop. /// </summary> /// private readonly double _maxStep; /// <summary> /// The update values, for the weights and thresholds. /// </summary> /// private readonly double[] _updateValues; /// <summary> /// The zero tolerance. /// </summary> /// private readonly double _zeroTolerance; /// <summary> /// The last error. /// </summary> private double _lastError; /// <summary> /// Construct an RPROP trainer, allows an OpenCL device to be specified. Use /// the defaults for all training parameters. Usually this is the constructor /// to use as the resilient training algorithm is designed for the default /// parameters to be acceptable for nearly all problems. /// </summary> /// /// <param name="network">The network to train.</param> /// <param name="training">The training data to use.</param> public ResilientPropagation(IContainsFlat network, IMLDataSet training) : this(network, training, RPROPConst.DefaultInitialUpdate, RPROPConst.DefaultMaxStep) { } /// <summary> /// Construct a resilient training object, allow the training parameters to /// be specified. Usually the default parameters are acceptable for the /// resilient training algorithm. Therefore you should usually use the other /// constructor, that makes use of the default values. /// </summary> /// /// <param name="network">The network to train.</param> /// <param name="training">The training set to use.</param> /// <param name="initialUpdate"></param> /// <param name="maxStep">The maximum that a delta can reach.</param> public ResilientPropagation(IContainsFlat network, IMLDataSet training, double initialUpdate, double maxStep) : base(network, training) { _updateValues = new double[network.Flat.Weights.Length]; _zeroTolerance = RPROPConst.DefaultZeroTolerance; _maxStep = maxStep; _lastWeightChanged = new double[Network.Flat.Weights.Length]; _lastDelta = new double[Network.Flat.Weights.Length]; for (int i = 0; i < _updateValues.Length; i++) { _updateValues[i] = initialUpdate; } } /// <inheritdoc /> public override sealed bool CanContinue { get { return true; } } /// <summary> /// Determine if the specified continuation object is valid to resume with. /// </summary> /// /// <param name="state">The continuation object to check.</param> /// <returns>True if the specified continuation object is valid for this /// training method and network.</returns> public bool IsValidResume(TrainingContinuation state) { if (!state.Contents.ContainsKey( LastGradientsConst) || !state.Contents.ContainsKey( UpdateValuesConst)) { return false; } if (!state.TrainingType.Equals(GetType().Name)) { return false; } var d = (double[]) state.Get(LastGradientsConst); return d.Length == Network.Flat.Weights.Length; } /// <summary> /// Pause the training. /// </summary> /// /// <returns>A training continuation object to continue with.</returns> public override sealed TrainingContinuation Pause() { var result = new TrainingContinuation(); result.TrainingType = GetType().Name; result.Set(LastGradientsConst,LastGradient); result.Set(UpdateValuesConst,_updateValues); return result; } /// <summary> /// Resume training. /// </summary> /// /// <param name="state">The training state to return to.</param> public override sealed void Resume(TrainingContinuation state) { if (!IsValidResume(state)) { throw new TrainingError("Invalid training resume data length"); } var lastGradient = (double[]) state.Get(LastGradientsConst); var updateValues = (double[]) state.Get(UpdateValuesConst); EngineArray.ArrayCopy(lastGradient,LastGradient); EngineArray.ArrayCopy(updateValues,_updateValues); } /// <summary> /// The type of RPROP to use. /// </summary> public RPROPType RType { get; set; } /// <value>The RPROP update values.</value> public double[] UpdateValues { get { return _updateValues; } } /// <summary> /// Determine the sign of the value. /// </summary> /// /// <param name="v">The value to check.</param> /// <returns>-1 if less than zero, 1 if greater, or 0 if zero.</returns> private int Sign(double v) { if (Math.Abs(v) < _zeroTolerance) { return 0; } if (v > 0) { return 1; } return -1; } /// <summary> /// Calculate the amount to change the weight by. /// </summary> /// /// <param name="gradients">The gradients.</param> /// <param name="lastGradient">The last gradients.</param> /// <param name="index">The index to update.</param> /// <returns>The amount to change the weight by.</returns> public override double UpdateWeight(double[] gradients, double[] lastGradient, int index) { double weightChange = 0; switch (RType) { case RPROPType.RPROPp: weightChange = UpdateWeightPlus(gradients, lastGradient, index); break; case RPROPType.RPROPm: weightChange = UpdateWeightMinus(gradients, lastGradient, index); break; case RPROPType.iRPROPp: weightChange = UpdateiWeightPlus(gradients, lastGradient, index); break; case RPROPType.iRPROPm: weightChange = UpdateiWeightMinus(gradients, lastGradient, index); break; default: throw new TrainingError("Unknown RPROP type: " + RType); } _lastWeightChanged[index] = weightChange; return weightChange; } public double UpdateWeightPlus(double[] gradients, double[] lastGradient, int index) { // multiply the current and previous gradient, and take the // sign. We want to see if the gradient has changed its sign. int change = Sign(gradients[index] * lastGradient[index]); double weightChange = 0; // if the gradient has retained its sign, then we increase the // delta so that it will converge faster if (change > 0) { double delta = UpdateValues[index] * RPROPConst.PositiveEta; delta = Math.Min(delta, _maxStep); weightChange = Sign(gradients[index]) * delta; UpdateValues[index] = delta; lastGradient[index] = gradients[index]; } else if (change < 0) { // if change<0, then the sign has changed, and the last // delta was too big double delta = UpdateValues[index] * RPROPConst.NegativeEta; delta = Math.Max(delta, RPROPConst.DeltaMin); UpdateValues[index] = delta; weightChange = -_lastWeightChanged[index]; // set the previous gradent to zero so that there will be no // adjustment the next iteration lastGradient[index] = 0; } else if (change == 0) { // if change==0 then there is no change to the delta double delta = _updateValues[index]; weightChange = Sign(gradients[index]) * delta; lastGradient[index] = gradients[index]; } // apply the weight change, if any return weightChange; } public double UpdateWeightMinus(double[] gradients, double[] lastGradient, int index) { // multiply the current and previous gradient, and take the // sign. We want to see if the gradient has changed its sign. int change = Sign(gradients[index] * lastGradient[index]); double weightChange = 0; double delta; // if the gradient has retained its sign, then we increase the // delta so that it will converge faster if (change > 0) { delta = _lastDelta[index] * RPROPConst.PositiveEta; delta = Math.Min(delta, _maxStep); } else { // if change<0, then the sign has changed, and the last // delta was too big delta = _lastDelta[index] * RPROPConst.NegativeEta; delta = Math.Max(delta, RPROPConst.DeltaMin); } lastGradient[index] = gradients[index]; weightChange = Sign(gradients[index]) * delta; _lastDelta[index] = delta; // apply the weight change, if any return weightChange; } public double UpdateiWeightPlus(double[] gradients, double[] lastGradient, int index) { // multiply the current and previous gradient, and take the // sign. We want to see if the gradient has changed its sign. int change = Sign(gradients[index] * lastGradient[index]); double weightChange = 0; // if the gradient has retained its sign, then we increase the // delta so that it will converge faster if (change > 0) { double delta = _updateValues[index] * RPROPConst.PositiveEta; delta = Math.Min(delta, _maxStep); weightChange = Sign(gradients[index]) * delta; _updateValues[index] = delta; lastGradient[index] = gradients[index]; } else if (change < 0) { // if change<0, then the sign has changed, and the last // delta was too big double delta = UpdateValues[index] * RPROPConst.NegativeEta; delta = Math.Max(delta, RPROPConst.DeltaMin); UpdateValues[index] = delta; if (Error > _lastError) { weightChange = -_lastWeightChanged[index]; } // set the previous gradent to zero so that there will be no // adjustment the next iteration lastGradient[index] = 0; } else if (change == 0) { // if change==0 then there is no change to the delta double delta = _updateValues[index]; weightChange = Sign(gradients[index]) * delta; lastGradient[index] = gradients[index]; } // apply the weight change, if any return weightChange; } public double UpdateiWeightMinus(double[] gradients, double[] lastGradient, int index) { // multiply the current and previous gradient, and take the // sign. We want to see if the gradient has changed its sign. int change = Sign(gradients[index] * lastGradient[index]); double weightChange = 0; double delta; // if the gradient has retained its sign, then we increase the // delta so that it will converge faster if (change > 0) { delta = _lastDelta[index] * RPROPConst.PositiveEta; delta = Math.Min(delta, _maxStep); } else { // if change<0, then the sign has changed, and the last // delta was too big delta = _lastDelta[index] * RPROPConst.NegativeEta; delta = Math.Max(delta, RPROPConst.DeltaMin); lastGradient[index] = 0; } lastGradient[index] = gradients[index]; weightChange = Sign(gradients[index]) * delta; _lastDelta[index] = delta; // apply the weight change, if any return weightChange; } /// <summary> /// Not needed for this training type. /// </summary> public override void InitOthers() { } public override void PostIteration() { _lastError = Error; } } }
// 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.Text.RegularExpressions; using System.Globalization; using Xunit; public class RegexLangElementsCoverageTests { // This class mainly exists to hit language elements that were missed in other test cases. [Fact] public static void RegexLangElementsCoverage() { for (int i = 0; i < s_regexTests.Length; i++) { Assert.True(s_regexTests[i].Run()); } } //private const int GERMAN_PHONEBOOK = 0x10407; //private const int ENGLISH_US = 0x0409; //private const int INVARIANT = 0x007F; //private const int CZECH = 0x0405; //private const int DANISH = 0x0406; //private const int TURKISH = 0x041F; //private const int LATIN_AZERI = 0x042C; private static CultureInfo _GERMAN_PHONEBOOK = new CultureInfo("de-DE"); private static CultureInfo _ENGLISH_US = new CultureInfo("en-US"); private static CultureInfo _INVARIANT = new CultureInfo(""); private static CultureInfo _CZECH = new CultureInfo("cs-CZ"); private static CultureInfo _DANISH = new CultureInfo("da-DK"); private static CultureInfo _TURKISH = new CultureInfo("tr-TR"); private static CultureInfo _LATIN_AZERI = new CultureInfo("az-Latn-AZ"); private static RegexTestCase[] s_regexTests = new RegexTestCase[] { /********************************************************* Unicode Char Classes *********************************************************/ new RegexTestCase(@"(\p{Lu}\w*)\s(\p{Lu}\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\p{Lu}\p{Ll}*)\s(\p{Lu}\p{Ll}*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\P{Ll}\p{Ll}*)\s(\P{Ll}\p{Ll}*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"(\P{Lu}+\p{Lu})\s(\P{Lu}+\p{Lu})", "hellO worlD", new string[] {"hellO worlD", "hellO", "worlD"}), new RegexTestCase(@"(\p{Lt}\w*)\s(\p{Lt}*\w*)", "\u01C5ello \u01C5orld", new string[] {"\u01C5ello \u01C5orld", "\u01C5ello", "\u01C5orld"}), new RegexTestCase(@"(\P{Lt}\w*)\s(\P{Lt}*\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), /********************************************************* Character ranges IgnoreCase *********************************************************/ new RegexTestCase(@"[@-D]+", RegexOptions.IgnoreCase, "eE?@ABCDabcdeE", new string[] {"@ABCDabcd"}), new RegexTestCase(@"[>-D]+", RegexOptions.IgnoreCase, "eE=>?@ABCDabcdeE", new string[] {">?@ABCDabcd"}), new RegexTestCase(@"[\u0554-\u0557]+", RegexOptions.IgnoreCase, "\u0583\u0553\u0554\u0555\u0556\u0584\u0585\u0586\u0557\u0558", new string[] {"\u0554\u0555\u0556\u0584\u0585\u0586\u0557"}), new RegexTestCase(@"[X-\]]+", RegexOptions.IgnoreCase, "wWXYZxyz[\\]^", new string[] {"XYZxyz[\\]"}), new RegexTestCase(@"[X-\u0533]+", RegexOptions.IgnoreCase, "\u0551\u0554\u0560AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563\u0564", new string[] {"AXYZaxyz\u0531\u0532\u0533\u0561\u0562\u0563"}), new RegexTestCase(@"[X-a]+", RegexOptions.IgnoreCase, "wWAXYZaxyz", new string[] {"AXYZaxyz"}), new RegexTestCase(@"[X-c]+", RegexOptions.IgnoreCase, "wWABCXYZabcxyz", new string[] {"ABCXYZabcxyz"}), new RegexTestCase(@"[X-\u00C0]+", RegexOptions.IgnoreCase, "\u00C1\u00E1\u00C0\u00E0wWABCXYZabcxyz", new string[] {"\u00C0\u00E0wWABCXYZabcxyz"}), new RegexTestCase(@"[\u0100\u0102\u0104]+", RegexOptions.IgnoreCase, "\u00FF \u0100\u0102\u0104\u0101\u0103\u0105\u0106", new string[] {"\u0100\u0102\u0104\u0101\u0103\u0105"}), new RegexTestCase(@"[B-D\u0130]+", RegexOptions.IgnoreCase, "aAeE\u0129\u0131\u0068 BCDbcD\u0130\u0069\u0070", new string[] {"BCDbcD\u0130\u0069"}), new RegexTestCase(@"[\u013B\u013D\u013F]+", RegexOptions.IgnoreCase, "\u013A\u013B\u013D\u013F\u013C\u013E\u0140\u0141", new string[] {"\u013B\u013D\u013F\u013C\u013E\u0140"}), new RegexTestCase(@"[\uFFFD-\uFFFF]+", RegexOptions.IgnoreCase, "\uFFFC\uFFFD\uFFFE\uFFFF", new string[] {"\uFFFD\uFFFE\uFFFF"}), new RegexTestCase(@"[\uFFFC-\uFFFE]+", RegexOptions.IgnoreCase, "\uFFFB\uFFFC\uFFFD\uFFFE\uFFFF", new string[] {"\uFFFC\uFFFD\uFFFE"}), /********************************************************* Escape Chars *********************************************************/ new RegexTestCase("(Cat)\r(Dog)", "Cat\rDog", new string[] {"Cat\rDog", "Cat", "Dog"}), new RegexTestCase("(Cat)\t(Dog)", "Cat\tDog", new string[] {"Cat\tDog", "Cat", "Dog"}), new RegexTestCase("(Cat)\f(Dog)", "Cat\fDog", new string[] {"Cat\fDog", "Cat", "Dog"}), /********************************************************* Miscellaneous { witout matching } *********************************************************/ new RegexTestCase(@"\p{klsak", typeof(ArgumentException)), new RegexTestCase(@"{5", "hello {5 world", new string[] {"{5"}), new RegexTestCase(@"{5,", "hello {5, world", new string[] {"{5,"}), new RegexTestCase(@"{5,6", "hello {5,6 world", new string[] {"{5,6"}), /********************************************************* Miscellaneous inline options *********************************************************/ new RegexTestCase(@"(?r:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?c:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?n:(?<cat>cat)(\s+)(?<dog>dog))", "cat dog", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(?n:(cat)(\s+)(dog))", "cat dog", new string[] {"cat dog"}), new RegexTestCase(@"(?n:(cat)(?<SpaceChars>\s+)(dog))", "cat dog", new string[] {"cat dog", " "}), new RegexTestCase(@"(?x: (?<cat>cat) # Cat statement (\s+) # Whitespace chars (?<dog>dog # Dog statement ))", "cat dog", new string[] {"cat dog", " ", "cat", "dog"}), new RegexTestCase(@"(?e:cat)", typeof(ArgumentException)), new RegexTestCase(@"(?+i:cat)", "CAT", new string[] {"CAT"}), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p inside character range *********************************************************/ new RegexTestCase(@"cat([\d]*)dog", "hello123cat230927dog1412d", new string[] {"cat230927dog", "230927"}), new RegexTestCase(@"([\D]*)dog", "65498catdog58719", new string[] {"catdog", "cat"}), new RegexTestCase(@"cat([\s]*)dog", "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"cat([\S]*)", "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\w]*)", "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\W]*)dog", "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"cat([a-\d]*)dog", typeof(ArgumentException)), new RegexTestCase(@"([5-\D]*)dog", typeof(ArgumentException)), new RegexTestCase(@"cat([6-\s]*)dog", typeof(ArgumentException)), new RegexTestCase(@"cat([c-\S]*)", typeof(ArgumentException)), new RegexTestCase(@"cat([7-\w]*)", typeof(ArgumentException)), new RegexTestCase(@"cat([a-\W]*)dog", typeof(ArgumentException)), new RegexTestCase(@"([f-\p{Lu}]\w*)\s([\p{Lu}]\w*)", typeof(ArgumentException)), new RegexTestCase(@"([1-\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", typeof(ArgumentException)), new RegexTestCase(@"[\p]", typeof(ArgumentException)), new RegexTestCase(@"[\P]", typeof(ArgumentException)), new RegexTestCase(@"([\pcat])", typeof(ArgumentException)), new RegexTestCase(@"([\Pcat])", typeof(ArgumentException)), new RegexTestCase(@"(\p{", typeof(ArgumentException)), new RegexTestCase(@"(\p{Ll", typeof(ArgumentException)), /********************************************************* \x, \u, \a, \b, \e, \f, \n, \r, \t, \v, \c, inside character range *********************************************************/ new RegexTestCase(@"(cat)([\x41]*)(dog)", "catAAAdog", new string[] {"catAAAdog", "cat", "AAA", "dog"}), new RegexTestCase(@"(cat)([\u0041]*)(dog)", "catAAAdog", new string[] {"catAAAdog", "cat", "AAA", "dog"}), new RegexTestCase(@"(cat)([\a]*)(dog)", "cat\a\a\adog", new string[] {"cat\a\a\adog", "cat", "\a\a\a", "dog"}), new RegexTestCase(@"(cat)([\b]*)(dog)", "cat\b\b\bdog", new string[] {"cat\b\b\bdog", "cat", "\b\b\b", "dog"}), new RegexTestCase(@"(cat)([\e]*)(dog)", "cat\u001B\u001B\u001Bdog", new string[] {"cat\u001B\u001B\u001Bdog", "cat", "\u001B\u001B\u001B", "dog"}), new RegexTestCase(@"(cat)([\f]*)(dog)", "cat\f\f\fdog", new string[] {"cat\f\f\fdog", "cat", "\f\f\f", "dog"}), new RegexTestCase(@"(cat)([\r]*)(dog)", "cat\r\r\rdog", new string[] {"cat\r\r\rdog", "cat", "\r\r\r", "dog"}), new RegexTestCase(@"(cat)([\v]*)(dog)", "cat\v\v\vdog", new string[] {"cat\v\v\vdog", "cat", "\v\v\v", "dog"}), new RegexTestCase(@"(cat)([\o]*)(dog)", typeof(ArgumentException)), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p inside character range ([0-5]) with ECMA Option *********************************************************/ new RegexTestCase(@"cat([\d]*)dog", RegexOptions.ECMAScript, "hello123cat230927dog1412d", new string[] {"cat230927dog", "230927"}), new RegexTestCase(@"([\D]*)dog", RegexOptions.ECMAScript, "65498catdog58719", new string[] {"catdog", "cat"}), new RegexTestCase(@"cat([\s]*)dog", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"cat([\S]*)", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\w]*)", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "dog"}), new RegexTestCase(@"cat([\W]*)dog", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", " "}), new RegexTestCase(@"([\p{Lu}]\w*)\s([\p{Lu}]\w*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "Hello", "World"}), new RegexTestCase(@"([\P{Ll}][\p{Ll}]*)\s([\P{Ll}][\p{Ll}]*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "Hello", "World"}), /********************************************************* \d, \D, \s, \S, \w, \W, \P, \p outside character range ([0-5]) with ECMA Option *********************************************************/ new RegexTestCase(@"(cat)\d*dog", RegexOptions.ECMAScript, "hello123cat230927dog1412d", new string[] {"cat230927dog", "cat"}), new RegexTestCase(@"\D*(dog)", RegexOptions.ECMAScript, "65498catdog58719", new string[] {"catdog", "dog"}), new RegexTestCase(@"(cat)\s*(dog)", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\S*", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "cat"}), new RegexTestCase(@"(cat)\w*", RegexOptions.ECMAScript, "sfdcatdog 3270", new string[] {"catdog", "cat"}), new RegexTestCase(@"(cat)\W*(dog)", RegexOptions.ECMAScript, "wiocat dog3270", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"\p{Lu}(\w*)\s\p{Lu}(\w*)", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World", "ello", "orld"}), new RegexTestCase(@"\P{Ll}\p{Ll}*\s\P{Ll}\p{Ll}*", RegexOptions.ECMAScript, "Hello World", new string[] {"Hello World"}), /********************************************************* Use < in a group *********************************************************/ new RegexTestCase(@"cat(?<0>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<1dog>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog!>)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog >)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog<>)_*>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<>dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<->dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?<dog121>dog)", "catcatdogdogcat", new string[] {"catdog", "dog"}), new RegexTestCase(@"(?<cat>cat)\s*(?<cat>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<1>cat)\s*(?<1>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<2048>cat)\s*(?<2048>dog)", "catcat dogdogcat", new string[] {"cat dog", "dog"}), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", ""}), new RegexTestCase(@"(?<cat>cat)\w+(?<cat-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "_Hello_World_"}), new RegexTestCase(@"(?<1>cat)\w+(?<dog-1>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<2-cat>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<1>cat)\w+(?<2-1>dog)", "cat_Hello_World_dog", new string[] {"cat_Hello_World_dog", "", "_Hello_World_"}), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-16>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-1uosn>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-catdog>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-()*!@>dog)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\w+(?<dog-0>dog)", "cat_Hello_World_dog", null), /********************************************************* Quantifiers *********************************************************/ new RegexTestCase(@"(?<cat>cat){", "STARTcat{", new string[] {"cat{", "cat"}), new RegexTestCase(@"(?<cat>cat){fdsa", "STARTcat{fdsa", new string[] {"cat{fdsa", "cat"}), new RegexTestCase(@"(?<cat>cat){1", "STARTcat{1", new string[] {"cat{1", "cat"}), new RegexTestCase(@"(?<cat>cat){1END", "STARTcat{1END", new string[] {"cat{1END", "cat"}), new RegexTestCase(@"(?<cat>cat){1,", "STARTcat{1,", new string[] {"cat{1,", "cat"}), new RegexTestCase(@"(?<cat>cat){1,END", "STARTcat{1,END", new string[] {"cat{1,END", "cat"}), new RegexTestCase(@"(?<cat>cat){1,2", "STARTcat{1,2", new string[] {"cat{1,2", "cat"}), new RegexTestCase(@"(?<cat>cat){1,2END", "STARTcat{1,2END", new string[] {"cat{1,2END", "cat"}), /********************************************************* Use (? in a group *********************************************************/ new RegexTestCase(@"cat(?(?#COMMENT)cat)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?'cat'cat)dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?<cat>cat)dog)", typeof(ArgumentException)), new RegexTestCase(@"cat(?(?afdcat)dog)", typeof(ArgumentException)), /********************************************************* Use IgnorePatternWhitespace *********************************************************/ new RegexTestCase(@"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog ", RegexOptions.IgnorePatternWhitespace, "cat dog", new string[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) #cat \s+ #followed by 1 or more whitespace (dog) #followed by dog", RegexOptions.IgnorePatternWhitespace, "cat dog", new string[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace) (dog) (?#followed by dog)", RegexOptions.IgnorePatternWhitespace, "cat dog", new string[] {"cat dog", "cat", "dog" }), new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", RegexOptions.IgnorePatternWhitespace, typeof(ArgumentException)), /********************************************************* Without IgnorePatternWhitespace *********************************************************/ new RegexTestCase(@"(cat) (?#cat) \s+ (?#followed by 1 or more whitespace", typeof(ArgumentException)), /********************************************************* Back Reference *********************************************************/ new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<cat>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k'cat'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\<cat>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\'cat'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<1>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k'1'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\<1>", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\'1'", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\1", "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\1", RegexOptions.ECMAScript, "asdfcat dogcat dog", new string[] {"cat dogcat", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<dog>", "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\2", "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\2", RegexOptions.ECMAScript, "asdfcat dogdog dog", new string[] {"cat dogdog", "cat", "dog"}), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\kcat", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<cat2>", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k<8>cat", RegexOptions.ECMAScript, typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k8", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\k8", RegexOptions.ECMAScript, typeof(ArgumentException)), /********************************************************* Octal *********************************************************/ new RegexTestCase(@"(cat)(\077)", "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\77)", "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\176)", "hellocat~dogworld", new string[] {"cat~", "cat", "~"}), new RegexTestCase(@"(cat)(\400)", "hellocat\0dogworld", new string[] {"cat\0", "cat", "\0"}), new RegexTestCase(@"(cat)(\300)", "hellocat\u00C0dogworld", new string[] {"cat\u00C0", "cat", "\u00C0"}), new RegexTestCase(@"(cat)(\300)", "hellocat\u00C0dogworld", new string[] {"cat\u00C0", "cat", "\u00C0"}), new RegexTestCase(@"(cat)(\477)", "hellocat\u003Fdogworld", new string[] {"cat\u003F", "cat", "\u003F"}), new RegexTestCase(@"(cat)(\777)", "hellocat\u00FFdogworld", new string[] {"cat\u00FF", "cat", "\u00FF"}), new RegexTestCase(@"(cat)(\7770)", "hellocat\u00FF0dogworld", new string[] {"cat\u00FF0", "cat", "\u00FF0"}), new RegexTestCase(@"(cat)(\7)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\077)", RegexOptions.ECMAScript, "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\77)", RegexOptions.ECMAScript, "hellocat?dogworld", new string[] {"cat?", "cat", "?"}), new RegexTestCase(@"(cat)(\7)", RegexOptions.ECMAScript, "hellocat\adogworld", new string[] {"cat\a", "cat", "\a"}), new RegexTestCase(@"(cat)(\40)", RegexOptions.ECMAScript, "hellocat dogworld", new string[] {"cat ", "cat", " "}), new RegexTestCase(@"(cat)(\040)", RegexOptions.ECMAScript, "hellocat dogworld", new string[] {"cat ", "cat", " "}), new RegexTestCase(@"(cat)(\176)", RegexOptions.ECMAScript, "hellocatcat76dogworld", new string[] {"catcat76", "cat", "cat76"}), new RegexTestCase(@"(cat)(\377)", RegexOptions.ECMAScript, "hellocat\u00FFdogworld", new string[] {"cat\u00FF", "cat", "\u00FF"}), new RegexTestCase(@"(cat)(\400)", RegexOptions.ECMAScript, "hellocat 0Fdogworld", new string[] {"cat 0", "cat", " 0"}), /********************************************************* Decimal *********************************************************/ new RegexTestCase(@"(cat)\s+(?<2147483646>dog)", "asdlkcat dogiwod", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(?<2147483647>dog)", "asdlkcat dogiwod", new string[] {"cat dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(?<2147483648>dog)", typeof(System.ArgumentException)), new RegexTestCase(@"(cat)\s+(?<21474836481097>dog)", typeof(System.ArgumentException)), /********************************************************* Hex *********************************************************/ new RegexTestCase(@"(cat)(\x2a*)(dog)", "asdlkcat***dogiwod", new string[] {"cat***dog", "cat", "***", "dog"}), new RegexTestCase(@"(cat)(\x2b*)(dog)", "asdlkcat+++dogiwod", new string[] {"cat+++dog", "cat", "+++", "dog"}), new RegexTestCase(@"(cat)(\x2c*)(dog)", "asdlkcat,,,dogiwod", new string[] {"cat,,,dog", "cat", ",,,", "dog"}), new RegexTestCase(@"(cat)(\x2d*)(dog)", "asdlkcat---dogiwod", new string[] {"cat---dog", "cat", "---", "dog"}), new RegexTestCase(@"(cat)(\x2e*)(dog)", "asdlkcat...dogiwod", new string[] {"cat...dog", "cat", "...", "dog"}), new RegexTestCase(@"(cat)(\x2f*)(dog)", "asdlkcat///dogiwod", new string[] {"cat///dog", "cat", "///", "dog"}), new RegexTestCase(@"(cat)(\x2A*)(dog)", "asdlkcat***dogiwod", new string[] {"cat***dog", "cat", "***", "dog"}), new RegexTestCase(@"(cat)(\x2B*)(dog)", "asdlkcat+++dogiwod", new string[] {"cat+++dog", "cat", "+++", "dog"}), new RegexTestCase(@"(cat)(\x2C*)(dog)", "asdlkcat,,,dogiwod", new string[] {"cat,,,dog", "cat", ",,,", "dog"}), new RegexTestCase(@"(cat)(\x2D*)(dog)", "asdlkcat---dogiwod", new string[] {"cat---dog", "cat", "---", "dog"}), new RegexTestCase(@"(cat)(\x2E*)(dog)", "asdlkcat...dogiwod", new string[] {"cat...dog", "cat", "...", "dog"}), new RegexTestCase(@"(cat)(\x2F*)(dog)", "asdlkcat///dogiwod", new string[] {"cat///dog", "cat", "///", "dog"}), /********************************************************* ScanControl *********************************************************/ new RegexTestCase(@"(cat)(\c*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)\c", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c *)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c?*)(dog)", typeof(ArgumentException)), new RegexTestCase("(cat)(\\c\0*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c`*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c\|*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c\[*)(dog)", typeof(ArgumentException)), new RegexTestCase(@"(cat)(\c@*)(dog)", "asdlkcat\0\0dogiwod", new string[] {"cat\0\0dog", "cat", "\0\0", "dog"}), new RegexTestCase(@"(cat)(\cA*)(dog)", "asdlkcat\u0001dogiwod", new string[] {"cat\u0001dog", "cat", "\u0001", "dog"}), new RegexTestCase(@"(cat)(\ca*)(dog)", "asdlkcat\u0001dogiwod", new string[] {"cat\u0001dog", "cat", "\u0001", "dog"}), new RegexTestCase(@"(cat)(\cC*)(dog)", "asdlkcat\u0003dogiwod", new string[] {"cat\u0003dog", "cat", "\u0003", "dog"}), new RegexTestCase(@"(cat)(\cc*)(dog)", "asdlkcat\u0003dogiwod", new string[] {"cat\u0003dog", "cat", "\u0003", "dog"}), new RegexTestCase(@"(cat)(\cD*)(dog)", "asdlkcat\u0004dogiwod", new string[] {"cat\u0004dog", "cat", "\u0004", "dog"}), new RegexTestCase(@"(cat)(\cd*)(dog)", "asdlkcat\u0004dogiwod", new string[] {"cat\u0004dog", "cat", "\u0004", "dog"}), new RegexTestCase(@"(cat)(\cX*)(dog)", "asdlkcat\u0018dogiwod", new string[] {"cat\u0018dog", "cat", "\u0018", "dog"}), new RegexTestCase(@"(cat)(\cx*)(dog)", "asdlkcat\u0018dogiwod", new string[] {"cat\u0018dog", "cat", "\u0018", "dog"}), new RegexTestCase(@"(cat)(\cZ*)(dog)", "asdlkcat\u001adogiwod", new string[] {"cat\u001adog", "cat", "\u001a", "dog"}), new RegexTestCase(@"(cat)(\cz*)(dog)", "asdlkcat\u001adogiwod", new string[] {"cat\u001adog", "cat", "\u001a", "dog"}), /********************************************************* Atomic Zero-Width Assertions \A \Z \z \G \b \B *********************************************************/ //\A new RegexTestCase(@"\A(cat)\s+(dog)", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"\A(cat)\s+(dog)", "cat \n\n\ncat dog", null), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.Multiline, "cat \n\n\ncat dog", null), new RegexTestCase(@"\A(cat)\s+(dog)", RegexOptions.ECMAScript, "cat \n\n\ncat dog", null), //\Z new RegexTestCase(@"(cat)\s+(dog)\Z", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat \n\n\n dog\n", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\Z", "cat dog\n\n\ncat", null), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.Multiline, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\Z", RegexOptions.ECMAScript, "cat dog\n\n\ncat ", null), //\z new RegexTestCase(@"(cat)\s+(dog)\z", "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat \n\n\n dog", new string[] {"cat \n\n\n dog", "cat", "dog"}), new RegexTestCase(@"(cat)\s+(dog)\z", "cat dog\n\n\ncat", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat dog\n\n\ncat ", null), new RegexTestCase(@"(cat)\s+(dog)\z", "cat \n\n\n dog\n", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.Multiline, "cat \n\n\n dog\n", null), new RegexTestCase(@"(cat)\s+(dog)\z", RegexOptions.ECMAScript, "cat \n\n\n dog\n", null), //\b new RegexTestCase(@"\b@cat", "123START123@catEND", new string[] {"@cat"}), new RegexTestCase(@"\b\<cat", "123START123<catEND", new string[] {"<cat"}), new RegexTestCase(@"\b,cat", "satwe,,,START,catEND", new string[] {",cat"}), new RegexTestCase(@"\b\[cat", "`12START123[catEND", new string[] {"[cat"}), new RegexTestCase(@"\b@cat", "123START123;@catEND", null), new RegexTestCase(@"\b\<cat", "123START123'<catEND", null), new RegexTestCase(@"\b,cat", "satwe,,,START',catEND", null), new RegexTestCase(@"\b\[cat", "`12START123'[catEND", null), //\B new RegexTestCase(@"\B@cat", "123START123;@catEND", new string[] {"@cat"}), new RegexTestCase(@"\B\<cat", "123START123'<catEND", new string[] {"<cat"}), new RegexTestCase(@"\B,cat", "satwe,,,START',catEND", new string[] {",cat"}), new RegexTestCase(@"\B\[cat", "`12START123'[catEND", new string[] {"[cat"}), new RegexTestCase(@"\B@cat", "123START123@catEND", null), new RegexTestCase(@"\B\<cat", "123START123<catEND", null), new RegexTestCase(@"\B,cat", "satwe,,,START,catEND", null), new RegexTestCase(@"\B\[cat", "`12START123[catEND", null), /********************************************************* \w matching \p{Lm} (Letter, Modifier) *********************************************************/ new RegexTestCase(@"(\w+)\s+(\w+)", "cat\u02b0 dog\u02b1", new string[] {"cat\u02b0 dog\u02b1", "cat\u02b0", "dog\u02b1"}), new RegexTestCase(@"(cat\w+)\s+(dog\w+)", "STARTcat\u30FC dog\u3005END", new string[] {"cat\u30FC dog\u3005END", "cat\u30FC", "dog\u3005END"}), new RegexTestCase(@"(cat\w+)\s+(dog\w+)", "STARTcat\uff9e dog\uff9fEND", new string[] {"cat\uff9e dog\uff9fEND", "cat\uff9e", "dog\uff9fEND"}), /********************************************************* positive and negative character classes [a-c]|[^b-c] *********************************************************/ new RegexTestCase(@"[^a]|d", "d", new string[] {"d"}), new RegexTestCase(@"([^a]|[d])*", "Hello Worlddf", new string[] {"Hello Worlddf", "f"}), new RegexTestCase(@"([^{}]|\n)+", "{{{{Hello\n World \n}END", new string[] {"Hello\n World \n", "\n"}), new RegexTestCase(@"([a-d]|[^abcd])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), new RegexTestCase(@"([^a]|[a])*", "once upon a time", new string[] {"once upon a time", "e"}), new RegexTestCase(@"([a-d]|[^abcd]|[x-z]|^wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), new RegexTestCase(@"([a-d]|[e-i]|[^e]|wxyz])+", "\tonce\n upon\0 a- ()*&^%#time?", new string[] {"\tonce\n upon\0 a- ()*&^%#time?", "?"}), /********************************************************* canonical and non-canonical char class, where one group is in it's simplest form [a-e] and another is more complex . *********************************************************/ new RegexTestCase(@"^(([^b]+ )|(.* ))$", "aaa ", new string[] {"aaa ", "aaa ", "aaa ", ""}), new RegexTestCase(@"^(([^b]+ )|(.*))$", "aaa", new string[] {"aaa", "aaa", "", "aaa"}), new RegexTestCase(@"^(([^b]+ )|(.* ))$", "bbb ", new string[] {"bbb ", "bbb ", "", "bbb "}), new RegexTestCase(@"^(([^b]+ )|(.*))$", "bbb", new string[] {"bbb", "bbb", "", "bbb"}), new RegexTestCase(@"^((a*)|(.*))$", "aaa", new string[] {"aaa", "aaa", "aaa", ""}), new RegexTestCase(@"^((a*)|(.*))$", "aaabbb", new string[] {"aaabbb", "aaabbb", "", "aaabbb"}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{hello 1234567890 world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{hello 1234567890 world}", new string[] {"hello", "o", "", "o", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{HELLO 1234567890 world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{HELLO 1234567890 world}", new string[] {"HELLO", "O", "", "", "O"}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))*", "{1234567890 hello world}", new string[] {"", "", "", "", ""}), new RegexTestCase(@"(([0-9])|([a-z])|([A-Z]))+", "{1234567890 hello world}", new string[] {"1234567890", "0", "0", "", ""}), new RegexTestCase(@"^(([a-d]*)|([a-z]*))$", "aaabbbcccdddeeefff", new string[] {"aaabbbcccdddeeefff", "aaabbbcccdddeeefff", "", "aaabbbcccdddeeefff"}), new RegexTestCase(@"^(([d-f]*)|([c-e]*))$", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "", "dddeeeccceee"}), new RegexTestCase(@"^(([c-e]*)|([d-f]*))$", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), new RegexTestCase(@"(([a-d]*)|([a-z]*))", "aaabbbcccdddeeefff", new string[] {"aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", ""}), new RegexTestCase(@"(([d-f]*)|([c-e]*))", "dddeeeccceee", new string[] {"dddeee", "dddeee", "dddeee", ""}), new RegexTestCase(@"(([c-e]*)|([d-f]*))", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), new RegexTestCase(@"(([a-d]*)|(.*))", "aaabbbcccdddeeefff", new string[] {"aaabbbcccddd", "aaabbbcccddd", "aaabbbcccddd", ""}), new RegexTestCase(@"(([d-f]*)|(.*))", "dddeeeccceee", new string[] {"dddeee", "dddeee", "dddeee", ""}), new RegexTestCase(@"(([c-e]*)|(.*))", "dddeeeccceee", new string[] {"dddeeeccceee", "dddeeeccceee", "dddeeeccceee", ""}), /********************************************************* \p{Pi} (Punctuation Initial quote) \p{Pf} (Punctuation Final quote) *********************************************************/ new RegexTestCase(@"\p{Pi}(\w*)\p{Pf}", "\u00ABCat\u00BB \u00BBDog\u00AB'", new string[] {"\u00ABCat\u00BB", "Cat"}), new RegexTestCase(@"\p{Pi}(\w*)\p{Pf}", "\u2018Cat\u2019 \u2019Dog\u2018'", new string[] {"\u2018Cat\u2019", "Cat"}), /********************************************************* Use special Unicode characters *********************************************************/ /* new RegexTest(@"AE", "\u00C4", new string[] {"Hello World", "Hello", "World"}, GERMAN_PHONEBOOK), new RegexTest(@"oe", "\u00F6", new string[] {"Hello World", "Hello", "World"}, GERMAN_PHONEBOOK), new RegexTest("\u00D1", "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00D1", "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00D1", RegexOptions.IgnoreCase, "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00D1", RegexOptions.IgnoreCase, "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00F1", RegexOptions.IgnoreCase, "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00F1", RegexOptions.IgnoreCase, "\u004E\u0303", new string[] {"Hello World", "Hello", "World"}, INVARIANT), new RegexTest("\u00F1", "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), new RegexTest("\u00F1", "\u006E\u0303", new string[] {"Hello World", "Hello", "World"}, ENGLISH_US), */ new RegexTestCase("CH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _ENGLISH_US), new RegexTestCase("CH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _CZECH), new RegexTestCase("cH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _ENGLISH_US), new RegexTestCase("cH", RegexOptions.IgnoreCase, "Ch", new string[] {"Ch"}, _CZECH), new RegexTestCase("AA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _ENGLISH_US), new RegexTestCase("AA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _DANISH), new RegexTestCase("aA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _ENGLISH_US), new RegexTestCase("aA", RegexOptions.IgnoreCase, "Aa", new string[] {"Aa"}, _DANISH), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _TURKISH), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _TURKISH), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _LATIN_AZERI), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _LATIN_AZERI), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", null, _ENGLISH_US), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0069", null, _ENGLISH_US), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0049", new string[] {"\u0049"}, _ENGLISH_US), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", new string[] {"\u0069"}, _ENGLISH_US), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0049", null, _INVARIANT), new RegexTestCase("\u0131", RegexOptions.IgnoreCase, "\u0069", null, _INVARIANT), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0049", null, _INVARIANT), new RegexTestCase("\u0130", RegexOptions.IgnoreCase, "\u0069", null, _INVARIANT), /********************************************************* ECMAScript *********************************************************/ new RegexTestCase(@"(?<cat>cat)\s+(?<dog>dog)\s+\123\s+\234", RegexOptions.ECMAScript, "asdfcat dog cat23 dog34eia", new string[] {"cat dog cat23 dog34", "cat", "dog"}), /********************************************************* Balanced Matching *********************************************************/ new RegexTestCase(@"<div> (?> <div>(?<DEPTH>) | </div> (?<-DEPTH>) | .? )*? (?(DEPTH)(?!)) </div>", RegexOptions.IgnorePatternWhitespace, "<div>this is some <div>red</div> text</div></div></div>", new string[] {"<div>this is some <div>red</div> text</div>", ""}), new RegexTestCase(@"( ((?'open'<+)[^<>]*)+ ((?'close-open'>+)[^<>]*)+ )+", RegexOptions.IgnorePatternWhitespace, "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", new string[] {"<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", "<02deep_03<03deep_03>>>", "<03deep_03", ">>>", "<", "03deep_03"}), new RegexTestCase(@"( (?<start><)? [^<>]? (?<end-start>>)? )*", RegexOptions.IgnorePatternWhitespace, "<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", new string[] {"<01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>>", "", "", "01deep_01<02deep_01<03deep_01>><02deep_02><02deep_03<03deep_03>>"}), new RegexTestCase(@"( (?<start><[^/<>]*>)? [^<>]? (?<end-start></[^/<>]*>)? )*", RegexOptions.IgnorePatternWhitespace, "<b><a>Cat</a></b>", new string[] {"<b><a>Cat</a></b>", "", "", "<a>Cat</a>"}), new RegexTestCase(@"( (?<start><(?<TagName>[^/<>]*)>)? [^<>]? (?<end-start></\k<TagName>>)? )*", RegexOptions.IgnorePatternWhitespace, "<b>cat</b><a>dog</a>", new string[] {"<b>cat</b><a>dog</a>", "", "", "a", "dog"}), /********************************************************* Balanced Matching With Backtracking *********************************************************/ new RegexTestCase(@"( (?<start><[^/<>]*>)? .? (?<end-start></[^/<>]*>)? )* (?(start)(?!)) ", RegexOptions.IgnorePatternWhitespace, "<b><a>Cat</a></b><<<<c>>>><<d><e<f>><g><<<>>>>", new string[] {"<b><a>Cat</a></b><<<<c>>>><<d><e<f>><g><<<>>>>", "", "", "<a>Cat"}), /********************************************************* Character Classes and Lazy quantifier *********************************************************/ new RegexTestCase(@"([0-9]+?)([\w]+?)", RegexOptions.ECMAScript, "55488aheiaheiad", new string[] {"55", "5", "5"}), new RegexTestCase(@"([0-9]+?)([a-z]+?)", RegexOptions.ECMAScript, "55488aheiaheiad", new string[] {"55488a", "55488", "a"}), /********************************************************* Miscellaneous/Regression scenarios *********************************************************/ new RegexTestCase(@"(?<openingtag>1)(?<content>.*?)(?=2)", RegexOptions.Singleline | RegexOptions.ExplicitCapture, "1" + Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>" + Environment.NewLine + "2", new string[] {"1" + Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>" + Environment.NewLine, "1", Environment.NewLine + "<Projecaa DefaultTargets=\"x\"/>"+ Environment.NewLine }), new RegexTestCase(@"\G<%#(?<code>.*?)?%>", RegexOptions.Singleline, @"<%# DataBinder.Eval(this, ""MyNumber"") %>", new string[] {@"<%# DataBinder.Eval(this, ""MyNumber"") %>", @" DataBinder.Eval(this, ""MyNumber"") "}), /********************************************************* Nested Quantifiers *********************************************************/ new RegexTestCase(@"^[abcd]{0,0x10}*$", "a{0,0x10}}}", new string[] {"a{0,0x10}}}"}), new RegexTestCase(@"^[abcd]{0,16}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1,}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1}*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{0,16}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1,}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]{1}?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*+$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*?+$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+?*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]??*$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]*{0,5}$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]+{0,5}$", typeof(ArgumentException)), new RegexTestCase(@"^[abcd]?{0,5}$", typeof(ArgumentException)), /********************************************************* Lazy operator Backtracking *********************************************************/ new RegexTestCase(@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", RegexOptions.IgnoreCase, "http://www.msn.com", null), new RegexTestCase(@"http://([a-zA-z0-9\-]*\.?)*?(:[0-9]*)??/", RegexOptions.IgnoreCase, "http://www.msn.com/", new string[] {"http://www.msn.com/", "com", string.Empty}), new RegexTestCase(@"http://([a-zA-Z0-9\-]*\.?)*?/", RegexOptions.IgnoreCase, @"http://www.google.com/", new string[] {"http://www.google.com/", "com"}), new RegexTestCase(@"([a-z]*?)([\w])", RegexOptions.IgnoreCase, "cat", new string[] {"c", string.Empty, "c"}), new RegexTestCase(@"^([a-z]*?)([\w])$", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), // TODO: Come up with more scenarios here /********************************************************* Backtracking *********************************************************/ new RegexTestCase(@"([a-z]*)([\w])", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), new RegexTestCase(@"^([a-z]*)([\w])$", RegexOptions.IgnoreCase, "cat", new string[] {"cat", "ca", "t"}), // TODO: Come up with more scenarios here /********************************************************* Character Escapes Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"\u", typeof(ArgumentException)), new RegexTestCase(@"\ua", typeof(ArgumentException)), new RegexTestCase(@"\u0", typeof(ArgumentException)), new RegexTestCase(@"\x", typeof(ArgumentException)), new RegexTestCase(@"\x2", typeof(ArgumentException)), /********************************************************* Character class Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"[", typeof(ArgumentException)), new RegexTestCase(@"[]", typeof(ArgumentException)), new RegexTestCase(@"[a", typeof(ArgumentException)), new RegexTestCase(@"[^", typeof(ArgumentException)), new RegexTestCase(@"[cat", typeof(ArgumentException)), new RegexTestCase(@"[^cat", typeof(ArgumentException)), new RegexTestCase(@"[a-", typeof(ArgumentException)), new RegexTestCase(@"[a-]+", "ba-b", new string[] {"a-"}), new RegexTestCase(@"\p{", typeof(ArgumentException)), new RegexTestCase(@"\p{cat", typeof(ArgumentException)), new RegexTestCase(@"\p{cat}", typeof(ArgumentException)), new RegexTestCase(@"\P{", typeof(ArgumentException)), new RegexTestCase(@"\P{cat", typeof(ArgumentException)), new RegexTestCase(@"\P{cat}", typeof(ArgumentException)), /********************************************************* Quantifiers *********************************************************/ new RegexTestCase(@"(cat){", "cat{", new string[] {"cat{", "cat"}), new RegexTestCase(@"(cat){}", "cat{}", new string[] {"cat{}", "cat"}), new RegexTestCase(@"(cat){,", "cat{,", new string[] {"cat{,", "cat"}), new RegexTestCase(@"(cat){,}", "cat{,}", new string[] {"cat{,}", "cat"}), new RegexTestCase(@"(cat){cat}", "cat{cat}", new string[] {"cat{cat}", "cat"}), new RegexTestCase(@"(cat){cat,5}", "cat{cat,5}", new string[] {"cat{cat,5}", "cat"}), new RegexTestCase(@"(cat){5,dog}", "cat{5,dog}", new string[] {"cat{5,dog}", "cat"}), new RegexTestCase(@"(cat){cat,dog}", "cat{cat,dog}", new string[] {"cat{cat,dog}", "cat"}), new RegexTestCase(@"(cat){,}?", "cat{,}?", new string[] {"cat{,}", "cat"}), new RegexTestCase(@"(cat){cat}?", "cat{cat}?", new string[] {"cat{cat}", "cat"}), new RegexTestCase(@"(cat){cat,5}?", "cat{cat,5}?", new string[] {"cat{cat,5}", "cat"}), new RegexTestCase(@"(cat){5,dog}?", "cat{5,dog}?", new string[] {"cat{5,dog}", "cat"}), new RegexTestCase(@"(cat){cat,dog}?", "cat{cat,dog}?", new string[] {"cat{cat,dog}", "cat"}), /********************************************************* Grouping Constructs Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"(", typeof(ArgumentException)), new RegexTestCase(@"(?", typeof(ArgumentException)), new RegexTestCase(@"(?<", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>", typeof(ArgumentException)), new RegexTestCase(@"(?'", typeof(ArgumentException)), new RegexTestCase(@"(?'cat'", typeof(ArgumentException)), new RegexTestCase(@"(?:", typeof(ArgumentException)), new RegexTestCase(@"(?imn", typeof(ArgumentException)), new RegexTestCase(@"(?imn )", typeof(ArgumentException)), new RegexTestCase(@"(?=", typeof(ArgumentException)), new RegexTestCase(@"(?!", typeof(ArgumentException)), new RegexTestCase(@"(?<=", typeof(ArgumentException)), new RegexTestCase(@"(?<!", typeof(ArgumentException)), new RegexTestCase(@"(?>", typeof(ArgumentException)), new RegexTestCase(@"()", "cat", new string[] { string.Empty, string.Empty}), new RegexTestCase(@"(?)", typeof(ArgumentException)), new RegexTestCase(@"(?<)", typeof(ArgumentException)), new RegexTestCase(@"(?<cat>)", "cat", new string[] { string.Empty, string.Empty}), new RegexTestCase(@"(?')", typeof(ArgumentException)), new RegexTestCase(@"(?'cat')", "cat", new string[] { string.Empty, string.Empty}), new RegexTestCase(@"(?:)", "cat", new string[] { string.Empty}), new RegexTestCase(@"(?imn)", "cat", new string[] { string.Empty}), new RegexTestCase(@"(?imn)cat", "(?imn)cat", new string[] {"cat"}), new RegexTestCase(@"(?=)", "cat", new string[] { string.Empty}), new RegexTestCase(@"(?!)", "(?!)cat"), new RegexTestCase(@"(?<=)", "cat", new string[] { string.Empty}), new RegexTestCase(@"(?<!)", "(?<!)cat"), new RegexTestCase(@"(?>)", "cat", new string[] { string.Empty}), /********************************************************* Grouping Constructs Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"\1", typeof(ArgumentException)), new RegexTestCase(@"\1", typeof(ArgumentException)), new RegexTestCase(@"\k", typeof(ArgumentException)), new RegexTestCase(@"\k<", typeof(ArgumentException)), new RegexTestCase(@"\k<1", typeof(ArgumentException)), new RegexTestCase(@"\k<cat", typeof(ArgumentException)), new RegexTestCase(@"\k<>", typeof(ArgumentException)), /********************************************************* Alternation construct Invalid Regular Expressions *********************************************************/ new RegexTestCase(@"(?(", typeof(ArgumentException)), new RegexTestCase(@"(?()|", typeof(ArgumentException)), new RegexTestCase(@"(?()|)", "(?()|)", new string[] {""}), new RegexTestCase(@"(?(cat", typeof(ArgumentException)), new RegexTestCase(@"(?(cat)|", typeof(ArgumentException)), new RegexTestCase(@"(?(cat)|)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)catdog|)", "catdog", new string[] {"catdog"}), new RegexTestCase(@"(?(cat)catdog|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)dog|)", "dog", new string[] {""}), new RegexTestCase(@"(?(cat)dog|)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|catdog)", "cat", new string[] {""}), new RegexTestCase(@"(?(cat)|catdog)", "catdog", new string[] {""}), new RegexTestCase(@"(?(cat)|dog)", "dog", new string[] {"dog"}), new RegexTestCase(@"(?(cat)|dog)", "oof"), /********************************************************* Empty Match *********************************************************/ new RegexTestCase(@"([a*]*)+?$", "ab", new string[] {"", ""}), new RegexTestCase(@"(a*)+?$", "b", new string[] {"", ""}), }; }
#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.Hydra.Panes.HydraPublic File: DepthPane.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Hydra.Panes { using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Ecng.Collections; using Ecng.Common; using Ecng.Serialization; using StockSharp.Algo; using StockSharp.Algo.Storages; using StockSharp.BusinessEntities; using StockSharp.Hydra.Core; using StockSharp.Messages; using StockSharp.Xaml; using StockSharp.Localization; public partial class DepthPane { private readonly List<QuoteChangeMessage> _loadedDepths = new List<QuoteChangeMessage>(); public DepthPane() { InitializeComponent(); Init(ExportBtn, MainGrid, GetDepths); DepthGrid.Columns.RemoveAt(0); DepthGrid.Columns.RemoveAt(3); DepthGrid.Columns[0].Width = DepthGrid.Columns[2].Width = 50; } protected override Type DataType => typeof(QuoteChangeMessage); public override string Title => LocalizedStrings.MarketDepths + " " + SelectedSecurity; public override Security SelectedSecurity { get { return SelectSecurityBtn.SelectedSecurity; } set { SelectSecurityBtn.SelectedSecurity = value; if (value != null) DepthGrid.UpdateFormat(value); } } private IEnumerable<QuoteChangeMessage> GetDepths() { int maxDepth; if (!int.TryParse(Depth.Text, out maxDepth)) maxDepth = int.MaxValue; if (maxDepth <= 0) maxDepth = 1; var interval = TimeSpan.FromMilliseconds(DepthGenerationInterval.Value ?? 0); switch (BuildFrom.SelectedIndex) { case 0: { var retVal = StorageRegistry .GetQuoteMessageStorage(SelectedSecurity, Drive, StorageFormat) .Load(From, To + TimeHelper.LessOneDay); return retVal .Select(md => { md.Bids = md.Bids.Take(maxDepth).ToArray(); md.Asks = md.Asks.Take(maxDepth).ToArray(); return md; }) .WhereWithPrevious((prev, curr) => (curr.ServerTime - prev.ServerTime) >= interval); } case 1: { return StorageRegistry .GetOrderLogMessageStorage(SelectedSecurity, Drive, StorageFormat) .Load(From + new TimeSpan(18, 45, 0), To + TimeHelper.LessOneDay + new TimeSpan(18, 45, 0)) // TODO .ToMarketDepths(OrderLogBuilders.Plaza2.CreateBuilder(SelectedSecurity.ToSecurityId()), interval, maxDepth); } case 2: { var level1 = StorageRegistry .GetLevel1MessageStorage(SelectedSecurity, Drive, StorageFormat) .Load(From, To + TimeHelper.LessOneDay); return level1.ToOrderBooks(); } default: throw new InvalidOperationException(); } } private void FindClick(object sender, RoutedEventArgs e) { if (!CheckSecurity()) return; int maxDepth; DepthGrid.MaxDepth = int.TryParse(Depth.Text, out maxDepth) ? maxDepth : MarketDepthControl.DefaultDepth; var isFirstAdded = false; _loadedDepths.Clear(); Progress.Load(GetDepths(), _loadedDepths.AddRange, 1000, item => { QuotesSlider.Maximum = _loadedDepths.Count - 1; if (isFirstAdded) return; DisplayDepth(); isFirstAdded = true; }); QuotesSlider.Maximum = 0; QuotesSlider.Minimum = 0; QuotesSlider.SmallChange = 1; QuotesSlider.LargeChange = 5; } private void QuotesSliderValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { DisplayDepth(); } private void DisplayDepth() { var index = (int)QuotesSlider.Value; if (_loadedDepths.Count < (index + 1)) return; var depth = _loadedDepths[index]; DepthGrid.UpdateDepth(depth); DepthDate.Text = depth.ServerTime.ToString("yyyy.MM.dd HH:mm:ss.fff"); } protected override bool CanDirectExport => BuildFrom.SelectedIndex == 0; //protected override void OnClosed(EventArgs e) //{ // Progress.Stop(); // base.OnClosed(e); //} private void SelectSecurityBtn_SecuritySelected() { if (SelectedSecurity == null) { ExportBtn.IsEnabled = false; } else { ExportBtn.IsEnabled = true; UpdateTitle(); DepthGrid.UpdateFormat(SelectedSecurity); } } public override void Load(SettingsStorage storage) { base.Load(storage); DepthGrid.Load(storage.GetValue<SettingsStorage>(nameof(DepthGrid))); Depth.SelectedIndex = storage.GetValue<int>(nameof(Depth)); if (storage.ContainsKey(nameof(DepthGenerationInterval))) DepthGenerationInterval.Value = storage.GetValue<int>(nameof(DepthGenerationInterval)); BuildFrom.SelectedIndex = storage.GetValue<int>(nameof(BuildFrom)); } public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(DepthGrid), DepthGrid.Save()); storage.SetValue(nameof(Depth), Depth.SelectedIndex); if (DepthGenerationInterval.Value != null) storage.SetValue(nameof(DepthGenerationInterval), (int)DepthGenerationInterval.Value); storage.SetValue(nameof(BuildFrom), BuildFrom.SelectedIndex); } } }
#region Header /** * JsonWriter.cs * Stream-like facility to output JSON text. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace LitJson2 { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } public class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ('\n'); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { switch (str[i]) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (str[i]); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) str[i] >= 32 && (int) str[i] <= 126) { writer.Write (str[i]); continue; } // Default, turn into a \uXXXX sequence IntToHex ((int) str[i], hex_seq); writer.Write ("\\u"); writer.Write (hex_seq); } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); string str = Convert.ToString (number, number_format); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (long number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } [CLSCompliant(false)] public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using System.Reflection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding.Metadata { public class DefaultModelMetadataProviderTest { [Fact] public void GetMetadataForType_IncludesAttributes() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForType(typeof(ModelType)); // Assert var defaultMetadata = Assert.IsType<DefaultModelMetadata>(metadata); var attribute = Assert.IsType<ModelAttribute>(Assert.Single(defaultMetadata.Attributes.Attributes)); Assert.Equal("OnType", attribute.Value); } [Fact] public void GetMetadataForType_Cached() { // Arrange var provider = CreateProvider(); // Act var metadata1 = Assert.IsType<DefaultModelMetadata>(provider.GetMetadataForType(typeof(ModelType))); var metadata2 = Assert.IsType<DefaultModelMetadata>(provider.GetMetadataForType(typeof(ModelType))); // Assert Assert.Same(metadata1, metadata2); Assert.Same(metadata1.Attributes, metadata2.Attributes); Assert.Same(metadata1.BindingMetadata, metadata2.BindingMetadata); Assert.Same(metadata1.DisplayMetadata, metadata2.DisplayMetadata); Assert.Same(metadata1.ValidationMetadata, metadata2.ValidationMetadata); } [Fact] public void GetMetadataForObjectType_Cached() { // Arrange var provider = CreateProvider(); // Act var metadata1 = provider.GetMetadataForType(typeof(object)); var metadata2 = provider.GetMetadataForType(typeof(object)); // Assert Assert.Same(metadata1, metadata2); } [Fact] public void GetMetadataForProperties_IncludesContainerMetadataForAllProperties() { // Arrange var provider = CreateProvider(); var modelType = typeof(ModelType); // Act var metadata = provider.GetMetadataForProperties(modelType).ToArray(); // Assert Assert.Collection( metadata, (propertyMetadata) => { Assert.Equal("Property1", propertyMetadata.PropertyName); Assert.NotNull(propertyMetadata.ContainerMetadata); Assert.Equal(modelType, propertyMetadata.ContainerMetadata.ModelType); }, (propertyMetadata) => { Assert.Equal("Property2", propertyMetadata.PropertyName); Assert.NotNull(propertyMetadata.ContainerMetadata); Assert.Equal(modelType, propertyMetadata.ContainerMetadata.ModelType); }); } [Fact] public void GetMetadataForProperties_IncludesAllProperties() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperties(typeof(ModelType)).ToArray(); // Assert Assert.Equal(2, metadata.Length); Assert.Single(metadata, m => m.PropertyName == "Property1"); Assert.Single(metadata, m => m.PropertyName == "Property2"); } [Fact] public void GetMetadataForProperties_IncludesAllProperties_ExceptIndexer() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperties(typeof(ModelTypeWithIndexer)).ToArray(); // Assert Assert.Single(metadata); Assert.Single(metadata, m => m.PropertyName == "Property1"); } [Fact] public void GetMetadataForProperties_Cached() { // Arrange var provider = CreateProvider(); // Act var properties1 = provider.GetMetadataForProperties(typeof(ModelType)).Cast<DefaultModelMetadata>().ToArray(); var properties2 = provider.GetMetadataForProperties(typeof(ModelType)).Cast<DefaultModelMetadata>().ToArray(); // Assert Assert.Equal(properties1.Length, properties2.Length); for (var i = 0; i < properties1.Length; i++) { Assert.Same(properties1[i], properties2[i]); Assert.Same(properties1[i].Attributes, properties2[i].Attributes); Assert.Same(properties1[i].BindingMetadata, properties2[i].BindingMetadata); Assert.Same(properties1[i].DisplayMetadata, properties2[i].DisplayMetadata); Assert.Same(properties1[i].ValidationMetadata, properties2[i].ValidationMetadata); } } [Fact] public void GetMetadataForType_PropertiesCollection_Cached() { // Arrange var provider = CreateProvider(); // Act var metadata1 = Assert.IsType<DefaultModelMetadata>(provider.GetMetadataForType(typeof(ModelType))); var metadata2 = Assert.IsType<DefaultModelMetadata>(provider.GetMetadataForType(typeof(ModelType))); // Assert Assert.Same(metadata1.Properties, metadata2.Properties); } [Fact] public void GetMetadataForProperties_IncludesMergedAttributes() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperties(typeof(ModelType)).First(); // Assert var defaultMetadata = Assert.IsType<DefaultModelMetadata>(metadata); var attributes = defaultMetadata.Attributes.Attributes.ToArray(); Assert.Equal("OnProperty", Assert.IsType<ModelAttribute>(attributes[0]).Value); Assert.Equal("OnPropertyType", Assert.IsType<ModelAttribute>(attributes[1]).Value); } [Fact] public void GetMetadataForProperties_ExcludesHiddenProperties() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperties(typeof(DerivedModelWithHiding)); // Assert var propertyMetadata = Assert.Single(metadata); Assert.Equal(typeof(string), propertyMetadata.ModelType); } [Fact] public void GetMetadataForProperties_PropertyGetter_IsNullSafe() { // Arrange var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperties(typeof(ModelType)); // Assert foreach (var property in metadata) { Assert.NotNull(property.PropertyGetter); Assert.Null(property.PropertyGetter(null)); } } [Fact] public void GetMetadataForParameter_SuppliesEmptyAttributes_WhenParameterHasNoAttributes() { // Arrange var provider = CreateProvider(); var parameters = typeof(ModelType) .GetMethod(nameof(ModelType.Method1)) .GetParameters(); // Act var metadata = provider.GetMetadataForParameter(parameters[0]); // Assert var defaultMetadata = Assert.IsType<DefaultModelMetadata>(metadata); // Not exactly "no attributes" due to SerializableAttribute on object. Assert.IsType<SerializableAttribute>(Assert.Single(defaultMetadata.Attributes.Attributes)); } [Fact] public void GetMetadataForParameter_SuppliesAttributes_WhenParamHasAttributes() { // Arrange var provider = CreateProvider(); var parameters = typeof(ModelType) .GetMethod(nameof(ModelType.Method1)) .GetParameters(); // Act var metadata = provider.GetMetadataForParameter(parameters[1]); // Assert var defaultMetadata = Assert.IsType<DefaultModelMetadata>(metadata); Assert.Collection( // Take(2) to ignore SerializableAttribute on object. defaultMetadata.Attributes.Attributes.Take(2), attribute => { var modelAttribute = Assert.IsType<ModelAttribute>(attribute); Assert.Equal("ParamAttrib1", modelAttribute.Value); }, attribute => { var modelAttribute = Assert.IsType<ModelAttribute>(attribute); Assert.Equal("ParamAttrib2", modelAttribute.Value); }); } [Fact] public void GetMetadataForParameter_Cached() { // Arrange var provider = CreateProvider(); var parameter = typeof(ModelType) .GetMethod(nameof(ModelType.Method1)) .GetParameters()[1]; // Act var metadata1 = provider.GetMetadataForParameter(parameter); var metadata2 = provider.GetMetadataForParameter(parameter); // Assert Assert.Same(metadata1, metadata2); } [Fact] public void GetMetadataForParameter_WithModelType_ReturnsCombinedModelMetadata() { // Arrange var parameter = GetType() .GetMethod(nameof(GetMetadataForParameterTestMethod), BindingFlags.NonPublic | BindingFlags.Instance) .GetParameters()[0]; var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForParameter(parameter, typeof(DerivedModelType)); // Assert Assert.Equal(ModelMetadataKind.Parameter, metadata.MetadataKind); Assert.Equal(typeof(DerivedModelType), metadata.ModelType); var defaultModelMetadata = Assert.IsType<DefaultModelMetadata>(metadata); Assert.Collection( defaultModelMetadata.Attributes.Attributes, a => Assert.Equal("OnParameter", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnDerivedType", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnType", Assert.IsType<ModelAttribute>(a).Value)); Assert.Collection( metadata.Properties.OrderBy(p => p.Name), p => { Assert.Equal(nameof(DerivedModelType.DerivedProperty), p.Name); var defaultPropertyMetadata = Assert.IsType<DefaultModelMetadata>(p); Assert.Collection( defaultPropertyMetadata.Attributes.Attributes.OfType<ModelAttribute>(), a => Assert.Equal("OnDerivedProperty", Assert.IsType<ModelAttribute>(a).Value)); }, p => { Assert.Equal(nameof(DerivedModelType.Property1), p.Name); var defaultPropertyMetadata = Assert.IsType<DefaultModelMetadata>(p); Assert.Collection( defaultPropertyMetadata.Attributes.Attributes.OfType<ModelAttribute>(), a => Assert.Equal("OnProperty", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnPropertyType", Assert.IsType<ModelAttribute>(a).Value)); }, p => { Assert.Equal(nameof(DerivedModelType.Property2), p.Name); }); } [Fact] public void GetMetadataForParameter_WithModelType_CachesResults() { // Arrange var parameter = GetType() .GetMethod(nameof(GetMetadataForParameterTestMethod), BindingFlags.NonPublic | BindingFlags.Instance) .GetParameters()[0]; var provider = CreateProvider(); // Act var metadata1 = provider.GetMetadataForParameter(parameter, typeof(DerivedModelType)); var metadata2 = provider.GetMetadataForParameter(parameter, typeof(DerivedModelType)); // Assert Assert.Same(metadata1, metadata2); } [Fact] public void GetMetadataForParameter_WithModelType_VariesByModelType() { // Arrange var parameter = GetType() .GetMethod(nameof(GetMetadataForParameterTestMethod), BindingFlags.NonPublic | BindingFlags.Instance) .GetParameters()[0]; var provider = CreateProvider(); // Act var metadata1 = provider.GetMetadataForParameter(parameter, typeof(DerivedModelType)); var metadata2 = provider.GetMetadataForParameter(parameter, typeof(object)); // Assert Assert.NotSame(metadata1, metadata2); } [Fact] public void GetMetadataForProperty_WithModelType_ReturnsCombinedModelMetadata() { // Arrange var property = typeof(TestContainer) .GetProperty(nameof(TestContainer.ModelProperty)); var provider = CreateProvider(); // Act var metadata = provider.GetMetadataForProperty(property, typeof(DerivedModelType)); // Assert Assert.Equal(ModelMetadataKind.Property, metadata.MetadataKind); Assert.Equal(typeof(DerivedModelType), metadata.ModelType); var defaultModelMetadata = Assert.IsType<DefaultModelMetadata>(metadata); Assert.Collection( defaultModelMetadata.Attributes.Attributes, a => Assert.Equal("OnProperty", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnDerivedType", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnType", Assert.IsType<ModelAttribute>(a).Value)); Assert.Collection( metadata.Properties.OrderBy(p => p.Name), p => { Assert.Equal(nameof(DerivedModelType.DerivedProperty), p.Name); var defaultPropertyMetadata = Assert.IsType<DefaultModelMetadata>(p); Assert.Collection( defaultPropertyMetadata.Attributes.Attributes.OfType<ModelAttribute>(), a => Assert.Equal("OnDerivedProperty", Assert.IsType<ModelAttribute>(a).Value)); }, p => { Assert.Equal(nameof(DerivedModelType.Property1), p.Name); var defaultPropertyMetadata = Assert.IsType<DefaultModelMetadata>(p); Assert.Collection( defaultPropertyMetadata.Attributes.Attributes.OfType<ModelAttribute>(), a => Assert.Equal("OnProperty", Assert.IsType<ModelAttribute>(a).Value), a => Assert.Equal("OnPropertyType", Assert.IsType<ModelAttribute>(a).Value)); }, p => { Assert.Equal(nameof(DerivedModelType.Property2), p.Name); }); } [Fact] public void GetMetadataForProperty_WithModelType_CachesResults() { // Arrange var property = typeof(TestContainer) .GetProperty(nameof(TestContainer.ModelProperty)); var provider = CreateProvider(); // Act var metadata1 = provider.GetMetadataForProperty(property, typeof(DerivedModelType)); var metadata2 = provider.GetMetadataForProperty(property, typeof(DerivedModelType)); // Assert Assert.Same(metadata1, metadata2); } [Fact] public void GetMetadataForProperty_WithModelType_VariesByModelType() { // Arrange var property = typeof(TestContainer) .GetProperty(nameof(TestContainer.ModelProperty)); var provider = CreateProvider(); // Act var metadata1 = provider.GetMetadataForProperty(property, typeof(DerivedModelType)); var metadata2 = provider.GetMetadataForProperty(property, typeof(object)); // Assert Assert.NotSame(metadata1, metadata2); } private static DefaultModelMetadataProvider CreateProvider() { return new DefaultModelMetadataProvider( new EmptyCompositeMetadataDetailsProvider(), Options.Create(new MvcOptions())); } [Model("OnType")] private class ModelType { [Model("OnProperty")] public PropertyType Property1 { get; } = new PropertyType(); public PropertyType Property2 { get; set; } public void Method1( object paramWithNoAttributes, [Model("ParamAttrib1"), Model("ParamAttrib2")] object paramWithTwoAttributes) { } } [Model("OnPropertyType")] private class PropertyType { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] private class ModelAttribute : Attribute { public ModelAttribute(string value) { Value = value; } public string Value { get; } } private class ModelTypeWithIndexer { public PropertyType this[string key] => null; public PropertyType Property1 { get; set; } } private void GetMetadataForParameterTestMethod([Model("OnParameter")] ModelType parameter) { } private class BaseModelWithHiding { public int Property { get; set; } } private class DerivedModelWithHiding : BaseModelWithHiding { public new string Property { get; set; } } [Model("OnDerivedType")] private class DerivedModelType : ModelType { [Model("OnDerivedProperty")] public string DerivedProperty { get; set; } } private class TestContainer { [Model("OnProperty")] public ModelType ModelProperty { get; set; } } } }