context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache.Query { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; /// <summary> /// Abstract query cursor implementation. /// </summary> internal abstract class QueryCursorBase<T> : IQueryCursor<T>, IEnumerator<T> { /** Position before head. */ private const int BatchPosBeforeHead = -1; /** Keep binary flag. */ private readonly bool _keepBinary; /** Marshaller. */ private readonly Marshaller _marsh; /** Wherther "GetAll" was called. */ private bool _getAllCalled; /** Whether "GetEnumerator" was called. */ private bool _iterCalled; /** Batch with entries. */ private T[] _batch; /** Current position in batch. */ private int _batchPos = BatchPosBeforeHead; /** Disposed flag. */ private volatile bool _disposed; /** Whether next batch is available. */ private bool _hasNext = true; /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <param name="initialBatchStream">Optional stream with initial batch.</param> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "ConvertGetBatch calls Read, which does not rely on constructor being run.")] protected QueryCursorBase(Marshaller marsh, bool keepBinary, IBinaryStream initialBatchStream = null) { Debug.Assert(marsh != null); _keepBinary = keepBinary; _marsh = marsh; if (initialBatchStream != null) { _batch = ConvertGetBatch(initialBatchStream); } } /** <inheritdoc /> */ public IList<T> GetAll() { if (_getAllCalled) throw new InvalidOperationException("Failed to get all entries because GetAll() " + "method has already been called."); if (_iterCalled) throw new InvalidOperationException("Failed to get all entries because GetEnumerator() " + "method has already been called."); ThrowIfDisposed(); var res = GetAllInternal(); _getAllCalled = true; _hasNext = false; return res; } #region Public IEnumerable methods /** <inheritdoc /> */ public IEnumerator<T> GetEnumerator() { if (_getAllCalled) { throw new InvalidOperationException("Failed to get enumerator entries because " + "GetAll() method has already been called."); } if (_iterCalled) { throw new InvalidOperationException("Failed to get enumerator entries because " + "GetEnumerator() method has already been called."); } ThrowIfDisposed(); InitIterator(); _iterCalled = true; return this; } protected abstract void InitIterator(); /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Public IEnumerator methods /** <inheritdoc /> */ public T Current { get { ThrowIfDisposed(); if (_batchPos == BatchPosBeforeHead) throw new InvalidOperationException("MoveNext has not been called."); if (_batch == null) throw new InvalidOperationException("Previous call to MoveNext returned false."); return _batch[_batchPos]; } } /** <inheritdoc /> */ object IEnumerator.Current { get { return Current; } } /** <inheritdoc /> */ public bool MoveNext() { ThrowIfDisposed(); if (_batch == null) { if (_batchPos == BatchPosBeforeHead) // Standing before head, let's get batch and advance position. RequestBatch(); } else { _batchPos++; if (_batch.Length == _batchPos) // Reached batch end => request another. RequestBatch(); } return _batch != null; } /** <inheritdoc /> */ public void Reset() { throw new NotSupportedException("Reset is not supported."); } #endregion /// <summary> /// Gets all entries. /// </summary> protected abstract IList<T> GetAllInternal(); /// <summary> /// Reads entry from the reader. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Entry.</returns> protected abstract T Read(BinaryReader reader); /// <summary> /// Requests next batch. /// </summary> private void RequestBatch() { _batch = _hasNext ? GetBatch() : null; _batchPos = 0; } /// <summary> /// Gets the next batch. /// </summary> protected abstract T[] GetBatch(); /// <summary> /// Converter for GET_ALL operation. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Result.</returns> protected IList<T> ConvertGetAll(IBinaryStream stream) { var reader = _marsh.StartUnmarshal(stream, _keepBinary); var size = reader.ReadInt(); var res = new List<T>(size); for (var i = 0; i < size; i++) res.Add(Read(reader)); return res; } /// <summary> /// Converter for GET_BATCH operation. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Result.</returns> protected T[] ConvertGetBatch(IBinaryStream stream) { var reader = _marsh.StartUnmarshal(stream, _keepBinary); var size = reader.ReadInt(); if (size == 0) { _hasNext = false; return null; } var res = new T[size]; for (var i = 0; i < size; i++) { res[i] = Read(reader); } _hasNext = stream.ReadBool(); return res; } /** <inheritdoc /> */ public void Dispose() { lock (this) { if (_disposed) { return; } if (_hasNext) { Dispose(true); } GC.SuppressFinalize(this); _disposed = true; } } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> when called from Dispose; <c>false</c> when called from finalizer. /// </param> protected virtual void Dispose(bool disposing) { // No-op. } /// <summary> /// Throws <see cref="ObjectDisposedException"/> if this instance has been disposed. /// </summary> private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name, "Object has been disposed."); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Web; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; using OSDArray=OpenMetaverse.StructuredData.OSDArray; using OSDMap=OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.CoreModules.InterGrid { public struct OGPState { public string first_name; public string last_name; public UUID agent_id; public UUID local_agent_id; public UUID region_id; public uint circuit_code; public UUID secure_session_id; public UUID session_id; public bool agent_access; public string sim_access; public uint god_level; public bool god_overide; public bool identified; public bool transacted; public bool age_verified; public bool allow_redirect; public int limited_to_estate; public string inventory_host; public bool src_can_see_mainland; public int src_estate_id; public int src_version; public int src_parent_estate_id; public bool visible_to_parent; public string teleported_into_region; } public class OpenGridProtocolModule : IRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_scene = new List<Scene>(); private Dictionary<string, AgentCircuitData> CapsLoginID = new Dictionary<string, AgentCircuitData>(); private Dictionary<UUID, OGPState> m_OGPState = new Dictionary<UUID, OGPState>(); private Dictionary<string, string> m_loginToRegionState = new Dictionary<string, string>(); private string LastNameSuffix = "_EXTERNAL"; private string FirstNamePrefix = ""; private string httpsCN = ""; private bool httpSSL = false; private uint httpsslport = 0; private bool GridMode = false; #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { bool enabled = false; IConfig cfg = null; IConfig httpcfg = null; IConfig startupcfg = null; try { cfg = config.Configs["OpenGridProtocol"]; } catch (NullReferenceException) { enabled = false; } try { httpcfg = config.Configs["Network"]; } catch (NullReferenceException) { } try { startupcfg = config.Configs["Startup"]; } catch (NullReferenceException) { } if (startupcfg != null) { GridMode = enabled = startupcfg.GetBoolean("gridmode", false); } if (cfg != null) { enabled = cfg.GetBoolean("ogp_enabled", false); LastNameSuffix = cfg.GetString("ogp_lastname_suffix", "_EXTERNAL"); FirstNamePrefix = cfg.GetString("ogp_firstname_prefix", ""); if (enabled) { m_log.Warn("[OGP]: Open Grid Protocol is on, Listening for Clients on /agent/"); lock (m_scene) { if (m_scene.Count == 0) { MainServer.Instance.AddLLSDHandler("/agent/", ProcessAgentDomainMessage); MainServer.Instance.AddLLSDHandler("/", ProcessRegionDomainSeed); try { ServicePointManager.ServerCertificateValidationCallback += customXertificateValidation; } catch (NotImplementedException) { try { #pragma warning disable 0612, 0618 // Mono does not implement the ServicePointManager.ServerCertificateValidationCallback yet! Don't remove this! ServicePointManager.CertificatePolicy = new MonoCert(); #pragma warning restore 0612, 0618 } catch (Exception) { m_log.Error("[OGP]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions."); } } } // can't pick the region 'agent' because it would conflict with our agent domain handler // a zero length region name would conflict with are base region seed cap if (!SceneListDuplicateCheck(scene.RegionInfo.RegionName) && scene.RegionInfo.RegionName.ToLower() != "agent" && scene.RegionInfo.RegionName.Length > 0) { MainServer.Instance.AddLLSDHandler( "/" + HttpUtility.UrlPathEncode(scene.RegionInfo.RegionName.ToLower()), ProcessRegionDomainSeed); } if (!m_scene.Contains(scene)) m_scene.Add(scene); } } } lock (m_scene) { if (m_scene.Count == 1) { if (httpcfg != null) { httpSSL = httpcfg.GetBoolean("http_listener_ssl", false); httpsCN = httpcfg.GetString("http_listener_cn", scene.RegionInfo.ExternalHostName); if (httpsCN.Length == 0) httpsCN = scene.RegionInfo.ExternalHostName; httpsslport = (uint)httpcfg.GetInt("http_listener_sslport",((int)scene.RegionInfo.HttpPort + 1)); } } } } public void PostInitialise() { } public void Close() { //scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; } public string Name { get { return "OpenGridProtocolModule"; } } public bool IsSharedModule { get { return true; } } #endregion public OSD ProcessRegionDomainSeed(string path, OSD request, string endpoint) { string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } return GenerateRezAvatarRequestMessage(pathSegments[1]); //m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", // path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); //return new OSDMap(); } public OSD ProcessAgentDomainMessage(string path, OSD request, string endpoint) { // /agent/* string[] pathSegments = path.Split('/'); if (pathSegments.Length <= 1) { return GenerateNoHandlerMessage(); } if (pathSegments[0].Length == 0 && pathSegments[1].Length == 0) { return GenerateRezAvatarRequestMessage(""); } m_log.InfoFormat("[OGP]: path {0}, segments {1} segment[1] {2} Last segment {3}", path, pathSegments.Length, pathSegments[1], pathSegments[pathSegments.Length - 1]); switch (pathSegments[pathSegments.Length - 1]) { case "rez_avatar": return RezAvatarMethod(path, request); //break; case "derez_avatar": return DerezAvatarMethod(path, request); //break; } if (path.Length < 2) { return GenerateNoHandlerMessage(); } switch (pathSegments[pathSegments.Length - 2] + "/" + pathSegments[pathSegments.Length - 1]) { case "rez_avatar/rez": return RezAvatarMethod(path, request); //break; case "rez_avatar/request": return RequestRezAvatarMethod(path, request); case "rez_avatar/place": return RequestRezAvatarMethod(path, request); case "rez_avatar/derez": return DerezAvatarMethod(path, request); //break; default: return GenerateNoHandlerMessage(); } //return null; } private OSD GenerateRezAvatarRequestMessage(string regionname) { Scene region = null; bool usedroot = false; if (regionname.Length == 0) { region = GetRootScene(); usedroot = true; } else { region = GetScene(HttpUtility.UrlDecode(regionname).ToLower()); } // this shouldn't happen since we don't listen for a region that is down.. but // it might if the region was taken down or is in the middle of restarting if (region == null) { region = GetRootScene(); usedroot = true; } UUID statekeeper = UUID.Random(); RegionInfo reg = region.RegionInfo; OSDMap responseMap = new OSDMap(); string rezHttpProtocol = "http://"; //string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); string requestpath = "/agent/" + statekeeper + "/rez_avatar/request"; if (!usedroot) { lock (m_loginToRegionState) { if (!m_loginToRegionState.ContainsKey(requestpath)) { m_loginToRegionState.Add(requestpath, region.RegionInfo.RegionName.ToLower()); } } } if (httpSSL) { rezHttpProtocol = "https://"; //regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } responseMap["connect"] = OSD.FromBoolean(true); OSDMap capabilitiesMap = new OSDMap(); capabilitiesMap["rez_avatar/request"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + requestpath); responseMap["capabilities"] = capabilitiesMap; return responseMap; } // Using OpenSim.Framework.Capabilities.Caps here one time.. // so the long name is probably better then a using statement public void OnRegisterCaps(UUID agentID, Caps caps) { /* If we ever want to register our own caps here.... * string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler("CAPNAME", new RestStreamHandler("POST", capsBase + CAPSPOSTFIX!, delegate(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { return METHODHANDLER(request, path, param, agentID, caps); })); * */ } public OSD RequestRezAvatarMethod(string path, OSD request) { //m_log.Debug("[REQUESTREZAVATAR]: " + request.ToString()); OSDMap requestMap = (OSDMap)request; Scene homeScene = null; lock (m_loginToRegionState) { if (m_loginToRegionState.ContainsKey(path)) { homeScene = GetScene(m_loginToRegionState[path]); m_loginToRegionState.Remove(path); if (homeScene == null) homeScene = GetRootScene(); } else { homeScene = GetRootScene(); } } // Homescene is still null, we must have no regions that are up if (homeScene == null) return GenerateNoHandlerMessage(); RegionInfo reg = homeScene.RegionInfo; ulong regionhandle = GetOSCompatibleRegionHandle(reg); //string RegionURI = reg.ServerURI; //int RegionPort = (int)reg.HttpPort; UUID RemoteAgentID = requestMap["agent_id"].AsUUID(); // will be used in the future. The client always connects with the aditi agentid currently UUID LocalAgentID = RemoteAgentID; string FirstName = requestMap["first_name"].AsString(); string LastName = requestMap["last_name"].AsString(); FirstName = FirstNamePrefix + FirstName; LastName = LastName + LastNameSuffix; OGPState userState = GetOGPState(LocalAgentID); userState.first_name = requestMap["first_name"].AsString(); userState.last_name = requestMap["last_name"].AsString(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.allow_redirect = requestMap["allow_redirect"].AsBoolean(); userState.identified = requestMap["identified"].AsBoolean(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.sim_access = requestMap["sim_access"].AsString(); userState.agent_id = RemoteAgentID; userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_can_see_mainland = requestMap["src_can_see_mainland"].AsBoolean(); userState.src_estate_id = requestMap["src_estate_id"].AsInteger(); userState.local_agent_id = LocalAgentID; userState.teleported_into_region = reg.RegionName.ToLower(); UpdateOGPState(LocalAgentID, userState); OSDMap responseMap = new OSDMap(); if (RemoteAgentID == UUID.Zero) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString("No agent ID was specified in rez_avatar/request"); m_log.Error("[OGP]: rez_avatar/request failed because no avatar UUID was provided in the request body"); return responseMap; } responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["connect"] = OSD.FromBoolean(true); responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["region_x"] = OSD.FromInteger(reg.RegionLocX * (uint)Constants.RegionSize); // LLX responseMap["region_y"] = OSD.FromInteger(reg.RegionLocY * (uint)Constants.RegionSize); // LLY responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); if (reg.RegionSettings.Maturity == 1) { responseMap["sim_access"] = OSD.FromString("Mature"); } else if (reg.RegionSettings.Maturity == 2) { responseMap["sim_access"] = OSD.FromString("Adult"); } else { responseMap["sim_access"] = OSD.FromString("PG"); } // Generate a dummy agent for the user so we can get back a CAPS path AgentCircuitData agentData = new AgentCircuitData(); agentData.AgentID = LocalAgentID; agentData.BaseFolder = UUID.Zero; agentData.CapsPath = CapsUtil.GetRandomCapsObjectPath(); agentData.child = false; agentData.circuitcode = (uint)(Util.RandomClass.Next()); agentData.firstname = FirstName; agentData.lastname = LastName; agentData.SecureSessionID = UUID.Random(); agentData.SessionID = UUID.Random(); agentData.startpos = new Vector3(128f, 128f, 100f); // Pre-Fill our region cache with information on the agent. UserAgentData useragent = new UserAgentData(); useragent.AgentIP = "unknown"; useragent.AgentOnline = true; useragent.AgentPort = (uint)0; useragent.Handle = regionhandle; useragent.InitialRegion = reg.originRegionID; useragent.LoginTime = Util.UnixTimeSinceEpoch(); useragent.LogoutTime = 0; useragent.Position = agentData.startpos; useragent.Region = reg.originRegionID; useragent.SecureSessionID = agentData.SecureSessionID; useragent.SessionID = agentData.SessionID; UserProfileData userProfile = new UserProfileData(); userProfile.AboutText = "OGP User"; userProfile.CanDoMask = (uint)0; userProfile.Created = Util.UnixTimeSinceEpoch(); userProfile.CurrentAgent = useragent; userProfile.CustomType = "OGP"; userProfile.FirstLifeAboutText = "I'm testing OpenGrid Protocol"; userProfile.FirstLifeImage = UUID.Zero; userProfile.FirstName = agentData.firstname; userProfile.GodLevel = 0; userProfile.HomeLocation = agentData.startpos; userProfile.HomeLocationX = agentData.startpos.X; userProfile.HomeLocationY = agentData.startpos.Y; userProfile.HomeLocationZ = agentData.startpos.Z; userProfile.HomeLookAt = Vector3.Zero; userProfile.HomeLookAtX = userProfile.HomeLookAt.X; userProfile.HomeLookAtY = userProfile.HomeLookAt.Y; userProfile.HomeLookAtZ = userProfile.HomeLookAt.Z; userProfile.HomeRegion = reg.RegionHandle; userProfile.HomeRegionID = reg.originRegionID; userProfile.HomeRegionX = reg.RegionLocX; userProfile.HomeRegionY = reg.RegionLocY; userProfile.ID = agentData.AgentID; userProfile.Image = UUID.Zero; userProfile.LastLogin = Util.UnixTimeSinceEpoch(); userProfile.Partner = UUID.Zero; userProfile.PasswordHash = "$1$"; userProfile.PasswordSalt = ""; userProfile.SurName = agentData.lastname; userProfile.UserAssetURI = homeScene.CommsManager.NetworkServersInfo.AssetURL; userProfile.UserFlags = 0; userProfile.UserInventoryURI = homeScene.CommsManager.NetworkServersInfo.InventoryURL; userProfile.WantDoMask = 0; userProfile.WebLoginKey = UUID.Random(); // Do caps registration // get seed capagentData.firstname = FirstName;agentData.lastname = LastName; if (homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID) == null && !GridMode) { homeScene.CommsManager.UserAdminService.AddUser( agentData.firstname, agentData.lastname, CreateRandomStr(7), "", homeScene.RegionInfo.RegionLocX, homeScene.RegionInfo.RegionLocY, agentData.AgentID); UserProfileData userProfile2 = homeScene.CommsManager.UserService.GetUserProfile(agentData.AgentID); if (userProfile2 != null) { userProfile = userProfile2; userProfile.AboutText = "OGP USER"; userProfile.FirstLifeAboutText = "OGP USER"; homeScene.CommsManager.UserService.UpdateUserProfile(userProfile); } } // Stick our data in the cache so the region will know something about us homeScene.CommsManager.UserProfileCacheService.PreloadUserCache(userProfile); // Call 'new user' event handler string reason; if (!homeScene.NewUserConnection(agentData, (uint)TeleportFlags.ViaLogin, out reason)) { responseMap["connect"] = OSD.FromBoolean(false); responseMap["message"] = OSD.FromString(String.Format("Connection refused: {0}", reason)); m_log.ErrorFormat("[OGP]: rez_avatar/request failed: {0}", reason); return responseMap; } //string raCap = string.Empty; UUID AvatarRezCapUUID = LocalAgentID; string rezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/rez"; string derezAvatarPath = "/agent/" + AvatarRezCapUUID + "/rez_avatar/derez"; // Get a reference to the user's cap so we can pull out the Caps Object Path Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(agentData.AgentID); string rezHttpProtocol = "http://"; string regionCapsHttpProtocol = "http://"; string httpaddr = reg.ExternalHostName; string urlport = reg.HttpPort.ToString(); if (httpSSL) { rezHttpProtocol = "https://"; regionCapsHttpProtocol = "https://"; urlport = httpsslport.ToString(); if (httpsCN.Length > 0) httpaddr = httpsCN; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); // REPLACEMENT responseMap["region_seed_capability"] = OSD.FromString( regionCapsHttpProtocol + httpaddr + ":" + reg.HttpPort + CapsUtil.GetCapsSeedPath(userCap.CapsObjectPath)); responseMap["rez_avatar"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/rez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + rezAvatarPath); responseMap["rez_avatar/derez"] = OSD.FromString(rezHttpProtocol + httpaddr + ":" + urlport + derezAvatarPath); // Add the user to the list of CAPS that are outstanding. // well allow the caps hosts in this dictionary lock (CapsLoginID) { if (CapsLoginID.ContainsKey(rezAvatarPath)) { CapsLoginID[rezAvatarPath] = agentData; // This is a joke, if you didn't notice... It's so unlikely to happen, that I'll print this message if it does occur! m_log.Error("[OGP]: Holy anomoly batman! Caps path already existed! All the UUID Duplication worries were founded!"); } else { CapsLoginID.Add(rezAvatarPath, agentData); } } //m_log.Debug("Response:" + responseMap.ToString()); return responseMap; } public OSD RezAvatarMethod(string path, OSD request) { m_log.WarnFormat("[REZAVATAR]: {0}", request.ToString()); OSDMap responseMap = new OSDMap(); AgentCircuitData userData = null; // Only people we've issued a cap can go further if (TryGetAgentCircuitData(path,out userData)) { OSDMap requestMap = (OSDMap)request; // take these values to start. There's a few more UUID SecureSessionID=requestMap["secure_session_id"].AsUUID(); UUID SessionID = requestMap["session_id"].AsUUID(); int circuitcode = requestMap["circuit_code"].AsInteger(); OSDArray Parameter = new OSDArray(); if (requestMap.ContainsKey("parameter")) { Parameter = (OSDArray)requestMap["parameter"]; } //int version = 1; int estateID = 1; int parentEstateID = 1; UUID regionID = UUID.Zero; bool visibleToParent = true; for (int i = 0; i < Parameter.Count; i++) { OSDMap item = (OSDMap)Parameter[i]; // if (item.ContainsKey("version")) // { // version = item["version"].AsInteger(); // } if (item.ContainsKey("estate_id")) { estateID = item["estate_id"].AsInteger(); } if (item.ContainsKey("parent_estate_id")) { parentEstateID = item["parent_estate_id"].AsInteger(); } if (item.ContainsKey("region_id")) { regionID = item["region_id"].AsUUID(); } if (item.ContainsKey("visible_to_parent")) { visibleToParent = item["visible_to_parent"].AsBoolean(); } } //Update our Circuit data with the real values userData.SecureSessionID = SecureSessionID; userData.SessionID = SessionID; OGPState userState = GetOGPState(userData.AgentID); // Locate a home scene suitable for the user. Scene homeScene = null; homeScene = GetScene(userState.teleported_into_region); if (homeScene == null) homeScene = GetRootScene(); if (homeScene != null) { // Get a referenceokay - to their Cap object so we can pull out the capobjectroot Caps userCap = homeScene.CapsModule.GetCapsHandlerForUser(userData.AgentID); //Update the circuit data in the region so this user is authorized homeScene.UpdateCircuitData(userData); homeScene.ChangeCircuitCode(userData.circuitcode,(uint)circuitcode); // Load state // Keep state changes userState.first_name = requestMap["first_name"].AsString(); userState.secure_session_id = requestMap["secure_session_id"].AsUUID(); userState.age_verified = requestMap["age_verified"].AsBoolean(); userState.region_id = homeScene.RegionInfo.originRegionID; // replace 0000000 with our regionid userState.transacted = requestMap["transacted"].AsBoolean(); userState.agent_access = requestMap["agent_access"].AsBoolean(); userState.inventory_host = requestMap["inventory_host"].AsString(); userState.identified = requestMap["identified"].AsBoolean(); userState.session_id = requestMap["session_id"].AsUUID(); userState.god_level = (uint)requestMap["god_level"].AsInteger(); userState.last_name = requestMap["last_name"].AsString(); userState.god_overide = requestMap["god_override"].AsBoolean(); userState.circuit_code = (uint)requestMap["circuit_code"].AsInteger(); userState.limited_to_estate = requestMap["limited_to_estate"].AsInteger(); userState.src_estate_id = estateID; userState.region_id = regionID; userState.src_parent_estate_id = parentEstateID; userState.visible_to_parent = visibleToParent; // Save state changes UpdateOGPState(userData.AgentID, userState); // Get the region information for the home region. RegionInfo reg = homeScene.RegionInfo; // Dummy positional and look at info.. we don't have it. OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); // Our region's X and Y position in OpenSimulator space. uint fooX = reg.RegionLocX; uint fooY = reg.RegionLocY; m_log.InfoFormat("[OGP]: region x({0}) region y({1})", fooX, fooY); m_log.InfoFormat("[OGP]: region http {0} {1}", reg.ServerURI, reg.HttpPort); m_log.InfoFormat("[OGO]: region UUID {0} ", reg.RegionID); // Convert the X and Y position to LL space responseMap["region_x"] = OSD.FromInteger(fooX * (uint)Constants.RegionSize); // convert it to LL X responseMap["region_y"] = OSD.FromInteger(fooY * (uint)Constants.RegionSize); // convert it to LL Y // Give em a new seed capability responseMap["seed_capability"] = OSD.FromString("http://" + reg.ExternalHostName + ":" + reg.HttpPort + "/CAPS/" + userCap.CapsObjectPath + "0000/"); responseMap["region"] = OSD.FromUUID(reg.originRegionID); responseMap["look_at"] = LookAtArray; responseMap["sim_port"] = OSD.FromInteger(reg.InternalEndPoint.Port); responseMap["sim_host"] = OSD.FromString(reg.ExternalHostName);// + ":" + reg.InternalEndPoint.Port.ToString()); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(reg.ExternalHostName).ToString()); responseMap["session_id"] = OSD.FromUUID(SessionID); responseMap["secure_session_id"] = OSD.FromUUID(SecureSessionID); responseMap["circuit_code"] = OSD.FromInteger(circuitcode); responseMap["position"] = PositionArray; responseMap["region_id"] = OSD.FromUUID(reg.originRegionID); responseMap["sim_access"] = OSD.FromString("Mature"); responseMap["connect"] = OSD.FromBoolean(true); m_log.InfoFormat("[OGP]: host: {0}, IP {1}", responseMap["sim_host"].ToString(), responseMap["sim_ip"].ToString()); } } return responseMap; } public OSD DerezAvatarMethod(string path, OSD request) { m_log.ErrorFormat("DerezPath: {0}, Request: {1}", path, request.ToString()); //LLSD llsdResponse = null; OSDMap responseMap = new OSDMap(); string[] PathArray = path.Split('/'); m_log.InfoFormat("[OGP]: prefix {0}, uuid {1}, suffix {2}", PathArray[1], PathArray[2], PathArray[3]); string uuidString = PathArray[2]; m_log.InfoFormat("[OGP]: Request to Derez avatar with UUID {0}", uuidString); UUID userUUID = UUID.Zero; if (UUID.TryParse(uuidString, out userUUID)) { UUID RemoteID = (UUID)uuidString; UUID LocalID = RemoteID; // FIXME: TODO: Routine to map RemoteUUIDs to LocalUUIds // would be done already.. but the client connects with the Aditi UUID // regardless over the UDP stack OGPState userState = GetOGPState(LocalID); if (userState.agent_id != UUID.Zero) { //OSDMap outboundRequestMap = new OSDMap(); OSDMap inboundRequestMap = (OSDMap)request; string rezAvatarString = inboundRequestMap["rez_avatar"].AsString(); if (rezAvatarString.Length == 0) { rezAvatarString = inboundRequestMap["rez_avatar/rez"].AsString(); } OSDArray LookAtArray = new OSDArray(); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); LookAtArray.Add(OSD.FromInteger(1)); OSDArray PositionArray = new OSDArray(); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(128)); PositionArray.Add(OSD.FromInteger(40)); OSDArray lookArray = new OSDArray(); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(128)); lookArray.Add(OSD.FromInteger(40)); responseMap["connect"] = OSD.FromBoolean(true);// it's okay to give this user up responseMap["look_at"] = LookAtArray; m_log.WarnFormat("[OGP]: Invoking rez_avatar on host:{0} for avatar: {1} {2}", rezAvatarString, userState.first_name, userState.last_name); OSDMap rezResponseMap = invokeRezAvatarCap(responseMap, rezAvatarString,userState); // If invoking it returned an error, parse and end if (rezResponseMap.ContainsKey("connect")) { if (rezResponseMap["connect"].AsBoolean() == false) { return responseMap; } } string rezRespSeedCap = ""; // DEPRECATED if (rezResponseMap.ContainsKey("seed_capability")) rezRespSeedCap = rezResponseMap["seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("region_seed_capability")) rezRespSeedCap = rezResponseMap["region_seed_capability"].AsString(); // REPLACEMENT if (rezResponseMap.ContainsKey("rez_avatar/rez")) rezRespSeedCap = rezResponseMap["rez_avatar/rez"].AsString(); // DEPRECATED string rezRespSim_ip = rezResponseMap["sim_ip"].AsString(); string rezRespSim_host = rezResponseMap["sim_host"].AsString(); int rrPort = rezResponseMap["sim_port"].AsInteger(); int rrX = rezResponseMap["region_x"].AsInteger(); int rrY = rezResponseMap["region_y"].AsInteger(); m_log.ErrorFormat("X:{0}, Y:{1}", rrX, rrY); UUID rrRID = rezResponseMap["region_id"].AsUUID(); OSDArray RezResponsePositionArray = null; string rrAccess = rezResponseMap["sim_access"].AsString(); if (rezResponseMap.ContainsKey("position")) { RezResponsePositionArray = (OSDArray)rezResponseMap["position"]; } // DEPRECATED responseMap["seed_capability"] = OSD.FromString(rezRespSeedCap); // REPLACEMENT r3 responseMap["region_seed_capability"] = OSD.FromString(rezRespSeedCap); // DEPRECATED responseMap["sim_ip"] = OSD.FromString(Util.GetHostFromDNS(rezRespSim_ip).ToString()); responseMap["sim_host"] = OSD.FromString(rezRespSim_host); responseMap["sim_port"] = OSD.FromInteger(rrPort); responseMap["region_x"] = OSD.FromInteger(rrX); responseMap["region_y"] = OSD.FromInteger(rrY); responseMap["region_id"] = OSD.FromUUID(rrRID); responseMap["sim_access"] = OSD.FromString(rrAccess); if (RezResponsePositionArray != null) { responseMap["position"] = RezResponsePositionArray; } responseMap["look_at"] = lookArray; responseMap["connect"] = OSD.FromBoolean(true); ShutdownConnection(LocalID,this); // PLEASE STOP CHANGING THIS TO an M_LOG, M_LOG DOESN'T WORK ON MULTILINE .TOSTRINGS Console.WriteLine("RESPONSEDEREZ: " + responseMap.ToString()); return responseMap; } else { return GenerateNoStateMessage(LocalID); } } else { return GenerateNoHandlerMessage(); } //return responseMap; } private OSDMap invokeRezAvatarCap(OSDMap responseMap, string CapAddress, OGPState userState) { Scene reg = GetRootScene(); WebRequest DeRezRequest = WebRequest.Create(CapAddress); DeRezRequest.Method = "POST"; DeRezRequest.ContentType = "application/xml+llsd"; OSDMap RAMap = new OSDMap(); OSDMap AgentParms = new OSDMap(); OSDMap RegionParms = new OSDMap(); OSDArray Parameter = new OSDArray(2); OSDMap version = new OSDMap(); version["version"] = OSD.FromInteger(userState.src_version); Parameter.Add(version); OSDMap SrcData = new OSDMap(); SrcData["estate_id"] = OSD.FromInteger(reg.RegionInfo.EstateSettings.EstateID); SrcData["parent_estate_id"] = OSD.FromInteger((reg.RegionInfo.EstateSettings.ParentEstateID == 100 ? 1 : reg.RegionInfo.EstateSettings.ParentEstateID)); SrcData["region_id"] = OSD.FromUUID(reg.RegionInfo.originRegionID); SrcData["visible_to_parent"] = OSD.FromBoolean(userState.visible_to_parent); Parameter.Add(SrcData); AgentParms["first_name"] = OSD.FromString(userState.first_name); AgentParms["last_name"] = OSD.FromString(userState.last_name); AgentParms["agent_id"] = OSD.FromUUID(userState.agent_id); RegionParms["region_id"] = OSD.FromUUID(userState.region_id); AgentParms["circuit_code"] = OSD.FromInteger(userState.circuit_code); AgentParms["secure_session_id"] = OSD.FromUUID(userState.secure_session_id); AgentParms["session_id"] = OSD.FromUUID(userState.session_id); AgentParms["agent_access"] = OSD.FromBoolean(userState.agent_access); AgentParms["god_level"] = OSD.FromInteger(userState.god_level); AgentParms["god_overide"] = OSD.FromBoolean(userState.god_overide); AgentParms["identified"] = OSD.FromBoolean(userState.identified); AgentParms["transacted"] = OSD.FromBoolean(userState.transacted); AgentParms["age_verified"] = OSD.FromBoolean(userState.age_verified); AgentParms["limited_to_estate"] = OSD.FromInteger(userState.limited_to_estate); AgentParms["inventory_host"] = OSD.FromString(userState.inventory_host); // version 1 RAMap = AgentParms; // Planned for version 2 // RAMap["agent_params"] = AgentParms; RAMap["region_params"] = RegionParms; RAMap["parameter"] = Parameter; string RAMapString = RAMap.ToString(); m_log.InfoFormat("[OGP] RAMap string {0}", RAMapString); OSD LLSDofRAMap = RAMap; // RENAME if this works m_log.InfoFormat("[OGP]: LLSD of map as string was {0}", LLSDofRAMap.ToString()); //m_log.InfoFormat("[OGP]: LLSD+XML: {0}", LLSDParser.SerializeXmlString(LLSDofRAMap)); byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap); //string bufferDump = System.Text.Encoding.ASCII.GetString(buffer); //m_log.InfoFormat("[OGP]: buffer form is {0}",bufferDump); //m_log.InfoFormat("[OGP]: LLSD of map was {0}",buffer.Length); Stream os = null; try { // send the Post DeRezRequest.ContentLength = buffer.Length; //Count bytes to send os = DeRezRequest.GetRequestStream(); os.Write(buffer, 0, buffer.Length); //Send it os.Close(); m_log.InfoFormat("[OGP]: Derez Avatar Posted Rez Avatar request to remote sim {0}", CapAddress); } catch (WebException ex) { m_log.InfoFormat("[OGP] Bad send on de_rez_avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } m_log.Info("[OGP] waiting for a reply after rez avatar send"); string rez_avatar_reply = null; { // get the response try { WebResponse webResponse = DeRezRequest.GetResponse(); if (webResponse == null) { m_log.Info("[OGP:] Null reply on rez_avatar post"); } StreamReader sr = new StreamReader(webResponse.GetResponseStream()); rez_avatar_reply = sr.ReadToEnd().Trim(); m_log.InfoFormat("[OGP]: rez_avatar reply was {0} ", rez_avatar_reply); } catch (WebException ex) { m_log.InfoFormat("[OGP]: exception on read after send of rez avatar {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } OSD rezResponse = null; try { rezResponse = OSDParser.DeserializeLLSDXml(rez_avatar_reply); responseMap = (OSDMap)rezResponse; } catch (Exception ex) { m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message); responseMap["connect"] = OSD.FromBoolean(false); return responseMap; } } return responseMap; } public OSD GenerateNoHandlerMessage() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("LLSDRequest"); map["message"] = OSD.FromString("No handler registered for LLSD Requests"); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } public OSD GenerateNoStateMessage(UUID passedAvatar) { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("derez failed"); map["message"] = OSD.FromString("Unable to locate OGP state for avatar " + passedAvatar.ToString()); map["login"] = OSD.FromString("false"); map["connect"] = OSD.FromString("false"); return map; } private bool TryGetAgentCircuitData(string path, out AgentCircuitData userdata) { userdata = null; lock (CapsLoginID) { if (CapsLoginID.ContainsKey(path)) { userdata = CapsLoginID[path]; DiscardUsedCap(path); return true; } } return false; } private void DiscardUsedCap(string path) { CapsLoginID.Remove(path); } private Scene GetRootScene() { Scene ReturnScene = null; lock (m_scene) { if (m_scene.Count > 0) { ReturnScene = m_scene[0]; } } return ReturnScene; } private Scene GetScene(string scenename) { Scene ReturnScene = null; lock (m_scene) { foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName.ToLower() == scenename) { ReturnScene = s; break; } } } return ReturnScene; } private ulong GetOSCompatibleRegionHandle(RegionInfo reg) { return Util.UIntsToLong(reg.RegionLocX, reg.RegionLocY); } private OGPState InitializeNewState() { OGPState returnState = new OGPState(); returnState.first_name = ""; returnState.last_name = ""; returnState.agent_id = UUID.Zero; returnState.local_agent_id = UUID.Zero; returnState.region_id = UUID.Zero; returnState.circuit_code = 0; returnState.secure_session_id = UUID.Zero; returnState.session_id = UUID.Zero; returnState.agent_access = true; returnState.god_level = 0; returnState.god_overide = false; returnState.identified = false; returnState.transacted = false; returnState.age_verified = false; returnState.limited_to_estate = 1; returnState.inventory_host = "http://inv4.mysql.aditi.lindenlab.com"; returnState.allow_redirect = true; returnState.sim_access = ""; returnState.src_can_see_mainland = true; returnState.src_estate_id = 1; returnState.src_version = 1; returnState.src_parent_estate_id = 1; returnState.visible_to_parent = true; returnState.teleported_into_region = ""; return returnState; } private OGPState GetOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { return m_OGPState[agentId]; } else { return InitializeNewState(); } } } public void DeleteOGPState(UUID agentId) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) m_OGPState.Remove(agentId); } } private void UpdateOGPState(UUID agentId, OGPState state) { lock (m_OGPState) { if (m_OGPState.ContainsKey(agentId)) { m_OGPState[agentId] = state; } else { m_OGPState.Add(agentId,state); } } } private bool SceneListDuplicateCheck(string str) { // no lock, called from locked space! bool found = false; foreach (Scene s in m_scene) { if (s.RegionInfo.RegionName == str) { found = true; break; } } return found; } public void ShutdownConnection(UUID avatarId, OpenGridProtocolModule mod) { Scene homeScene = GetRootScene(); ScenePresence avatar = null; if (homeScene.TryGetAvatar(avatarId,out avatar)) { KillAUser ku = new KillAUser(avatar,mod); Watchdog.StartThread(ku.ShutdownNoLogout, "OGPShutdown", ThreadPriority.Normal, true); } } private string CreateRandomStr(int len) { Random rnd = new Random(Environment.TickCount); string returnstring = ""; string chars = "abcdefghijklmnopqrstuvwxyz0123456789"; for (int i = 0; i < len; i++) { returnstring += chars.Substring(rnd.Next(chars.Length), 1); } return returnstring; } // Temporary hack to allow teleporting to and from Vaak private static bool customXertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { //if (cert.Subject == "E=root@lindenlab.com, CN=*.vaak.lindenlab.com, O=\"Linden Lab, Inc.\", L=San Francisco, S=California, C=US") //{ return true; //} //return false; } } public class KillAUser { private ScenePresence avToBeKilled = null; private OpenGridProtocolModule m_mod = null; public KillAUser(ScenePresence avatar, OpenGridProtocolModule mod) { avToBeKilled = avatar; m_mod = mod; } public void ShutdownNoLogout() { UUID avUUID = UUID.Zero; if (avToBeKilled != null) { avUUID = avToBeKilled.UUID; avToBeKilled.MakeChildAgent(); avToBeKilled.ControllingClient.SendLogoutPacketWhenClosing = false; int sleepMS = 30000; while (sleepMS > 0) { Watchdog.UpdateThread(); Thread.Sleep(1000); sleepMS -= 1000; } // test for child agent because they might have come back if (avToBeKilled.IsChildAgent) { m_mod.DeleteOGPState(avUUID); avToBeKilled.ControllingClient.Close(); } } Watchdog.RemoveThread(); } } public class MonoCert : ICertificatePolicy { #region ICertificatePolicy Members public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.SiteMapPath.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { public partial class SiteMapPath : CompositeControl { #region Methods and constructors protected internal override void CreateChildControls() { } protected virtual new void CreateControlHierarchy() { } public override void DataBind() { } protected virtual new void InitializeItem(SiteMapNodeItem item) { } protected override void LoadViewState(Object savedState) { } protected override void OnDataBinding(EventArgs e) { } protected virtual new void OnItemCreated(SiteMapNodeItemEventArgs e) { } protected virtual new void OnItemDataBound(SiteMapNodeItemEventArgs e) { } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } protected internal override void RenderContents(System.Web.UI.HtmlTextWriter writer) { } protected override Object SaveViewState() { return default(Object); } public SiteMapPath() { } protected override void TrackViewState() { } #endregion #region Properties and indexers public Style CurrentNodeStyle { get { return default(Style); } } public virtual new System.Web.UI.ITemplate CurrentNodeTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public Style NodeStyle { get { return default(Style); } } public virtual new System.Web.UI.ITemplate NodeTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new int ParentLevelsDisplayed { get { return default(int); } set { } } public virtual new PathDirection PathDirection { get { return default(PathDirection); } set { } } public virtual new string PathSeparator { get { return default(string); } set { } } public Style PathSeparatorStyle { get { return default(Style); } } public virtual new System.Web.UI.ITemplate PathSeparatorTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public System.Web.SiteMapProvider Provider { get { return default(System.Web.SiteMapProvider); } set { } } public virtual new bool RenderCurrentNodeAsLink { get { return default(bool); } set { } } public Style RootNodeStyle { get { return default(Style); } } public virtual new System.Web.UI.ITemplate RootNodeTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public virtual new bool ShowToolTips { get { return default(bool); } set { } } public virtual new string SiteMapProvider { get { return default(string); } set { } } public virtual new string SkipLinkText { get { return default(string); } set { } } #endregion #region Events public event SiteMapNodeItemEventHandler ItemCreated { add { } remove { } } public event SiteMapNodeItemEventHandler ItemDataBound { add { } remove { } } #endregion } }
// // CoreFoundation.cs // // Author: // Michael Hutchinson <mhutchinson@novell.com> // Miguel de Icaza // // Copyright (c) 2009 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace Moscrif.IDE { internal static class CoreFoundation { const string CFLib = "/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation"; const string LSLib = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/ApplicationServices"; [DllImport (CFLib)] static extern IntPtr CFStringCreateWithCString (IntPtr alloc, string str, int encoding); public static IntPtr CreateString (string s) { // The magic value is "kCFStringENcodingUTF8" return CFStringCreateWithCString (IntPtr.Zero, s, 0x08000100); } [DllImport (CFLib, EntryPoint="CFRelease")] public static extern void Release (IntPtr cfRef); struct CFRange { public int Location, Length; public CFRange (int l, int len) { Location = l; Length = len; } } [DllImport (CFLib, CharSet=CharSet.Unicode)] extern static int CFStringGetLength (IntPtr handle); [DllImport (CFLib, CharSet=CharSet.Unicode)] extern static IntPtr CFStringGetCharactersPtr (IntPtr handle); [DllImport (CFLib, CharSet=CharSet.Unicode)] extern static IntPtr CFStringGetCharacters (IntPtr handle, CFRange range, IntPtr buffer); public static string FetchString (IntPtr handle) { if (handle == IntPtr.Zero) return null; string str; int l = CFStringGetLength (handle); IntPtr u = CFStringGetCharactersPtr (handle); IntPtr buffer = IntPtr.Zero; if (u == IntPtr.Zero){ CFRange r = new CFRange (0, l); buffer = Marshal.AllocCoTaskMem (l * 2); CFStringGetCharacters (handle, r, buffer); u = buffer; } unsafe { str = new string ((char *) u, 0, l); } if (buffer != IntPtr.Zero) Marshal.FreeCoTaskMem (buffer); return str; } public static string FSRefToString (ref FSRef fsref) { IntPtr url = IntPtr.Zero; IntPtr str = IntPtr.Zero; try { url = CFURLCreateFromFSRef (IntPtr.Zero, ref fsref); if (url == IntPtr.Zero) return null; str = CFURLCopyFileSystemPath (url, CFUrlPathStyle.Posix); if (str == IntPtr.Zero) return null; return FetchString (str); } finally { if (url != IntPtr.Zero) Release (url); if (str != IntPtr.Zero) Release (str); } } [DllImport (CFLib)] extern static IntPtr CFURLCreateFromFSRef (IntPtr allocator, ref FSRef fsref); [DllImport (CFLib)] extern static IntPtr CFURLCopyFileSystemPath (IntPtr urlRef, CFUrlPathStyle pathStyle); enum CFUrlPathStyle { Posix = 0, Hfs = 1, Windows = 2 }; [DllImport (CFLib)] extern static IntPtr CFURLCreateWithFileSystemPath (IntPtr allocator, IntPtr filePathString, CFUrlPathStyle pathStyle, bool isDirectory); [DllImport (LSLib)] extern static IntPtr LSCopyApplicationURLsForURL (IntPtr urlRef, LSRolesMask roleMask); //CFArrayRef [DllImport (LSLib)] extern static int LSGetApplicationForURL (IntPtr url, LSRolesMask roleMask, IntPtr fsRefZero, ref IntPtr appUrl); [DllImport (CFLib)] extern static int CFArrayGetCount (IntPtr theArray); [DllImport (CFLib)] extern static IntPtr CFArrayGetValueAtIndex (IntPtr theArray, int idx); [Flags] public enum LSRolesMask : uint { None = 0x00000001, Viewer = 0x00000002, Editor = 0x00000004, Shell = 0x00000008, All = 0xFFFFFFFF } static IntPtr CreatePathUrl (string path) { IntPtr str = IntPtr.Zero; IntPtr url = IntPtr.Zero; try { str = CreateString (path); if (str == IntPtr.Zero) throw new Exception ("CreateString failed"); url = CFURLCreateWithFileSystemPath (IntPtr.Zero, str, CFUrlPathStyle.Posix, false); if (url == IntPtr.Zero) throw new Exception ("CFURLCreateWithFileSystemPath failed"); return url; } finally { if (str != IntPtr.Zero) Release (str); } } public static string UrlToPath (IntPtr url) { IntPtr str = IntPtr.Zero; try { str = CFURLCopyFileSystemPath (url, CFUrlPathStyle.Posix); return str == IntPtr.Zero? null : FetchString (str); } finally { if (str != IntPtr.Zero) Release (str); } } public static string GetApplicationUrl (string filePath, LSRolesMask roles) { IntPtr url = IntPtr.Zero; try { url = CreatePathUrl (filePath); IntPtr appUrl = IntPtr.Zero; if (LSGetApplicationForURL (url, roles, IntPtr.Zero, ref appUrl) == 0 && appUrl != IntPtr.Zero) return UrlToPath (appUrl); return null; } finally { if (url != IntPtr.Zero) Release (url); } } public static string[] GetApplicationUrls (string filePath, LSRolesMask roles) { IntPtr url = IntPtr.Zero; IntPtr arr = IntPtr.Zero; try { url = CreatePathUrl (filePath); arr = LSCopyApplicationURLsForURL (url, roles); if (arr == IntPtr.Zero) return new string[0]; int count = CFArrayGetCount (arr); string[] values = new string [count]; for (int i = 0; i < values.Length; i++ ) { var u = CFArrayGetValueAtIndex (arr, i); if (u != IntPtr.Zero) values[i] = UrlToPath (u); } return values; } finally { if (url != IntPtr.Zero) Release (url); if (arr != IntPtr.Zero) Release (arr); } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Autodiscover { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Text; using System.Xml; using Microsoft.Exchange.WebServices.Data; /// <summary> /// Represents the response to a GetDomainSettings call for an individual domain. /// </summary> public sealed class GetDomainSettingsResponse : AutodiscoverResponse { private string domain; private string redirectTarget; private Dictionary<DomainSettingName, object> settings; private Collection<DomainSettingError> domainSettingErrors; /// <summary> /// Initializes a new instance of the <see cref="GetDomainSettingsResponse"/> class. /// </summary> public GetDomainSettingsResponse() : base() { this.domain = string.Empty; this.settings = new Dictionary<DomainSettingName, object>(); this.domainSettingErrors = new Collection<DomainSettingError>(); } /// <summary> /// Gets the domain this response applies to. /// </summary> public string Domain { get { return this.domain; } internal set { this.domain = value; } } /// <summary> /// Gets the redirectionTarget (URL or email address) /// </summary> public string RedirectTarget { get { return this.redirectTarget; } } /// <summary> /// Gets the requested settings for the domain. /// </summary> public IDictionary<DomainSettingName, object> Settings { get { return this.settings; } } /// <summary> /// Gets error information for settings that could not be returned. /// </summary> public Collection<DomainSettingError> DomainSettingErrors { get { return this.domainSettingErrors; } } /// <summary> /// Loads response from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="endElementName">End element name.</param> internal override void LoadFromXml(EwsXmlReader reader, string endElementName) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case XmlElementNames.RedirectTarget: this.redirectTarget = reader.ReadElementValue(); break; case XmlElementNames.DomainSettingErrors: this.LoadDomainSettingErrorsFromXml(reader); break; case XmlElementNames.DomainSettings: this.LoadDomainSettingsFromXml(reader); break; default: base.LoadFromXml(reader, endElementName); break; } } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, endElementName)); } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> internal void LoadDomainSettingsFromXml(EwsXmlReader reader) { if (!reader.IsEmptyElement) { do { reader.Read(); if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.DomainSetting)) { string settingClass = reader.ReadAttributeValue(XmlNamespace.XmlSchemaInstance, XmlAttributeNames.Type); switch (settingClass) { case XmlElementNames.DomainStringSetting: this.ReadSettingFromXml(reader); break; default: EwsUtilities.Assert( false, "GetDomainSettingsResponse.LoadDomainSettingsFromXml", string.Format("Invalid setting class '{0}' returned", settingClass)); break; } } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.DomainSettings)); } } /// <summary> /// Reads domain setting from XML. /// </summary> /// <param name="reader">The reader.</param> private void ReadSettingFromXml(EwsXmlReader reader) { DomainSettingName? name = null; object value = null; do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case XmlElementNames.Name: name = reader.ReadElementValue<DomainSettingName>(); break; case XmlElementNames.Value: value = reader.ReadElementValue(); break; } } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.DomainSetting)); EwsUtilities.Assert( name.HasValue, "GetDomainSettingsResponse.ReadSettingFromXml", "Missing name element in domain setting"); this.settings.Add(name.Value, value); } /// <summary> /// Loads the domain setting errors. /// </summary> /// <param name="reader">The reader.</param> private void LoadDomainSettingErrorsFromXml(EwsXmlReader reader) { if (!reader.IsEmptyElement) { do { reader.Read(); if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == XmlElementNames.DomainSettingError)) { DomainSettingError error = new DomainSettingError(); error.LoadFromXml(reader); domainSettingErrors.Add(error); } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.DomainSettingErrors)); } } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ #if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1) #define IS_UNITY #endif using System; using System.IO; using System.Collections.Generic; #if WINDOWS_STOREAPP using System.Threading.Tasks; using Windows.Storage; #endif namespace Spine { public class SkeletonBinary { public const int BONE_ROTATE = 0; public const int BONE_TRANSLATE = 1; public const int BONE_SCALE = 2; public const int BONE_SHEAR = 3; public const int SLOT_ATTACHMENT = 0; public const int SLOT_COLOR = 1; public const int SLOT_TWO_COLOR = 2; public const int PATH_POSITION = 0; public const int PATH_SPACING = 1; public const int PATH_MIX = 2; public const int CURVE_LINEAR = 0; public const int CURVE_STEPPED = 1; public const int CURVE_BEZIER = 2; public float Scale { get; set; } private AttachmentLoader attachmentLoader; private byte[] buffer = new byte[32]; private List<SkeletonJson.LinkedMesh> linkedMeshes = new List<SkeletonJson.LinkedMesh>(); public SkeletonBinary (params Atlas[] atlasArray) : this(new AtlasAttachmentLoader(atlasArray)) { } public SkeletonBinary (AttachmentLoader attachmentLoader) { if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader"); this.attachmentLoader = attachmentLoader; Scale = 1; } #if !ISUNITY && WINDOWS_STOREAPP private async Task<SkeletonData> ReadFile(string path) { var folder = Windows.ApplicationModel.Package.Current.InstalledLocation; using (var input = new BufferedStream(await folder.GetFileAsync(path).AsTask().ConfigureAwait(false))) { SkeletonData skeletonData = ReadSkeletonData(input); skeletonData.Name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } public SkeletonData ReadSkeletonData (String path) { return this.ReadFile(path).Result; } #else public SkeletonData ReadSkeletonData (String path) { #if WINDOWS_PHONE using (var input = new BufferedStream(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) { #else using (var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { #endif SkeletonData skeletonData = ReadSkeletonData(input); skeletonData.name = Path.GetFileNameWithoutExtension(path); return skeletonData; } } #endif // WINDOWS_STOREAPP public static readonly TransformMode[] TransformModeValues = { TransformMode.Normal, TransformMode.OnlyTranslation, TransformMode.NoRotationOrReflection, TransformMode.NoScale, TransformMode.NoScaleOrReflection }; /// <summary>Returns the version string of binary skeleton data.</summary> public static string GetVersionString (Stream input) { if (input == null) throw new ArgumentNullException("input"); try { // Hash. int byteCount = ReadVarint(input, true); if (byteCount > 1) input.Position += byteCount - 1; // Version. byteCount = ReadVarint(input, true); if (byteCount > 1) { byteCount--; var buffer = new byte[byteCount]; ReadFully(input, buffer, 0, byteCount); return System.Text.Encoding.UTF8.GetString(buffer, 0, byteCount); } throw new ArgumentException("Stream does not contain a valid binary Skeleton Data.", "input"); } catch (Exception e) { throw new ArgumentException("Stream does not contain a valid binary Skeleton Data.\n" + e, "input"); } } public SkeletonData ReadSkeletonData (Stream input) { if (input == null) throw new ArgumentNullException("input"); float scale = Scale; var skeletonData = new SkeletonData(); skeletonData.hash = ReadString(input); if (skeletonData.hash.Length == 0) skeletonData.hash = null; skeletonData.version = ReadString(input); if (skeletonData.version.Length == 0) skeletonData.version = null; skeletonData.width = ReadFloat(input); skeletonData.height = ReadFloat(input); bool nonessential = ReadBoolean(input); if (nonessential) { skeletonData.fps = ReadFloat(input); skeletonData.imagesPath = ReadString(input); if (skeletonData.imagesPath.Length == 0) skeletonData.imagesPath = null; } // Bones. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { String name = ReadString(input); BoneData parent = i == 0 ? null : skeletonData.bones.Items[ReadVarint(input, true)]; BoneData data = new BoneData(i, name, parent); data.rotation = ReadFloat(input); data.x = ReadFloat(input) * scale; data.y = ReadFloat(input) * scale; data.scaleX = ReadFloat(input); data.scaleY = ReadFloat(input); data.shearX = ReadFloat(input); data.shearY = ReadFloat(input); data.length = ReadFloat(input) * scale; data.transformMode = TransformModeValues[ReadVarint(input, true)]; if (nonessential) ReadInt(input); // Skip bone color. skeletonData.bones.Add(data); } // Slots. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { String slotName = ReadString(input); BoneData boneData = skeletonData.bones.Items[ReadVarint(input, true)]; SlotData slotData = new SlotData(i, slotName, boneData); int color = ReadInt(input); slotData.r = ((color & 0xff000000) >> 24) / 255f; slotData.g = ((color & 0x00ff0000) >> 16) / 255f; slotData.b = ((color & 0x0000ff00) >> 8) / 255f; slotData.a = ((color & 0x000000ff)) / 255f; int darkColor = ReadInt(input); // 0x00rrggbb if (darkColor != -1) { slotData.hasSecondColor = true; slotData.r2 = ((darkColor & 0x00ff0000) >> 16) / 255f; slotData.g2 = ((darkColor & 0x0000ff00) >> 8) / 255f; slotData.b2 = ((darkColor & 0x000000ff)) / 255f; } slotData.attachmentName = ReadString(input); slotData.blendMode = (BlendMode)ReadVarint(input, true); skeletonData.slots.Add(slotData); } // IK constraints. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { IkConstraintData data = new IkConstraintData(ReadString(input)); data.order = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) data.bones.Add(skeletonData.bones.Items[ReadVarint(input, true)]); data.target = skeletonData.bones.Items[ReadVarint(input, true)]; data.mix = ReadFloat(input); data.bendDirection = ReadSByte(input); skeletonData.ikConstraints.Add(data); } // Transform constraints. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { TransformConstraintData data = new TransformConstraintData(ReadString(input)); data.order = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) data.bones.Add(skeletonData.bones.Items[ReadVarint(input, true)]); data.target = skeletonData.bones.Items[ReadVarint(input, true)]; data.local = ReadBoolean(input); data.relative = ReadBoolean(input); data.offsetRotation = ReadFloat(input); data.offsetX = ReadFloat(input) * scale; data.offsetY = ReadFloat(input) * scale; data.offsetScaleX = ReadFloat(input); data.offsetScaleY = ReadFloat(input); data.offsetShearY = ReadFloat(input); data.rotateMix = ReadFloat(input); data.translateMix = ReadFloat(input); data.scaleMix = ReadFloat(input); data.shearMix = ReadFloat(input); skeletonData.transformConstraints.Add(data); } // Path constraints for (int i = 0, n = ReadVarint(input, true); i < n; i++) { PathConstraintData data = new PathConstraintData(ReadString(input)); data.order = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) data.bones.Add(skeletonData.bones.Items[ReadVarint(input, true)]); data.target = skeletonData.slots.Items[ReadVarint(input, true)]; data.positionMode = (PositionMode)Enum.GetValues(typeof(PositionMode)).GetValue(ReadVarint(input, true)); data.spacingMode = (SpacingMode)Enum.GetValues(typeof(SpacingMode)).GetValue(ReadVarint(input, true)); data.rotateMode = (RotateMode)Enum.GetValues(typeof(RotateMode)).GetValue(ReadVarint(input, true)); data.offsetRotation = ReadFloat(input); data.position = ReadFloat(input); if (data.positionMode == PositionMode.Fixed) data.position *= scale; data.spacing = ReadFloat(input); if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale; data.rotateMix = ReadFloat(input); data.translateMix = ReadFloat(input); skeletonData.pathConstraints.Add(data); } // Default skin. Skin defaultSkin = ReadSkin(input, skeletonData, "default", nonessential); if (defaultSkin != null) { skeletonData.defaultSkin = defaultSkin; skeletonData.skins.Add(defaultSkin); } // Skins. for (int i = 0, n = ReadVarint(input, true); i < n; i++) skeletonData.skins.Add(ReadSkin(input, skeletonData, ReadString(input), nonessential)); // Linked meshes. for (int i = 0, n = linkedMeshes.Count; i < n; i++) { SkeletonJson.LinkedMesh linkedMesh = linkedMeshes[i]; Skin skin = linkedMesh.skin == null ? skeletonData.DefaultSkin : skeletonData.FindSkin(linkedMesh.skin); if (skin == null) throw new Exception("Skin not found: " + linkedMesh.skin); Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent); if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent); linkedMesh.mesh.ParentMesh = (MeshAttachment)parent; linkedMesh.mesh.UpdateUVs(); } linkedMeshes.Clear(); // Events. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { EventData data = new EventData(ReadString(input)); data.Int = ReadVarint(input, false); data.Float = ReadFloat(input); data.String = ReadString(input); skeletonData.events.Add(data); } // Animations. for (int i = 0, n = ReadVarint(input, true); i < n; i++) ReadAnimation(ReadString(input), input, skeletonData); skeletonData.bones.TrimExcess(); skeletonData.slots.TrimExcess(); skeletonData.skins.TrimExcess(); skeletonData.events.TrimExcess(); skeletonData.animations.TrimExcess(); skeletonData.ikConstraints.TrimExcess(); skeletonData.pathConstraints.TrimExcess(); return skeletonData; } /// <returns>May be null.</returns> private Skin ReadSkin (Stream input, SkeletonData skeletonData, String skinName, bool nonessential) { int slotCount = ReadVarint(input, true); if (slotCount == 0) return null; Skin skin = new Skin(skinName); for (int i = 0; i < slotCount; i++) { int slotIndex = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) { String name = ReadString(input); Attachment attachment = ReadAttachment(input, skeletonData, skin, slotIndex, name, nonessential); if (attachment != null) skin.AddAttachment(slotIndex, name, attachment); } } return skin; } private Attachment ReadAttachment (Stream input, SkeletonData skeletonData, Skin skin, int slotIndex, String attachmentName, bool nonessential) { float scale = Scale; String name = ReadString(input); if (name == null) name = attachmentName; AttachmentType type = (AttachmentType)input.ReadByte(); switch (type) { case AttachmentType.Region: { String path = ReadString(input); float rotation = ReadFloat(input); float x = ReadFloat(input); float y = ReadFloat(input); float scaleX = ReadFloat(input); float scaleY = ReadFloat(input); float width = ReadFloat(input); float height = ReadFloat(input); int color = ReadInt(input); if (path == null) path = name; RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path); if (region == null) return null; region.Path = path; region.x = x * scale; region.y = y * scale; region.scaleX = scaleX; region.scaleY = scaleY; region.rotation = rotation; region.width = width * scale; region.height = height * scale; region.r = ((color & 0xff000000) >> 24) / 255f; region.g = ((color & 0x00ff0000) >> 16) / 255f; region.b = ((color & 0x0000ff00) >> 8) / 255f; region.a = ((color & 0x000000ff)) / 255f; region.UpdateOffset(); return region; } case AttachmentType.Boundingbox: { int vertexCount = ReadVarint(input, true); Vertices vertices = ReadVertices(input, vertexCount); if (nonessential) ReadInt(input); //int color = nonessential ? ReadInt(input) : 0; // Avoid unused local warning. BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name); if (box == null) return null; box.worldVerticesLength = vertexCount << 1; box.vertices = vertices.vertices; box.bones = vertices.bones; return box; } case AttachmentType.Mesh: { String path = ReadString(input); int color = ReadInt(input); int vertexCount = ReadVarint(input, true); float[] uvs = ReadFloatArray(input, vertexCount << 1, 1); int[] triangles = ReadShortArray(input); Vertices vertices = ReadVertices(input, vertexCount); int hullLength = ReadVarint(input, true); int[] edges = null; float width = 0, height = 0; if (nonessential) { edges = ReadShortArray(input); width = ReadFloat(input); height = ReadFloat(input); } if (path == null) path = name; MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; mesh.r = ((color & 0xff000000) >> 24) / 255f; mesh.g = ((color & 0x00ff0000) >> 16) / 255f; mesh.b = ((color & 0x0000ff00) >> 8) / 255f; mesh.a = ((color & 0x000000ff)) / 255f; mesh.bones = vertices.bones; mesh.vertices = vertices.vertices; mesh.WorldVerticesLength = vertexCount << 1; mesh.triangles = triangles; mesh.regionUVs = uvs; mesh.UpdateUVs(); mesh.HullLength = hullLength << 1; if (nonessential) { mesh.Edges = edges; mesh.Width = width * scale; mesh.Height = height * scale; } return mesh; } case AttachmentType.Linkedmesh: { String path = ReadString(input); int color = ReadInt(input); String skinName = ReadString(input); String parent = ReadString(input); bool inheritDeform = ReadBoolean(input); float width = 0, height = 0; if (nonessential) { width = ReadFloat(input); height = ReadFloat(input); } if (path == null) path = name; MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path); if (mesh == null) return null; mesh.Path = path; mesh.r = ((color & 0xff000000) >> 24) / 255f; mesh.g = ((color & 0x00ff0000) >> 16) / 255f; mesh.b = ((color & 0x0000ff00) >> 8) / 255f; mesh.a = ((color & 0x000000ff)) / 255f; mesh.inheritDeform = inheritDeform; if (nonessential) { mesh.Width = width * scale; mesh.Height = height * scale; } linkedMeshes.Add(new SkeletonJson.LinkedMesh(mesh, skinName, slotIndex, parent)); return mesh; } case AttachmentType.Path: { bool closed = ReadBoolean(input); bool constantSpeed = ReadBoolean(input); int vertexCount = ReadVarint(input, true); Vertices vertices = ReadVertices(input, vertexCount); float[] lengths = new float[vertexCount / 3]; for (int i = 0, n = lengths.Length; i < n; i++) lengths[i] = ReadFloat(input) * scale; if (nonessential) ReadInt(input); //int color = nonessential ? ReadInt(input) : 0; PathAttachment path = attachmentLoader.NewPathAttachment(skin, name); if (path == null) return null; path.closed = closed; path.constantSpeed = constantSpeed; path.worldVerticesLength = vertexCount << 1; path.vertices = vertices.vertices; path.bones = vertices.bones; path.lengths = lengths; return path; } case AttachmentType.Point: { float rotation = ReadFloat(input); float x = ReadFloat(input); float y = ReadFloat(input); if (nonessential) ReadInt(input); //int color = nonessential ? ReadInt(input) : 0; PointAttachment point = attachmentLoader.NewPointAttachment(skin, name); if (point == null) return null; point.x = x * scale; point.y = y * scale; point.rotation = rotation; //if (nonessential) point.color = color; return point; } case AttachmentType.Clipping: { int endSlotIndex = ReadVarint(input, true); int vertexCount = ReadVarint(input, true); Vertices vertices = ReadVertices(input, vertexCount); if (nonessential) ReadInt(input); ClippingAttachment clip = attachmentLoader.NewClippingAttachment(skin, name); if (clip == null) return null; clip.EndSlot = skeletonData.slots.Items[endSlotIndex]; clip.worldVerticesLength = vertexCount << 1; clip.vertices = vertices.vertices; clip.bones = vertices.bones; return clip; } } return null; } private Vertices ReadVertices (Stream input, int vertexCount) { float scale = Scale; int verticesLength = vertexCount << 1; Vertices vertices = new Vertices(); if(!ReadBoolean(input)) { vertices.vertices = ReadFloatArray(input, verticesLength, scale); return vertices; } var weights = new ExposedList<float>(verticesLength * 3 * 3); var bonesArray = new ExposedList<int>(verticesLength * 3); for (int i = 0; i < vertexCount; i++) { int boneCount = ReadVarint(input, true); bonesArray.Add(boneCount); for (int ii = 0; ii < boneCount; ii++) { bonesArray.Add(ReadVarint(input, true)); weights.Add(ReadFloat(input) * scale); weights.Add(ReadFloat(input) * scale); weights.Add(ReadFloat(input)); } } vertices.vertices = weights.ToArray(); vertices.bones = bonesArray.ToArray(); return vertices; } private float[] ReadFloatArray (Stream input, int n, float scale) { float[] array = new float[n]; if (scale == 1) { for (int i = 0; i < n; i++) array[i] = ReadFloat(input); } else { for (int i = 0; i < n; i++) array[i] = ReadFloat(input) * scale; } return array; } private int[] ReadShortArray (Stream input) { int n = ReadVarint(input, true); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = (input.ReadByte() << 8) | input.ReadByte(); return array; } private void ReadAnimation (String name, Stream input, SkeletonData skeletonData) { var timelines = new ExposedList<Timeline>(); float scale = Scale; float duration = 0; // Slot timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { int slotIndex = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) { int timelineType = input.ReadByte(); int frameCount = ReadVarint(input, true); switch (timelineType) { case SLOT_ATTACHMENT: { AttachmentTimeline timeline = new AttachmentTimeline(frameCount); timeline.slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) timeline.SetFrame(frameIndex, ReadFloat(input), ReadString(input)); timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount - 1]); break; } case SLOT_COLOR: { ColorTimeline timeline = new ColorTimeline(frameCount); timeline.slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float time = ReadFloat(input); int color = ReadInt(input); float r = ((color & 0xff000000) >> 24) / 255f; float g = ((color & 0x00ff0000) >> 16) / 255f; float b = ((color & 0x0000ff00) >> 8) / 255f; float a = ((color & 0x000000ff)) / 255f; timeline.SetFrame(frameIndex, time, r, g, b, a); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * ColorTimeline.ENTRIES]); break; } case SLOT_TWO_COLOR: { TwoColorTimeline timeline = new TwoColorTimeline(frameCount); timeline.slotIndex = slotIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float time = ReadFloat(input); int color = ReadInt(input); float r = ((color & 0xff000000) >> 24) / 255f; float g = ((color & 0x00ff0000) >> 16) / 255f; float b = ((color & 0x0000ff00) >> 8) / 255f; float a = ((color & 0x000000ff)) / 255f; int color2 = ReadInt(input); // 0x00rrggbb float r2 = ((color2 & 0x00ff0000) >> 16) / 255f; float g2 = ((color2 & 0x0000ff00) >> 8) / 255f; float b2 = ((color2 & 0x000000ff)) / 255f; timeline.SetFrame(frameIndex, time, r, g, b, a, r2, g2, b2); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TwoColorTimeline.ENTRIES]); break; } } } } // Bone timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { int boneIndex = ReadVarint(input, true); for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) { int timelineType = input.ReadByte(); int frameCount = ReadVarint(input, true); switch (timelineType) { case BONE_ROTATE: { RotateTimeline timeline = new RotateTimeline(frameCount); timeline.boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * RotateTimeline.ENTRIES]); break; } case BONE_TRANSLATE: case BONE_SCALE: case BONE_SHEAR: { TranslateTimeline timeline; float timelineScale = 1; if (timelineType == BONE_SCALE) timeline = new ScaleTimeline(frameCount); else if (timelineType == BONE_SHEAR) timeline = new ShearTimeline(frameCount); else { timeline = new TranslateTimeline(frameCount); timelineScale = scale; } timeline.boneIndex = boneIndex; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input) * timelineScale, ReadFloat(input) * timelineScale); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TranslateTimeline.ENTRIES]); break; } } } } // IK timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { int index = ReadVarint(input, true); int frameCount = ReadVarint(input, true); IkConstraintTimeline timeline = new IkConstraintTimeline(frameCount); timeline.ikConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadSByte(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * IkConstraintTimeline.ENTRIES]); } // Transform constraint timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { int index = ReadVarint(input, true); int frameCount = ReadVarint(input, true); TransformConstraintTimeline timeline = new TransformConstraintTimeline(frameCount); timeline.transformConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TransformConstraintTimeline.ENTRIES]); } // Path constraint timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { int index = ReadVarint(input, true); PathConstraintData data = skeletonData.pathConstraints.Items[index]; for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) { int timelineType = ReadSByte(input); int frameCount = ReadVarint(input, true); switch(timelineType) { case PATH_POSITION: case PATH_SPACING: { PathConstraintPositionTimeline timeline; float timelineScale = 1; if (timelineType == PATH_SPACING) { timeline = new PathConstraintSpacingTimeline(frameCount); if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) timelineScale = scale; } else { timeline = new PathConstraintPositionTimeline(frameCount); if (data.positionMode == PositionMode.Fixed) timelineScale = scale; } timeline.pathConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input) * timelineScale); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintPositionTimeline.ENTRIES]); break; } case PATH_MIX: { PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(frameCount); timeline.pathConstraintIndex = index; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input)); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintMixTimeline.ENTRIES]); break; } } } } // Deform timelines. for (int i = 0, n = ReadVarint(input, true); i < n; i++) { Skin skin = skeletonData.skins.Items[ReadVarint(input, true)]; for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++) { int slotIndex = ReadVarint(input, true); for (int iii = 0, nnn = ReadVarint(input, true); iii < nnn; iii++) { VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, ReadString(input)); bool weighted = attachment.bones != null; float[] vertices = attachment.vertices; int deformLength = weighted ? vertices.Length / 3 * 2 : vertices.Length; int frameCount = ReadVarint(input, true); DeformTimeline timeline = new DeformTimeline(frameCount); timeline.slotIndex = slotIndex; timeline.attachment = attachment; for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) { float time = ReadFloat(input); float[] deform; int end = ReadVarint(input, true); if (end == 0) deform = weighted ? new float[deformLength] : vertices; else { deform = new float[deformLength]; int start = ReadVarint(input, true); end += start; if (scale == 1) { for (int v = start; v < end; v++) deform[v] = ReadFloat(input); } else { for (int v = start; v < end; v++) deform[v] = ReadFloat(input) * scale; } if (!weighted) { for (int v = 0, vn = deform.Length; v < vn; v++) deform[v] += vertices[v]; } } timeline.SetFrame(frameIndex, time, deform); if (frameIndex < frameCount - 1) ReadCurve(input, frameIndex, timeline); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[frameCount - 1]); } } } // Draw order timeline. int drawOrderCount = ReadVarint(input, true); if (drawOrderCount > 0) { DrawOrderTimeline timeline = new DrawOrderTimeline(drawOrderCount); int slotCount = skeletonData.slots.Count; for (int i = 0; i < drawOrderCount; i++) { float time = ReadFloat(input); int offsetCount = ReadVarint(input, true); int[] drawOrder = new int[slotCount]; for (int ii = slotCount - 1; ii >= 0; ii--) drawOrder[ii] = -1; int[] unchanged = new int[slotCount - offsetCount]; int originalIndex = 0, unchangedIndex = 0; for (int ii = 0; ii < offsetCount; ii++) { int slotIndex = ReadVarint(input, true); // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; // Set changed items. drawOrder[originalIndex + ReadVarint(input, true)] = originalIndex++; } // Collect remaining unchanged items. while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++; // Fill in unchanged items. for (int ii = slotCount - 1; ii >= 0; ii--) if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex]; timeline.SetFrame(i, time, drawOrder); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[drawOrderCount - 1]); } // Event timeline. int eventCount = ReadVarint(input, true); if (eventCount > 0) { EventTimeline timeline = new EventTimeline(eventCount); for (int i = 0; i < eventCount; i++) { float time = ReadFloat(input); EventData eventData = skeletonData.events.Items[ReadVarint(input, true)]; Event e = new Event(time, eventData); e.Int = ReadVarint(input, false); e.Float = ReadFloat(input); e.String = ReadBoolean(input) ? ReadString(input) : eventData.String; timeline.SetFrame(i, e); } timelines.Add(timeline); duration = Math.Max(duration, timeline.frames[eventCount - 1]); } timelines.TrimExcess(); skeletonData.animations.Add(new Animation(name, timelines, duration)); } private void ReadCurve (Stream input, int frameIndex, CurveTimeline timeline) { switch (input.ReadByte()) { case CURVE_STEPPED: timeline.SetStepped(frameIndex); break; case CURVE_BEZIER: timeline.SetCurve(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input)); break; } } private static sbyte ReadSByte (Stream input) { int value = input.ReadByte(); if (value == -1) throw new EndOfStreamException(); return (sbyte)value; } private static bool ReadBoolean (Stream input) { return input.ReadByte() != 0; } private float ReadFloat (Stream input) { buffer[3] = (byte)input.ReadByte(); buffer[2] = (byte)input.ReadByte(); buffer[1] = (byte)input.ReadByte(); buffer[0] = (byte)input.ReadByte(); return BitConverter.ToSingle(buffer, 0); } private static int ReadInt (Stream input) { return (input.ReadByte() << 24) + (input.ReadByte() << 16) + (input.ReadByte() << 8) + input.ReadByte(); } private static int ReadVarint (Stream input, bool optimizePositive) { int b = input.ReadByte(); int result = b & 0x7F; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 7; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 14; if ((b & 0x80) != 0) { b = input.ReadByte(); result |= (b & 0x7F) << 21; if ((b & 0x80) != 0) result |= (input.ReadByte() & 0x7F) << 28; } } } return optimizePositive ? result : ((result >> 1) ^ -(result & 1)); } private string ReadString (Stream input) { int byteCount = ReadVarint(input, true); switch (byteCount) { case 0: return null; case 1: return ""; } byteCount--; byte[] buffer = this.buffer; if (buffer.Length < byteCount) buffer = new byte[byteCount]; ReadFully(input, buffer, 0, byteCount); return System.Text.Encoding.UTF8.GetString(buffer, 0, byteCount); } private static void ReadFully (Stream input, byte[] buffer, int offset, int length) { while (length > 0) { int count = input.Read(buffer, offset, length); if (count <= 0) throw new EndOfStreamException(); offset += count; length -= count; } } internal class Vertices { public int[] bones; public float[] vertices; } } }
using EIDSS.Reports.Parameterized.Human.AJ.DataSets; using EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { partial class FormN1Page2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormN1Page2)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.tableInterval = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.xrTable3 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.lblReportName = new DevExpress.XtraReports.UI.XRLabel(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell76 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel(); this.formN1InfectiousDataSet1 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSet(); this.spRepHumFormN1InfectiousDiseasesTableAdapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters.spRepHumFormN1InfectiousDiseasesTableAdapter(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.labelFooterInfo = new DevExpress.XtraReports.UI.XRLabel(); this.labelFooterPage3 = new DevExpress.XtraReports.UI.XRLabel(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.tableInterval}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.StylePriority.UseBorders = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UseTextAlignment = false; // // tableInterval // resources.ApplyResources(this.tableInterval, "tableInterval"); this.tableInterval.Name = "tableInterval"; this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.tableInterval.StylePriority.UseBorders = false; this.tableInterval.StylePriority.UseFont = false; this.tableInterval.StylePriority.UsePadding = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell11, this.xrTableCell10, this.xrTableCell14, this.xrTableCell9, this.xrTableCell17, this.xrTableCell16, this.xrTableCell18, this.xrTableCell20, this.xrTableCell15, this.xrTableCell21, this.xrTableCell19, this.xrTableCell22, this.xrTableCell8}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; // // xrTableCell11 // this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRowNumber")}); resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strDiseaseName")}); resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseTextAlignment = false; // // xrTableCell14 // this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strICD10")}); resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.StylePriority.UseFont = false; // // xrTableCell9 // this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intTotal")}); resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; // // xrTableCell17 // this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intWomen")}); resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Name = "xrTableCell17"; // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_17")}); resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Name = "xrTableCell16"; // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_1")}); resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Name = "xrTableCell18"; // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_1_4")}); resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Name = "xrTableCell20"; // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_5_13")}); resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Name = "xrTableCell15"; // // xrTableCell21 // this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_14_17")}); resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Name = "xrTableCell21"; // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_18_more")}); resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; // // xrTableCell22 // this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralTotal")}); resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Name = "xrTableCell22"; // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralAge_0_17")}); resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Name = "xrTableCell8"; // // TopMargin // resources.ApplyResources(this.TopMargin, "TopMargin"); this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // BottomMargin // resources.ApplyResources(this.BottomMargin, "BottomMargin"); this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // xrTable3 // resources.ApplyResources(this.xrTable3, "xrTable3"); this.xrTable3.Name = "xrTable3"; this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow7, this.xrTableRow1, this.xrTableRow8, this.xrTableRow9}); this.xrTable3.StylePriority.UseTextAlignment = false; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell31}); resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); this.xrTableRow7.Name = "xrTableRow7"; // // xrTableCell31 // this.xrTableCell31.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.StylePriority.UseBorders = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell2, this.xrTableCell4, this.xrTableCell3, this.xrTableCell5}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; // // xrTableCell7 // this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseBorders = false; // // xrTableCell2 // this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTableCell2.StylePriority.UseBorders = false; this.xrTableCell2.StylePriority.UsePadding = false; this.xrTableCell2.StylePriority.UseTextAlignment = false; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; // // xrTableCell3 // this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseBorders = false; this.xrTableCell3.StylePriority.UseTextAlignment = false; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Multiline = true; this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTableCell5.StylePriority.UsePadding = false; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.xrTableCell36, this.xrTableCell37, this.xrTableCell38, this.xrTableCell39, this.xrTableCell41, this.xrTableCell42, this.xrTableCell43, this.xrTableCell44}); resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); this.xrTableRow8.Name = "xrTableRow8"; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseTextAlignment = false; // // xrTableCell36 // this.xrTableCell36.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell36, "xrTableCell36"); this.xrTableCell36.Multiline = true; this.xrTableCell36.Name = "xrTableCell36"; this.xrTableCell36.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTableCell36.StylePriority.UseBorders = false; this.xrTableCell36.StylePriority.UsePadding = false; this.xrTableCell36.StylePriority.UseTextAlignment = false; // // xrTableCell37 // this.xrTableCell37.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell37, "xrTableCell37"); this.xrTableCell37.Multiline = true; this.xrTableCell37.Name = "xrTableCell37"; this.xrTableCell37.StylePriority.UseBorders = false; this.xrTableCell37.StylePriority.UseTextAlignment = false; // // xrTableCell38 // resources.ApplyResources(this.xrTableCell38, "xrTableCell38"); this.xrTableCell38.Multiline = true; this.xrTableCell38.Name = "xrTableCell38"; // // xrTableCell39 // resources.ApplyResources(this.xrTableCell39, "xrTableCell39"); this.xrTableCell39.Multiline = true; this.xrTableCell39.Name = "xrTableCell39"; // // xrTableCell41 // resources.ApplyResources(this.xrTableCell41, "xrTableCell41"); this.xrTableCell41.Multiline = true; this.xrTableCell41.Name = "xrTableCell41"; // // xrTableCell42 // this.xrTableCell42.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell42, "xrTableCell42"); this.xrTableCell42.Name = "xrTableCell42"; this.xrTableCell42.StylePriority.UseBorders = false; this.xrTableCell42.StylePriority.UseTextAlignment = false; // // xrTableCell43 // resources.ApplyResources(this.xrTableCell43, "xrTableCell43"); this.xrTableCell43.Multiline = true; this.xrTableCell43.Name = "xrTableCell43"; // // xrTableCell44 // resources.ApplyResources(this.xrTableCell44, "xrTableCell44"); this.xrTableCell44.Multiline = true; this.xrTableCell44.Name = "xrTableCell44"; // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell6, this.xrTableCell57, this.xrTableCell58, this.xrTableCell59, this.xrTableCell60, this.xrTableCell62, this.xrTableCell63, this.xrTableCell64, this.xrTableCell65}); resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); this.xrTableRow9.Name = "xrTableRow9"; this.xrTableRow9.StylePriority.UseFont = false; // // xrTableCell6 // resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Name = "xrTableCell6"; // // xrTableCell57 // resources.ApplyResources(this.xrTableCell57, "xrTableCell57"); this.xrTableCell57.Name = "xrTableCell57"; // // xrTableCell58 // resources.ApplyResources(this.xrTableCell58, "xrTableCell58"); this.xrTableCell58.Name = "xrTableCell58"; // // xrTableCell59 // resources.ApplyResources(this.xrTableCell59, "xrTableCell59"); this.xrTableCell59.Name = "xrTableCell59"; // // xrTableCell60 // resources.ApplyResources(this.xrTableCell60, "xrTableCell60"); this.xrTableCell60.Name = "xrTableCell60"; // // xrTableCell62 // resources.ApplyResources(this.xrTableCell62, "xrTableCell62"); this.xrTableCell62.Name = "xrTableCell62"; // // xrTableCell63 // resources.ApplyResources(this.xrTableCell63, "xrTableCell63"); this.xrTableCell63.Name = "xrTableCell63"; // // xrTableCell64 // resources.ApplyResources(this.xrTableCell64, "xrTableCell64"); this.xrTableCell64.Name = "xrTableCell64"; // // xrTableCell65 // resources.ApplyResources(this.xrTableCell65, "xrTableCell65"); this.xrTableCell65.Name = "xrTableCell65"; // // ReportHeader // this.ReportHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.lblReportName, this.xrTable1, this.xrTable3}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.ReportHeader.StylePriority.UseBorders = false; this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UsePadding = false; // // lblReportName // this.lblReportName.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.lblReportName.BorderWidth = 1F; resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.Name = "lblReportName"; this.lblReportName.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5, this.xrTableRow10}); this.xrTable1.StylePriority.UsePadding = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell24, this.xrTableCell25, this.xrTableCell12, this.xrTableCell53}); resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); this.xrTableRow5.Name = "xrTableRow5"; // // xrTableCell24 // this.xrTableCell24.Angle = 90F; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.StylePriority.UseBorders = false; this.xrTableCell24.StylePriority.UseFont = false; this.xrTableCell24.StylePriority.UseTextAlignment = false; // // xrTableCell25 // resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.StylePriority.UseBorders = false; this.xrTableCell25.StylePriority.UseTextAlignment = false; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Multiline = true; this.xrTableCell12.Name = "xrTableCell12"; // // xrTableCell53 // this.xrTableCell53.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell53, "xrTableCell53"); this.xrTableCell53.Name = "xrTableCell53"; this.xrTableCell53.StylePriority.UseBorders = false; // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell54, this.xrTableCell55, this.xrTableCell13, this.xrTableCell76}); resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); this.xrTableRow10.Name = "xrTableRow10"; this.xrTableRow10.StylePriority.UseFont = false; // // xrTableCell54 // resources.ApplyResources(this.xrTableCell54, "xrTableCell54"); this.xrTableCell54.Name = "xrTableCell54"; // // xrTableCell55 // resources.ApplyResources(this.xrTableCell55, "xrTableCell55"); this.xrTableCell55.Name = "xrTableCell55"; // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTableCell13.StylePriority.UseFont = false; this.xrTableCell13.StylePriority.UsePadding = false; // // xrTableCell76 // this.xrTableCell76.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTableCell76, "xrTableCell76"); this.xrTableCell76.Name = "xrTableCell76"; this.xrTableCell76.StylePriority.UseBorders = false; // // ReportFooter // resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.StylePriority.UseFont = false; // // xrLabel2 // this.xrLabel2.BorderWidth = 1F; this.xrLabel2.CanGrow = false; resources.ApplyResources(this.xrLabel2, "xrLabel2"); this.xrLabel2.Name = "xrLabel2"; this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel2.StylePriority.UseBorders = false; this.xrLabel2.StylePriority.UseBorderWidth = false; this.xrLabel2.StylePriority.UseFont = false; this.xrLabel2.StylePriority.UseTextAlignment = false; // // formN1InfectiousDataSet1 // this.formN1InfectiousDataSet1.DataSetName = "FormN1InfectiousDataSet"; this.formN1InfectiousDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // spRepHumFormN1InfectiousDiseasesTableAdapter // this.spRepHumFormN1InfectiousDiseasesTableAdapter.ClearBeforeFill = true; // // PageFooter // this.PageFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.labelFooterInfo, this.labelFooterPage3, this.xrLabel2}); resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; // // labelFooterInfo // this.labelFooterInfo.CanGrow = false; resources.ApplyResources(this.labelFooterInfo, "labelFooterInfo"); this.labelFooterInfo.Multiline = true; this.labelFooterInfo.Name = "labelFooterInfo"; this.labelFooterInfo.StylePriority.UseBorders = false; this.labelFooterInfo.StylePriority.UseBorderWidth = false; this.labelFooterInfo.StylePriority.UseFont = false; this.labelFooterInfo.StylePriority.UsePadding = false; this.labelFooterInfo.StylePriority.UseTextAlignment = false; // // labelFooterPage3 // this.labelFooterPage3.CanGrow = false; resources.ApplyResources(this.labelFooterPage3, "labelFooterPage3"); this.labelFooterPage3.Name = "labelFooterPage3"; this.labelFooterPage3.StylePriority.UseBorders = false; this.labelFooterPage3.StylePriority.UseBorderWidth = false; this.labelFooterPage3.StylePriority.UseFont = false; this.labelFooterPage3.StylePriority.UsePadding = false; this.labelFooterPage3.StylePriority.UseTextAlignment = false; // // FormN1Page2 // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.TopMargin, this.BottomMargin, this.ReportHeader, this.ReportFooter, this.PageFooter}); this.DataAdapter = this.spRepHumFormN1InfectiousDiseasesTableAdapter; this.DataMember = "spRepHumFormN1InfectiousDiseases"; this.DataSource = this.formN1InfectiousDataSet1; resources.ApplyResources(this, "$this"); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.TopMarginBand TopMargin; private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin; private DevExpress.XtraReports.UI.XRTable xrTable3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell36; private DevExpress.XtraReports.UI.XRTableCell xrTableCell37; private DevExpress.XtraReports.UI.XRTableCell xrTableCell38; private DevExpress.XtraReports.UI.XRTableCell xrTableCell39; private DevExpress.XtraReports.UI.XRTableCell xrTableCell41; private DevExpress.XtraReports.UI.XRTableCell xrTableCell42; private DevExpress.XtraReports.UI.XRTableCell xrTableCell43; private DevExpress.XtraReports.UI.XRTableCell xrTableCell44; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell57; private DevExpress.XtraReports.UI.XRTableCell xrTableCell58; private DevExpress.XtraReports.UI.XRTableCell xrTableCell59; private DevExpress.XtraReports.UI.XRTableCell xrTableCell60; private DevExpress.XtraReports.UI.XRTableCell xrTableCell63; private DevExpress.XtraReports.UI.XRTableCell xrTableCell64; private DevExpress.XtraReports.UI.XRTableCell xrTableCell65; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell53; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell54; private DevExpress.XtraReports.UI.XRTableCell xrTableCell55; private DevExpress.XtraReports.UI.XRTableCell xrTableCell76; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; protected DevExpress.XtraReports.UI.XRLabel lblReportName; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell62; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; protected DevExpress.XtraReports.UI.XRTable tableInterval; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; protected DevExpress.XtraReports.UI.XRLabel xrLabel2; private FormN1InfectiousDataSet formN1InfectiousDataSet1; private spRepHumFormN1InfectiousDiseasesTableAdapter spRepHumFormN1InfectiousDiseasesTableAdapter; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private DevExpress.XtraReports.UI.XRLabel labelFooterPage3; private DevExpress.XtraReports.UI.XRLabel labelFooterInfo; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Data.ProviderBase; using System.Diagnostics; using System.Globalization; namespace System.Data.Common { public class DataAdapter : Component, IDataAdapter { private static readonly object s_eventFillError = new object(); private bool _acceptChangesDuringUpdate = true; private bool _acceptChangesDuringUpdateAfterInsert = true; private bool _continueUpdateOnError = false; private bool _hasFillErrorHandler = false; private bool _returnProviderSpecificTypes = false; private bool _acceptChangesDuringFill = true; private LoadOption _fillLoadOption; private MissingMappingAction _missingMappingAction = System.Data.MissingMappingAction.Passthrough; private MissingSchemaAction _missingSchemaAction = System.Data.MissingSchemaAction.Add; private DataTableMappingCollection _tableMappings; private static int s_objectTypeCount; // Bid counter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); #if DEBUG // if true, we are asserting that the caller has provided a select command // which should not return an empty result set private bool _debugHookNonEmptySelectCommand = false; #endif [Conditional("DEBUG")] private void AssertReaderHandleFieldCount(DataReaderContainer readerHandler) { #if DEBUG Debug.Assert(!_debugHookNonEmptySelectCommand || readerHandler.FieldCount > 0, "Scenario expects non-empty results but no fields reported by reader"); #endif } [Conditional("DEBUG")] private void AssertSchemaMapping(SchemaMapping mapping) { #if DEBUG if (_debugHookNonEmptySelectCommand) { Debug.Assert(mapping != null && mapping.DataValues != null && mapping.DataTable != null, "Debug hook specifies that non-empty results are not expected"); } #endif } protected DataAdapter() : base() { GC.SuppressFinalize(this); } protected DataAdapter(DataAdapter from) : base() { CloneFrom(from); } [DefaultValue(true)] public bool AcceptChangesDuringFill { get { return _acceptChangesDuringFill; } set { _acceptChangesDuringFill = value; } } [EditorBrowsable(EditorBrowsableState.Never)] public virtual bool ShouldSerializeAcceptChangesDuringFill() { return (0 == _fillLoadOption); } [DefaultValue(true)] public bool AcceptChangesDuringUpdate { get { return _acceptChangesDuringUpdate; } set { _acceptChangesDuringUpdate = value; } } [DefaultValue(false)] public bool ContinueUpdateOnError { get { return _continueUpdateOnError; } set { _continueUpdateOnError = value; } } [RefreshProperties(RefreshProperties.All)] public LoadOption FillLoadOption { get { LoadOption fillLoadOption = _fillLoadOption; return ((0 != fillLoadOption) ? _fillLoadOption : LoadOption.OverwriteChanges); } set { switch (value) { case 0: // to allow simple resetting case LoadOption.OverwriteChanges: case LoadOption.PreserveChanges: case LoadOption.Upsert: _fillLoadOption = value; break; default: throw ADP.InvalidLoadOption(value); } } } [EditorBrowsable(EditorBrowsableState.Never)] public void ResetFillLoadOption() { _fillLoadOption = 0; } [EditorBrowsable(EditorBrowsableState.Never)] public virtual bool ShouldSerializeFillLoadOption() => 0 != _fillLoadOption; [DefaultValue(System.Data.MissingMappingAction.Passthrough)] public MissingMappingAction MissingMappingAction { get { return _missingMappingAction; } set { switch (value) { case MissingMappingAction.Passthrough: case MissingMappingAction.Ignore: case MissingMappingAction.Error: _missingMappingAction = value; break; default: throw ADP.InvalidMissingMappingAction(value); } } } [DefaultValue(Data.MissingSchemaAction.Add)] public MissingSchemaAction MissingSchemaAction { get { return _missingSchemaAction; } set { switch (value) { case MissingSchemaAction.Add: case MissingSchemaAction.Ignore: case MissingSchemaAction.Error: case MissingSchemaAction.AddWithKey: _missingSchemaAction = value; break; default: throw ADP.InvalidMissingSchemaAction(value); } } } internal int ObjectID => _objectID; [DefaultValue(false)] public virtual bool ReturnProviderSpecificTypes { get { return _returnProviderSpecificTypes; } set { _returnProviderSpecificTypes = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DataTableMappingCollection TableMappings { get { DataTableMappingCollection mappings = _tableMappings; if (null == mappings) { mappings = CreateTableMappings(); if (null == mappings) { mappings = new DataTableMappingCollection(); } _tableMappings = mappings; } return mappings; // constructed by base class } } ITableMappingCollection IDataAdapter.TableMappings => TableMappings; protected virtual bool ShouldSerializeTableMappings() => true; protected bool HasTableMappings() => ((null != _tableMappings) && (0 < TableMappings.Count)); public event FillErrorEventHandler FillError { add { _hasFillErrorHandler = true; Events.AddHandler(s_eventFillError, value); } remove { Events.RemoveHandler(s_eventFillError, value); } } [Obsolete("CloneInternals() has been deprecated. Use the DataAdapter(DataAdapter from) constructor. https://go.microsoft.com/fwlink/?linkid=14202")] protected virtual DataAdapter CloneInternals() { DataAdapter clone = (DataAdapter)Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); clone.CloneFrom(this); return clone; } private void CloneFrom(DataAdapter from) { _acceptChangesDuringUpdate = from._acceptChangesDuringUpdate; _acceptChangesDuringUpdateAfterInsert = from._acceptChangesDuringUpdateAfterInsert; _continueUpdateOnError = from._continueUpdateOnError; _returnProviderSpecificTypes = from._returnProviderSpecificTypes; _acceptChangesDuringFill = from._acceptChangesDuringFill; _fillLoadOption = from._fillLoadOption; _missingMappingAction = from._missingMappingAction; _missingSchemaAction = from._missingSchemaAction; if ((null != from._tableMappings) && (0 < from.TableMappings.Count)) { DataTableMappingCollection parameters = TableMappings; foreach (object parameter in from.TableMappings) { parameters.Add((parameter is ICloneable) ? ((ICloneable)parameter).Clone() : parameter); } } } protected virtual DataTableMappingCollection CreateTableMappings() { DataCommonEventSource.Log.Trace("<comm.DataAdapter.CreateTableMappings|API> {0}", ObjectID); return new DataTableMappingCollection(); } protected override void Dispose(bool disposing) { if (disposing) { // release mananged objects _tableMappings = null; } // release unmanaged objects base.Dispose(disposing); // notify base classes } public virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType) { throw ADP.NotSupported(); } protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, string srcTable, IDataReader dataReader) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.FillSchema|API> {0}, dataSet, schemaType={1}, srcTable, dataReader", ObjectID, schemaType); try { if (null == dataSet) { throw ADP.ArgumentNull(nameof(dataSet)); } if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) { throw ADP.InvalidSchemaType(schemaType); } if (string.IsNullOrEmpty(srcTable)) { throw ADP.FillSchemaRequiresSourceTableName(nameof(srcTable)); } if ((null == dataReader) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } // user must Close/Dispose of the dataReader object value = FillSchemaFromReader(dataSet, null, schemaType, srcTable, dataReader); return (DataTable[])value; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } protected virtual DataTable FillSchema(DataTable dataTable, SchemaType schemaType, IDataReader dataReader) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.FillSchema|API> {0}, dataTable, schemaType, dataReader", ObjectID); try { if (null == dataTable) { throw ADP.ArgumentNull(nameof(dataTable)); } if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) { throw ADP.InvalidSchemaType(schemaType); } if ((null == dataReader) || dataReader.IsClosed) { throw ADP.FillRequires(nameof(dataReader)); } // user must Close/Dispose of the dataReader // user will have to call NextResult to access remaining results object value = FillSchemaFromReader(null, dataTable, schemaType, null, dataReader); return (DataTable)value; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } internal object FillSchemaFromReader(DataSet dataset, DataTable datatable, SchemaType schemaType, string srcTable, IDataReader dataReader) { DataTable[] dataTables = null; int schemaCount = 0; do { DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); AssertReaderHandleFieldCount(readerHandler); if (0 >= readerHandler.FieldCount) { continue; } string tmp = null; if (null != dataset) { tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) } SchemaMapping mapping = new SchemaMapping(this, dataset, datatable, readerHandler, true, schemaType, tmp, false, null, null); if (null != datatable) { // do not read remaining results in single DataTable case return mapping.DataTable; } else if (null != mapping.DataTable) { if (null == dataTables) { dataTables = new DataTable[1] { mapping.DataTable }; } else { dataTables = DataAdapter.AddDataTableToArray(dataTables, mapping.DataTable); } } } while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event object value = dataTables; if ((null == value) && (null == datatable)) { value = Array.Empty<DataTable>(); } return value; // null if datatable had no results } public virtual int Fill(DataSet dataSet) { throw ADP.NotSupported(); } protected virtual int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.Fill|API> {0}, dataSet, srcTable, dataReader, startRecord, maxRecords", ObjectID); try { if (null == dataSet) { throw ADP.FillRequires(nameof(dataSet)); } if (string.IsNullOrEmpty(srcTable)) { throw ADP.FillRequiresSourceTableName(nameof(srcTable)); } if (null == dataReader) { throw ADP.FillRequires(nameof(dataReader)); } if (startRecord < 0) { throw ADP.InvalidStartRecord(nameof(startRecord), startRecord); } if (maxRecords < 0) { throw ADP.InvalidMaxRecords(nameof(maxRecords), maxRecords); } if (dataReader.IsClosed) { return 0; } // user must Close/Dispose of the dataReader DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); return FillFromReader(dataSet, null, srcTable, readerHandler, startRecord, maxRecords, null, null); } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } protected virtual int Fill(DataTable dataTable, IDataReader dataReader) { DataTable[] dataTables = new DataTable[] { dataTable }; return Fill(dataTables, dataReader, 0, 0); } protected virtual int Fill(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) { long logScopeId = DataCommonEventSource.Log.EnterScope("<comm.DataAdapter.Fill|API> {0}, dataTables[], dataReader, startRecord, maxRecords", ObjectID); try { ADP.CheckArgumentLength(dataTables, nameof(dataTables)); if ((null == dataTables) || (0 == dataTables.Length) || (null == dataTables[0])) { throw ADP.FillRequires("dataTable"); } if (null == dataReader) { throw ADP.FillRequires(nameof(dataReader)); } if ((1 < dataTables.Length) && ((0 != startRecord) || (0 != maxRecords))) { throw ADP.NotSupported(); // FillChildren is not supported with FillPage } int result = 0; bool enforceContraints = false; DataSet commonDataSet = dataTables[0].DataSet; try { if (null != commonDataSet) { enforceContraints = commonDataSet.EnforceConstraints; commonDataSet.EnforceConstraints = false; } for (int i = 0; i < dataTables.Length; ++i) { Debug.Assert(null != dataTables[i], "null DataTable Fill"); if (dataReader.IsClosed) { #if DEBUG Debug.Assert(!_debugHookNonEmptySelectCommand, "Debug hook asserts data reader should be open"); #endif break; } DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes); AssertReaderHandleFieldCount(readerHandler); if (readerHandler.FieldCount <= 0) { if (i == 0) { bool lastFillNextResult; do { lastFillNextResult = FillNextResult(readerHandler); } while (lastFillNextResult && readerHandler.FieldCount <= 0); if (!lastFillNextResult) { break; } } else { continue; } } if ((0 < i) && !FillNextResult(readerHandler)) { break; } // user must Close/Dispose of the dataReader // user will have to call NextResult to access remaining results int count = FillFromReader(null, dataTables[i], null, readerHandler, startRecord, maxRecords, null, null); if (0 == i) { result = count; } } } catch (ConstraintException) { enforceContraints = false; throw; } finally { if (enforceContraints) { commonDataSet.EnforceConstraints = true; } } return result; } finally { DataCommonEventSource.Log.ExitScope(logScopeId); } } internal int FillFromReader(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn parentChapterColumn, object parentChapterValue) { int rowsAddedToDataSet = 0; int schemaCount = 0; do { AssertReaderHandleFieldCount(dataReader); if (0 >= dataReader.FieldCount) { continue; // loop to next result } SchemaMapping mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); schemaCount++; // don't increment if no SchemaTable ( a non-row returning result ) AssertSchemaMapping(mapping); if (null == mapping) { continue; // loop to next result } if (null == mapping.DataValues) { continue; // loop to next result } if (null == mapping.DataTable) { continue; // loop to next result } mapping.DataTable.BeginLoadData(); try { // startRecord and maxRecords only apply to the first resultset if ((1 == schemaCount) && ((0 < startRecord) || (0 < maxRecords))) { rowsAddedToDataSet = FillLoadDataRowChunk(mapping, startRecord, maxRecords); } else { int count = FillLoadDataRow(mapping); if (1 == schemaCount) { // only return LoadDataRow count for first resultset // not secondary or chaptered results rowsAddedToDataSet = count; } } } finally { mapping.DataTable.EndLoadData(); } if (null != datatable) { break; // do not read remaining results in single DataTable case } } while (FillNextResult(dataReader)); return rowsAddedToDataSet; } private int FillLoadDataRowChunk(SchemaMapping mapping, int startRecord, int maxRecords) { DataReaderContainer dataReader = mapping.DataReader; while (0 < startRecord) { if (!dataReader.Read()) { // there are no more rows on first resultset return 0; } --startRecord; } int rowsAddedToDataSet = 0; if (0 < maxRecords) { while ((rowsAddedToDataSet < maxRecords) && dataReader.Read()) { if (_hasFillErrorHandler) { try { mapping.LoadDataRowWithClear(); rowsAddedToDataSet++; } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues); } } else { mapping.LoadDataRow(); rowsAddedToDataSet++; } } // skip remaining rows of the first resultset } else { rowsAddedToDataSet = FillLoadDataRow(mapping); } return rowsAddedToDataSet; } private int FillLoadDataRow(SchemaMapping mapping) { int rowsAddedToDataSet = 0; DataReaderContainer dataReader = mapping.DataReader; if (_hasFillErrorHandler) { while (dataReader.Read()) { // read remaining rows of first and subsequent resultsets try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users mapping.LoadDataRowWithClear(); rowsAddedToDataSet++; } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues); } } } else { while (dataReader.Read()) { // read remaining rows of first and subsequent resultset mapping.LoadDataRow(); rowsAddedToDataSet++; } } return rowsAddedToDataSet; } private SchemaMapping FillMappingInternal(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) { bool withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction); string tmp = null; if (null != dataset) { tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount); } return new SchemaMapping(this, dataset, datatable, dataReader, withKeyInfo, SchemaType.Mapped, tmp, true, parentChapterColumn, parentChapterValue); } private SchemaMapping FillMapping(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) { SchemaMapping mapping = null; if (_hasFillErrorHandler) { try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, null, null); } } else { mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue); } return mapping; } private bool FillNextResult(DataReaderContainer dataReader) { bool result = true; if (_hasFillErrorHandler) { try { // only try-catch if a FillErrorEventHandler is registered so that // in the default case we get the full callstack from users result = dataReader.NextResult(); } catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ADP.TraceExceptionForCapture(e); OnFillErrorHandler(e, null, null); } } else { result = dataReader.NextResult(); } return result; } [EditorBrowsable(EditorBrowsableState.Advanced)] public virtual IDataParameter[] GetFillParameters() => Array.Empty<IDataParameter>(); internal DataTableMapping GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction) { return DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMappings, sourceTableName, dataSetTableName, mappingAction); } internal int IndexOfDataSetTable(string dataSetTable) { if (null != _tableMappings) { return TableMappings.IndexOfDataSetTable(dataSetTable); } return -1; } protected virtual void OnFillError(FillErrorEventArgs value) { ((FillErrorEventHandler)Events[s_eventFillError])?.Invoke(this, value); } private void OnFillErrorHandler(Exception e, DataTable dataTable, object[] dataValues) { FillErrorEventArgs fillErrorEvent = new FillErrorEventArgs(dataTable, dataValues); fillErrorEvent.Errors = e; OnFillError(fillErrorEvent); if (!fillErrorEvent.Continue) { if (null != fillErrorEvent.Errors) { throw fillErrorEvent.Errors; } throw e; } } public virtual int Update(DataSet dataSet) { throw ADP.NotSupported(); } // used by FillSchema which returns an array of datatables added to the dataset private static DataTable[] AddDataTableToArray(DataTable[] tables, DataTable newTable) { for (int i = 0; i < tables.Length; ++i) { // search for duplicates if (tables[i] == newTable) { return tables; // duplicate found } } DataTable[] newTables = new DataTable[tables.Length + 1]; // add unique data table for (int i = 0; i < tables.Length; ++i) { newTables[i] = tables[i]; } newTables[tables.Length] = newTable; return newTables; } // dynamically generate source table names private static string GetSourceTableName(string srcTable, int index) { //if ((null != srcTable) && (0 <= index) && (index < srcTable.Length)) { if (0 == index) { return srcTable; //[index]; } return srcTable + index.ToString(System.Globalization.CultureInfo.InvariantCulture); } } internal sealed class LoadAdapter : DataAdapter { internal LoadAdapter() { } internal int FillFromReader(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) { return Fill(dataTables, dataReader, startRecord, maxRecords); } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(SgtJovianDepth))] public class SgtJovianDepth_Editor : SgtEditor<SgtJovianDepth> { protected override void OnInspector() { var updateTexture = false; var updateApply = false; BeginError(Any(t => t.Jovian == null)); DrawDefault("Jovian", ref updateApply); EndError(); BeginError(Any(t => t.Width < 1)); DrawDefault("Width", ref updateTexture); EndError(); DrawDefault("Format", ref updateTexture); Separator(); DrawDefault("RimEase", ref updateTexture); BeginError(Any(t => t.RimPower < 1.0f)); DrawDefault("RimPower", ref updateTexture); EndError(); DrawDefault("RimColor", ref updateTexture); Separator(); BeginError(Any(t => t.AlphaDensity < 1.0f)); DrawDefault("AlphaDensity", ref updateTexture); EndError(); BeginError(Any(t => t.AlphaFade < 1.0f)); DrawDefault("AlphaFade", ref updateTexture); EndError(); if (updateTexture == true) DirtyEach(t => t.UpdateTextures()); if (updateApply == true) DirtyEach(t => t.UpdateApply ()); } } #endif [ExecuteInEditMode] [AddComponentMenu(SgtHelper.ComponentMenuPrefix + "Jovian Depth")] public class SgtJovianDepth : MonoBehaviour { [Tooltip("The jovian this texture will be applied to")] public SgtJovian Jovian; [Tooltip("The resolution of the surface/space optical thickness transition in pixels")] public int Width = 256; [Tooltip("The format of this texture")] public TextureFormat Format = TextureFormat.ARGB32; [Tooltip("The rim transition style")] public SgtEase.Type RimEase = SgtEase.Type.Exponential; [Tooltip("The rim transition sharpness")] public float RimPower = 5.0f; [Tooltip("The rim color")] public Color RimColor = new Color(1.0f, 0.0f, 0.0f, 0.25f); [Tooltip("The density of the atmosphere")] public float AlphaDensity = 50.0f; [Tooltip("The strength of the density fading in the upper atmosphere")] public float AlphaFade = 2.0f; [System.NonSerialized] private Texture2D generatedTexture; [SerializeField] [HideInInspector] private bool startCalled; public Texture2D GeneratedTexture { get { return generatedTexture; } } #if UNITY_EDITOR [ContextMenu("Export Texture")] public void ExportTexture() { var importer = SgtHelper.ExportTextureDialog(generatedTexture, "Jovian Depth"); if (importer != null) { importer.textureCompression = TextureImporterCompression.Uncompressed; importer.alphaSource = TextureImporterAlphaSource.FromInput; importer.wrapMode = TextureWrapMode.Clamp; importer.filterMode = FilterMode.Trilinear; importer.anisoLevel = 16; importer.alphaIsTransparency = true; importer.SaveAndReimport(); } } #endif [ContextMenu("Update Textures")] public void UpdateTextures() { if (Width > 0) { // Destroy if invalid if (generatedTexture != null) { if (generatedTexture.width != Width || generatedTexture.height != 1 || generatedTexture.format != Format) { generatedTexture = SgtHelper.Destroy(generatedTexture); } } // Create? if (generatedTexture == null) { generatedTexture = SgtHelper.CreateTempTexture2D("Jovian Depth (Generated)", Width, 1, Format); generatedTexture.wrapMode = TextureWrapMode.Clamp; UpdateApply(); } var color = Color.clear; var stepX = 1.0f / (Width - 1); for (var x = 0; x < Width; x++) { var u = x * stepX; WriteTexture(u, x); } generatedTexture.Apply(); } } private void WriteTexture(float u, int x) { var rim = 1.0f - SgtEase.Evaluate(RimEase, 1.0f - Mathf.Pow(1.0f - u, RimPower)); var color = Color.Lerp(Color.white, RimColor, rim * RimColor.a); color.a = 1.0f - Mathf.Pow(1.0f - Mathf.Pow(u, AlphaFade), AlphaDensity); generatedTexture.SetPixel(x, 0, color); } [ContextMenu("Update Apply")] public void UpdateApply() { if (Jovian != null) { Jovian.DepthTex = generatedTexture; Jovian.UpdateMaterial(); } } protected virtual void OnEnable() { if (startCalled == true) { CheckUpdateCalls(); } } protected virtual void Start() { if (startCalled == false) { startCalled = true; if (Jovian == null) { Jovian = GetComponent<SgtJovian>(); } CheckUpdateCalls(); } } protected virtual void OnDestroy() { SgtHelper.Destroy(generatedTexture); } private void CheckUpdateCalls() { if (generatedTexture == null) { UpdateTextures(); } UpdateApply(); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: UInt64 ** ** Purpose: This class will encapsulate an unsigned long and ** provide an Object representation of it. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // Wrapper for unsigned 64 bit integers. [Microsoft.Zelig.Internals.WellKnownType( "System_UInt64" )] [Serializable] [CLSCompliant( false )] [StructLayout( LayoutKind.Sequential )] public struct UInt64 : IComparable, IFormattable, IConvertible, IComparable<UInt64>, IEquatable<UInt64> { public const ulong MaxValue = (ulong)0xFFFFFFFFFFFFFFFFL; public const ulong MinValue = 0x0; private ulong m_value; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt64, this method throws an ArgumentException. // public int CompareTo( Object value ) { if(value == null) { return 1; } if(value is UInt64) { return CompareTo( (UInt64)value ); } #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeUInt64" ) ); #else throw new ArgumentException(); #endif } public int CompareTo( UInt64 value ) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if(m_value < value) return -1; if(m_value > value) return 1; return 0; } public override bool Equals( Object obj ) { if(!(obj is UInt64)) { return false; } return Equals( (UInt64)obj ); } public bool Equals( UInt64 obj ) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return ((int)m_value) ^ (int)(m_value >> 32); } public override String ToString() { return Number.FormatUInt64( m_value, /*null,*/ NumberFormatInfo.CurrentInfo ); } public String ToString( IFormatProvider provider ) { return Number.FormatUInt64( m_value, /*null,*/ NumberFormatInfo.GetInstance( provider ) ); } public String ToString( String format ) { return Number.FormatUInt64( m_value, format, NumberFormatInfo.CurrentInfo ); } public String ToString( String format , IFormatProvider provider ) { return Number.FormatUInt64( m_value, format, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static ulong Parse( String s ) { return Number.ParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ulong Parse( String s , NumberStyles style ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt64( s, style, NumberFormatInfo.CurrentInfo ); } [CLSCompliant( false )] public static ulong Parse( string s , IFormatProvider provider ) { return Number.ParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static ulong Parse( String s , NumberStyles style , IFormatProvider provider ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.ParseUInt64( s, style, NumberFormatInfo.GetInstance( provider ) ); } [CLSCompliant( false )] public static Boolean TryParse( String s , out UInt64 result ) { return Number.TryParseUInt64( s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result ); } [CLSCompliant( false )] public static Boolean TryParse( String s , NumberStyles style , IFormatProvider provider , out UInt64 result ) { NumberFormatInfo.ValidateParseStyleInteger( style ); return Number.TryParseUInt64( s, style, NumberFormatInfo.GetInstance( provider ), out result ); } #region IConvertible public TypeCode GetTypeCode() { return TypeCode.UInt64; } /// <internalonly/> bool IConvertible.ToBoolean( IFormatProvider provider ) { return Convert.ToBoolean( m_value ); } /// <internalonly/> char IConvertible.ToChar( IFormatProvider provider ) { return Convert.ToChar( m_value ); } /// <internalonly/> sbyte IConvertible.ToSByte( IFormatProvider provider ) { return Convert.ToSByte( m_value ); } /// <internalonly/> byte IConvertible.ToByte( IFormatProvider provider ) { return Convert.ToByte( m_value ); } /// <internalonly/> short IConvertible.ToInt16( IFormatProvider provider ) { return Convert.ToInt16( m_value ); } /// <internalonly/> ushort IConvertible.ToUInt16( IFormatProvider provider ) { return Convert.ToUInt16( m_value ); } /// <internalonly/> int IConvertible.ToInt32( IFormatProvider provider ) { return Convert.ToInt32( m_value ); } /// <internalonly/> uint IConvertible.ToUInt32( IFormatProvider provider ) { return Convert.ToUInt32( m_value ); } /// <internalonly/> long IConvertible.ToInt64( IFormatProvider provider ) { return Convert.ToInt64( m_value ); } /// <internalonly/> ulong IConvertible.ToUInt64( IFormatProvider provider ) { return m_value; } /// <internalonly/> float IConvertible.ToSingle( IFormatProvider provider ) { return Convert.ToSingle( m_value ); } /// <internalonly/> double IConvertible.ToDouble( IFormatProvider provider ) { return Convert.ToDouble( m_value ); } /// <internalonly/> Decimal IConvertible.ToDecimal( IFormatProvider provider ) { return Convert.ToDecimal( m_value ); } /// <internalonly/> DateTime IConvertible.ToDateTime( IFormatProvider provider ) { #if EXCEPTION_STRINGS throw new InvalidCastException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "InvalidCast_FromTo" ), "UInt64", "DateTime" ) ); #else throw new InvalidCastException(); #endif } /// <internalonly/> Object IConvertible.ToType( Type type, IFormatProvider provider ) { return Convert.DefaultToType( (IConvertible)this, type, provider ); } #endregion } }
/* * Copyright (c) 2013-2014 Behrooz Amoozad * 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 bd2 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 Behrooz Amoozad BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using BD2.Core; using BD2.Frontend.Table; using System.Security.Cryptography; using System.IO; namespace BD2.Frontend.Table { [BaseDataObjectTypeIdAttribute ("10ec2d31-3291-43ae-96fe-da8537b22af6", typeof(Row), "Deserialize")] public sealed class Row : BaseDataObjectVersion, IIndexable { readonly IDictionary<int, ColumnSet> columnSets; public IDictionary<int, ColumnSet> ColumnSets { get { return columnSets; } } readonly Table table; public Table Table { get { return table; } } public object[] GetValues (int columnSetID, ColumnSet outputColumnSet) { if (columnSets [columnSetID].Equals (outputColumnSet)) return GetValues (columnSetID); return ((Frontend)table.FrontendBase).GetColumnSetConverter (columnSets [columnSetID], outputColumnSet).Convert (GetValues (columnSetID), columnSets [columnSetID], outputColumnSet); } public override IEnumerable<BaseDataObjectVersion> GetDependenies () { Log.WriteLine ("Row.GetDependenies ()"); foreach (DataContext dc in ((BD2.Frontend.Table.Frontend)table.FrontendBase).SnapshotObjects.Values) { Log.WriteLine ("Trying dataContext-{0}", dc.ID.ToHexadecimal ()); foreach (var r in ReplacingIDs) { Log.WriteLine ("Searching for {0}", r.ToHexadecimal ()); var row = dc.GetRowByID (r); if (row != null) { Log.WriteLine ("ref:{0}, id:{1}", row, r.ToHexadecimal ()); yield return row; } } } yield break; } IDictionary<int, object[]> data; public object GetRawDataClone (int columnSetIndex) { return data [columnSetIndex].Clone (); } internal Row (byte[] id, byte[] chunkID, byte[][] replacingIDs, Table table, IDictionary<int, ColumnSet> columnSets, IDictionary<int, object[]> data) : base (id, chunkID, replacingIDs) { if (table == null) throw new ArgumentNullException ("table"); if (columnSets == null) throw new ArgumentNullException ("columnSets"); if (data == null) throw new ArgumentNullException ("data"); this.table = table; this.columnSets = columnSets; this.data = data; } #region implemented abstract members of Serializable public static Row Deserialize (FrontendBase fb, byte[] chunkID, byte[] buffer) { using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) { using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) { byte[] id = BR.ReadBytes (32); byte[][] replacingIDs = new byte[BR.ReadInt32 ()][]; for (int n = 0; n != replacingIDs.Length; n++) { replacingIDs [n] = BR.ReadBytes (32); } Table table = ((Frontend)fb).GetTableByID (BR.ReadBytes (32)); byte columnSetCount = BR.ReadByte (); Dictionary<int, ColumnSet> columnSets = new Dictionary<int, ColumnSet> (); for (int columnSetIndex = 0; columnSetIndex != columnSetCount; columnSetIndex++) { ColumnSet columnSet = ((Frontend)fb).GetColumnSetByID (BR.ReadBytes (32)); columnSets.Add (columnSetIndex, columnSet); } //int previousVersionCount = BR.ReadInt32 (); Dictionary<int, object[]> objs = new Dictionary<int, object[]> (); for (int n = 0; n != columnSetCount; n++) objs.Add (n, columnSets [n].DeserializeObjects (BR.ReadBytes (BR.ReadInt32 ()))); Row R = new Row (id, chunkID, replacingIDs, table, columnSets, objs); return R; } } } public override void Serialize (System.IO.Stream stream, EncryptedStorageManager encryptedStorageManager) { using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter (stream)) { BW.Write (ID); BW.Write (ReplacingIDs.Length); foreach (var rid in ReplacingIDs) BW.Write (rid); BW.Write (Table.ObjectID, 0, 32); BW.Write ((byte)columnSets.Count); foreach (var columnSet in columnSets) BW.Write (columnSet.Value.ObjectID, 0, 32); for (int index = 0; index != columnSets.Count; index++) { byte[] buf = ColumnSets [index].SerializeObjects (data [index]); BW.Write (buf.Length); BW.Write (buf); } } } #endregion #region implemented abstract members of Row public object[] GetValues (int columnSetIndex) { return data [columnSetIndex]; } public object GetValue (int columnSetIndex, string fieldName) { return data [columnSets [columnSetIndex].IndexOf (fieldName, StringComparison.Ordinal)]; } public object GetValue (int fieldIndex) { return data [fieldIndex]; } public IEnumerable<KeyValuePair<Column, object>> GetValuesWithColumns (int columnSetID) { int n = 0; foreach (Column col in ColumnSets[columnSetID].Columns) { yield return new KeyValuePair<Column, object> (col, data [n]); n++; } } #endregion #region implemented abstract members of BaseDataObject public override Guid ObjectType { get { return Guid.Parse ("10ec2d31-3291-43ae-96fe-da8537b22af6"); } } #endregion #region IIndexable implementation public byte[] GetRawData () { MemoryStream ms = new MemoryStream (); Serialize (ms, null); return ms.ToArray (); } public T GetIndexValue<T> (IIndex<T> iIndex) { throw new NotImplementedException (); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Collections.Generic.SortedSet_1.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Collections.Generic { public partial class SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Runtime.Serialization.ISerializable, System.Runtime.Serialization.IDeserializationCallback { #region Methods and constructors public bool Add(T item) { return default(bool); } public virtual new void Clear() { } public virtual new bool Contains(T item) { return default(bool); } public void CopyTo(T[] array, int index, int count) { } public void CopyTo(T[] array) { } public void CopyTo(T[] array, int index) { } public static IEqualityComparer<System.Collections.Generic.SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer) { Contract.Ensures(Contract.Result<System.Collections.Generic.IEqualityComparer<System.Collections.Generic.SortedSet<T>>>() != null); return default(IEqualityComparer<System.Collections.Generic.SortedSet<T>>); } public static IEqualityComparer<System.Collections.Generic.SortedSet<T>> CreateSetComparer() { Contract.Ensures(Contract.Result<System.Collections.Generic.IEqualityComparer<System.Collections.Generic.SortedSet<T>>>() != null); return default(IEqualityComparer<System.Collections.Generic.SortedSet<T>>); } public void ExceptWith(IEnumerable<T> other) { } public System.Collections.Generic.SortedSet<T>.Enumerator GetEnumerator() { return default(System.Collections.Generic.SortedSet<T>.Enumerator); } protected virtual new void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public virtual new System.Collections.Generic.SortedSet<T> GetViewBetween(T lowerValue, T upperValue) { Contract.Requires(this.Comparer != null); return default(System.Collections.Generic.SortedSet<T>); } public virtual new void IntersectWith(IEnumerable<T> other) { } public bool IsProperSubsetOf(IEnumerable<T> other) { return default(bool); } public bool IsProperSupersetOf(IEnumerable<T> other) { return default(bool); } public bool IsSubsetOf(IEnumerable<T> other) { return default(bool); } public bool IsSupersetOf(IEnumerable<T> other) { return default(bool); } protected virtual new void OnDeserialization(Object sender) { } public bool Overlaps(IEnumerable<T> other) { return default(bool); } public bool Remove(T item) { return default(bool); } public int RemoveWhere(Predicate<T> match) { Contract.Ensures(0 <= Contract.Result<int>()); return default(int); } public IEnumerable<T> Reverse() { Contract.Ensures(Contract.Result<System.Collections.Generic.IEnumerable<T>>() != null); return default(IEnumerable<T>); } public bool SetEquals(IEnumerable<T> other) { return default(bool); } protected SortedSet(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public SortedSet(IEnumerable<T> collection) { } public SortedSet(IComparer<T> comparer) { } public SortedSet() { } public SortedSet(IEnumerable<T> collection, IComparer<T> comparer) { } public void SymmetricExceptWith(IEnumerable<T> other) { } void System.Collections.Generic.ICollection<T>.Add(T item) { } IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { return default(IEnumerator<T>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(Object sender) { } void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public void UnionWith(IEnumerable<T> other) { } #endregion #region Properties and indexers public IComparer<T> Comparer { get { return default(IComparer<T>); } } public int Count { get { return default(int); } } public T Max { get { return default(T); } } public T Min { get { return default(T); } } bool System.Collections.Generic.ICollection<T>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using PCSComUtils.Common; using PCSComUtils.Framework.ReportFrame.BO; using PCSComUtils.Framework.ReportFrame.DS; using PCSComUtils.PCSExc; using PCSUtils.Log; using PCSUtils.Utils; namespace PCSUtils.Framework.ReportFrame { /// <summary> /// Summary description for LastReport. /// </summary> public class LastReport : Form { /// <summary> /// Required designer variable. /// </summary> private Container components = null; private System.Windows.Forms.TreeView tvwReportList; private const string THIS = "PCSUtils.Framework.ReportFrame.LastReport"; // read-only property public sys_ReportHistoryVO ReturnValue { get { return mReturnValue; } } private sys_ReportHistoryVO mReturnValue; public LastReport() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(LastReport)); this.tvwReportList = new System.Windows.Forms.TreeView(); this.SuspendLayout(); // // tvwReportList // this.tvwReportList.AccessibleDescription = resources.GetString("tvwReportList.AccessibleDescription"); this.tvwReportList.AccessibleName = resources.GetString("tvwReportList.AccessibleName"); this.tvwReportList.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("tvwReportList.Anchor"))); this.tvwReportList.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("tvwReportList.BackgroundImage"))); this.tvwReportList.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("tvwReportList.Dock"))); this.tvwReportList.Enabled = ((bool)(resources.GetObject("tvwReportList.Enabled"))); this.tvwReportList.Font = ((System.Drawing.Font)(resources.GetObject("tvwReportList.Font"))); this.tvwReportList.ImageIndex = ((int)(resources.GetObject("tvwReportList.ImageIndex"))); this.tvwReportList.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("tvwReportList.ImeMode"))); this.tvwReportList.Indent = ((int)(resources.GetObject("tvwReportList.Indent"))); this.tvwReportList.ItemHeight = ((int)(resources.GetObject("tvwReportList.ItemHeight"))); this.tvwReportList.Location = ((System.Drawing.Point)(resources.GetObject("tvwReportList.Location"))); this.tvwReportList.Name = "tvwReportList"; this.tvwReportList.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("tvwReportList.RightToLeft"))); this.tvwReportList.SelectedImageIndex = ((int)(resources.GetObject("tvwReportList.SelectedImageIndex"))); this.tvwReportList.Size = ((System.Drawing.Size)(resources.GetObject("tvwReportList.Size"))); this.tvwReportList.TabIndex = ((int)(resources.GetObject("tvwReportList.TabIndex"))); this.tvwReportList.Text = resources.GetString("tvwReportList.Text"); this.tvwReportList.Visible = ((bool)(resources.GetObject("tvwReportList.Visible"))); this.tvwReportList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LastReport_KeyDown); this.tvwReportList.DoubleClick += new System.EventHandler(this.tvwReportList_DoubleClick); // // LastReport // this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.Add(this.tvwReportList); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.KeyPreview = true; this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "LastReport"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.LastReport_KeyDown); this.Load += new System.EventHandler(this.LastReport_Load); this.ResumeLayout(false); } #endregion private void LastReport_Load(object sender, EventArgs e) { // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.WaitCursor; #endregion Code Inserted Automatically const string METHOD_NAME = THIS + ".LastReport_Load()"; const string SEPARATOR = " - "; const string DATE_FORMAT = "dd-MM-yyyy hh:mm:ss"; try { // get last 10 report executed by user ArrayList arrObjects = new ArrayList(); LastReportBO boLastReport = new LastReportBO(); ReportManagementBO boReportManagement = new ReportManagementBO(); arrObjects = boLastReport.GetLast10Report(SystemProperty.UserName); // bind to list sys_ReportHistoryVO voReportHistory; string strReportName = string.Empty; TreeNode tnNode; for (int i = 0; i < arrObjects.Count; i++) { voReportHistory = (sys_ReportHistoryVO)arrObjects[i]; strReportName = boReportManagement.GetReportName(voReportHistory.ReportID); tnNode = new TreeNode(Constants.OPEN_SBRACKET + voReportHistory.ExecDateTime.ToString(DATE_FORMAT) + Constants.CLOSE_SBRACKET + SEPARATOR + strReportName); tnNode.Tag = voReportHistory; tvwReportList.Nodes.Add(tnNode); } } catch (PCSException ex) { // displays the error message. PCSMessageBox.Show(ex.mCode, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex.CauseException, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } catch (Exception ex) { // displays the error message. PCSMessageBox.Show(ErrorCode.OTHER_ERROR, MessageBoxIcon.Error); // log message. try { Logger.LogMessage(ex, METHOD_NAME, Level.ERROR); } catch { PCSMessageBox.Show(ErrorCode.LOG_EXCEPTION, MessageBoxIcon.Error); } } // Code Inserted Automatically #region Code Inserted Automatically this.Cursor = Cursors.Default; #endregion Code Inserted Automatically } private void LastReport_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { // get selected report data if (tvwReportList.SelectedNode != null) { // return to parent this.mReturnValue = (sys_ReportHistoryVO)tvwReportList.SelectedNode.Tag; // close the form this.Close(); } } if (e.KeyCode == Keys.Escape) { this.Close(); } } private void tvwReportList_DoubleClick(object sender, EventArgs e) { this.LastReport_KeyDown(this, new KeyEventArgs(Keys.Enter)); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DynamicTests : ExpressionCompilerTestBase { [Fact] public void Local_Simple() { var source = @"class C { static void M() { dynamic d = 1; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Array() { var source = @"class C { static void M() { dynamic[] d = new dynamic[1]; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (dynamic[] V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Local_Generic() { var source = @"class C { static void M() { System.Collections.Generic.List<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (System.Collections.Generic.List<dynamic> V_0) //d IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Simple() { var source = @"class C { static void M() { const dynamic d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Array() { var source = @"class C { static void M() { const dynamic[] d = null; } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [Fact] public void LocalConstant_Generic() { var source = @"class C { static void M() { const Generic<dynamic> d = null; } static dynamic ForceDynamicAttribute() { return null; } } class Generic<T> { } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt: @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantDynamic() { var source = @"class C { static void M() { { #line 799 dynamic a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 dynamic[] b = null; } } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "a", 0x01); } else { VerifyCustomTypeInfo(locals[0], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", 0x02); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndNonConstantNonDynamic() { var source = @"class C { static void M() { { #line 799 object a = null; const dynamic b = null; } { const dynamic[] a = null; #line 899 object[] b = null; } } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "a", null); VerifyCustomTypeInfo(locals[1], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "b", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const dynamic b = null; #line 799 object e = null; } { const dynamic[] a = null; const dynamic[] c = null; #line 899 object[] e = null; } { #line 999 object e = null; const dynamic a = null; const dynamic c = null; } } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "b", 0x01); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x02); VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); VerifyCustomTypeInfo(locals[2], "c", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [WorkItem(4106, "https://github.com/dotnet/roslyn/issues/4106")] [Fact] public void LocalDuplicateConstantAndConstantNonDynamic() { var source = @"class C { static void M() { { const dynamic a = null; const object c = null; #line 799 object e = null; } { const dynamic[] b = null; #line 899 object[] e = null; } { const object[] a = null; #line 999 object e = null; const dynamic[] c = null; } } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 799); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[1], "a", 0x01); } else { VerifyCustomTypeInfo(locals[1], "a", null); // Dynamic info ignored because ambiguous. } VerifyCustomTypeInfo(locals[2], "c", null); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 899); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "b", 0x02); locals.Free(); context = CreateMethodContext(runtime, methodName: "C.M", atLineNumber: 999); testData = new CompilationTestData(); locals = ArrayBuilder<LocalAndMethod>.GetInstance(); context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(3, locals.Count); VerifyCustomTypeInfo(locals[0], "e", null); VerifyCustomTypeInfo(locals[1], "a", null); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[2], "c", 0x02); } else { VerifyCustomTypeInfo(locals[2], "c", null); // Dynamic info ignored because ambiguous. } locals.Free(); }); } [Fact] public void LocalsWithLongAndShortNames() { var source = @"class C { static void M() { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b = null; dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d = null; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, methodName: "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(4, locals.Count); if (runtime.DebugFormat == DebugInformationFormat.PortablePdb) { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", 0x01); VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", 0x01); } else { VerifyCustomTypeInfo(locals[0], "c123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped VerifyCustomTypeInfo(locals[2], "a123456789012345678901234567890123456789012345678901234567890123", null); // dynamic info dropped } VerifyCustomTypeInfo(locals[1], "d", 0x01); VerifyCustomTypeInfo(locals[3], "b", 0x01); locals.Free(); }); } [Fact] public void Parameter_Simple() { var source = @"class C { static void M(dynamic d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, method.ReturnType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Array() { var source = @"class C { static void M(dynamic[] d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((ArrayTypeSymbol)method.ReturnType).ElementType.TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [Fact] public void Parameter_Generic() { var source = @"class C { static void M(System.Collections.Generic.List<dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } }"; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); Assert.Equal(TypeKind.Dynamic, ((NamedTypeSymbol)method.ReturnType).TypeArguments.Single().TypeKind); VerifyCustomTypeInfo(locals[0], "d", 0x02); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); locals.Free(); }); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void ComplexDynamicType() { var source = @"class C { static void M(Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> d) { } static dynamic ForceDynamicAttribute() { return null; } } public class Outer<T, U> { public class Inner<V, W> { } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasDynamicAttribute(method); VerifyCustomTypeInfo(locals[0], "d", 0x04, 0x03); VerifyLocal(testData, typeName, locals[0], "<>m0", "d", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); string error; var result = context.CompileExpression("d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, 0x04, 0x03); // Note that the method produced by CompileAssignment returns void // so there is never custom type info. result = context.CompileAssignment("d", "d", out error); Assert.Null(error); VerifyCustomTypeInfo(result, null); ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; testData = new CompilationTestData(); result = context.CompileExpression( "var dd = d;", DkmEvaluationFlags.None, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 60 (0x3c) .maxstack 6 IL_0000: ldtoken ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""dd"" IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1"" IL_0014: newobj ""System.Guid..ctor(string)"" IL_0019: ldc.i4.3 IL_001a: newarr ""byte"" IL_001f: dup IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=3 <PrivateImplementationDetails>.A4E591DA7617172655FE45FC3878ECC8CC0D44B3"" IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])"" IL_002f: ldstr ""dd"" IL_0034: call ""Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<Outer<dynamic[], object[]>.Inner<Outer<object, dynamic>[], dynamic>>(string)"" IL_0039: ldarg.0 IL_003a: stind.ref IL_003b: ret }"); locals.Free(); }); } [Fact] public void DynamicAliases() { var source = @"class C { static void M() { } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( Alias( DkmClrAliasKind.Variable, "d1", "d1", typeof(object).AssemblyQualifiedName, MakeCustomTypeInfo(true)), Alias( DkmClrAliasKind.Variable, "d2", "d2", typeof(Dictionary<Dictionary<dynamic, Dictionary<object[], dynamic[]>>, object>).AssemblyQualifiedName, MakeCustomTypeInfo(false, false, true, false, false, false, false, true, false))); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var diagnostics = DiagnosticBag.GetInstance(); var testData = new CompilationTestData(); context.CompileGetLocals( locals, argumentsOnly: false, aliases: aliases, diagnostics: diagnostics, typeName: out typeName, testData: testData); diagnostics.Free(); Assert.Equal(locals.Count, 2); VerifyCustomTypeInfo(locals[0], "d1", 0x01); VerifyLocal(testData, typeName, locals[0], "<>m0", "d1", expectedILOpt: @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""d1"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: ret }"); VerifyCustomTypeInfo(locals[1], "d2", 0x84, 0x00); // Note: read flags right-to-left in each byte: 0010 0001 0(000 0000) VerifyLocal(testData, typeName, locals[1], "<>m1", "d2", expectedILOpt: @"{ // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr ""d2"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""System.Collections.Generic.Dictionary<System.Collections.Generic.Dictionary<dynamic, System.Collections.Generic.Dictionary<object[], dynamic[]>>, object>"" IL_000f: ret }"); locals.Free(); }); } private static ReadOnlyCollection<byte> MakeCustomTypeInfo(params bool[] flags) { Assert.NotNull(flags); var builder = ArrayBuilder<bool>.GetInstance(); builder.AddRange(flags); var bytes = DynamicFlagsCustomTypeInfo.ToBytes(builder); builder.Free(); return CustomTypeInfo.Encode(bytes, null); } [Fact] public void DynamicAttribute_NotAvailable() { var source = @"class C { static void M() { dynamic d = 1; } }"; var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); var method = testData.Methods.Single().Value.Method; AssertHasNoDynamicAttribute(method); locals.Free(); }); } private static void AssertHasDynamicAttribute(IMethodSymbol method) { Assert.Contains( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } private static void AssertHasNoDynamicAttribute(IMethodSymbol method) { Assert.DoesNotContain( "System.Runtime.CompilerServices.DynamicAttribute", method.GetSynthesizedAttributes(forReturnType: true).Select(a => a.AttributeClass.ToTestDisplayString())); } [Fact] public void DynamicCall() { var source = @" class C { void M() { dynamic d = this; d.M(); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("d.M()", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); Assert.Equal(TypeKind.Dynamic, methodData.Method.ReturnType.TypeKind); methodData.VerifyIL(@" { // Code size 77 (0x4d) .maxstack 9 .locals init (dynamic V_0) //d IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0037 IL_0007: ldc.i4.0 IL_0008: ldstr ""M"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.1 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0027: stelem.ref IL_0028: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002d: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0032: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0037: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_003c: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0041: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldloc.0 IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: ret } "); }); } [WorkItem(1160855, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1160855")] [Fact] public void AwaitDynamic() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C { dynamic d; void M(int p) { d.Test(); // Force reference to runtime binder. } static void G(Func<Task<object>> f) { } } "; var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("G(async () => await d())", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); var methodData = testData.GetMethodData("<>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()"); methodData.VerifyIL(@" { // Code size 539 (0x21b) .maxstack 10 .locals init (int V_0, object V_1, object V_2, System.Runtime.CompilerServices.ICriticalNotifyCompletion V_3, System.Runtime.CompilerServices.INotifyCompletion V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse IL_0185 IL_000d: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0012: brtrue.s IL_0044 IL_0014: ldc.i4.0 IL_0015: ldstr ""GetAwaiter"" IL_001a: ldnull IL_001b: ldtoken ""C"" IL_0020: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0025: ldc.i4.1 IL_0026: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldc.i4.0 IL_002e: ldnull IL_002f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0034: stelem.ref IL_0035: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0044: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0049: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_004e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__0"" IL_0053: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0058: brtrue.s IL_0084 IL_005a: ldc.i4.0 IL_005b: ldtoken ""C"" IL_0060: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0065: ldc.i4.1 IL_0066: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_006b: dup IL_006c: ldc.i4.0 IL_006d: ldc.i4.0 IL_006e: ldnull IL_006f: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0074: stelem.ref IL_0075: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Invoke(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_007a: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_007f: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0084: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0089: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_008e: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0093: ldarg.0 IL_0094: ldfld ""<>x.<>c__DisplayClass0_0 <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>4__this"" IL_0099: ldfld ""C <>x.<>c__DisplayClass0_0.<>4__this"" IL_009e: ldfld ""dynamic C.d"" IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00ad: stloc.2 IL_00ae: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00b3: brtrue.s IL_00da IL_00b5: ldc.i4.s 16 IL_00b7: ldtoken ""bool"" IL_00bc: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00c1: ldtoken ""C"" IL_00c6: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_00cb: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_00d0: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_00d5: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00da: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00df: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_00e4: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__2"" IL_00e9: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_00ee: brtrue.s IL_011f IL_00f0: ldc.i4.0 IL_00f1: ldstr ""IsCompleted"" IL_00f6: ldtoken ""C"" IL_00fb: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0100: ldc.i4.1 IL_0101: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldc.i4.0 IL_0109: ldnull IL_010a: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_010f: stelem.ref IL_0110: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0115: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_011a: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_011f: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_0124: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0129: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__1"" IL_012e: ldloc.2 IL_012f: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0134: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_0139: brtrue.s IL_019c IL_013b: ldarg.0 IL_013c: ldc.i4.0 IL_013d: dup IL_013e: stloc.0 IL_013f: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_0144: ldarg.0 IL_0145: ldloc.2 IL_0146: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_014b: ldloc.2 IL_014c: isinst ""System.Runtime.CompilerServices.ICriticalNotifyCompletion"" IL_0151: stloc.3 IL_0152: ldloc.3 IL_0153: brtrue.s IL_0170 IL_0155: ldloc.2 IL_0156: castclass ""System.Runtime.CompilerServices.INotifyCompletion"" IL_015b: stloc.s V_4 IL_015d: ldarg.0 IL_015e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0163: ldloca.s V_4 IL_0165: ldarg.0 IL_0166: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitOnCompleted<System.Runtime.CompilerServices.INotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.INotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_016b: ldnull IL_016c: stloc.s V_4 IL_016e: br.s IL_017e IL_0170: ldarg.0 IL_0171: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0176: ldloca.s V_3 IL_0178: ldarg.0 IL_0179: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.ICriticalNotifyCompletion, <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d>(ref System.Runtime.CompilerServices.ICriticalNotifyCompletion, ref <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d)"" IL_017e: ldnull IL_017f: stloc.3 IL_0180: leave IL_021a IL_0185: ldarg.0 IL_0186: ldfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_018b: stloc.2 IL_018c: ldarg.0 IL_018d: ldnull IL_018e: stfld ""object <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>u__1"" IL_0193: ldarg.0 IL_0194: ldc.i4.m1 IL_0195: dup IL_0196: stloc.0 IL_0197: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_019c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01a1: brtrue.s IL_01d3 IL_01a3: ldc.i4.0 IL_01a4: ldstr ""GetResult"" IL_01a9: ldnull IL_01aa: ldtoken ""C"" IL_01af: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_01b4: ldc.i4.1 IL_01b5: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_01ba: dup IL_01bb: ldc.i4.0 IL_01bc: ldc.i4.0 IL_01bd: ldnull IL_01be: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_01c3: stelem.ref IL_01c4: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_01c9: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_01ce: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d3: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01d8: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_01dd: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>o.<>p__3"" IL_01e2: ldloc.2 IL_01e3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_01e8: ldnull IL_01e9: stloc.2 IL_01ea: stloc.1 IL_01eb: leave.s IL_0206 } catch System.Exception { IL_01ed: stloc.s V_5 IL_01ef: ldarg.0 IL_01f0: ldc.i4.s -2 IL_01f2: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_01f7: ldarg.0 IL_01f8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_01fd: ldloc.s V_5 IL_01ff: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetException(System.Exception)"" IL_0204: leave.s IL_021a } IL_0206: ldarg.0 IL_0207: ldc.i4.s -2 IL_0209: stfld ""int <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>1__state"" IL_020e: ldarg.0 IL_020f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object> <>x.<>c__DisplayClass0_0.<<<>m0>b__0>d.<>t__builder"" IL_0214: ldloc.1 IL_0215: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<object>.SetResult(object)"" IL_021a: ret } "); }); } [WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")] [Fact] public void InvokeStaticMemberInLambda() { var source = @" class C { static dynamic x; static void Foo(dynamic y) { System.Action a = () => Foo(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.Foo"); var testData = new CompilationTestData(); string error; var result = context.CompileAssignment("a", "() => Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, null); testData.GetMethodData("<>x.<>c.<<>m0>b__0_0").VerifyIL(@" { // Code size 106 (0x6a) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0046 IL_0007: ldc.i4 0x100 IL_000c: ldstr ""Foo"" IL_0011: ldnull IL_0012: ldtoken ""C"" IL_0017: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001c: ldc.i4.2 IL_001d: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0022: dup IL_0023: ldc.i4.0 IL_0024: ldc.i4.s 33 IL_0026: ldnull IL_0027: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_002c: stelem.ref IL_002d: dup IL_002e: ldc.i4.1 IL_002f: ldc.i4.0 IL_0030: ldnull IL_0031: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0036: stelem.ref IL_0037: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_003c: call ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0041: stsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0046: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_004b: ldfld ""System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic> System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>>.Target"" IL_0050: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>> <>x.<>o__0.<>p__0"" IL_0055: ldtoken ""<>x"" IL_005a: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005f: ldsfld ""dynamic C.x"" IL_0064: callvirt ""void System.Action<System.Runtime.CompilerServices.CallSite, System.Type, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0069: ret }"); context = CreateMethodContext(runtime, "C.<>c.<Foo>b__1_0"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL(@" { // Code size 102 (0x66) .maxstack 9 IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldsfld ""dynamic C.x"" IL_0060: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0065: ret }"); }); } [WorkItem(1095613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095613")] [Fact] public void HoistedLocalsLoseDynamicAttribute() { var source = @" class C { static void M(dynamic x) { dynamic y = 3; System.Func<dynamic> a = () => x + y; } static void Foo(int x) { M(x); } } "; var comp = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, TestOptions.DebugDll); WithRuntimeInstance(comp, runtime => { var context = CreateMethodContext(runtime, "C.M"); var testData = new CompilationTestData(); string error; var result = context.CompileExpression("Foo(x)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.x"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); testData = new CompilationTestData(); result = context.CompileExpression("Foo(y)", out error, testData); Assert.Null(error); VerifyCustomTypeInfo(result, 0x01); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 103 (0x67) .maxstack 9 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 System.Func<dynamic> V_1) //a IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0005: brtrue.s IL_0042 IL_0007: ldc.i4.0 IL_0008: ldstr ""Foo"" IL_000d: ldnull IL_000e: ldtoken ""C"" IL_0013: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0018: ldc.i4.2 IL_0019: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001e: dup IL_001f: ldc.i4.0 IL_0020: ldc.i4.s 33 IL_0022: ldnull IL_0023: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0028: stelem.ref IL_0029: dup IL_002a: ldc.i4.1 IL_002b: ldc.i4.0 IL_002c: ldnull IL_002d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0032: stelem.ref IL_0033: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0038: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_003d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0042: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0047: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>>.Target"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>> <>x.<>o__0.<>p__0"" IL_0051: ldtoken ""<>x"" IL_0056: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_005b: ldloc.0 IL_005c: ldfld ""dynamic C.<>c__DisplayClass0_0.y"" IL_0061: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, System.Type, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, System.Type, dynamic)"" IL_0066: ret }"); }); } private static void VerifyCustomTypeInfo(LocalAndMethod localAndMethod, string expectedName, params byte[] expectedBytes) { Assert.Equal(localAndMethod.LocalName, expectedName); ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = localAndMethod.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(CompileResult compileResult, params byte[] expectedBytes) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = compileResult.GetCustomTypeInfo(out customTypeInfo); VerifyCustomTypeInfo(customTypeInfoId, customTypeInfo, expectedBytes); } private static void VerifyCustomTypeInfo(Guid customTypeInfoId, ReadOnlyCollection<byte> customTypeInfo, params byte[] expectedBytes) { if (expectedBytes == null) { Assert.Equal(Guid.Empty, customTypeInfoId); Assert.Null(customTypeInfo); } else { Assert.Equal(CustomTypeInfo.PayloadTypeId, customTypeInfoId); // Include leading count byte. var builder = ArrayBuilder<byte>.GetInstance(); builder.Add((byte)expectedBytes.Length); builder.AddRange(expectedBytes); expectedBytes = builder.ToArrayAndFree(); Assert.Equal(expectedBytes, customTypeInfo); } } } }
//--------------------------------------------------------------------- // Author: jachymko // // Description: Interface for opening files. // // Creation Date: Dec 29, 2006 //--------------------------------------------------------------------- using System; using System.IO; using Pscx.IO; namespace Pscx.Commands { public interface IPscxFileHandler { Stream OpenWrite(string filePath); Stream OpenWrite(string filePath, bool noClobber); Stream OpenWrite(string filePath, bool noClobber, bool force); Stream OpenWrite(string filePath, bool noClobber, bool force, bool terminateOnError); void ProcessRead(string filePath, Action<Stream> action); void ProcessRead(FileInfo file, Action<Stream> action); void ProcessText(string filePath, Action<StreamReader> action); void ProcessText(string filePath, bool detectEncodingFromByteMarks, Action<StreamReader> action); void ProcessWrite(string filePath, Action<Stream> action); void ProcessWrite(FileInfo file, Action<Stream> action); } partial class PscxCmdlet : IPscxFileHandler { Stream IPscxFileHandler.OpenWrite(string filePath) { return FileHandler.OpenWrite(filePath, false); } Stream IPscxFileHandler.OpenWrite(string filePath, bool noClobber) { return FileHandler.OpenWrite(filePath, noClobber, false); } Stream IPscxFileHandler.OpenWrite(string filePath, bool noClobber, bool force) { return FileHandler.OpenWrite(filePath, noClobber, force, false); } Stream IPscxFileHandler.OpenWrite(string filePath, bool noClobber, bool force, bool terminateOnError) { try { FileInfo file = new FileInfo(filePath); FileMode mode = noClobber ? FileMode.CreateNew : FileMode.Create; if (force && !noClobber && file.Exists && file.IsReadOnly) { return new ResetReadOnlyOnDisposeStream(file); } return file.Open(mode, FileAccess.Write); } catch (IOException exc) { ErrorHandler.HandleFileAlreadyExistsError(terminateOnError, filePath, exc); } catch (Exception exc) { ErrorHandler.HandleFileError(terminateOnError, filePath, exc); } return null; } void IPscxFileHandler.ProcessText(string filePath, bool detectEncodingFromByteMarks, Action<StreamReader> action) { FileHandler.ProcessRead(filePath, delegate(Stream stream) { using (StreamReader reader = new StreamReader(stream, detectEncodingFromByteMarks)) { action(reader); } }); } void IPscxFileHandler.ProcessText(string filePath, Action<StreamReader> action) { FileHandler.ProcessText(filePath, true, action); } void IPscxFileHandler.ProcessRead(string filePath, Action<Stream> action) { Stream stream = null; try { try { stream = File.OpenRead(filePath); } catch (Exception exc) { ErrorHandler.WriteFileError(filePath, exc); } if (stream != null) { action(stream); } } finally { if (stream != null) { stream.Dispose(); } } } void IPscxFileHandler.ProcessRead(FileInfo file, Action<Stream> action) { FileHandler.ProcessRead(file.FullName, action); } void IPscxFileHandler.ProcessWrite(string filePath, Action<Stream> action) { Stream stream = null; try { try { stream = File.Create(filePath); } catch (Exception exc) { ErrorHandler.WriteFileError(filePath, exc); } if (stream != null) { action(stream); } } finally { if (stream != null) { stream.Dispose(); } } } void IPscxFileHandler.ProcessWrite(FileInfo file, Action<Stream> action) { FileHandler.ProcessWrite(file.FullName, action); } class ResetReadOnlyOnDisposeStream : StreamDecorator { private readonly FileInfo _file; private bool _disposed; public ResetReadOnlyOnDisposeStream(FileInfo file) { _file = file; _file.IsReadOnly = false; InnerStream = _file.OpenWrite(); } public override void Close() { base.Close(); ResetReadOnly(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { ResetReadOnly(); } } private void ResetReadOnly() { if( _disposed) { return; } _file.IsReadOnly = true; _disposed = true; } } } }
/* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.InteropServices; namespace PixelFarm.VectorMath { /// <summary> /// Represents a 3D vector using three float-precision floating-point numbers. /// </summary> //[Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3Float : IEquatable<Vector3Float> { /// <summary> /// The X component of the Vector3Float. /// </summary> public float x; /// <summary> /// The Y component of the Vector3Float. /// </summary> public float y; /// <summary> /// The Z component of the Vector3Float. /// </summary> public float z; /// <summary> /// Constructs a new Vector3Float. /// </summary> /// <param name="x">The x component of the Vector3Float.</param> /// <param name="y">The y component of the Vector3Float.</param> /// <param name="z">The z component of the Vector3Float.</param> public Vector3Float(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } /// <summary> /// Constructs a new instance from the given Vector2d. /// </summary> /// <param name="v">The Vector2d to copy components from.</param> public Vector3Float(Vector2 v, float z = 0) { #if true throw new NotImplementedException(); #else x = v.x; y = v.y; this.z = z; #endif } /// <summary> /// Constructs a new instance from the given Vector3Floatd. /// </summary> /// <param name="v">The Vector3Floatd to copy components from.</param> public Vector3Float(Vector3Float v) { x = v.x; y = v.y; z = v.z; } public Vector3Float(float[] floatArray) { x = floatArray[0]; y = floatArray[1]; z = floatArray[2]; } /// <summary> /// Constructs a new instance from the given Vector4d. /// </summary> /// <param name="v">The Vector4d to copy components from.</param> public Vector3Float(Vector4 v) { #if true throw new NotImplementedException(); #else x = v.x; y = v.y; z = v.z; #endif } public Vector3Float(Vector3 position) { this.x = (float)position.x; this.y = (float)position.y; this.z = (float)position.z; } public float this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: return 0; } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new Exception(); } } } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)Math.Sqrt(x * x + y * y + z * z); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthFast"/> public float LengthSquared { get { return x * x + y * y + z * z; } } /// <summary> /// Returns a normalized Vector of this. /// </summary> /// <returns></returns> public Vector3Float GetNormal() { Vector3Float temp = this; temp.Normalize(); return temp; } /// <summary> /// Scales the Vector3Floatd to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; x *= scale; y *= scale; z *= scale; } public float[] ToArray() { return new float[] { x, y, z }; } /// <summary> /// Defines a unit-length Vector3Floatd that points towards the X-axis. /// </summary> public static readonly Vector3Float UnitX = new Vector3Float(1, 0, 0); /// <summary> /// Defines a unit-length Vector3Floatd that points towards the Y-axis. /// </summary> public static readonly Vector3Float UnitY = new Vector3Float(0, 1, 0); /// <summary> /// /// Defines a unit-length Vector3Floatd that points towards the Z-axis. /// </summary> public static readonly Vector3Float UnitZ = new Vector3Float(0, 0, 1); /// <summary> /// Defines a zero-length Vector3Float. /// </summary> public static readonly Vector3Float Zero = new Vector3Float(0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector3Float One = new Vector3Float(1, 1, 1); /// <summary> /// Defines an instance with all components set to positive infinity. /// </summary> public static readonly Vector3Float PositiveInfinity = new Vector3Float(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); /// <summary> /// Defines an instance with all components set to negative infinity. /// </summary> public static readonly Vector3Float NegativeInfinity = new Vector3Float(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); /// <summary> /// Defines the size of the Vector3Floatd struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3Float()); /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector3Float Add(Vector3Float a, Vector3Float b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector3Float a, ref Vector3Float b, out Vector3Float result) { result = new Vector3Float(a.x + b.x, a.y + b.y, a.z + b.z); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector3Float Subtract(Vector3Float a, Vector3Float b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector3Float a, ref Vector3Float b, out Vector3Float result) { result = new Vector3Float(a.x - b.x, a.y - b.y, a.z - b.z); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3Float Multiply(Vector3Float vector, float scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3Float vector, float scale, out Vector3Float result) { result = new Vector3Float(vector.x * scale, vector.y * scale, vector.z * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3Float Multiply(Vector3Float vector, Vector3Float scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3Float vector, ref Vector3Float scale, out Vector3Float result) { result = new Vector3Float(vector.x * scale.x, vector.y * scale.y, vector.z * scale.z); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3Float Divide(Vector3Float vector, float scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3Float vector, float scale, out Vector3Float result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3Float Divide(Vector3Float vector, Vector3Float scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3Float vector, ref Vector3Float scale, out Vector3Float result) { result = new Vector3Float(vector.x / scale.x, vector.y / scale.y, vector.z / scale.z); } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector3Float ComponentMin(Vector3Float a, Vector3Float b) { a.x = a.x < b.x ? a.x : b.x; a.y = a.y < b.y ? a.y : b.y; a.z = a.z < b.z ? a.z : b.z; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void ComponentMin(ref Vector3Float a, ref Vector3Float b, out Vector3Float result) { result.x = a.x < b.x ? a.x : b.x; result.y = a.y < b.y ? a.y : b.y; result.z = a.z < b.z ? a.z : b.z; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector3Float ComponentMax(Vector3Float a, Vector3Float b) { a.x = a.x > b.x ? a.x : b.x; a.y = a.y > b.y ? a.y : b.y; a.z = a.z > b.z ? a.z : b.z; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void ComponentMax(ref Vector3Float a, ref Vector3Float b, out Vector3Float result) { result.x = a.x > b.x ? a.x : b.x; result.y = a.y > b.y ? a.y : b.y; result.z = a.z > b.z ? a.z : b.z; } /// <summary> /// Returns the Vector3d with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3Float</returns> public static Vector3Float Min(Vector3Float left, Vector3Float right) { return left.LengthSquared < right.LengthSquared ? left : right; } /// <summary> /// Returns the Vector3d with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3Float</returns> public static Vector3Float Max(Vector3Float left, Vector3Float right) { return left.LengthSquared >= right.LengthSquared ? left : right; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector3Float Clamp(Vector3Float vec, Vector3Float min, Vector3Float max) { vec.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x; vec.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y; vec.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector3Float vec, ref Vector3Float min, ref Vector3Float max, out Vector3Float result) { result.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x; result.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y; result.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector3Float Normalize(Vector3Float vec) { float scale = 1.0f / vec.Length; vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector3Float vec, out Vector3Float result) { float scale = 1.0f / vec.Length; result.x = vec.x * scale; result.y = vec.y * scale; result.z = vec.z * scale; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector3Float left, Vector3Float right) { return left.x * right.x + left.y * right.y + left.z * right.z; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector3Float left, ref Vector3Float right, out float result) { result = left.x * right.x + left.y * right.y + left.z * right.z; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> public static Vector3Float Cross(Vector3Float left, Vector3Float right) { Vector3Float result; Cross(ref left, ref right, out result); return result; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> /// <param name="result">The cross product of the two inputs</param> public static void Cross(ref Vector3Float left, ref Vector3Float right, out Vector3Float result) { result = new Vector3Float(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); } /// <summary> /// Checks if 3 points are collinear (all lie on the same line). /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="epsilon"></param> /// <returns></returns> public static bool Collinear(Vector3Float a, Vector3Float b, Vector3Float c, float epsilon = .000001f) { // Return true if a, b, and c all lie on the same line. return Math.Abs(Cross(b - a, c - a).Length) < epsilon; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector3Float Lerp(Vector3Float a, Vector3Float b, float blend) { a.x = blend * (b.x - a.x) + a.x; a.y = blend * (b.y - a.y) + a.y; a.z = blend * (b.z - a.z) + a.z; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector3Float a, ref Vector3Float b, float blend, out Vector3Float result) { result.x = blend * (b.x - a.x) + a.x; result.y = blend * (b.y - a.y) + a.y; result.z = blend * (b.z - a.z) + a.z; } /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector3Float BaryCentric(Vector3Float a, Vector3Float b, Vector3Float c, float u, float v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector3Float a, ref Vector3Float b, ref Vector3Float c, float u, float v, out Vector3Float result) { result = a; // copy Vector3Float temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3Float TransformVector(Vector3Float vec, Matrix4X4 mat) { return new Vector3Float( Vector3Float.Dot(vec, new Vector3Float(mat.Column0)), Vector3Float.Dot(vec, new Vector3Float(mat.Column1)), Vector3Float.Dot(vec, new Vector3Float(mat.Column2))); } /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformVector(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result) { #if true throw new NotImplementedException(); #else result.x = vec.x * mat.Row0.x + vec.y * mat.Row1.x + vec.z * mat.Row2.x; result.y = vec.x * mat.Row0.y + vec.y * mat.Row1.y + vec.z * mat.Row2.y; result.z = vec.x * mat.Row0.z + vec.y * mat.Row1.z + vec.z * mat.Row2.z; #endif } /// <summary>Transform a Normal by the given Matrix</summary> /// <remarks> /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed normal</returns> public static Vector3Float TransformNormal(Vector3Float norm, Matrix4X4 mat) { mat.Invert(); return TransformNormalInverse(norm, mat); } /// <summary>Transform a Normal by the given Matrix</summary> /// <remarks> /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed normal</param> public static void TransformNormal(ref Vector3Float norm, ref Matrix4X4 mat, out Vector3Float result) { Matrix4X4 Inverse = Matrix4X4.Invert(mat); Vector3Float.TransformNormalInverse(ref norm, ref Inverse, out result); } /// <summary>Transform a Normal by the (transpose of the) given Matrix</summary> /// <remarks> /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="invMat">The inverse of the desired transformation</param> /// <returns>The transformed normal</returns> public static Vector3Float TransformNormalInverse(Vector3Float norm, Matrix4X4 invMat) { return new Vector3Float( Vector3Float.Dot(norm, new Vector3Float(invMat.Row0)), Vector3Float.Dot(norm, new Vector3Float(invMat.Row1)), Vector3Float.Dot(norm, new Vector3Float(invMat.Row2))); } /// <summary>Transform a Normal by the (transpose of the) given Matrix</summary> /// <remarks> /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="invMat">The inverse of the desired transformation</param> /// <param name="result">The transformed normal</param> public static void TransformNormalInverse(ref Vector3Float norm, ref Matrix4X4 invMat, out Vector3Float result) { #if true throw new NotImplementedException(); #else result.x = norm.x * invMat.Row0.x + norm.y * invMat.Row0.y + norm.z * invMat.Row0.z; result.y = norm.x * invMat.Row1.x + norm.y * invMat.Row1.y + norm.z * invMat.Row1.z; result.z = norm.x * invMat.Row2.x + norm.y * invMat.Row2.y + norm.z * invMat.Row2.z; #endif } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed position</returns> public static Vector3Float TransformPosition(Vector3Float pos, Matrix4X4 mat) { #if true throw new NotImplementedException(); #else return new Vector3Float( Vector3Float.Dot(pos, new Vector3Float((float)mat.Column0)) + mat.Row3.x, Vector3Float.Dot(pos, new Vector3Float((float)mat.Column1)) + mat.Row3.y, Vector3Float.Dot(pos, new Vector3Float((float)mat.Column2)) + mat.Row3.z); #endif } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed position</param> public static void TransformPosition(ref Vector3Float pos, ref Matrix4X4 mat, out Vector3Float result) { #if true throw new NotImplementedException(); #else result.x = pos.x * mat.Row0.x + pos.y * mat.Row1.x + pos.z * mat.Row2.x + mat.Row3.x; result.y = pos.x * mat.Row0.y + pos.y * mat.Row1.y + pos.z * mat.Row2.y + mat.Row3.y; result.z = pos.x * mat.Row0.z + pos.y * mat.Row1.z + pos.z * mat.Row2.z + mat.Row3.z; #endif } /// <summary> /// Transform all the vectors in the array by the given Matrix. /// </summary> /// <param name="boundsVerts"></param> /// <param name="rotationQuaternion"></param> public static void Transform(Vector3Float[] vecArray, Matrix4X4 mat) { for (int i = 0; i < vecArray.Length; i++) { vecArray[i] = Transform(vecArray[i], mat); } } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3Float Transform(Vector3Float vec, Matrix4X4 mat) { Vector3Float result; Transform(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result) { #if true throw new NotImplementedException(); #else Vector4 v4 = new Vector4(vec.x, vec.y, vec.z, 1.0); Vector4.Transform(ref v4, ref mat, out v4); result = v4.Xyz; #endif } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector3Float Transform(Vector3Float vec, Quaternion quat) { #if true throw new NotImplementedException(); #else Vector3Float result; Transform(ref vec, ref quat, out result); return result; #endif } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector3Float vec, ref Quaternion quat, out Vector3Float result) { #if true throw new NotImplementedException(); #else // Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows: // vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec) Vector3Float xyz = quat.Xyz, temp, temp2; Vector3Float.Cross(ref xyz, ref vec, out temp); Vector3Float.Multiply(ref vec, quat.W, out temp2); Vector3Float.Add(ref temp, ref temp2, out temp); Vector3Float.Cross(ref xyz, ref temp, out temp); Vector3Float.Multiply(ref temp, 2, out temp); Vector3Float.Add(ref vec, ref temp, out result); #endif } /// <summary> /// Transform all the vectors in the array by the quaternion rotation. /// </summary> /// <param name="boundsVerts"></param> /// <param name="rotationQuaternion"></param> public static void Transform(Vector3Float[] vecArray, Quaternion rotationQuaternion) { for (int i = 0; i < vecArray.Length; i++) { vecArray[i] = Transform(vecArray[i], rotationQuaternion); } } /// <summary> /// Transform a Vector3d by the given Matrix, and project the resulting Vector4 back to a Vector3Float /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3Float TransformPerspective(Vector3Float vec, Matrix4X4 mat) { #if true throw new NotImplementedException(); #else Vector3Float result; TransformPerspective(ref vec, ref mat, out result); return result; #endif } /// <summary>Transform a Vector3d by the given Matrix, and project the resulting Vector4d back to a Vector3d</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformPerspective(ref Vector3Float vec, ref Matrix4X4 mat, out Vector3Float result) { #if true throw new NotImplementedException(); #else Vector4 v = new Vector4(vec); Vector4.Transform(ref v, ref mat, out v); result.x = v.x / v.w; result.y = v.y / v.w; result.z = v.z / v.w; #endif } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float CalculateAngle(Vector3Float first, Vector3Float second) { return (float)Math.Acos((Vector3Float.Dot(first, second)) / (first.Length * second.Length)); } /// <summary>Calculates the angle (in radians) between two vectors.</summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void CalculateAngle(ref Vector3Float first, ref Vector3Float second, out float result) { float temp; Vector3Float.Dot(ref first, ref second, out temp); result = (float)Math.Acos(temp / (first.Length * second.Length)); } /// <summary> /// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance. /// </summary> public Vector2 Xy { get { return new Vector2(x, y); } set { #if true throw new NotImplementedException(); #else x = value.x; y = value.y; #endif } } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator +(Vector3Float left, Vector3Float right) { left.x += right.x; left.y += right.y; left.z += right.z; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator -(Vector3Float left, Vector3Float right) { left.x -= right.x; left.y -= right.y; left.z -= right.z; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator -(Vector3Float vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } /// <summary> /// Component wise multiply two vectors together, x*x, y*y, z*z. /// </summary> /// <param name="vecA"></param> /// <param name="vecB"></param> /// <returns></returns> public static Vector3Float operator *(Vector3Float vecA, Vector3Float vecB) { vecA.x *= vecB.x; vecA.y *= vecB.y; vecA.z *= vecB.z; return vecA; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator *(Vector3Float vec, float scale) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator *(float scale, Vector3Float vec) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Creates a new vector which is the numerator devided by each component of the vector. /// </summary> /// <param name="numerator"></param> /// <param name="vec"></param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator /(float numerator, Vector3Float vec) { return new Vector3Float((numerator / vec.x), (numerator / vec.y), (numerator / vec.z)); } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3Float operator /(Vector3Float vec, float scale) { float mult = 1 / scale; vec.x *= mult; vec.y *= mult; vec.z *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector3Float left, Vector3Float right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector3Float left, Vector3Float right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector3Float. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("[{0}, {1}, {2}]", x, y, z); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return new { x, y, z }.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector3Float)) return false; return this.Equals((Vector3Float)obj); } /// <summary> /// Indicates whether this instance and a specified object are equal within an error range. /// </summary> /// <param name="OtherVector"></param> /// <param name="ErrorValue"></param> /// <returns>True if the instances are equal; false otherwise.</returns> public bool Equals(Vector3Float OtherVector, float ErrorValue) { if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) && (y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue) && (z < OtherVector.z + ErrorValue && z > OtherVector.z - ErrorValue)) { return true; } return false; } /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector3Float other) { return x == other.x && y == other.y && z == other.z; } public static float ComponentMax(Vector3Float vector3) { return Math.Max(vector3.x, Math.Max(vector3.y, vector3.z)); } public static float ComponentMin(Vector3Float vector3) { return Math.Min(vector3.x, Math.Min(vector3.y, vector3.z)); } } }
// // JsonDeserializer.cs // // Author: // Marek Habersack <mhabersack@novell.com> // // (C) 2008 Novell, Inc. http://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. // // Code is based on JSON_checker (http://www.json.org/JSON_checker/) and JSON_parser // (http://fara.cs.uni-potsdam.de/~jsg/json_parser/) C sources. License for the original code // follows: #region Original License /* Copyright (c) 2005 JSON.org 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 shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace Nancy.Json { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; internal sealed class JsonDeserializer { /* Universal error constant */ const int __ = -1; const int UNIVERSAL_ERROR = __; /* Characters are mapped into these 31 character classes. This allows for a significant reduction in the size of the state transition table. */ const int C_SPACE = 0x00; /* space */ const int C_WHITE = 0x01; /* other whitespace */ const int C_LCURB = 0x02; /* { */ const int C_RCURB = 0x03; /* } */ const int C_LSQRB = 0x04; /* [ */ const int C_RSQRB = 0x05; /* ] */ const int C_COLON = 0x06; /* : */ const int C_COMMA = 0x07; /* , */ const int C_QUOTE = 0x08; /* " */ const int C_BACKS = 0x09; /* \ */ const int C_SLASH = 0x0A; /* / */ const int C_PLUS = 0x0B; /* + */ const int C_MINUS = 0x0C; /* - */ const int C_POINT = 0x0D; /* . */ const int C_ZERO = 0x0E; /* 0 */ const int C_DIGIT = 0x0F; /* 123456789 */ const int C_LOW_A = 0x10; /* a */ const int C_LOW_B = 0x11; /* b */ const int C_LOW_C = 0x12; /* c */ const int C_LOW_D = 0x13; /* d */ const int C_LOW_E = 0x14; /* e */ const int C_LOW_F = 0x15; /* f */ const int C_LOW_L = 0x16; /* l */ const int C_LOW_N = 0x17; /* n */ const int C_LOW_R = 0x18; /* r */ const int C_LOW_S = 0x19; /* s */ const int C_LOW_T = 0x1A; /* t */ const int C_LOW_U = 0x1B; /* u */ const int C_ABCDF = 0x1C; /* ABCDF */ const int C_E = 0x1D; /* E */ const int C_ETC = 0x1E; /* everything else */ const int C_STAR = 0x1F; /* * */ const int C_I = 0x20; /* I */ const int C_LOW_I = 0x21; /* i */ const int C_LOW_Y = 0x22; /* y */ const int C_N = 0x23; /* N */ /* The state codes. */ const int GO = 0x00; /* start */ const int OK = 0x01; /* ok */ const int OB = 0x02; /* object */ const int KE = 0x03; /* key */ const int CO = 0x04; /* colon */ const int VA = 0x05; /* value */ const int AR = 0x06; /* array */ const int ST = 0x07; /* string */ const int ES = 0x08; /* escape */ const int U1 = 0x09; /* u1 */ const int U2 = 0x0A; /* u2 */ const int U3 = 0x0B; /* u3 */ const int U4 = 0x0C; /* u4 */ const int MI = 0x0D; /* minus */ const int ZE = 0x0E; /* zero */ const int IN = 0x0F; /* integer */ const int FR = 0x10; /* fraction */ const int E1 = 0x11; /* e */ const int E2 = 0x12; /* ex */ const int E3 = 0x13; /* exp */ const int T1 = 0x14; /* tr */ const int T2 = 0x15; /* tru */ const int T3 = 0x16; /* true */ const int F1 = 0x17; /* fa */ const int F2 = 0x18; /* fal */ const int F3 = 0x19; /* fals */ const int F4 = 0x1A; /* false */ const int N1 = 0x1B; /* nu */ const int N2 = 0x1C; /* nul */ const int N3 = 0x1D; /* null */ const int FX = 0x1E; /* *.* *eE* */ const int IV = 0x1F; /* invalid input */ const int UK = 0x20; /* unquoted key name */ const int UI = 0x21; /* ignore during unquoted key name construction */ const int I1 = 0x22; /* In */ const int I2 = 0x23; /* Inf */ const int I3 = 0x24; /* Infi */ const int I4 = 0x25; /* Infin */ const int I5 = 0x26; /* Infini */ const int I6 = 0x27; /* Infinit */ const int I7 = 0x28; /* Infinity */ const int V1 = 0x29; /* Na */ const int V2 = 0x2A; /* NaN */ /* Actions */ const int FA = -10; /* false */ const int TR = -11; /* false */ const int NU = -12; /* null */ const int DE = -13; /* double detected by exponent e E */ const int DF = -14; /* double detected by fraction . */ const int SB = -15; /* string begin */ const int MX = -16; /* integer detected by minus */ const int ZX = -17; /* integer detected by zero */ const int IX = -18; /* integer detected by 1-9 */ const int EX = -19; /* next char is escaped */ const int UC = -20; /* Unicode character read */ const int SE = -4; /* string end */ const int AB = -5; /* array begin */ const int AE = -7; /* array end */ const int OS = -6; /* object start */ const int OE = -8; /* object end */ const int EO = -9; /* empty object */ const int CM = -3; /* comma */ const int CA = -2; /* colon action */ const int PX = -21; /* integer detected by plus */ const int KB = -22; /* unquoted key name begin */ const int UE = -23; /* unquoted key name end */ const int IF = -25; /* Infinity */ const int NN = -26; /* NaN */ enum JsonMode { NONE, ARRAY, DONE, KEY, OBJECT }; enum JsonType { NONE = 0, ARRAY_BEGIN, ARRAY_END, OBJECT_BEGIN, OBJECT_END, INTEGER, FLOAT, NULL, TRUE, FALSE, STRING, KEY, MAX }; /* This array maps the 128 ASCII characters into character classes. The remaining Unicode characters should be mapped to C_ETC. Non-whitespace control characters are errors. */ static readonly int[] ascii_class = { __, __, __, __, __, __, __, __, __, C_WHITE, C_WHITE, __, __, C_WHITE, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, C_SPACE, C_ETC, C_QUOTE, C_ETC, C_ETC, C_ETC, C_ETC, C_QUOTE, C_ETC, C_ETC, C_STAR, C_PLUS, C_COMMA, C_MINUS, C_POINT, C_SLASH, C_ZERO, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_COLON, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ABCDF, C_ABCDF, C_ABCDF, C_ABCDF, C_E, C_ABCDF, C_ETC, C_ETC, C_I, C_ETC, C_ETC, C_ETC, C_ETC, C_N, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_ETC, C_LSQRB, C_BACKS, C_RSQRB, C_ETC, C_ETC, C_ETC, C_LOW_A, C_LOW_B, C_LOW_C, C_LOW_D, C_LOW_E, C_LOW_F, C_ETC, C_ETC, C_LOW_I, C_ETC, C_ETC, C_LOW_L, C_ETC, C_LOW_N, C_ETC, C_ETC, C_ETC, C_LOW_R, C_LOW_S, C_LOW_T, C_LOW_U, C_ETC, C_ETC, C_ETC, C_LOW_Y, C_ETC, C_LCURB, C_ETC, C_RCURB, C_ETC, C_ETC }; static readonly int[,] state_transition_table = { /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. An action is represented as a negative number. A JSON text is accepted if at the end of the text the state is OK and if the mode is MODE_DONE. white ' 1-9 ABCDF etc space | { } [ ] : , " \ / + - . 0 | a b c d e f l n r s t u | E | * I i y N */ /*start GO*/ {GO,GO,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,__,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*ok OK*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*object OB*/ {OB,OB,__,EO,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*key KE*/ {KE,KE,__,__,__,__,__,__,SB,__,__,__,KB,__,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,KB,__,KB,KB,KB,KB}, /*colon CO*/ {CO,CO,__,__,__,__,CA,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*value VA*/ {VA,VA,OS,__,AB,__,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*array AR*/ {AR,AR,OS,__,AB,AE,__,__,SB,__,__,PX,MX,__,ZX,IX,__,__,__,__,__,FA,__,NU,__,__,TR,__,__,__,__,__,I1,__,__,V1}, /*string ST*/ {ST,__,ST,ST,ST,ST,ST,ST,SE,EX,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST,ST}, /*escape ES*/ {__,__,__,__,__,__,__,__,ST,ST,ST,__,__,__,__,__,__,ST,__,__,__,ST,__,ST,ST,__,ST,U1,__,__,__,__,__,__,__,__}, /*u1 U1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U2,U2,U2,U2,U2,U2,U2,U2,__,__,__,__,__,__,U2,U2,__,__,__,__,__,__}, /*u2 U2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U3,U3,U3,U3,U3,U3,U3,U3,__,__,__,__,__,__,U3,U3,__,__,__,__,__,__}, /*u3 U3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,U4,U4,U4,U4,U4,U4,U4,U4,__,__,__,__,__,__,U4,U4,__,__,__,__,__,__}, /*u4 U4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,UC,UC,UC,UC,UC,UC,UC,UC,__,__,__,__,__,__,UC,UC,__,__,__,__,__,__}, /*minus MI*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,ZE,IN,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I1,__,__,__}, /*zero ZE*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*int IN*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,DF,IN,IN,__,__,__,__,DE,__,__,__,__,__,__,__,__,DE,__,__,__,__,__,__}, /*frac FR*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*e E1*/ {__,__,__,__,__,__,__,__,__,__,__,E2,E2,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*ex E2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*exp E3*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,E3,E3,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*tr T1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T2,__,__,__,__,__,__,__,__,__,__,__}, /*tru T2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,T3,__,__,__,__,__,__,__,__}, /*true T3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fa F1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fal F2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*fals F3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,F4,__,__,__,__,__,__,__,__,__,__}, /*false F4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*nu N1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N2,__,__,__,__,__,__,__,__}, /*nul N2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,N3,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*null N3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,OK,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*_. FX*/ {OK,OK,__,OE,__,AE,__,CM,__,__,__,__,__,__,FR,FR,__,__,__,__,E1,__,__,__,__,__,__,__,__,E1,__,__,__,__,__,__}, /*inval. IV*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*unq.key UK*/ {UI,UI,__,__,__,__,UE,__,__,__,__,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,UK,__,UK,UK,UK,UK}, /*unq.ign. UI*/ {UI,UI,__,__,__,__,UE,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i1 I1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I2,__,__,__,__,__,__,__,__,__,__,__,__}, /*i2 I2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I3,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*i3 I3*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I4,__,__}, /*i4 I4*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I5,__,__,__,__,__,__,__,__,__,__,__,__}, /*i5 I5*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I6,__,__}, /*i6 I6*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,I7,__,__,__,__,__,__,__,__,__}, /*i7 I7*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,IF,__}, /*v1 V1*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,V2,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__}, /*v2 V2*/ {__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,NN}, }; JavaScriptSerializer serializer; JavaScriptTypeResolver typeResolver; int maxJsonLength; int currentPosition; int recursionLimit; int recursionDepth; Stack <JsonMode> modes; Stack <object> returnValue; JsonType jsonType; bool escaped; int state; Stack <string> currentKey; StringBuilder buffer; char quoteChar; public JsonDeserializer (JavaScriptSerializer serializer) { this.serializer = serializer; this.maxJsonLength = serializer.MaxJsonLength; this.recursionLimit = serializer.RecursionLimit; this.typeResolver = serializer.TypeResolver; this.modes = new Stack <JsonMode> (); this.currentKey = new Stack <string> (); this.returnValue = new Stack <object> (); this.state = GO; this.currentPosition = 0; this.recursionDepth = 0; } public object Deserialize (string input) { if (input == null) throw new ArgumentNullException ("input"); return Deserialize (new StringReader (input)); } public object Deserialize (TextReader input) { if (input == null) throw new ArgumentNullException ("input"); int value; buffer = new StringBuilder (); while (true) { value = input.Read (); if (value < 0) break; currentPosition++; if (currentPosition > maxJsonLength) throw new ArgumentException ("Maximum JSON input length has been exceeded."); if (!ProcessCharacter ((char) value)) throw new InvalidOperationException ("JSON syntax error."); } object topObject = PeekObject (); if (buffer.Length > 0) { object result; if (ParseBuffer (out result)) { if (topObject != null) StoreValue (result); else PushObject (result); } } if (returnValue.Count > 1) throw new InvalidOperationException ("JSON syntax error."); object ret = PopObject (); return ret; } #if DEBUG void DumpObject (string indent, object obj) { if (obj is Dictionary <string, object>) { Console.WriteLine (indent + "{"); foreach (KeyValuePair <string, object> kvp in (Dictionary <string, object>)obj) { Console.WriteLine (indent + "\t\"{0}\": ", kvp.Key); DumpObject (indent + "\t\t", kvp.Value); } Console.WriteLine (indent + "}"); } else if (obj is object[]) { Console.WriteLine (indent + "["); foreach (object o in (object[])obj) DumpObject (indent + "\t", o); Console.WriteLine (indent + "]"); } else if (obj != null) Console.WriteLine (indent + obj.ToString ()); else Console.WriteLine ("null"); } #endif void DecodeUnicodeChar () { int len = buffer.Length; if (len < 6) throw new ArgumentException ("Invalid escaped unicode character specification (" + currentPosition + ")"); int code = Int32.Parse (buffer.ToString ().Substring (len - 4), NumberStyles.HexNumber); buffer.Length = len - 6; buffer.Append ((char)code); } string GetModeMessage (JsonMode expectedMode) { switch (expectedMode) { case JsonMode.ARRAY: return "Invalid array passed in, ',' or ']' expected (" + currentPosition + ")"; case JsonMode.KEY: return "Invalid object passed in, key name or ':' expected (" + currentPosition + ")"; case JsonMode.OBJECT: return "Invalid object passed in, key value expected (" + currentPosition + ")"; default: return "Invalid JSON string"; } } void PopMode (JsonMode expectedMode) { JsonMode mode = PeekMode (); if (mode != expectedMode) throw new ArgumentException (GetModeMessage (mode)); modes.Pop (); } void PushMode (JsonMode newMode) { modes.Push (newMode); } JsonMode PeekMode () { if (modes.Count == 0) return JsonMode.NONE; return modes.Peek (); } void PushObject (object o) { returnValue.Push (o); } object PopObject (bool notIfLast) { int count = returnValue.Count; if (count == 0) return null; if (notIfLast && count == 1) return null; return returnValue.Pop (); } object PopObject () { return PopObject (false); } object PeekObject () { if (returnValue.Count == 0) return null; return returnValue.Peek (); } void RemoveLastCharFromBuffer () { int len = buffer.Length; if (len == 0) return; buffer.Length = len - 1; } bool ParseBuffer (out object result) { result = null; if (jsonType == JsonType.NONE) { buffer.Length = 0; return false; } string s = buffer.ToString (); bool converted = true; int intValue; long longValue; decimal decimalValue; double doubleValue; switch (jsonType) { case JsonType.INTEGER: /* MS AJAX.NET JSON parser promotes big integers to double */ if (Int32.TryParse (s, out intValue)) result = intValue; else if (Int64.TryParse (s, out longValue)) result = longValue; else if (Decimal.TryParse (s, out decimalValue)) result = decimalValue; else if (Double.TryParse (s, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.FLOAT: if (Decimal.TryParse (s, out decimalValue)) result = decimalValue; else if (Double.TryParse (s, out doubleValue)) result = doubleValue; else converted = false; break; case JsonType.TRUE: if (String.Compare (s, "true", StringComparison.Ordinal) == 0) result = true; else converted = false; break; case JsonType.FALSE: if (String.Compare (s, "false", StringComparison.Ordinal) == 0) result = false; else converted = false; break; case JsonType.NULL: if (String.Compare (s, "null", StringComparison.Ordinal) != 0) converted = false; break; case JsonType.STRING: if (s.StartsWith ("/Date(", StringComparison.Ordinal) && s.EndsWith (")/", StringComparison.Ordinal)) { long javaScriptTicks = Convert.ToInt64 (s.Substring (6, s.Length - 8)); result = new DateTime ((javaScriptTicks * 10000) + JsonSerializer.InitialJavaScriptDateTicks, DateTimeKind.Utc); } else result = s; break; default: throw new InvalidOperationException (String.Format ("Internal error: unexpected JsonType ({0})", jsonType)); } if (!converted) throw new ArgumentException ("Invalid JSON primitive: " + s); buffer.Length = 0; return true; } bool ProcessCharacter (char ch) { int next_class, next_state; if (ch >= 128) next_class = C_ETC; else { next_class = ascii_class [ch]; if (next_class <= UNIVERSAL_ERROR) return false; } if (escaped) { escaped = false; RemoveLastCharFromBuffer (); switch (ch) { case 'b': buffer.Append ('\b'); break; case 'f': buffer.Append ('\f'); break; case 'n': buffer.Append ('\n'); break; case 'r': buffer.Append ('\r'); break; case 't': buffer.Append ('\t'); break; case '"': case '\\': case '/': buffer.Append (ch); break; case 'u': buffer.Append ("\\u"); break; default: return false; } } else if (jsonType != JsonType.NONE || !(next_class == C_SPACE || next_class == C_WHITE)) buffer.Append (ch); next_state = state_transition_table [state, next_class]; if (next_state >= 0) { state = next_state; return true; } object result; /* An action to perform */ switch (next_state) { case UC: /* Unicode character */ DecodeUnicodeChar (); state = ST; break; case EX: /* Escaped character */ escaped = true; state = ES; break; case MX: /* integer detected by minus */ jsonType = JsonType.INTEGER; state = MI; break; case PX: /* integer detected by plus */ jsonType = JsonType.INTEGER; state = MI; break; case ZX: /* integer detected by zero */ jsonType = JsonType.INTEGER; state = ZE; break; case IX: /* integer detected by 1-9 */ jsonType = JsonType.INTEGER; state = IN; break; case DE: /* floating point number detected by exponent*/ jsonType = JsonType.FLOAT; state = E1; break; case DF: /* floating point number detected by fraction */ jsonType = JsonType.FLOAT; state = FX; break; case SB: /* string begin " or ' */ buffer.Length = 0; quoteChar = ch; jsonType = JsonType.STRING; state = ST; break; case KB: /* unquoted key name begin */ jsonType = JsonType.STRING; state = UK; break; case UE: /* unquoted key name end ':' */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; buffer.Length = 0; break; case NU: /* n */ jsonType = JsonType.NULL; state = N1; break; case FA: /* f */ jsonType = JsonType.FALSE; state = F1; break; case TR: /* t */ jsonType = JsonType.TRUE; state = T1; break; case EO: /* empty } */ result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.KEY); state = OK; break; case OE: /* } */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); result = PopObject (true); if (result != null) StoreValue (result); PopMode (JsonMode.OBJECT); jsonType = JsonType.NONE; state = OK; break; case AE: /* ] */ RemoveLastCharFromBuffer (); if (ParseBuffer (out result)) StoreValue (result); PopMode (JsonMode.ARRAY); result = PopObject (true); if (result != null) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case OS: /* { */ RemoveLastCharFromBuffer (); CreateObject (); PushMode (JsonMode.KEY); state = OB; break; case AB: /* [ */ RemoveLastCharFromBuffer (); CreateArray (); PushMode (JsonMode.ARRAY); state = AR; break; case SE: /* string end " or ' */ if (ch == quoteChar) { RemoveLastCharFromBuffer (); switch (PeekMode ()) { case JsonMode.KEY: if (ParseBuffer (out result)) StoreKey (result); jsonType = JsonType.NONE; state = CO; buffer.Length = 0; break; case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone string */ jsonType = JsonType.STRING; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: string in unexpected place."); } } break; case CM: /* , */ RemoveLastCharFromBuffer (); // With MS.AJAX, a comma resets the recursion depth recursionDepth = 0; bool doStore = ParseBuffer (out result); switch (PeekMode ()) { case JsonMode.OBJECT: if (doStore) StoreValue (result); PopMode (JsonMode.OBJECT); PushMode (JsonMode.KEY); jsonType = JsonType.NONE; state = KE; break; case JsonMode.ARRAY: jsonType = JsonType.NONE; state = VA; if (doStore) StoreValue (result); break; default: throw new ArgumentException ("Syntax error: unexpected comma."); } break; case CA: /* : */ RemoveLastCharFromBuffer (); // With MS.AJAX a colon increases recursion depth if (++recursionDepth >= recursionLimit) throw new ArgumentException ("Recursion limit has been reached on parsing input."); PopMode (JsonMode.KEY); PushMode (JsonMode.OBJECT); state = VA; break; case IF: /* Infinity */ case NN: /* NaN */ jsonType = JsonType.FLOAT; switch (PeekMode ()) { case JsonMode.ARRAY: case JsonMode.OBJECT: if (ParseBuffer (out result)) StoreValue (result); jsonType = JsonType.NONE; state = OK; break; case JsonMode.NONE: /* A stand-alone NaN/Infinity */ jsonType = JsonType.FLOAT; state = IV; /* the rest of input is invalid */ if (ParseBuffer (out result)) PushObject (result); break; default: throw new ArgumentException ("Syntax error: misplaced NaN/Infinity."); } buffer.Length = 0; break; default: throw new ArgumentException (GetModeMessage (PeekMode ())); } return true; } void CreateArray () { var arr = new ArrayList (); PushObject (arr); } void CreateObject () { var dict = new Dictionary <string, object> (); PushObject (dict); } void StoreKey (object o) { string key = o as string; if (key != null) key = key.Trim (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: key is null, empty or not a string."); currentKey.Push (key); Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary."); /* MS AJAX.NET silently overwrites existing currentKey value */ dict [key] = null; } void StoreValue (object o) { Dictionary <string, object> dict = PeekObject () as Dictionary <string, object>; if (dict == null) { ArrayList arr = PeekObject () as ArrayList; if (arr == null) throw new InvalidOperationException ("Internal error: current object is not a dictionary or an array."); arr.Add (o); return; } string key; if (currentKey.Count == 0) key = null; else key = currentKey.Pop (); if (String.IsNullOrEmpty (key)) throw new InvalidOperationException ("Internal error: object is a dictionary, but no key present."); dict [key] = o; } } }
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; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmStockBreakList { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockBreakList() : base() { FormClosed += frmStockBreakList_FormClosed; KeyPress += frmStockBreakList_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdNew; public System.Windows.Forms.Button cmdNew { get { return withEventsField_cmdNew; } set { if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click -= cmdNew_Click; } withEventsField_cmdNew = value; if (withEventsField_cmdNew != null) { withEventsField_cmdNew.Click += cmdNew_Click; } } } private myDataGridView withEventsField_DataList1; public myDataGridView DataList1 { get { return withEventsField_DataList1; } set { if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick -= DataList1_DblClick; withEventsField_DataList1.KeyPress -= DataList1_KeyPress; } withEventsField_DataList1 = value; if (withEventsField_DataList1 != null) { withEventsField_DataList1.DoubleClick += DataList1_DblClick; withEventsField_DataList1.KeyPress += DataList1_KeyPress; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter -= txtSearch_Enter; withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.Enter += txtSearch_Enter; withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Label lbl; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockBreakList)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.cmdNew = new System.Windows.Forms.Button(); this.DataList1 = new myDataGridView(); this.txtSearch = new System.Windows.Forms.TextBox(); this.cmdExit = new System.Windows.Forms.Button(); this.lbl = new System.Windows.Forms.Label(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataList1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Select a Stock Conversion Item"; this.ClientSize = new System.Drawing.Size(576, 433); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockBreakList"; this.cmdNew.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdNew.Text = "&New"; this.cmdNew.Size = new System.Drawing.Size(97, 52); this.cmdNew.Location = new System.Drawing.Point(6, 375); this.cmdNew.TabIndex = 4; this.cmdNew.TabStop = false; this.cmdNew.BackColor = System.Drawing.SystemColors.Control; this.cmdNew.CausesValidation = true; this.cmdNew.Enabled = true; this.cmdNew.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdNew.Cursor = System.Windows.Forms.Cursors.Default; this.cmdNew.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdNew.Name = "cmdNew"; //'DataList1.OcxState = CType(resources.GetObject("'DataList1.OcxState"), System.Windows.Forms.AxHost.State) this.DataList1.Size = new System.Drawing.Size(559, 342); this.DataList1.Location = new System.Drawing.Point(6, 27); this.DataList1.TabIndex = 2; this.DataList1.Name = "DataList1"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(514, 19); this.txtSearch.Location = new System.Drawing.Point(51, 3); this.txtSearch.TabIndex = 1; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(468, 375); this.cmdExit.TabIndex = 3; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lbl.TextAlign = System.Drawing.ContentAlignment.TopRight; this.lbl.Text = "&Search :"; this.lbl.Size = new System.Drawing.Size(40, 13); this.lbl.Location = new System.Drawing.Point(8, 6); this.lbl.TabIndex = 0; this.lbl.BackColor = System.Drawing.Color.Transparent; this.lbl.Enabled = true; this.lbl.ForeColor = System.Drawing.SystemColors.ControlText; this.lbl.Cursor = System.Windows.Forms.Cursors.Default; this.lbl.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lbl.UseMnemonic = true; this.lbl.Visible = true; this.lbl.AutoSize = true; this.lbl.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lbl.Name = "lbl"; this.Controls.Add(cmdNew); this.Controls.Add(DataList1); this.Controls.Add(txtSearch); this.Controls.Add(cmdExit); this.Controls.Add(lbl); ((System.ComponentModel.ISupportInitialize)this.DataList1).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #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.Runtime.CompilerServices; namespace System.Runtime.Intrinsics.Arm { /// <summary> /// This class provides access to the ARM AdvSIMD hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class AdvSimd : ArmBase { internal AdvSimd() { } public static new bool IsSupported { [Intrinsic] get { return false; } } public new abstract class Arm64 : ArmBase.Arm64 { internal Arm64() { } public static new bool IsSupported { [Intrinsic] get { return false; } } /// <summary> /// float64x2_t vabsq_f64 (float64x2_t a) /// A64: FABS Vd.2D, Vn.2D /// </summary> public static Vector128<double> Abs(Vector128<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int64x2_t vabsq_s64 (int64x2_t a) /// A64: ABS Vd.2D, Vn.2D /// </summary> public static Vector128<ulong> Abs(Vector128<long> value) { throw new PlatformNotSupportedException(); } // /// <summary> // /// int64x1_t vabs_s64 (int64x1_t a) // /// A64: ABS Dd, Dn // /// </summary> // public static Vector64<ulong> AbsScalar(Vector64<long> value) { throw new PlatformNotSupportedException(); } /// <summary> /// float64x2_t vaddq_f64 (float64x2_t a, float64x2_t b) /// A64: FADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } } /// <summary> /// int8x8_t vabs_s8 (int8x8_t a) /// A32: VABS.S8 Dd, Dm /// A64: ABS Vd.8B, Vn.8B /// </summary> public static Vector64<byte> Abs(Vector64<sbyte> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x4_t vabs_s16 (int16x4_t a) /// A32: VABS.S16 Dd, Dm /// A64: ABS Vd.4H, Vn.4H /// </summary> public static Vector64<ushort> Abs(Vector64<short> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x2_t vabs_s32 (int32x2_t a) /// A32: VABS.S32 Dd, Dm /// A64: ABS Vd.2S, Vn.2S /// </summary> public static Vector64<uint> Abs(Vector64<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x2_t vabs_f32 (float32x2_t a) /// A32: VABS.F32 Dd, Dm /// A64: FABS Vd.2S, Vn.2S /// </summary> public static Vector64<float> Abs(Vector64<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int8x16_t vabsq_s8 (int8x16_t a) /// A32: VABS.S8 Qd, Qm /// A64: ABS Vd.16B, Vn.16B /// </summary> public static Vector128<byte> Abs(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x8_t vabsq_s16 (int16x8_t a) /// A32: VABS.S16 Qd, Qm /// A64: ABS Vd.8H, Vn.8H /// </summary> public static Vector128<ushort> Abs(Vector128<short> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x4_t vabsq_s32 (int32x4_t a) /// A32: VABS.S32 Qd, Qm /// A64: ABS Vd.4S, Vn.4S /// </summary> public static Vector128<uint> Abs(Vector128<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x4_t vabsq_f32 (float32x4_t a) /// A32: VABS.F32 Qd, Qm /// A64: FABS Vd.4S, Vn.4S /// </summary> public static Vector128<float> Abs(Vector128<float> value) { throw new PlatformNotSupportedException(); } // /// <summary> // /// float64x1_t vabs_f64 (float64x1_t a) // /// A32: VABS.F64 Dd, Dm // /// A64: FABS Dd, Dn // /// </summary> // public static Vector64<double> AbsScalar(Vector64<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// A32: VABS.F32 Sd, Sm /// A64: FABS Sd, Sn /// </summary> public static Vector64<float> AbsScalar(Vector64<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// uint8x8_t vadd_u8 (uint8x8_t a, uint8x8_t b) /// A32: VADD.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<byte> Add(Vector64<byte> left, Vector64<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x4_t vadd_s16 (int16x4_t a, int16x4_t b) /// A32: VADD.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<short> Add(Vector64<short> left, Vector64<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x2_t vadd_s32 (int32x2_t a, int32x2_t b) /// A32: VADD.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<int> Add(Vector64<int> left, Vector64<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int8x8_t vadd_s8 (int8x8_t a, int8x8_t b) /// A32: VADD.I8 Dd, Dn, Dm /// A64: ADD Vd.8B, Vn.8B, Vm.8B /// </summary> public static Vector64<sbyte> Add(Vector64<sbyte> left, Vector64<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x2_t vadd_f32 (float32x2_t a, float32x2_t b) /// A32: VADD.F32 Dd, Dn, Dm /// A64: FADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<float> Add(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint16x4_t vadd_u16 (uint16x4_t a, uint16x4_t b) /// A32: VADD.I16 Dd, Dn, Dm /// A64: ADD Vd.4H, Vn.4H, Vm.4H /// </summary> public static Vector64<ushort> Add(Vector64<ushort> left, Vector64<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint32x2_t vadd_u32 (uint32x2_t a, uint32x2_t b) /// A32: VADD.I32 Dd, Dn, Dm /// A64: ADD Vd.2S, Vn.2S, Vm.2S /// </summary> public static Vector64<uint> Add(Vector64<uint> left, Vector64<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint8x16_t vaddq_u8 (uint8x16_t a, uint8x16_t b) /// A32: VADD.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x8_t vaddq_s16 (int16x8_t a, int16x8_t b) /// A32: VADD.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x4_t vaddq_s32 (int32x4_t a, int32x4_t b) /// A32: VADD.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int64x2_t vaddq_s64 (int64x2_t a, int64x2_t b) /// A32: VADD.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<long> Add(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int8x16_t vaddq_s8 (int8x16_t a, int8x16_t b) /// A32: VADD.I8 Qd, Qn, Qm /// A64: ADD Vd.16B, Vn.16B, Vm.16B /// </summary> public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x4_t vaddq_f32 (float32x4_t a, float32x4_t b) /// A32: VADD.F32 Qd, Qn, Qm /// A64: FADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint16x8_t vaddq_u16 (uint16x8_t a, uint16x8_t b) /// A32: VADD.I16 Qd, Qn, Qm /// A64: ADD Vd.8H, Vn.8H, Vm.8H /// </summary> public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint32x4_t vaddq_u32 (uint32x4_t a, uint32x4_t b) /// A32: VADD.I32 Qd, Qn, Qm /// A64: ADD Vd.4S, Vn.4S, Vm.4S /// </summary> public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint64x2_t vaddq_u64 (uint64x2_t a, uint64x2_t b) /// A32: VADD.I64 Qd, Qn, Qm /// A64: ADD Vd.2D, Vn.2D, Vm.2D /// </summary> public static Vector128<ulong> Add(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); } // /// <summary> // /// float64x1_t vadd_f64 (float64x1_t a, float64x1_t b) // /// A32: VADD.F64 Dd, Dn, Dm // /// A64: FADD Dd, Dn, Dm // /// </summary> // public static Vector64<double> AddScalar(Vector64<double> left, Vector64<double> right) { throw new PlatformNotSupportedException(); } // /// <summary> // /// int64x1_t vadd_s64 (int64x1_t a, int64x1_t b) // /// A32: VADD.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<long> AddScalar(Vector64<long> left, Vector64<long> right) { throw new PlatformNotSupportedException(); } // /// <summary> // /// uint64x1_t vadd_u64 (uint64x1_t a, uint64x1_t b) // /// A32: VADD.I64 Dd, Dn, Dm // /// A64: ADD Dd, Dn, Dm // /// </summary> // public static Vector64<ulong> AddScalar(Vector64<ulong> left, Vector64<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// A32: VADD.F32 Sd, Sn, Sm /// A64: /// </summary> public static Vector64<float> AddScalar(Vector64<float> left, Vector64<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// uint8x8_t vld1_u8 (uint8_t const * ptr) /// A32: VLD1.8 Dd, [Rn] /// A64: LD1 Vt.8B, [Xn] /// </summary> public static unsafe Vector64<byte> LoadVector64(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x4_t vld1_s16 (int16_t const * ptr) /// A32: VLD1.16 Dd, [Rn] /// A64: LD1 Vt.4H, [Xn] /// </summary> public static unsafe Vector64<short> LoadVector64(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x2_t vld1_s32 (int32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<int> LoadVector64(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int8x8_t vld1_s8 (int8_t const * ptr) /// A32: VLD1.8 Dd, [Rn] /// A64: LD1 Vt.8B, [Xn] /// </summary> public static unsafe Vector64<sbyte> LoadVector64(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x2_t vld1_f32 (float32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<float> LoadVector64(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint16x4_t vld1_u16 (uint16_t const * ptr) /// A32: VLD1.16 Dd, [Rn] /// A64: LD1 Vt.4H, [Xn] /// </summary> public static unsafe Vector64<ushort> LoadVector64(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint32x2_t vld1_u32 (uint32_t const * ptr) /// A32: VLD1.32 Dd, [Rn] /// A64: LD1 Vt.2S, [Xn] /// </summary> public static unsafe Vector64<uint> LoadVector64(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint8x16_t vld1q_u8 (uint8_t const * ptr) /// A32: VLD1.8 Dd, Dd+1, [Rn] /// A64: LD1 Vt.16B, [Xn] /// </summary> public static unsafe Vector128<byte> LoadVector128(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// float64x2_t vld1q_f64 (float64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<double> LoadVector128(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int16x8_t vld1q_s16 (int16_t const * ptr) /// A32: VLD1.16 Dd, Dd+1, [Rn] /// A64: LD1 Vt.8H, [Xn] /// </summary> public static unsafe Vector128<short> LoadVector128(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int32x4_t vld1q_s32 (int32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<int> LoadVector128(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int64x2_t vld1q_s64 (int64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<long> LoadVector128(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// int8x16_t vld1q_s8 (int8_t const * ptr) /// A32: VLD1.8 Dd, Dd+1, [Rn] /// A64: LD1 Vt.16B, [Xn] /// </summary> public static unsafe Vector128<sbyte> LoadVector128(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// float32x4_t vld1q_f32 (float32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<float> LoadVector128(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint16x8_t vld1q_s16 (uint16_t const * ptr) /// A32: VLD1.16 Dd, Dd+1, [Rn] /// A64: LD1 Vt.8H, [Xn] /// </summary> public static unsafe Vector128<ushort> LoadVector128(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint32x4_t vld1q_s32 (uint32_t const * ptr) /// A32: VLD1.32 Dd, Dd+1, [Rn] /// A64: LD1 Vt.4S, [Xn] /// </summary> public static unsafe Vector128<uint> LoadVector128(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// uint64x2_t vld1q_u64 (uint64_t const * ptr) /// A32: VLD1.64 Dd, Dd+1, [Rn] /// A64: LD1 Vt.2D, [Xn] /// </summary> public static unsafe Vector128<ulong> LoadVector128(ulong* address) { throw new PlatformNotSupportedException(); } } }
//#define DEBUG //#define RETX_DEBUG //#define memD using System; using System.Collections.Generic; using System.Collections; using System.Text; namespace ICSimulator { public abstract class Router_Flit : Router { // injectSlot is from Node; injectSlot2 is higher-priority from // network-level re-injection (e.g., placeholder schemes) protected Flit m_injectSlot, m_injectSlot2; Queue<Flit> [] ejectBuffer; public Router_Flit(Coord myCoord) : base(myCoord) { m_injectSlot = null; m_injectSlot2 = null; ejectBuffer = new Queue<Flit>[4]; for (int n = 0; n < 4; n++) ejectBuffer[n] = new Queue<Flit>(); } Flit handleGolden(Flit f) { if (f == null) return f; if (f.state == Flit.State.Normal) return f; if (f.state == Flit.State.Rescuer) { if (m_injectSlot == null) { m_injectSlot = f; f.state = Flit.State.Placeholder; } else m_injectSlot.state = Flit.State.Carrier; return null; } if (f.state == Flit.State.Carrier) { f.state = Flit.State.Normal; Flit newPlaceholder = new Flit(null, 0); newPlaceholder.state = Flit.State.Placeholder; if (m_injectSlot != null) m_injectSlot2 = newPlaceholder; else m_injectSlot = newPlaceholder; return f; } if (f.state == Flit.State.Placeholder) throw new Exception("Placeholder should never be ejected!"); return null; } // accept one ejected flit into rxbuf protected void acceptFlit(Flit f) { statsEjectFlit(f); if (f.packet.nrOfArrivedFlits + 1 == f.packet.nrOfFlits) statsEjectPacket(f.packet); m_n.receiveFlit(f); } Flit ejectLocal() { // eject locally-destined flit (highest-ranked, if multiple) Flit ret = null; int bestDir = -1; for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.state != Flit.State.Placeholder && linkIn[dir].Out.dest.ID == ID && (ret == null || rank(linkIn[dir].Out, ret) < 0)) { ret = linkIn[dir].Out; bestDir = dir; } if (bestDir != -1) linkIn[bestDir].Out = null; #if DEBUG if (ret != null) Console.WriteLine("ejecting flit {0}.{1} at node {2} cyc {3}", ret.packet.ID, ret.flitNr, coord, Simulator.CurrentRound); #endif ret = handleGolden(ret); return ret; } Flit[] input = new Flit[4]; // keep this as a member var so we don't // have to allocate on every step (why can't // we have arrays on the stack like in C?) protected override void _doStep() { if (Config.EjectBufferSize != -1) { for (int dir =0; dir < 4; dir ++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.packet.dest.ID == ID && ejectBuffer[dir].Count < Config.EjectBufferSize) { ejectBuffer[dir].Enqueue(linkIn[dir].Out); linkIn[dir].Out = null; } int bestdir = -1; for (int dir = 0; dir < 4; dir ++) if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Peek().injectionTime < ejectBuffer[bestdir].Peek().injectionTime)) // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || ejectBuffer[dir].Count > ejectBuffer[bestdir].Count)) // if (ejectBuffer[dir].Count > 0 && (bestdir == -1 || Simulator.rand.Next(2) == 1)) bestdir = dir; if (bestdir != -1) acceptFlit(ejectBuffer[bestdir].Dequeue()); } else { int flitsTryToEject = 0; for (int dir = 0; dir < 4; dir ++) if (linkIn[dir] != null && linkIn[dir].Out != null && linkIn[dir].Out.dest.ID == ID) { flitsTryToEject ++; if (linkIn[dir].Out.ejectTrial == 0) linkIn[dir].Out.firstEjectTrial = Simulator.CurrentRound; linkIn[dir].Out.ejectTrial ++; } Simulator.stats.flitsTryToEject[flitsTryToEject].Add(); Flit f1 = null,f2 = null; for (int i = 0; i < Config.meshEjectTrial; i++) { Flit eject = ejectLocal(); if (i == 0) f1 = eject; else if (i == 1) f2 = eject; if (eject != null) acceptFlit(eject); } if (f1 != null && f2 != null && f1.packet == f2.packet) Simulator.stats.ejectsFromSamePacket.Add(1); else if (f1 != null && f2 != null) Simulator.stats.ejectsFromSamePacket.Add(0); } for (int i = 0; i < 4; i++) input[i] = null; // grab inputs into a local array so we can sort int c = 0; for (int dir = 0; dir < 4; dir++) if (linkIn[dir] != null && linkIn[dir].Out != null) { input[c++] = linkIn[dir].Out; linkIn[dir].Out.inDir = dir; linkIn[dir].Out = null; } // sometimes network-meddling such as flit-injection can put unexpected // things in outlinks... int outCount = 0; for (int dir = 0; dir < 4; dir++) if (linkOut[dir] != null && linkOut[dir].In != null) outCount++; bool wantToInject = m_injectSlot2 != null || m_injectSlot != null; bool canInject = (c + outCount) < neighbors; bool starved = wantToInject && !canInject; if (starved) { Flit starvedFlit = null; if (starvedFlit == null) starvedFlit = m_injectSlot2; if (starvedFlit == null) starvedFlit = m_injectSlot; Simulator.controller.reportStarve(coord.ID); statsStarve(starvedFlit); } if (canInject && wantToInject) { Flit inj_peek=null; if(m_injectSlot2!=null) inj_peek=m_injectSlot2; else if (m_injectSlot!=null) inj_peek=m_injectSlot; if(inj_peek==null) throw new Exception("Inj flit peek is null!!"); if(!Simulator.controller.ThrottleAtRouter || Simulator.controller.tryInject(coord.ID)) { Flit inj = null; if (m_injectSlot2 != null) { inj = m_injectSlot2; m_injectSlot2 = null; } else if (m_injectSlot != null) { inj = m_injectSlot; m_injectSlot = null; } else throw new Exception("what???inject null flits??"); input[c++] = inj; #if DEBUG Console.WriteLine("injecting flit {0}.{1} at node {2} cyc {3}", m_injectSlot.packet.ID, m_injectSlot.flitNr, coord, Simulator.CurrentRound); #endif #if memD int r=inj.packet.requesterID; if(r==coord.ID) Console.WriteLine("inject flit at node {0}<>request:{1}",coord.ID,r); else Console.WriteLine("Diff***inject flit at node {0}<>request:{1}",coord.ID,r); #endif statsInjectFlit(inj); } } // inline bubble sort is faster for this size than Array.Sort() // sort input[] by descending priority. rank(a,b) < 0 iff a has higher priority. for (int i = 0; i < 4; i++) for (int j = i + 1; j < 4; j++) if (input[j] != null && (input[i] == null || rank(input[j], input[i]) < 0)) { Flit t = input[i]; input[i] = input[j]; input[j] = t; } // assign outputs for (int i = 0; i < 4 && input[i] != null; i++) { PreferredDirection pd = determineDirection(input[i], coord); int outDir = -1; bool deflect = false; if (Config.RandOrderRouting) { int dimensionOrder = Simulator.rand.Next(2); //0: x over y 1:y over x if (dimensionOrder == 0) { if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null) { linkOut[pd.xDir].In = input[i]; outDir = pd.xDir; } else if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null) { linkOut[pd.yDir].In = input[i]; outDir = pd.yDir; } else deflect = true; } else //y over x { if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null) { linkOut[pd.yDir].In = input[i]; outDir = pd.yDir; } else if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null) { linkOut[pd.xDir].In = input[i]; outDir = pd.xDir; } else deflect = true; } } else if (Config.DeflectOrderRouting) { if (input[i].routingOrder == false) { if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null) { linkOut[pd.xDir].In = input[i]; linkOut[pd.xDir].In.routingOrder = false; outDir = pd.xDir; } else if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null) { linkOut[pd.yDir].In = input[i]; linkOut[pd.yDir].In.routingOrder = true; outDir = pd.yDir; } else deflect = true; } else //y over x { if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null) { linkOut[pd.yDir].In = input[i]; linkOut[pd.yDir].In.routingOrder = true; outDir = pd.yDir; } else if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null) { linkOut[pd.xDir].In = input[i]; linkOut[pd.xDir].In.routingOrder = false; outDir = pd.xDir; } else deflect = true; } } else //original Router { if (pd.xDir != Simulator.DIR_NONE && linkOut[pd.xDir].In == null) { linkOut[pd.xDir].In = input[i]; outDir = pd.xDir; } else if (pd.yDir != Simulator.DIR_NONE && linkOut[pd.yDir].In == null) { linkOut[pd.yDir].In = input[i]; outDir = pd.yDir; } else deflect = true; } // deflect! if (deflect) { input[i].Deflected = true; int dir = 0; if (Config.randomize_defl) dir = Simulator.rand.Next(4); // randomize deflection dir (so no bias) for (int count = 0; count < 4; count++, dir = (dir + 1) % 4) if (linkOut[dir] != null && linkOut[dir].In == null) { linkOut[dir].In = input[i]; outDir = dir; if (dir == 0 || dir ==2) linkOut[dir].In.routingOrder = false; else linkOut[dir].In.routingOrder = true; break; } if (outDir == -1) throw new Exception( String.Format("Ran out of outlinks in arbitration at node {0} on input {1} cycle {2} flit {3} c {4} neighbors {5} outcount {6}", coord, i, Simulator.CurrentRound, input[i], c, neighbors, outCount)); } } } public override bool canInjectFlit(Flit f) { return m_injectSlot == null; } public override void InjectFlit(Flit f) { if (m_injectSlot != null) throw new Exception("Trying to inject twice in one cycle"); m_injectSlot = f; } public override void flush() { m_injectSlot = null; } protected virtual bool needFlush(Flit f) { return false; } } public class Router_Flit_OldestFirst : Router_Flit { public Router_Flit_OldestFirst(Coord myCoord) : base(myCoord) { } protected override bool needFlush(Flit f) { return Config.cheap_of_cap != -1 && age(f) > (ulong)Config.cheap_of_cap; } public static ulong age(Flit f) { if (Config.net_age_arbitration) return Simulator.CurrentRound - f.packet.injectionTime; else return (Simulator.CurrentRound - f.packet.creationTime) / (ulong)Config.cheap_of; } public static int _rank(Flit f1, Flit f2) { if (f1 == null && f2 == null) return 0; if (f1 == null) return 1; if (f2 == null) return -1; bool f1_resc = (f1.state == Flit.State.Rescuer) || (f1.state == Flit.State.Carrier); bool f2_resc = (f2.state == Flit.State.Rescuer) || (f2.state == Flit.State.Carrier); bool f1_place = (f1.state == Flit.State.Placeholder); bool f2_place = (f2.state == Flit.State.Placeholder); int c0 = 0; if (f1_resc && f2_resc) c0 = 0; else if (f1_resc) c0 = -1; else if (f2_resc) c0 = 1; else if (f1_place && f2_place) c0 = 0; else if (f1_place) c0 = 1; else if (f2_place) c0 = -1; int c1 = 0, c2 = 0; if (f1.packet != null && f2.packet != null) { c1 = -age(f1).CompareTo(age(f2)); c2 = f1.packet.ID.CompareTo(f2.packet.ID); } int c3 = f1.flitNr.CompareTo(f2.flitNr); int zerosSeen = 0; foreach (int i in new int[] { c0, c1, c2, c3 }) { if (i == 0) zerosSeen++; else break; } Simulator.stats.net_decisionLevel.Add(zerosSeen); return (c0 != 0) ? c0 : (c1 != 0) ? c1 : (c2 != 0) ? c2 : c3; } public override int rank(Flit f1, Flit f2) { return _rank(f1, f2); } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } } public class Router_Flit_Prio : Router_Flit { public Router_Flit_Prio(Coord myCoord) : base(myCoord) { } protected override bool needFlush(Flit f) { return Config.cheap_of_cap != -1 && age(f) > (ulong)Config.cheap_of_cap; } public static ulong age(Flit f) { if (Config.net_age_arbitration) return Simulator.CurrentRound - f.packet.injectionTime; else return (Simulator.CurrentRound - f.packet.creationTime) / (ulong)Config.cheap_of; } public static int _rank(Flit f1, Flit f2) { if (f1 == null && f2 == null) return 0; if (f1 == null) return 1; if (f2 == null) return -1; bool f1_resc = (f1.state == Flit.State.Rescuer) || (f1.state == Flit.State.Carrier); bool f2_resc = (f2.state == Flit.State.Rescuer) || (f2.state == Flit.State.Carrier); bool f1_place = (f1.state == Flit.State.Placeholder); bool f2_place = (f2.state == Flit.State.Placeholder); int c0 = 0; if (f1_resc && f2_resc) c0 = 0; else if (f1_resc) c0 = -1; else if (f2_resc) c0 = 1; else if (f1_place && f2_place) c0 = 0; else if (f1_place) c0 = 1; else if (f2_place) c0 = -1; int c1 = 0, c2 = 0; if (f1.packet != null && f2.packet != null) { //TODO: need to change here to take into account of the priority c1 = -age(f1).CompareTo(age(f2)); c2 = f1.packet.ID.CompareTo(f2.packet.ID); } int c3 = f1.flitNr.CompareTo(f2.flitNr); int zerosSeen = 0; foreach (int i in new int[] { c0, c1, c2, c3 }) { if (i == 0) zerosSeen++; else break; } Simulator.stats.net_decisionLevel.Add(zerosSeen); return (c0 != 0) ? c0 : (c1 != 0) ? c1 : (c2 != 0) ? c2 : c3; } public override int rank(Flit f1, Flit f2) { return _rank(f1, f2); } public override void visitFlits(Flit.Visitor fv) { if (m_injectSlot != null) fv(m_injectSlot); if (m_injectSlot2 != null) fv(m_injectSlot2); } } /* Golden Packet is conceptually like this: for mshr in mshrs: for node in nodes: prioritize (node,mshr) request packet over all others, for L cycles where L = X+Y for an XxY network. All non-prioritized packets are arbitrated arbitrarily, if you will (say, round-robin). */ public class Router_Flit_GP : Router_Flit { public Router_Flit_GP(Coord myCoord) : base(myCoord) { } public static int _rank(Flit f1, Flit f2) { // priority is: // 1. Carrier (break ties by dest ID) // 2. Rescuer (break ties by dest ID) // 3. Golden normal flits (break ties by flit no.) // 4. Non-golden normal flits (break ties arbitrarily) // 5. Placeholders if (f1 == null && f2 == null) return 0; if (f1 == null) return 1; if (f2 == null) return -1; if (f1.state == Flit.State.Carrier && f2.state == Flit.State.Carrier) return f1.dest.ID.CompareTo(f2.dest.ID); else if (f1.state == Flit.State.Carrier) return -1; else if (f2.state == Flit.State.Carrier) return 1; if (f1.state == Flit.State.Rescuer && f2.state == Flit.State.Rescuer) return f1.dest.ID.CompareTo(f2.dest.ID); else if (f1.state == Flit.State.Carrier) return -1; else if (f2.state == Flit.State.Carrier) return 1; if (f1.state == Flit.State.Normal && f2.state == Flit.State.Normal) { bool golden1 = Simulator.network.golden.isGolden(f1), golden2 = Simulator.network.golden.isGolden(f2); if (golden1 && golden2) { int g1 = Simulator.network.golden.goldenLevel(f1), g2 = Simulator.network.golden.goldenLevel(f2); if (g1 != g2) return g1.CompareTo(g2); else return f1.flitNr.CompareTo(f2.flitNr); } else if (golden1) return -1; else if (golden2) return 1; else return (Simulator.rand.Next(2) == 1) ? 1 : -1; } else if (f1.state == Flit.State.Normal) return -1; else if (f2.state == Flit.State.Normal) return 1; else // both are placeholders return (Simulator.rand.Next(2) == 1) ? 1 : -1; } public override int rank(Flit f1, Flit f2) { return Router_Flit_GP._rank(f1, f2); } } public class Router_Flit_Random : Router_Flit { public Router_Flit_Random(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Simulator.rand.Next(3) - 1; // one of {-1,0,1} } } public class Router_Flit_Exhaustive : Router_Flit { const int LOCAL = 4; public Router_Flit_Exhaustive(Coord myCoord) : base(myCoord) { } protected override void _doStep() { int index; int bestPermutationProgress = -1; IEnumerable<int> bestPermutation = null; foreach (IEnumerable<int> thisPermutation in PermuteUtils.Permute<int>(new int[] { 0, 1, 2, 3, 4 }, 4)) { index = 0; int thisPermutationProgress = 0; foreach (int direction in thisPermutation) { Flit f = linkIn[index++].Out; if (f == null) continue; if (direction == LOCAL) { if (f.dest.ID == this.ID) thisPermutationProgress++; else goto PermutationDone; // don't allow ejection of non-arrived flits } else if (isDirectionProductive(f.packet.dest, direction)) thisPermutationProgress++; //Console.Write(" " + direction); } if (thisPermutationProgress > bestPermutationProgress) { bestPermutation = thisPermutation; bestPermutationProgress = thisPermutationProgress; } PermutationDone: continue; } index = 0; foreach (int direction in bestPermutation) { Flit f = linkIn[index++].Out; //Console.Write(" {1}->{0}", direction, (f == null ? "null" : f.dest.ID.ToString())); if (direction == LOCAL) this.acceptFlit(f); else { if (f != null && !isDirectionProductive(f.packet.dest, direction)) f.Deflected = true; linkOut[direction].In = f; } } //Console.WriteLine(); //throw new Exception("Done!"); } } public class Router_Flit_Ctlr : Router_Flit { public Router_Flit_Ctlr(Coord myCoord) : base(myCoord) { } public override int rank(Flit f1, Flit f2) { return Simulator.controller.rankFlits(f1, f2); } } }
namespace Nancy.Tests.Unit { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Configuration; using Nancy.Diagnostics; using Nancy.ErrorHandling; using Nancy.Extensions; using Nancy.Helpers; using Nancy.Routing; using Nancy.Tests.Fakes; using Xunit; using Nancy.Responses.Negotiation; using Nancy.Tests.xUnitExtensions; public class NancyEngineFixture { private readonly INancyEngine engine; private readonly IRouteResolver resolver; private readonly FakeRoute route; private readonly NancyContext context; private readonly INancyContextFactory contextFactory; private readonly Response response; private readonly IStatusCodeHandler statusCodeHandler; private readonly IRouteInvoker routeInvoker; private readonly IRequestDispatcher requestDispatcher; private readonly IResponseNegotiator negotiator; private readonly INancyEnvironment environment; public NancyEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.Tracing( enabled: true, displayErrorTraces: true); this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake<IStatusCodeHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); this.negotiator = A.Fake<IResponseNegotiator>(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)) .Returns(Task.FromResult(new Response())); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment) { RequestPipelinesFactory = ctx => applicationPipelines }; } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_dispatcher() { // Given, When var exception = Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_context_factory() { // Given, When var exception = Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void Should_throw_argumentnullexception_when_created_with_null_status_handler() { // Given, When var exception = Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public async Task HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request() { // Given, Request request = null; // When var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request)); // Then exception.ShouldBeOfType<ArgumentNullException>(); } [Fact] public void HandleRequest_should_get_context_from_context_factory() { // Given var request = new Request("GET", "/", "http"); // When this.engine.HandleRequest(request); // Then A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappenedOnceExactly(); } [Fact] public async Task HandleRequest_should_set_correct_response_on_returned_context() { // Given var request = new Request("GET", "/", "http"); A.CallTo(() => this.requestDispatcher.Dispatch(this.context, A<CancellationToken>._)) .Returns(Task.FromResult(this.response)); // When var result = await this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(this.response); } [Fact] public async Task Should_not_add_nancy_version_number_header_on_returned_response() { // NOTE: Regression for removal of nancy-version from response headers // Given var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Response.Headers.ContainsKey("Nancy-Version").ShouldBeFalse(); } [Fact] public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null() { // Given var pipelines = new Pipelines { BeforeRequest = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; // When var request = new Request("GET", "/", "http"); // Then await this.engine.HandleRequest(request); } [Fact] public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null() { // Given var pipelines = new Pipelines { AfterRequest = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; // When var request = new Request("GET", "/", "http"); // Then await this.engine.HandleRequest(request); } [Fact] public async Task Should_call_pre_request_hook_should_be_invoked_with_request_from_context() { // Given Request passedRequest = null; var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) => { passedRequest = ctx.Request; return null; }); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); this.context.Request = request; // When await this.engine.HandleRequest(request); // Then passedRequest.ShouldBeSameAs(request); } [Fact] public async Task Should_return_response_from_pre_request_hook_when_not_null() { // Given var returnedResponse = A.Fake<Response>(); var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(returnedResponse); } [Fact] public async Task Should_allow_post_request_hook_to_modify_context_items() { // Given var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => { ctx.Items.Add("PostReqTest", new object()); return null; }); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Items.ContainsKey("PostReqTest").ShouldBeTrue(); } [Fact] public async Task Should_allow_post_request_hook_to_replace_response() { // Given var newResponse = new Response(); var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(newResponse); } [Fact] public async Task HandleRequest_prereq_returns_response_should_still_run_postreq() { // Given var returnedResponse = A.Fake<Response>(); var postReqCalled = false; var pipelines = new Pipelines(); pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse); pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When await this.engine.HandleRequest(request); // Then postReqCalled.ShouldBeTrue(); } [Fact] public async Task Should_ask_status_handler_if_it_can_handle_status_code() { // Given var request = new Request("GET", "/", "http"); // When await this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly(); } [Fact] public async Task Should_not_invoke_status_handler_if_not_supported_status_code() { // Given var request = new Request("GET", "/", "http"); // When await this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened(); } [Fact] public async Task Should_invoke_status_handler_if_supported_status_code() { // Given var request = new Request("GET", "/", "http"); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true); // When await this.engine.HandleRequest(request); // Then A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly(); } [Fact] public async Task Should_catch_exception_inside_status_code_handler_and_return_default_error_response() { // Given A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>.Ignored, A<CancellationToken>.Ignored)) .Returns(new Response() { StatusCode = HttpStatusCode.InternalServerError }); var statusCodeHandlers = new[] { this.statusCodeHandler, new DefaultStatusCodeHandler(this.negotiator, this.environment), }; var engine = new NancyEngine(this.requestDispatcher, this.contextFactory, statusCodeHandlers, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment) { RequestPipelinesFactory = ctx => new Pipelines() }; var request = new Request("GET", "/", "http"); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true); A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)) .Throws<Exception>(); // When await engine.HandleRequest(request); // Then this.context.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); } [Fact] public async Task Should_throw_exception_if_no_default_status_code_handler_present_when_custom_status_code_handler_throws() { // Given var request = new Request("GET", "/", "http"); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true); A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)) .Throws<Exception>(); // When,Then await AssertAsync.Throws<Exception>(async () => await this.engine.HandleRequest(request)); } [Fact] public async Task Should_set_status_code_to_500_if_route_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException())); var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); } [Fact] public async Task Should_store_exception_details_if_dispatcher_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException())); var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.GetExceptionDetails().ShouldContain("NotImplementedException"); } [Fact] public async Task Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws() { // Given var testEx = new Exception(); var errorRoute = new Route<object>("GET", "/", null, (x, c) => { throw testEx; }); var resolvedRoute = new ResolveResult( errorRoute, DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(testEx)); Exception handledException = null; NancyContext handledContext = null; var errorResponse = new Response(); A.CallTo(() => this.negotiator.NegotiateResponse(A<object>.Ignored, A<NancyContext>.Ignored)) .Returns(errorResponse); Func<NancyContext, Exception, dynamic> routeErrorHook = (ctx, ex) => { handledContext = ctx; handledException = ex; return errorResponse; }; var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then Assert.Equal(testEx, handledException); Assert.Equal(result, handledContext); Assert.Equal(result.Response, errorResponse); } [Fact] public async Task Should_add_unhandled_exception_to_context_as_requestexecutionexception() { // Given var routeUnderTest = new Route<object>("GET", "/", null, (x, c) => { throw new Exception(); }); var resolved = new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)) .Invokes((x) => routeUnderTest.Action.Invoke(DynamicDictionary.Empty, new CancellationToken())); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(new Exception())); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue(); result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>(); } [Fact] public async Task Should_persist_original_exception_in_requestexecutionexception() { // Given var expectedException = new Exception(); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public async Task Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null() { // Given var expectedException = new Exception(); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(expectedException)); var pipelines = new Pipelines { OnError = null }; engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); } [Fact] public async Task Should_return_static_content_response_if_one_returned() { // Given var localResponse = new Response(); var staticContent = A.Fake<IStaticContentProvider>(); A.CallTo(() => staticContent.GetContent(A<NancyContext>._)) .Returns(localResponse); var localEngine = new NancyEngine( this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), staticContent, this.negotiator , this.environment); var request = new Request("GET", "/", "http"); // When var result = await localEngine.HandleRequest(request); // Then result.Response.ShouldBeSameAs(localResponse); } [Fact] public async Task Should_set_status_code_to_500_if_pre_execute_response_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(Task.FromResult<Response>(new PreExecuteFailureResponse())); var request = new Request("GET", "/", "http"); // When var result = await this.engine.HandleRequest(request); // Then result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); } [Fact] public async Task Should_throw_operationcancelledexception_when_disposed_handling_request() { // Given var request = new Request("GET", "/", "http"); var engine = new NancyEngine(A.Fake<IRequestDispatcher>(), A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment); engine.Dispose(); // When var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request)); // Then exception.ShouldBeOfType<OperationCanceledException>(); } } public class PreExecuteFailureResponse : Response { public override Task PreExecute(NancyContext context) { return TaskHelpers.GetFaultedTask<object>(new InvalidOperationException()); } } }
using System; using System.Collections; using UnityEngine; #if !UniRxLibrary && !SystemReactive using ObservableUnity = UniRx.Observable; #endif #if SystemReactive using System.Reactive; using System.Threading; #endif namespace UniRx { #if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6) // Fallback for Unity versions below 4.5 using Hash = System.Collections.Hashtable; using HashEntry = System.Collections.DictionaryEntry; #else // Unity 4.5 release notes: // WWW: deprecated 'WWW(string url, byte[] postData, Hashtable headers)', // use 'public WWW(string url, byte[] postData, Dictionary<string, string> headers)' instead. using Hash = System.Collections.Generic.Dictionary<string, string>; using HashEntry = System.Collections.Generic.KeyValuePair<string, string>; #endif public static partial class ObservableWWW { public static IObservable<string> Get(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<byte[]> GetAndGetBytes(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<WWW> GetWWW(string url, Hash headers = null, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, null, (headers ?? new Hash())), observer, progress, cancellation)); } public static IObservable<string> Post(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<string> Post(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<string> Post(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<string> Post(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<string>((observer, cancellation) => FetchText(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<byte[]> PostAndGetBytes(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<byte[]>((observer, cancellation) => FetchBytes(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, byte[] postData, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, byte[] postData, Hash headers, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, postData, headers), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, WWWForm content, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content), observer, progress, cancellation)); } public static IObservable<WWW> PostWWW(string url, WWWForm content, Hash headers, IProgress<float> progress = null) { var contentHeaders = content.headers; return ObservableUnity.FromCoroutine<WWW>((observer, cancellation) => Fetch(new WWW(url, content.data, MergeHash(contentHeaders, headers)), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, int version, uint crc, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, version, crc), observer, progress, cancellation)); } // over Unity5 supports Hash128 #if !(UNITY_4_7 || UNITY_4_6 || UNITY_4_5 || UNITY_4_4 || UNITY_4_3 || UNITY_4_2 || UNITY_4_1 || UNITY_4_0_1 || UNITY_4_0 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3 || UNITY_3_2 || UNITY_3_1 || UNITY_3_0_0 || UNITY_3_0 || UNITY_2_6_1 || UNITY_2_6) public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128), observer, progress, cancellation)); } public static IObservable<AssetBundle> LoadFromCacheOrDownload(string url, Hash128 hash128, uint crc, IProgress<float> progress = null) { return ObservableUnity.FromCoroutine<AssetBundle>((observer, cancellation) => FetchAssetBundle(WWW.LoadFromCacheOrDownload(url, hash128, crc), observer, progress, cancellation)); } #endif // over 4.5, Hash define is Dictionary. // below Unity 4.5, WWW only supports Hashtable. // Unity 4.5, 4.6 WWW supports Dictionary and [Obsolete]Hashtable but WWWForm.content is Hashtable. // Unity 5.0 WWW only supports Dictionary and WWWForm.content is also Dictionary. #if !(UNITY_METRO || UNITY_WP8) && (UNITY_4_5 || UNITY_4_6 || UNITY_4_7) static Hash MergeHash(Hashtable wwwFormHeaders, Hash externalHeaders) { var newHeaders = new Hash(); foreach (DictionaryEntry item in wwwFormHeaders) { newHeaders[item.Key.ToString()] = item.Value.ToString(); } foreach (HashEntry item in externalHeaders) { newHeaders[item.Key] = item.Value; } return newHeaders; } #else static Hash MergeHash(Hash wwwFormHeaders, Hash externalHeaders) { foreach (HashEntry item in externalHeaders) { wwwFormHeaders[item.Key] = item.Value; } return wwwFormHeaders; } #endif static IEnumerator Fetch(WWW www, IObserver<WWW> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www); observer.OnCompleted(); } } } static IEnumerator FetchText(WWW www, IObserver<string> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www.text); observer.OnCompleted(); } } } static IEnumerator FetchBytes(WWW www, IObserver<byte[]> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, www.text)); } else { observer.OnNext(www.bytes); observer.OnCompleted(); } } } static IEnumerator FetchAssetBundle(WWW www, IObserver<AssetBundle> observer, IProgress<float> reportProgress, CancellationToken cancel) { using (www) { if (reportProgress != null) { while (!www.isDone && !cancel.IsCancellationRequested) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } yield return null; } } else { if (!www.isDone) { yield return www; } } if (cancel.IsCancellationRequested) { if (!www.isDone) yield return www; // workaround for freeze bug of dispose WWW when WWW is not completed yield break; } if (reportProgress != null) { try { reportProgress.Report(www.progress); } catch (Exception ex) { observer.OnError(ex); yield break; } } if (!string.IsNullOrEmpty(www.error)) { observer.OnError(new WWWErrorException(www, "")); } else { observer.OnNext(www.assetBundle); observer.OnCompleted(); } } } } public class WWWErrorException : Exception { public string RawErrorMessage { get; private set; } public bool HasResponse { get; private set; } public string Text { get; private set; } public System.Net.HttpStatusCode StatusCode { get; private set; } public System.Collections.Generic.Dictionary<string, string> ResponseHeaders { get; private set; } public WWW WWW { get; private set; } // cache the text because if www was disposed, can't access it. public WWWErrorException(WWW www, string text) { this.WWW = www; this.RawErrorMessage = www.error; this.ResponseHeaders = www.responseHeaders; this.HasResponse = false; this.Text = text; var splitted = RawErrorMessage.Split(' ', ':'); if (splitted.Length != 0) { int statusCode; if (int.TryParse(splitted[0], out statusCode)) { this.HasResponse = true; this.StatusCode = (System.Net.HttpStatusCode)statusCode; } } } public override string ToString() { var text = this.Text; if (string.IsNullOrEmpty(text)) { return RawErrorMessage; } else { return RawErrorMessage + " " + text; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SPAScaffold.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// This file enables setting of the machine time zone // using .NET framework classes. // It can be used to set the time zone when the // PowerShell time zone cmdlets are not available. // // It creates a namespace Microsoft.PowerShell.TimeZone // containing the classes and structures required to // set the time zone. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security; using System.Runtime.InteropServices; using Microsoft.Win32; namespace Microsoft.PowerShell.TimeZone { [StructLayoutAttribute(LayoutKind.Sequential)] public struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public int Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public int StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public int DaylightBias; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DynamicTimeZoneInformation { public int Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; public int StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; public int DaylightBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string TimeZoneKeyName; [MarshalAs(UnmanagedType.U1)] public bool DynamicDaylightTimeDisabled; } [StructLayout(LayoutKind.Sequential)] public struct RegistryTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public int Bias; [MarshalAs(UnmanagedType.I4)] public int StandardBias; [MarshalAs(UnmanagedType.I4)] public int DaylightBias; public SystemTime StandardDate; public SystemTime DaylightDate; public RegistryTimeZoneInformation(TimeZoneInformation tzi) { this.Bias = tzi.Bias; this.StandardDate = tzi.StandardDate; this.StandardBias = tzi.StandardBias; this.DaylightDate = tzi.DaylightDate; this.DaylightBias = tzi.DaylightBias; } public RegistryTimeZoneInformation(byte[] bytes) { if ((bytes == null) || (bytes.Length != 0x2c)) { throw new ArgumentException("Argument_InvalidREG_TZI_FORMAT"); } this.Bias = BitConverter.ToInt32(bytes, 0); this.StandardBias = BitConverter.ToInt32(bytes, 4); this.DaylightBias = BitConverter.ToInt32(bytes, 8); this.StandardDate.Year = BitConverter.ToInt16(bytes, 12); this.StandardDate.Month = BitConverter.ToInt16(bytes, 14); this.StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 0x10); this.StandardDate.Day = BitConverter.ToInt16(bytes, 0x12); this.StandardDate.Hour = BitConverter.ToInt16(bytes, 20); this.StandardDate.Minute = BitConverter.ToInt16(bytes, 0x16); this.StandardDate.Second = BitConverter.ToInt16(bytes, 0x18); this.StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 0x1a); this.DaylightDate.Year = BitConverter.ToInt16(bytes, 0x1c); this.DaylightDate.Month = BitConverter.ToInt16(bytes, 30); this.DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 0x20); this.DaylightDate.Day = BitConverter.ToInt16(bytes, 0x22); this.DaylightDate.Hour = BitConverter.ToInt16(bytes, 0x24); this.DaylightDate.Minute = BitConverter.ToInt16(bytes, 0x26); this.DaylightDate.Second = BitConverter.ToInt16(bytes, 40); this.DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 0x2a); } } public class TokenPrivilegesAccess { [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int OpenProcessToken(int ProcessHandle, int DesiredAccess, ref int tokenhandle); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern int GetCurrentProcess(); [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); [DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGE Newstate, int bufferlength, int PreivousState, int Returnlength); public const int TOKEN_ASSIGN_PRIMARY = 0x00000001; public const int TOKEN_DUPLICATE = 0x00000002; public const int TOKEN_IMPERSONATE = 0x00000004; public const int TOKEN_QUERY = 0x00000008; public const int TOKEN_QUERY_SOURCE = 0x00000010; public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; public const int TOKEN_ADJUST_GROUPS = 0x00000040; public const int TOKEN_ADJUST_DEFAULT = 0x00000080; public const UInt32 SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001; public const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002; public const UInt32 SE_PRIVILEGE_REMOVED = 0x00000004; public const UInt32 SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000; public static bool EnablePrivilege(string privilege) { try { int token = 0; int retVal = 0; TOKEN_PRIVILEGE TP = new TOKEN_PRIVILEGE(); LUID LD = new LUID(); retVal = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); retVal = LookupPrivilegeValue(null, privilege, ref LD); TP.PrivilegeCount = 1; var luidAndAtt = new LUID_AND_ATTRIBUTES(); luidAndAtt.Attributes = SE_PRIVILEGE_ENABLED; luidAndAtt.Luid = LD; TP.Privilege = luidAndAtt; retVal = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); return true; } catch { return false; } } public static bool DisablePrivilege(string privilege) { try { int token = 0; int retVal = 0; TOKEN_PRIVILEGE TP = new TOKEN_PRIVILEGE(); LUID LD = new LUID(); retVal = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token); retVal = LookupPrivilegeValue(null, privilege, ref LD); TP.PrivilegeCount = 1; // TP.Attributes should be none (not set) to disable privilege var luidAndAtt = new LUID_AND_ATTRIBUTES(); luidAndAtt.Luid = LD; TP.Privilege = luidAndAtt; retVal = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0); return true; } catch { return false; } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LUID { internal uint LowPart; internal uint HighPart; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LUID_AND_ATTRIBUTES { internal LUID Luid; internal uint Attributes; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TOKEN_PRIVILEGE { internal uint PrivilegeCount; internal LUID_AND_ATTRIBUTES Privilege; } public class TimeZone { public const int ERROR_ACCESS_DENIED = 0x005; public const int CORSEC_E_MISSING_STRONGNAME = -2146233317; [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool SetTimeZoneInformation([In] ref TimeZoneInformation lpTimeZoneInformation); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] private static extern bool SetDynamicTimeZoneInformation([In] ref DynamicTimeZoneInformation lpTimeZoneInformation); public static void Set(string name) { var regTimeZones = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones"); var subKey = regTimeZones.GetSubKeyNames().Where(s => s == name).First(); string daylightName = (string)regTimeZones.OpenSubKey(subKey).GetValue("Dlt"); string standardName = (string)regTimeZones.OpenSubKey(subKey).GetValue("Std"); byte[] tzi = (byte[])regTimeZones.OpenSubKey(subKey).GetValue("TZI"); var regTzi = new RegistryTimeZoneInformation(tzi); TokenPrivilegesAccess.EnablePrivilege("SeTimeZonePrivilege"); bool didSet; if (Environment.OSVersion.Version.Major < 6) { var tz = new TimeZoneInformation(); tz.Bias = regTzi.Bias; tz.DaylightBias = regTzi.DaylightBias; tz.StandardBias = regTzi.StandardBias; tz.DaylightDate = regTzi.DaylightDate; tz.StandardDate = regTzi.StandardDate; tz.DaylightName = daylightName; tz.StandardName = standardName; didSet = TimeZone.SetTimeZoneInformation(ref tz); } else { var tz = new DynamicTimeZoneInformation(); tz.Bias = regTzi.Bias; tz.DaylightBias = regTzi.DaylightBias; tz.StandardBias = regTzi.StandardBias; tz.DaylightDate = regTzi.DaylightDate; tz.StandardDate = regTzi.StandardDate; tz.DaylightName = daylightName; tz.StandardName = standardName; tz.TimeZoneKeyName = subKey; tz.DynamicDaylightTimeDisabled = false; didSet = TimeZone.SetDynamicTimeZoneInformation(ref tz); } int lastError = Marshal.GetLastWin32Error(); TokenPrivilegesAccess.DisablePrivilege("SeTimeZonePrivilege"); if (! didSet) { if (lastError == TimeZone.ERROR_ACCESS_DENIED) { throw new SecurityException("Access denied changing System TimeZone."); } else if (lastError == TimeZone.CORSEC_E_MISSING_STRONGNAME) { throw new SystemException("Application is not signed."); } else { throw new SystemException("Win32Error: " + lastError + "\nHRESULT: " + Marshal.GetHRForLastWin32Error()); } } } } }
/* * PropertyDescriptorCollection.cs - Implementation of the * "System.ComponentModel.PropertyDescriptorCollection" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.ComponentModel { #if CONFIG_COMPONENT_MODEL using System.Collections; using System.Globalization; using System.Runtime.InteropServices; public class PropertyDescriptorCollection : IList, ICollection, IEnumerable, IDictionary { // Internal state. private ArrayList list; // Empty collection. public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null); // Constructors. public PropertyDescriptorCollection(PropertyDescriptor[] properties) { list = new ArrayList(); if(properties != null) { foreach(PropertyDescriptor descr in properties) { list.Add(descr); } } } private PropertyDescriptorCollection(PropertyDescriptorCollection copyFrom, String[] names, IComparer comparer) { list = (ArrayList)(copyFrom.list.Clone()); InternalSort(names, comparer); } // Get the number of items in the collection. public int Count { get { return list.Count; } } // Get a specific property by index. public virtual PropertyDescriptor this[int index] { get { if(index < 0 || index >= list.Count) { throw new IndexOutOfRangeException (S._("Arg_InvalidArrayIndex")); } return (PropertyDescriptor)(list[index]); } } // Get a specific property by name. public virtual PropertyDescriptor this[String name] { get { return Find(name, false); } } // Add an descriptor to this collection. public int Add(PropertyDescriptor value) { return list.Add(value); } // Clear this collection. public void Clear() { list.Clear(); } // Determine if this collection contains a particular descriptor. public bool Contains(PropertyDescriptor value) { return list.Contains(value); } // Find a descriptor with a specific name. public virtual PropertyDescriptor Find(String name, bool ignoreCase) { foreach(PropertyDescriptor descr in list) { if(String.Compare(descr.Name, name, ignoreCase, CultureInfo.InvariantCulture) == 0) { return descr; } } return null; } // Get an enumerator for this collection. public virtual IEnumerator GetEnumerator() { return list.GetEnumerator(); } // Get the index of a specific descriptor within the collection. public int IndexOf(PropertyDescriptor value) { return list.IndexOf(value); } // Insert a descriptor into this collection. public void Insert(int index, PropertyDescriptor value) { list.Insert(index, value); } // Remove a descriptor from this collection. public void Remove(PropertyDescriptor value) { list.Remove(value); } // Remove a descriptor at a particular index within this collection. public void RemoveAt(int index) { list.RemoveAt(index); } // Sort the descriptor collection. public virtual PropertyDescriptorCollection Sort() { return new PropertyDescriptorCollection(this, null, null); } public virtual PropertyDescriptorCollection Sort(IComparer comparer) { return new PropertyDescriptorCollection(this, null, comparer); } public virtual PropertyDescriptorCollection Sort(String[] names) { return new PropertyDescriptorCollection(this, names, null); } public virtual PropertyDescriptorCollection Sort (String[] names, IComparer comparer) { return new PropertyDescriptorCollection(this, names, comparer); } // Internal version of "Sort". private void InternalSort(String[] names, IComparer comparer) { if(comparer == null) { comparer = new TypeDescriptor.DescriptorComparer(); } if(names != null && names.Length > 0) { // Copy across elements from "names" before // sorting the main list and appending it. ArrayList newList = new ArrayList(list.Count); foreach(String name in names) { PropertyDescriptor descr = Find(name, false); if(descr != null) { newList.Add(descr); list.Remove(descr); } } list.Sort(comparer); foreach(PropertyDescriptor ed in list) { newList.Add(ed); } list = newList; } else { // No names, so just sort the main list. list.Sort(comparer); } } protected void InternalSort(IComparer comparer) { InternalSort(null, comparer); } protected void InternalSort(String[] names) { InternalSort(names, null); } // Implement the IList interface. int IList.Add(Object value) { return Add((PropertyDescriptor)value); } void IList.Clear() { Clear(); } bool IList.Contains(Object value) { return list.Contains(value); } int IList.IndexOf(Object value) { return list.IndexOf(value); } void IList.Insert(int index, Object value) { Insert(index, (PropertyDescriptor)value); } void IList.Remove(Object value) { list.Remove(value); } void IList.RemoveAt(int index) { list.RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } Object IList.this[int index] { get { return this[index]; } set { list[index] = (PropertyDescriptor)value; } } // Implement the ICollection interface. public void CopyTo(Array array, int index) { list.CopyTo(array, index); } int ICollection.Count { get { return list.Count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // Implement the IDictionary interface. void IDictionary.Add(Object key, Object value) { if(value is PropertyDescriptor) { Add((PropertyDescriptor)value); } else { throw new ArgumentException (S._("Arg_InvalidElement")); } } void IDictionary.Clear() { Clear(); } bool IDictionary.Contains(Object key) { if(key is String) { return (Find((String)key, false) != null); } else { return false; } } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(GetEnumerator()); } void IDictionary.Remove(Object key) { if(key is String) { PropertyDescriptor descr = Find((String)key, false); if(descr != null) { Remove(descr); } } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } Object IDictionary.this[Object key] { get { if(key is String) { return Find((String)key, false); } else { return null; } } set { ((IDictionary)this).Add(key, value); } } ICollection IDictionary.Keys { get { String[] keys = new String [list.Count]; int posn = 0; foreach(PropertyDescriptor descr in list) { keys[posn++] = descr.Name; } return keys; } } ICollection IDictionary.Values { get { PropertyDescriptor[] values; values = new PropertyDescriptor [list.Count]; int posn = 0; foreach(PropertyDescriptor descr in list) { values[posn++] = descr; } return values; } } // Dictionary enumerator for property descriptor collections. private sealed class Enumerator : IDictionaryEnumerator { // Internal state. private IEnumerator e; // Constructor. public Enumerator(IEnumerator e) { this.e = e; } // Implement the IEnumerator interface. public bool MoveNext() { return e.MoveNext(); } public void Reset() { e.Reset(); } public Object Current { get { return Entry; } } // Implement the IDictionaryEnumerator interface. public DictionaryEntry Entry { get { PropertyDescriptor descr; descr = (PropertyDescriptor)(e.Current); return new DictionaryEntry(descr.Name, descr); } } public Object Key { get { return ((PropertyDescriptor)(e.Current)).Name; } } public Object Value { get { return (PropertyDescriptor)(e.Current); } } }; // class IDictionaryEnumerator }; // class PropertyDescriptorCollection #endif // CONFIG_COMPONENT_MODEL }; // namespace System.ComponentModel
// 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; public class BringUpTests { const int Pass = 100; const int Fail = -1; public static int Main() { int result = Pass; if (!TestValueTypeDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestVirtualDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestInterfaceDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestStaticOpenClosedDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestMulticastDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestDynamicInvoke()) { Console.WriteLine("Failed"); result = Fail; } return result; } public static bool TestValueTypeDelegates() { Console.Write("Testing delegates to value types..."); { TestValueType t = new TestValueType { X = 123 }; Func<string, string> d = t.GiveX; string result = d("MyPrefix"); if (result != "MyPrefix123") return false; } { object t = new TestValueType { X = 456 }; Func<string> d = t.ToString; string result = d(); if (result != "456") return false; } { Func<int, TestValueType> d = TestValueType.MakeValueType; TestValueType result = d(789); if (result.X != 789) return false; } Console.WriteLine("OK"); return true; } public static bool TestVirtualDelegates() { Console.Write("Testing delegates to virtual methods..."); { Mid t = new Mid(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Mid") return false; } { Mid t = new Derived(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Derived") return false; } Console.WriteLine("OK"); return true; } public static bool TestInterfaceDelegates() { Console.Write("Testing delegates to interface methods..."); { IFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if (d(987) != "Class987") return false; } { IFoo t = new StructWithIFoo("Struct"); Func<int, string> d = t.DoFoo; if (d(654) != "Struct654") return false; } Console.WriteLine("OK"); return true; } public static bool TestStaticOpenClosedDelegates() { Console.Write("Testing static open and closed delegates..."); { Func<string, string, string> d = ExtensionClass.Combine; if (d("Hello", "World") != "HelloWorld") return false; } { Func<string, string> d = "Hi".Combine; if (d("There") != "HiThere") return false; } Console.WriteLine("OK"); return true; } public static bool TestMulticastDelegates() { Console.Write("Testing multicast delegates..."); { ClassThatMutates t = new ClassThatMutates(); Action d = t.AddOne; d(); if (t.State != 1) return false; t.State = 0; d += t.AddTwo; d(); if (t.State != 3) return false; t.State = 0; d += t.AddOne; d(); if (t.State != 4) return false; } Console.WriteLine("OK"); return true; } public static bool TestDynamicInvoke() { Console.Write("Testing dynamic invoke..."); { TestValueType t = new TestValueType { X = 123 }; Func<string, string> d = t.GiveX; string result = (string)d.DynamicInvoke(new object[] { "MyPrefix" }); if (result != "MyPrefix123") return false; } { Func<int, TestValueType> d = TestValueType.MakeValueType; TestValueType result = (TestValueType)d.DynamicInvoke(new object[] { 789 }); if (result.X != 789) return false; } { IFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if ((string)d.DynamicInvoke(new object[] { 987 }) != "Class987") return false; } { IFoo t = new StructWithIFoo("Struct"); Func<int, string> d = t.DoFoo; if ((string)d.DynamicInvoke(new object[] { 654 }) != "Struct654") return false; } { Func<string, string, string> d = ExtensionClass.Combine; if ((string)d.DynamicInvoke(new object[] { "Hello", "World" }) != "HelloWorld") return false; } { Func<string, string> d = "Hi".Combine; if ((string)d.DynamicInvoke(new object[] { "There" }) != "HiThere") return false; } { Mutate<int> d = ClassWithByRefs.Mutate; object[] args = new object[] { 8 }; d.DynamicInvoke(args); if ((int)args[0] != 50) return false; } { Mutate<string> d = ClassWithByRefs.Mutate; object[] args = new object[] { "Hello" }; d.DynamicInvoke(args); if ((string)args[0] != "HelloMutated") return false; } unsafe { GetAndReturnPointerDelegate d = ClassWithPointers.GetAndReturnPointer; if ((IntPtr)d.DynamicInvoke(new object[] { (IntPtr)8 }) != (IntPtr)50) return false; } #if false // This is hitting an EH bug around throw/rethrow from a catch block (pass is not set properly) unsafe { PassPointerByRefDelegate d = ClassWithPointers.PassPointerByRef; var args = new object[] { (IntPtr)8 }; bool caught = false; try { d.DynamicInvoke(args); } catch (ArgumentException) { caught = true; } if (!caught) return false; } #endif Console.WriteLine("OK"); return true; } struct TestValueType { public int X; public string GiveX(string prefix) { return prefix + X.ToString(); } public static TestValueType MakeValueType(int value) { return new TestValueType { X = value }; } public override string ToString() { return X.ToString(); } } class Base { public virtual string Do() { return "Base"; } } class Mid : Base { public override string Do() { return "Mid"; } public Func<string> GetBaseDo() { return base.Do; } public Func<string> GetDerivedDo() { return Do; } } class Derived : Mid { public override string Do() { return "Derived"; } } interface IFoo { string DoFoo(int x); } class ClassWithIFoo : IFoo { string _prefix; public ClassWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } struct StructWithIFoo : IFoo { string _prefix; public StructWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } class ClassThatMutates { public int State; public void AddOne() { State++; } public void AddTwo() { State += 2; } } } static class ExtensionClass { public static string Combine(this string s1, string s2) { return s1 + s2; } } unsafe delegate IntPtr GetAndReturnPointerDelegate(void* ptr); unsafe delegate void PassPointerByRefDelegate(ref void* ptr); unsafe static class ClassWithPointers { public static IntPtr GetAndReturnPointer(void* ptr) { return (IntPtr)((byte*)ptr + 42); } public static void PassPointerByRef(ref void* ptr) { ptr = (byte*)ptr + 42; } } delegate void Mutate<T>(ref T x); class ClassWithByRefs { public static void Mutate(ref int x) { x += 42; } public static void Mutate(ref string x) { x += "Mutated"; } }
using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Cyotek.Windows.Forms { // Cyotek GroupBox Component // www.cyotek.com /// <summary> /// Represents a Windows control that displays a frame at the top of a group of controls with an optional caption and icon. /// </summary> [ToolboxItem(true)] [DefaultEvent("Click")] [DefaultProperty("Text")] [Designer("System.Windows.Forms.Design.GroupBoxDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [Designer("System.Windows.Forms.Design.DocumentDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(IRootDesigner))] internal class GroupBox : System.Windows.Forms.GroupBox { #region Instance Fields private Border3DSide _borders = Border3DSide.Top; private Pen _bottomPen; private Color _headerForeColor; private Size _iconMargin; private Image _image; private Color _lineColorBottom; private Color _lineColorTop; private bool _showBorders; private Pen _topPen; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="GroupBox"/> class. /// </summary> public GroupBox() { _showBorders = true; _iconMargin = new Size(0, 6); _lineColorBottom = SystemColors.ButtonHighlight; _lineColorTop = SystemColors.ButtonShadow; _headerForeColor = SystemColors.HotTrack; this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.SupportsTransparentBackColor, true); this.CreateResources(); } #endregion #region Overridden Properties /// <summary> /// Gets a rectangle that represents the dimensions of the <see cref="T:System.Windows.Forms.GroupBox"/>. /// </summary> /// <value></value> /// <returns> /// A <see cref="T:System.Drawing.Rectangle"/> with the dimensions of the <see cref="T:System.Windows.Forms.GroupBox"/>. /// </returns> public override Rectangle DisplayRectangle { get { Size clientSize; int fontHeight; int imageSize; clientSize = base.ClientSize; fontHeight = this.Font.Height; if (_image != null) { imageSize = _iconMargin.Width + _image.Width + 3; } else { imageSize = 0; } return new Rectangle(3 + imageSize, fontHeight + 3, Math.Max(clientSize.Width - (imageSize + 6), 0), Math.Max((clientSize.Height - fontHeight) - 6, 0)); } } /// <summary> /// Returns or sets the text displayed in this control. /// </summary> /// <value></value> /// <returns> /// The text associated with this control. /// </returns> [Browsable(true)] [DefaultValue("")] public override string Text { get { return base.Text; } set { base.Text = value; this.Invalidate(); } } #endregion #region Overridden Methods /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { this.CleanUpResources(); } base.Dispose(disposing); } /// <summary> /// Occurs when the control is to be painted. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { SizeF size; int y; TextFormatFlags flags; Rectangle textBounds; flags = TextFormatFlags.WordEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.Left | TextFormatFlags.SingleLine; size = TextRenderer.MeasureText(e.Graphics, this.Text, this.Font, this.ClientSize, flags); y = (int)(size.Height + 3) / 2; textBounds = new Rectangle(1, 1, (int)size.Width, (int)size.Height); if (this.ShowBorders) { if ((_borders & Border3DSide.All) == Border3DSide.All) { e.Graphics.DrawRectangle(_bottomPen, 1, y + 1, this.Width - 2, this.Height - (y + 2)); e.Graphics.DrawRectangle(_topPen, 0, y, this.Width - 2, this.Height - (y + 2)); } else { if ((_borders & Border3DSide.Top) == Border3DSide.Top) { e.Graphics.DrawLine(_topPen, size.Width + 3, y, this.Width - 5, y); e.Graphics.DrawLine(_bottomPen, size.Width + 3, y + 1, this.Width - 5, y + 1); } if ((_borders & Border3DSide.Left) == Border3DSide.Left) { e.Graphics.DrawLine(_topPen, 0, y, 0, this.Height - 1); e.Graphics.DrawLine(_bottomPen, 1, y, 1, this.Height - 1); } if ((_borders & Border3DSide.Right) == Border3DSide.Right) { e.Graphics.DrawLine(_bottomPen, this.Width - 1, y, this.Width - 1, this.Height - 1); e.Graphics.DrawLine(_topPen, this.Width - 2, y, this.Width - 2, this.Height - 1); } if ((_borders & Border3DSide.Bottom) == Border3DSide.Bottom) { e.Graphics.DrawLine(_topPen, 0, this.Height - 2, this.Width, this.Height - 2); e.Graphics.DrawLine(_bottomPen, 0, this.Height - 1, this.Width, this.Height - 1); } } } // header text TextRenderer.DrawText(e.Graphics, this.Text, this.Font, textBounds, this.HeaderForeColor, flags); // draw the image if ((_image != null)) { e.Graphics.DrawImage(_image, this.Padding.Left + _iconMargin.Width, this.Padding.Top + (int)size.Height + _iconMargin.Height, _image.Width, _image.Height); } //draw a designtime outline if (this.DesignMode && (_borders & Border3DSide.All) != Border3DSide.All) { using (Pen pen = new Pen(SystemColors.ButtonShadow)) { pen.DashStyle = DashStyle.Dot; e.Graphics.DrawRectangle(pen, 0, 0, Width - 1, Height - 1); } } } /// <summary> /// Raises the <see cref="System.Windows.Forms.Control.SystemColorsChanged"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> protected override void OnSystemColorsChanged(EventArgs e) { base.OnSystemColorsChanged(e); this.CreateResources(); this.Invalidate(); } #endregion #region Public Properties [Category("Appearance")] [DefaultValue(typeof(Border3DSide), "Top")] public Border3DSide Borders { get { return _borders; } set { _borders = value; this.Invalidate(); } } [Category("Appearance")] [DefaultValue(typeof(Color), "HotTrack")] public Color HeaderForeColor { get { return _headerForeColor; } set { _headerForeColor = value; this.CreateResources(); this.Invalidate(); } } /// <summary> /// Gets or sets the icon margin. /// </summary> /// <value>The icon margin.</value> [Category("Appearance")] [DefaultValue(typeof(Size), "0, 6")] public Size IconMargin { get { return _iconMargin; } set { _iconMargin = value; this.Invalidate(); } } /// <summary> /// Gets or sets the image to display. /// </summary> /// <value>The image to display.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Image), "")] public Image Image { get { return _image; } set { _image = value; this.Invalidate(); } } /// <summary> /// Gets or sets the line color bottom. /// </summary> /// <value>The line color bottom.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Color), "ButtonHighlight")] public Color LineColorBottom { get { return _lineColorBottom; } set { _lineColorBottom = value; this.CreateResources(); this.Invalidate(); } } /// <summary> /// Gets or sets the line color top. /// </summary> /// <value>The line color top.</value> [Browsable(true)] [Category("Appearance")] [DefaultValue(typeof(Color), "ButtonShadow")] public Color LineColorTop { get { return _lineColorTop; } set { _lineColorTop = value; this.CreateResources(); this.Invalidate(); } } [DefaultValue(true)] [Category("Appearance")] public bool ShowBorders { get { return _showBorders; } set { _showBorders = value; this.Invalidate(); } } #endregion #region Private Members /// <summary> /// Cleans up GDI resources. /// </summary> private void CleanUpResources() { if (_topPen != null) { _topPen.Dispose(); } if (_bottomPen != null) { _bottomPen.Dispose(); } } /// <summary> /// Creates GDI resources. /// </summary> private void CreateResources() { this.CleanUpResources(); _topPen = new Pen(_lineColorTop); _bottomPen = new Pen(_lineColorBottom); } #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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.LanguageServices.ProjectInfoService; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> : IGenerateTypeService where TService : AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> where TSimpleNameSyntax : TExpressionSyntax where TObjectCreationExpressionSyntax : TExpressionSyntax where TExpressionSyntax : SyntaxNode where TTypeDeclarationSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode { protected AbstractGenerateTypeService() { } protected abstract bool TryInitializeState(SemanticDocument document, TSimpleNameSyntax simpleName, CancellationToken cancellationToken, out GenerateTypeServiceStateOptions generateTypeServiceStateOptions); protected abstract TExpressionSyntax GetLeftSideOfDot(TSimpleNameSyntax simpleName); protected abstract bool TryGetArgumentList(TObjectCreationExpressionSyntax objectCreationExpression, out IList<TArgumentSyntax> argumentList); protected abstract string DefaultFileExtension { get; } protected abstract IList<ITypeParameterSymbol> GetTypeParameters(State state, SemanticModel semanticModel, CancellationToken cancellationToken); protected abstract Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken); protected abstract IList<string> GenerateParameterNames(SemanticModel semanticModel, IList<TArgumentSyntax> arguments); protected abstract INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, TSimpleNameSyntax simpleName, CancellationToken cancellationToken); protected abstract ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, TArgumentSyntax argument, CancellationToken cancellationToken); protected abstract bool IsInCatchDeclaration(TExpressionSyntax expression); protected abstract bool IsArrayElementType(TExpressionSyntax expression); protected abstract bool IsInVariableTypeContext(TExpressionSyntax expression); protected abstract bool IsInValueTypeConstraintContext(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken); protected abstract bool IsInInterfaceList(TExpressionSyntax expression); internal abstract bool TryGetBaseList(TExpressionSyntax expression, out TypeKindOptions returnValue); internal abstract bool IsPublicOnlyAccessibility(TExpressionSyntax expression, Project project); internal abstract bool IsGenericName(TSimpleNameSyntax simpleName); internal abstract bool IsSimpleName(TExpressionSyntax expression); internal abstract Solution TryAddUsingsOrImportToDocument(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, TSimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken); protected abstract bool TryGetNameParts(TExpressionSyntax expression, out IList<string> nameParts); public abstract string GetRootNamespace(CompilationOptions options); public abstract Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbol(INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken); public async Task<IEnumerable<CodeAction>> GenerateTypeAsync( Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateType, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = State.Generate((TService)this, semanticDocument, node, cancellationToken); if (state != null) { var actions = GetActions(semanticDocument, node, state, cancellationToken).ToList(); if (actions.Count > 1) { // Wrap the generate type actions into a single top level suggestion // so as to not clutter the list. return SpecializedCollections.SingletonEnumerable( new MyCodeAction(FeaturesResources.Generate_type, actions.AsImmutable())); } else { return actions; } } return SpecializedCollections.EmptyEnumerable<CodeAction>(); } } private IEnumerable<CodeAction> GetActions( SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken) { var generateNewTypeInDialog = false; if (state.NamespaceToGenerateInOpt != null) { var workspace = document.Project.Solution.Workspace; if (workspace == null || workspace.CanApplyChange(ApplyChangesKind.AddDocument)) { generateNewTypeInDialog = true; yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: true); } // If they just are generating "Foo" then we want to offer to generate it into the // namespace in the same file. However, if they are generating "SomeNS.Foo", then we // only want to allow them to generate if "SomeNS" is the namespace they are // currently in. var isSimpleName = state.SimpleName == state.NameOrMemberAccessExpression; var generateIntoContaining = IsGeneratingIntoContainingNamespace(document, node, state, cancellationToken); if ((isSimpleName || generateIntoContaining) && CanGenerateIntoContainingNamespace(document, node, state, cancellationToken)) { yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: true, inNewFile: false); } } if (state.TypeToGenerateInOpt != null) { yield return new GenerateTypeCodeAction((TService)this, document.Document, state, intoNamespace: false, inNewFile: false); } if (generateNewTypeInDialog) { yield return new GenerateTypeCodeActionWithOption((TService)this, document.Document, state); } } private bool CanGenerateIntoContainingNamespace(SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken) { var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken); // Only allow if the containing namespace is one that can be generated // into. var declarationService = document.Project.LanguageServices.GetService<ISymbolDeclarationService>(); var decl = declarationService.GetDeclarations(containingNamespace) .Where(r => r.SyntaxTree == node.SyntaxTree) .Select(r => r.GetSyntax(cancellationToken)) .FirstOrDefault(node.GetAncestorsOrThis<SyntaxNode>().Contains); return decl != null && document.Project.LanguageServices.GetService<ICodeGenerationService>().CanAddTo(decl, document.Project.Solution, cancellationToken); } private bool IsGeneratingIntoContainingNamespace( SemanticDocument document, SyntaxNode node, State state, CancellationToken cancellationToken) { var containingNamespace = document.SemanticModel.GetEnclosingNamespace(node.SpanStart, cancellationToken); if (containingNamespace != null) { var containingNamespaceName = containingNamespace.ToDisplayString(); return containingNamespaceName.Equals(state.NamespaceToGenerateInOpt); } return false; } protected static string GetTypeName(State state) { const string AttributeSuffix = "Attribute"; return state.IsAttribute && !state.NameIsVerbatim && !state.Name.EndsWith(AttributeSuffix, StringComparison.Ordinal) ? state.Name + AttributeSuffix : state.Name; } protected IList<ITypeParameterSymbol> GetTypeParameters( State state, SemanticModel semanticModel, IEnumerable<SyntaxNode> typeArguments, CancellationToken cancellationToken) { var arguments = typeArguments.ToList(); var arity = arguments.Count; var typeParameters = new List<ITypeParameterSymbol>(); // For anything that was a type parameter, just use the name (if we haven't already // used it). Otherwise, synthesize new names for the parameters. var names = new string[arity]; var isFixed = new bool[arity]; for (var i = 0; i < arity; i++) { var argument = i < arguments.Count ? arguments[i] : null; var type = argument == null ? null : semanticModel.GetTypeInfo(argument, cancellationToken).Type; if (type is ITypeParameterSymbol) { var name = type.Name; // If we haven't seen this type parameter already, then we can use this name // and 'fix' it so that it doesn't change. Otherwise, use it, but allow it // to be changed if it collides with anything else. isFixed[i] = !names.Contains(name); names[i] = name; typeParameters.Add((ITypeParameterSymbol)type); } else { names[i] = "T"; typeParameters.Add(null); } } // We can use a type parameter as long as it hasn't been used in an outer type. var canUse = state.TypeToGenerateInOpt == null ? default(Func<string, bool>) : s => state.TypeToGenerateInOpt.GetAllTypeParameters().All(t => t.Name != s); var uniqueNames = NameGenerator.EnsureUniqueness(names, isFixed, canUse: canUse); for (int i = 0; i < uniqueNames.Count; i++) { if (typeParameters[i] == null || typeParameters[i].Name != uniqueNames[i]) { typeParameters[i] = CodeGenerationSymbolFactory.CreateTypeParameterSymbol(uniqueNames[i]); } } return typeParameters; } protected Accessibility DetermineDefaultAccessibility( State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { if (state.IsPublicAccessibilityForTypeGeneration) { return Accessibility.Public; } // If we're a nested type of the type being generated into, then the new type can be // private. otherwise, it needs to be internal. if (!intoNamespace && state.TypeToGenerateInOpt != null) { var outerTypeSymbol = semanticModel.GetEnclosingNamedType(state.SimpleName.SpanStart, cancellationToken); if (outerTypeSymbol != null && outerTypeSymbol.IsContainedWithin(state.TypeToGenerateInOpt)) { return Accessibility.Private; } } return Accessibility.Internal; } protected IList<ITypeParameterSymbol> GetAvailableTypeParameters( State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken) { var availableInnerTypeParameters = GetTypeParameters(state, semanticModel, cancellationToken); var availableOuterTypeParameters = !intoNamespace && state.TypeToGenerateInOpt != null ? state.TypeToGenerateInOpt.GetAllTypeParameters() : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList(); } protected bool IsWithinTheImportingNamespace(Document document, int triggeringPosition, string includeUsingsOrImports, CancellationToken cancellationToken) { var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); if (semanticModel != null) { var namespaceSymbol = semanticModel.GetEnclosingNamespace(triggeringPosition, cancellationToken); if (namespaceSymbol != null && namespaceSymbol.ToDisplayString().StartsWith(includeUsingsOrImports, StringComparison.Ordinal)) { return true; } } return false; } protected bool GeneratedTypesMustBePublic(Project project) { var projectInfoService = project.Solution.Workspace.Services.GetService<IProjectInfoService>(); if (projectInfoService != null) { return projectInfoService.GeneratedTypesMustBePublic(project); } return false; } private class MyCodeAction : CodeAction.SimpleCodeAction { public MyCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions) { } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Reflection; using System.Text.RegularExpressions; using NLog.Common; using NLog.Config; using Xunit.Extensions; namespace NLog.UnitTests.Config { using System.IO; using MyExtensionNamespace; using NLog.Filters; using NLog.Layouts; using NLog.Targets; using Xunit; public class ExtensionTests : NLogTestBase { private string extensionAssemblyName1 = "SampleExtensions"; private string extensionAssemblyFullPath1 = Path.GetFullPath("SampleExtensions.dll"); private string GetExtensionAssemblyFullPath() { #if NETSTANDARD Assert.NotNull(typeof(FooLayout)); return typeof(FooLayout).GetTypeInfo().Assembly.Location; #else return extensionAssemblyFullPath1; #endif } [Fact] public void ExtensionTest1() { Assert.NotNull(typeof(FooLayout)); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>"); Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest2() { var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <extensions> <add assembly='" + extensionAssemblyName1 + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> <when condition='myrandom(10)==3' action='Log' /> </filters> </logger> </rules> </nlog>"); Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(2, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter; Assert.NotNull(cbf); Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString()); } [Fact] public void ExtensionWithPrefixTest() { var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <extensions> <add prefix='myprefix' assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='t' type='myprefix.MyTarget' /> <target name='d1' type='Debug' layout='${myprefix.foo}' /> <target name='d2' type='Debug'> <layout type='myprefix.FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <myprefix.whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>"); Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest4() { Assert.NotNull(typeof(FooLayout)); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <extensions> <add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayout).AssemblyQualifiedName + @"' /> <add type='" + typeof(FooLayoutRenderer).AssemblyQualifiedName + @"' /> <add type='" + typeof(WhenFooFilter).AssemblyQualifiedName + @"' /> </extensions> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> </nlog>"); Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionTest_extensions_not_top_and_used() { Assert.NotNull(typeof(FooLayout)); var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='t' type='MyTarget' /> <target name='d1' type='Debug' layout='${foo}' /> <target name='d2' type='Debug'> <layout type='FooLayout' x='1'> </layout> </target> </targets> <rules> <logger name='*' writeTo='t'> <filters> <whenFoo x='44' action='Ignore' /> </filters> </logger> </rules> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> </nlog>"); Target myTarget = configuration.FindTargetByName("t"); Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName); var d1Target = (DebugTarget)configuration.FindTargetByName("d1"); var layout = d1Target.Layout as SimpleLayout; Assert.NotNull(layout); Assert.Single(layout.Renderers); Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName); var d2Target = (DebugTarget)configuration.FindTargetByName("d2"); Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName); Assert.Equal(1, configuration.LoggingRules[0].Filters.Count); Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidType() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add type='some_type_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => CreateConfigurationFromString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssembly() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => CreateConfigurationFromString(configXml)); } [Fact] public void ExtensionShouldThrowNLogConfiguratonExceptionWhenRegisteringInvalidAssemblyFile() { var configXml = @" <nlog throwConfigExceptions='true'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; Assert.Throws<NLogConfigurationException>(() => CreateConfigurationFromString(configXml)); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidTypeIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add type='some_type_that_doesnt_exist'/> <add assembly='NLog'/> </extensions> </nlog>"; CreateConfigurationFromString(configXml); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assembly='some_assembly_that_doesnt_exist'/> </extensions> </nlog>"; CreateConfigurationFromString(configXml); } [Fact] public void ExtensionShouldNotThrowWhenRegisteringInvalidAssemblyFileIfThrowConfigExceptionsFalse() { var configXml = @" <nlog throwConfigExceptions='false'> <extensions> <add assemblyfile='some_file_that_doesnt_exist'/> </extensions> </nlog>"; CreateConfigurationFromString(configXml); } [Fact] public void CustomXmlNamespaceTest() { var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true' xmlns:foo='http://bar'> <targets> <target name='d' type='foo:Debug' /> </targets> </nlog>"); var d1Target = (DebugTarget)configuration.FindTargetByName("d"); Assert.NotNull(d1Target); } [Fact] public void Extension_should_be_auto_loaded_when_following_NLog_dll_format() { try { var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>"); var autoLoadedTarget = configuration.FindTargetByName("t"); Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().FullName); } finally { ConfigurationItemFactory.Default.Clear(); ConfigurationItemFactory.Default = null; //build new factory next time } } [Theory] [InlineData(true)] [InlineData(false)] public void Extension_loading_could_be_canceled(bool cancel) { EventHandler<AssemblyLoadingEventArgs> onAssemblyLoading = (sender, e) => { if (e.Assembly.FullName.Contains("NLogAutoLoadExtension")) { e.Cancel = cancel; } }; try { ConfigurationItemFactory.Default = null; //build new factory next time ConfigurationItemFactory.AssemblyLoading += onAssemblyLoading; var configuration = CreateConfigurationFromString(@" <nlog throwExceptions='false'> <targets> <target name='t' type='AutoLoadTarget' /> </targets> <rules> <logger name='*' writeTo='t'> </logger> </rules> </nlog>"); var autoLoadedTarget = configuration.FindTargetByName("t"); if (cancel) { Assert.Null(autoLoadedTarget); } else { Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().FullName); } } finally { //cleanup ConfigurationItemFactory.AssemblyLoading -= onAssemblyLoading; ConfigurationItemFactory.Default.Clear(); ConfigurationItemFactory.Default = null; //build new factory next time } } [Fact] public void Extensions_NLogPackageLoader_should_beCalled() { try { var writer = new StringWriter(); InternalLogger.LogWriter = writer; InternalLogger.LogLevel = LogLevel.Debug; //reload ConfigurationItemFactory ConfigurationItemFactory.Default = null; var fact = ConfigurationItemFactory.Default; //also throw exceptions LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> </nlog>"); var logs = writer.ToString(); Assert.Contains("Preload succesfully invoked for 'LoaderTestInternal.NLogPackageLoader'", logs); Assert.Contains("Preload succesfully invoked for 'LoaderTestPublic.NLogPackageLoader'", logs); Assert.Contains("Preload succesfully invoked for 'LoaderTestPrivateNestedStatic.SomeType+NLogPackageLoader'", logs); Assert.Contains("Preload succesfully invoked for 'LoaderTestPrivateNested.SomeType+NLogPackageLoader'", logs); //4 times succesful Assert.Equal(4, Regex.Matches(logs, Regex.Escape("Preload succesfully invoked for '")).Count); } finally { InternalLogger.Reset(); } } [Fact] public void ImplicitConversionOperatorTest() { var config = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <extensions> <add assemblyFile='" + GetExtensionAssemblyFullPath() + @"' /> </extensions> <targets> <target name='myTarget' type='MyTarget' layout='123' /> </targets> <rules> <logger name='*' level='Debug' writeTo='myTarget' /> </rules> </nlog>"); var target = config.FindTargetByName<MyTarget>("myTarget"); Assert.NotNull(target); Assert.Equal(123, target.Layout.X); } } }
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Modes { /** * Implements OpenPGP's rather strange version of Cipher-FeedBack (CFB) mode * on top of a simple cipher. This class assumes the IV has been prepended * to the data stream already, and just accomodates the reset after * (blockSize + 2) bytes have been read. * <p> * For further info see <a href="http://www.ietf.org/rfc/rfc2440.html">RFC 2440</a>. * </p> */ public class OpenPgpCfbBlockCipher : IBlockCipher { private byte[] IV; private byte[] FR; private byte[] FRE; private readonly IBlockCipher cipher; private readonly int blockSize; private int count; private bool forEncryption; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. */ public OpenPgpCfbBlockCipher( IBlockCipher cipher) { this.cipher = cipher; this.blockSize = cipher.GetBlockSize(); this.IV = new byte[blockSize]; this.FR = new byte[blockSize]; this.FRE = new byte[blockSize]; } /** * return the underlying block cipher that we are wrapping. * * @return the underlying block cipher that we are wrapping. */ public IBlockCipher GetUnderlyingCipher() { return cipher; } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/PGPCFB" * and the block size in bits. */ public string AlgorithmName { get { return cipher.AlgorithmName + "/OpenPGPCFB"; } } public bool IsPartialBlockOkay { get { return true; } } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int GetBlockSize() { return cipher.GetBlockSize(); } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { return (forEncryption) ? EncryptBlock(input, inOff, output, outOff) : DecryptBlock(input, inOff, output, outOff); } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void Reset() { count = 0; Array.Copy(IV, 0, FR, 0, FR.Length); cipher.Reset(); } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param parameters the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; if (parameters is ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)parameters; byte[] iv = ivParam.GetIV(); if (iv.Length < IV.Length) { // prepend the supplied IV with zeros (per FIPS PUB 81) Array.Copy(iv, 0, IV, IV.Length - iv.Length, iv.Length); for (int i = 0; i < IV.Length - iv.Length; i++) { IV[i] = 0; } } else { Array.Copy(iv, 0, IV, 0, IV.Length); } parameters = ivParam.Parameters; } Reset(); cipher.Init(true, parameters); } /** * Encrypt one byte of data according to CFB mode. * @param data the byte to encrypt * @param blockOff offset in the current block * @returns the encrypted byte */ private byte EncryptByte(byte data, int blockOff) { return (byte)(FRE[blockOff] ^ data); } /** * Do the appropriate processing for CFB IV mode encryption. * * @param in the array containing the data to be encrypted. * @param inOff offset into the in array the data starts at. * @param out the array the encrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ private int EncryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + blockSize) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } if (count > blockSize) { FR[blockSize - 2] = outBytes[outOff] = EncryptByte(input[inOff], blockSize - 2); FR[blockSize - 1] = outBytes[outOff + 1] = EncryptByte(input[inOff + 1], blockSize - 1); cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 2; n < blockSize; n++) { FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2); } } else if (count == 0) { cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 0; n < blockSize; n++) { FR[n] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n); } count += blockSize; } else if (count == blockSize) { cipher.ProcessBlock(FR, 0, FRE, 0); outBytes[outOff] = EncryptByte(input[inOff], 0); outBytes[outOff + 1] = EncryptByte(input[inOff + 1], 1); // // do reset // Array.Copy(FR, 2, FR, 0, blockSize - 2); Array.Copy(outBytes, outOff, FR, blockSize - 2, 2); cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 2; n < blockSize; n++) { FR[n - 2] = outBytes[outOff + n] = EncryptByte(input[inOff + n], n - 2); } count += blockSize; } return blockSize; } /** * Do the appropriate processing for CFB IV mode decryption. * * @param in the array containing the data to be decrypted. * @param inOff offset into the in array the data starts at. * @param out the array the encrypted data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception InvalidOperationException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ private int DecryptBlock( byte[] input, int inOff, byte[] outBytes, int outOff) { if ((inOff + blockSize) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + blockSize) > outBytes.Length) { throw new DataLengthException("output buffer too short"); } if (count > blockSize) { byte inVal = input[inOff]; FR[blockSize - 2] = inVal; outBytes[outOff] = EncryptByte(inVal, blockSize - 2); inVal = input[inOff + 1]; FR[blockSize - 1] = inVal; outBytes[outOff + 1] = EncryptByte(inVal, blockSize - 1); cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 2; n < blockSize; n++) { inVal = input[inOff + n]; FR[n - 2] = inVal; outBytes[outOff + n] = EncryptByte(inVal, n - 2); } } else if (count == 0) { cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 0; n < blockSize; n++) { FR[n] = input[inOff + n]; outBytes[n] = EncryptByte(input[inOff + n], n); } count += blockSize; } else if (count == blockSize) { cipher.ProcessBlock(FR, 0, FRE, 0); byte inVal1 = input[inOff]; byte inVal2 = input[inOff + 1]; outBytes[outOff ] = EncryptByte(inVal1, 0); outBytes[outOff + 1] = EncryptByte(inVal2, 1); Array.Copy(FR, 2, FR, 0, blockSize - 2); FR[blockSize - 2] = inVal1; FR[blockSize - 1] = inVal2; cipher.ProcessBlock(FR, 0, FRE, 0); for (int n = 2; n < blockSize; n++) { byte inVal = input[inOff + n]; FR[n - 2] = inVal; outBytes[outOff + n] = EncryptByte(inVal, n - 2); } count += blockSize; } return blockSize; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Media; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudioTools.MockVsTests { #if DEV14_OR_LATER #pragma warning disable 0618 #endif internal class MockSmartTagSession : ISmartTagSession { private ITrackingSpan _applicableToSpan; private ImageSource _iconSource; private SmartTagState _state; private ITrackingSpan _tagSpan; private readonly MockSmartTagBroker _broker; private readonly ObservableCollection<SmartTagActionSet> _actionSets = new ObservableCollection<SmartTagActionSet>(); private readonly PropertyCollection _properties = new PropertyCollection(); public MockSmartTagSession(MockSmartTagBroker broker) { _broker = broker; } public ObservableCollection<SmartTagActionSet> ActionSets { get { return _actionSets; } } ReadOnlyObservableCollection<SmartTagActionSet> ISmartTagSession.ActionSets { get { return new ReadOnlyObservableCollection<SmartTagActionSet>(_actionSets); } } private void Raise(EventHandler evt) { if (evt != null) { evt(this, EventArgs.Empty); } } public ITrackingSpan ApplicableToSpan { get { return _applicableToSpan; } set { if (_applicableToSpan != value) { _applicableToSpan = value; Raise(ApplicableToSpanChanged); } } } public event EventHandler ApplicableToSpanChanged; public ImageSource IconSource { get { return _iconSource; } set { if (_iconSource != value) { _iconSource = value; Raise(IconSourceChanged); } } } public event EventHandler IconSourceChanged; public SmartTagState State { get { return _state; } set { if (_state != value) { _state = value; Raise(StateChanged); } } } public event EventHandler StateChanged; public ITrackingSpan TagSpan { get { return _tagSpan; } set { if (_tagSpan != value) { _tagSpan = value; Raise(TagSpanChanged); } } } public event EventHandler TagSpanChanged; public string TagText { get; set; } public SmartTagType Type { get; set; } public void Collapse() { throw new NotImplementedException(); } public void Dismiss() { if (IsDismissed == false) { IsDismissed = true; Raise(Dismissed); } } public event EventHandler Dismissed; public SnapshotPoint? GetTriggerPoint(ITextSnapshot textSnapshot) { return TriggerPoint.GetPoint(textSnapshot); } public ITrackingPoint GetTriggerPoint(ITextBuffer textBuffer) { return TriggerPoint; } public ITrackingPoint TriggerPoint { get; set; } public bool IsDismissed { get; set; } public bool Match() { throw new NotImplementedException(); } public IIntellisensePresenter Presenter { get { throw new NotImplementedException(); } set { Raise(PresenterChanged); } } public event EventHandler PresenterChanged; public void Recalculate() { if (_broker != null) { var sources = new List<ISmartTagSource>(); foreach (var p in _broker.SourceProviders) { var source = p.TryCreateSmartTagSource(TextView.TextBuffer); if (source != null) { sources.Add(source); } } var sets = new List<SmartTagActionSet>(); foreach (var source in sources) { source.AugmentSmartTagSession(this, sets); } _actionSets.Clear(); foreach (var set in sets) { if (set.Actions.Any()) { _actionSets.Add(set); } } } if (!_actionSets.Any()) { Dismiss(); } else { Raise(Recalculated); } } public event EventHandler Recalculated; public void Start() { Recalculate(); } public ITextView TextView { get; set; } public PropertyCollection Properties { get { return _properties; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type Complex with 2 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct cmat2 : IReadOnlyList<Complex>, IEquatable<cmat2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public Complex m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public Complex m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public Complex m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public Complex m11; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public cmat2(Complex m00, Complex m01, Complex m10, Complex m11) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } /// <summary> /// Constructs this matrix from a cmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a cmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public cmat2(cvec2 c0, cvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public Complex[,] Values => new[,] { { m00, m01 }, { m10, m11 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public Complex[] Values1D => new[] { m00, m01, m10, m11 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public cvec2 Column0 { get { return new cvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public cvec2 Column1 { get { return new cvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public cvec2 Row0 { get { return new cvec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public cvec2 Row1 { get { return new cvec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static cmat2 Zero { get; } = new cmat2(Complex.Zero, Complex.Zero, Complex.Zero, Complex.Zero); /// <summary> /// Predefined all-ones matrix /// </summary> public static cmat2 Ones { get; } = new cmat2(Complex.One, Complex.One, Complex.One, Complex.One); /// <summary> /// Predefined identity matrix /// </summary> public static cmat2 Identity { get; } = new cmat2(Complex.One, Complex.Zero, Complex.Zero, Complex.One); /// <summary> /// Predefined all-imaginary-ones matrix /// </summary> public static cmat2 ImaginaryOnes { get; } = new cmat2(Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne, Complex.ImaginaryOne); /// <summary> /// Predefined diagonal-imaginary-one matrix /// </summary> public static cmat2 ImaginaryIdentity { get; } = new cmat2(Complex.ImaginaryOne, Complex.Zero, Complex.Zero, Complex.ImaginaryOne); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<Complex> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 2 = 4). /// </summary> public int Count => 4; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public Complex this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public Complex this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(cmat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is cmat2 && Equals((cmat2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(cmat2 lhs, cmat2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(cmat2 lhs, cmat2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public cmat2 Transposed => new cmat2(m00, m10, m01, m11); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt(((m00.LengthSqr() + m01.LengthSqr()) + (m10.LengthSqr() + m11.LengthSqr()))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => ((m00.LengthSqr() + m01.LengthSqr()) + (m10.LengthSqr() + m11.LengthSqr())); /// <summary> /// Returns the sum of all fields. /// </summary> public Complex Sum => ((m00 + m01) + (m10 + m11)); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt(((m00.LengthSqr() + m01.LengthSqr()) + (m10.LengthSqr() + m11.LengthSqr()))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => ((m00.Magnitude + m01.Magnitude) + (m10.Magnitude + m11.Magnitude)); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt(((m00.LengthSqr() + m01.LengthSqr()) + (m10.LengthSqr() + m11.LengthSqr()))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public Complex NormMax => Math.Max(Math.Max(Math.Max(m00.Magnitude, m01.Magnitude), m10.Magnitude), m11.Magnitude); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((Math.Pow((double)m00.Magnitude, p) + Math.Pow((double)m01.Magnitude, p)) + (Math.Pow((double)m10.Magnitude, p) + Math.Pow((double)m11.Magnitude, p))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public Complex Determinant => m00 * m11 - m10 * m01; /// <summary> /// Returns the adjunct of this matrix. /// </summary> public cmat2 Adjugate => new cmat2(m11, -m01, -m10, m00); /// <summary> /// Returns the inverse of this matrix (use with caution). /// </summary> public cmat2 Inverse => Adjugate / Determinant; /// <summary> /// Executes a matrix-matrix-multiplication cmat2 * cmat2 -> cmat2. /// </summary> public static cmat2 operator*(cmat2 lhs, cmat2 rhs) => new cmat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication cmat2 * cmat3x2 -> cmat3x2. /// </summary> public static cmat3x2 operator*(cmat2 lhs, cmat3x2 rhs) => new cmat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication cmat2 * cmat4x2 -> cmat4x2. /// </summary> public static cmat4x2 operator*(cmat2 lhs, cmat4x2 rhs) => new cmat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static cvec2 operator*(cmat2 m, cvec2 v) => new cvec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y)); /// <summary> /// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution). /// </summary> public static cmat2 operator/(cmat2 A, cmat2 B) => A * B.Inverse; /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static cmat2 CompMul(cmat2 A, cmat2 B) => new cmat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static cmat2 CompDiv(cmat2 A, cmat2 B) => new cmat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static cmat2 CompAdd(cmat2 A, cmat2 B) => new cmat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static cmat2 CompSub(cmat2 A, cmat2 B) => new cmat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static cmat2 operator+(cmat2 lhs, cmat2 rhs) => new cmat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static cmat2 operator+(cmat2 lhs, Complex rhs) => new cmat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static cmat2 operator+(Complex lhs, cmat2 rhs) => new cmat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static cmat2 operator-(cmat2 lhs, cmat2 rhs) => new cmat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static cmat2 operator-(cmat2 lhs, Complex rhs) => new cmat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static cmat2 operator-(Complex lhs, cmat2 rhs) => new cmat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static cmat2 operator/(cmat2 lhs, Complex rhs) => new cmat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static cmat2 operator/(Complex lhs, cmat2 rhs) => new cmat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static cmat2 operator*(cmat2 lhs, Complex rhs) => new cmat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static cmat2 operator*(Complex lhs, cmat2 rhs) => new cmat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11); } }
// 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.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Security.Cryptography.Encryption.Tests.Asymmetric { public static partial class CryptoStreamTests { [Fact] public static void Ctor() { var transform = new IdentityTransform(1, 1, true); AssertExtensions.Throws<ArgumentException>(null, () => new CryptoStream(new MemoryStream(), transform, (CryptoStreamMode)12345)); AssertExtensions.Throws<ArgumentException>(null, "stream", () => new CryptoStream(new MemoryStream(new byte[0], writable: false), transform, CryptoStreamMode.Write)); AssertExtensions.Throws<ArgumentException>(null, "stream", () => new CryptoStream(new CryptoStream(new MemoryStream(new byte[0]), transform, CryptoStreamMode.Write), transform, CryptoStreamMode.Read)); } [Theory] [InlineData(64, 64, true)] [InlineData(64, 128, true)] [InlineData(128, 64, true)] [InlineData(1, 1, true)] [InlineData(37, 24, true)] [InlineData(128, 3, true)] [InlineData(8192, 64, true)] [InlineData(64, 64, false)] public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => encryptStream.Length); Assert.Throws<NotSupportedException>(() => encryptStream.Position); Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => encryptStream.Write(new byte[3], 1, 4)); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => decryptStream.Length); Assert.Throws<NotSupportedException>(() => decryptStream.Position); Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); AssertExtensions.Throws<ArgumentException>(null, () => decryptStream.Read(new byte[3], 1, 4)); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } } [Fact] public static void NestedCryptoStreams() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream1 = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) using (CryptoStream encryptStream2 = new CryptoStream(encryptStream1, encryptor, CryptoStreamMode.Write)) { encryptStream2.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); } } [Fact] public static void Clear() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Clear(); Assert.Throws<NotSupportedException>(() => encryptStream.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5)); } } [Fact] public static void FlushAsync() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false)); Assert.False(waitable.IsCanceled); encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); waitable = encryptStream.FlushAsync(new Threading.CancellationToken(true)); Assert.True(waitable.IsCanceled); } } [Fact] public static void FlushCalledOnFlushAsync_DeriveClass() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) using (MinimalCryptoStream encryptStream = new MinimalCryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5); Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false)); Assert.False(waitable.IsCanceled); waitable.Wait(); Assert.True(encryptStream.FlushCalled); } } [Fact] public static void MultipleDispose() { ICryptoTransform encryptor = new IdentityTransform(1, 1, true); using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) { encryptStream.Dispose(); } Assert.False(output.CanRead); } #if NETCOREAPP using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: false)) { encryptStream.Dispose(); } Assert.False(output.CanRead); } using (MemoryStream output = new MemoryStream()) { using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: true)) { encryptStream.Dispose(); } Assert.True(output.CanRead); } #endif } private const string LoremText = @"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy augue. Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy."; private sealed class IdentityTransform : ICryptoTransform { private readonly int _inputBlockSize, _outputBlockSize; private readonly bool _canTransformMultipleBlocks; private readonly object _lock = new object(); private long _writePos, _readPos; private MemoryStream _stream; internal IdentityTransform(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { _inputBlockSize = inputBlockSize; _outputBlockSize = outputBlockSize; _canTransformMultipleBlocks = canTransformMultipleBlocks; _stream = new MemoryStream(); } public bool CanReuseTransform { get { return true; } } public bool CanTransformMultipleBlocks { get { return _canTransformMultipleBlocks; } } public int InputBlockSize { get { return _inputBlockSize; } } public int OutputBlockSize { get { return _outputBlockSize; } } public void Dispose() { } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { lock (_lock) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _writePos = _stream.Position; _stream.Position = _readPos; int copied = _stream.Read(outputBuffer, outputOffset, outputBuffer.Length - outputOffset); _readPos = _stream.Position; return copied; } } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { lock (_lock) { _stream.Position = _writePos; _stream.Write(inputBuffer, inputOffset, inputCount); _stream.Position = _readPos; long len = _stream.Length - _stream.Position; byte[] outputBuffer = new byte[len]; _stream.Read(outputBuffer, 0, outputBuffer.Length); _stream = new MemoryStream(); _writePos = 0; _readPos = 0; return outputBuffer; } } } public class MinimalCryptoStream : CryptoStream { public bool FlushCalled; public MinimalCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : base(stream, transform, mode) { } public override void Flush() { FlushCalled = true; base.Flush(); } } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Cassandra.Tasks; using Microsoft.IO; namespace Cassandra.Connections { /// <summary> /// Represents a Tcp connection to a host. /// It emits Read and WriteCompleted events when data is received. /// Similar to Netty's Channel or Node.js's net.Socket /// It handles TLS validation and encryption when required. /// </summary> internal class TcpSocket : ITcpSocket { public static readonly Logger Logger = new Logger(typeof(TcpSocket)); private Socket _socket; private SocketAsyncEventArgs _receiveSocketEvent; private SocketAsyncEventArgs _sendSocketEvent; private Stream _socketStream; private byte[] _receiveBuffer; private volatile bool _isClosing; private Action _writeFlushCallback; public IConnectionEndPoint EndPoint { get; protected set; } public SocketOptions Options { get; protected set; } public SSLOptions SSLOptions { get; set; } /// <summary> /// Event that gets fired when new data is received. /// </summary> public event Action<byte[], int> Read; /// <summary> /// Event that gets fired when a write async request have been completed. /// </summary> public event Action WriteCompleted; /// <summary> /// Event that is fired when the host is closing the connection. /// </summary> public event Action Closing; public event Action<Exception, SocketError?> Error; /// <summary> /// Creates a new instance of TcpSocket using the endpoint and options provided. /// </summary> public TcpSocket(IConnectionEndPoint endPoint, SocketOptions options, SSLOptions sslOptions) { EndPoint = endPoint; Options = options; SSLOptions = sslOptions; } /// <summary> /// Get this socket's local address. /// </summary> /// <returns>The socket's local address.</returns> public IPEndPoint GetLocalIpEndPoint() { try { var s = _socket; return (IPEndPoint)s?.LocalEndPoint; } catch (Exception ex) { TcpSocket.Logger.Warning("Exception thrown when trying to get LocalIpEndpoint: {0}", ex.ToString()); return null; } } /// <summary> /// Initializes the socket options /// </summary> public void Init() { _socket = new Socket(EndPoint.SocketIpEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = Options.ConnectTimeoutMillis }; if (Options.KeepAlive != null) { _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, Options.KeepAlive.Value); } if (Options.SoLinger != null) { _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, Options.SoLinger.Value)); } if (Options.ReceiveBufferSize != null) { _socket.ReceiveBufferSize = Options.ReceiveBufferSize.Value; } if (Options.SendBufferSize != null) { _socket.SendBufferSize = Options.SendBufferSize.Value; } if (Options.TcpNoDelay != null) { _socket.NoDelay = Options.TcpNoDelay.Value; } _receiveBuffer = new byte[_socket.ReceiveBufferSize]; } /// <summary> /// Connects asynchronously to the host and starts reading /// </summary> /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception> public async Task<bool> Connect() { var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>( Options.ConnectTimeoutMillis, () => new SocketException((int)SocketError.TimedOut)); var socketConnectTask = tcs.Task; using (var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = EndPoint.SocketIpEndPoint }) { eventArgs.Completed += (sender, e) => { OnConnectComplete(tcs, e); }; var willCompleteAsync = _socket.ConnectAsync(eventArgs); if (!willCompleteAsync) { // Make the task complete asynchronously Task.Run(() => OnConnectComplete(tcs, eventArgs)).Forget(); } await socketConnectTask.ConfigureAwait(false); } if (SSLOptions != null) { return await ConnectSsl().ConfigureAwait(false); } // Prepare read and write // There are 2 modes: using SocketAsyncEventArgs (most performant) and Stream mode if (Options.UseStreamMode) { TcpSocket.Logger.Verbose("Socket connected, start reading using Stream interface"); //Stream mode: not the most performant but it is a choice _socketStream = new NetworkStream(_socket); ReceiveAsync(); return true; } TcpSocket.Logger.Verbose("Socket connected, start reading using SocketEventArgs interface"); //using SocketAsyncEventArgs _receiveSocketEvent = new SocketAsyncEventArgs(); _receiveSocketEvent.SetBuffer(_receiveBuffer, 0, _receiveBuffer.Length); _receiveSocketEvent.Completed += OnReceiveCompleted; _sendSocketEvent = new SocketAsyncEventArgs(); _sendSocketEvent.Completed += OnSendCompleted; ReceiveAsync(); return true; } private void OnConnectComplete(TaskCompletionSource<bool> tcs, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { tcs.TrySetException(new SocketException((int)e.SocketError)); return; } tcs.TrySetResult(true); } private async Task<bool> ConnectSsl() { TcpSocket.Logger.Verbose("Socket connected, starting SSL client authentication"); //Stream mode: not the most performant but it has ssl support TcpSocket.Logger.Verbose("Starting SSL authentication"); var sslStream = new SslStream(new NetworkStream(_socket), false, SSLOptions.RemoteCertValidationCallback, null); _socketStream = sslStream; // Use a timer to ensure that it does callback var tcs = TaskHelper.TaskCompletionSourceWithTimeout<bool>( Options.ConnectTimeoutMillis, () => new TimeoutException("The timeout period elapsed prior to completion of SSL authentication operation.")); sslStream.AuthenticateAsClientAsync(await EndPoint.GetServerNameAsync().ConfigureAwait(false), SSLOptions.CertificateCollection, SSLOptions.SslProtocol, SSLOptions.CheckCertificateRevocation) .ContinueWith(t => { if (t.Exception != null) { t.Exception.Handle(_ => true); // ReSharper disable once AssignNullToNotNullAttribute tcs.TrySetException(t.Exception.InnerException); return; } tcs.TrySetResult(true); }, TaskContinuationOptions.ExecuteSynchronously) // Avoid awaiting as it may never yield .Forget(); await tcs.Task.ConfigureAwait(false); TcpSocket.Logger.Verbose("SSL authentication successful"); ReceiveAsync(); return true; } /// <summary> /// Begins an asynchronous request to receive data from a connected Socket object. /// It handles the exceptions in case there is one. /// </summary> protected virtual void ReceiveAsync() { //Receive the next bytes if (_receiveSocketEvent != null) { var willRaiseEvent = true; try { willRaiseEvent = _socket.ReceiveAsync(_receiveSocketEvent); } catch (ObjectDisposedException) { OnError(null, SocketError.NotConnected); } catch (NullReferenceException) { // Mono can throw a NRE when being disposed concurrently // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185 // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L1873-L1874 OnError(null, SocketError.NotConnected); } catch (Exception ex) { OnError(ex); } if (!willRaiseEvent) { OnReceiveCompleted(this, _receiveSocketEvent); } } else { // Stream mode try { _socketStream .ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length) .ContinueWith(OnReceiveStreamCallback, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception ex) { HandleStreamException(ex); } } } protected virtual void OnError(Exception ex, SocketError? socketError = null) { Error?.Invoke(ex, socketError); } /// <summary> /// Handles the receive completed event /// </summary> protected void OnReceiveCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { //There was a socket error or the connection is being closed. OnError(null, e.SocketError); return; } if (e.BytesTransferred == 0) { OnClosing(); return; } //Emit event Read?.Invoke(e.Buffer, e.BytesTransferred); ReceiveAsync(); } /// <summary> /// Handles the callback for Completed or Cancelled Task on Stream mode /// </summary> protected void OnReceiveStreamCallback(Task<int> readTask) { if (readTask.Exception != null) { readTask.Exception.Handle(_ => true); HandleStreamException(readTask.Exception.InnerException); return; } var bytesRead = readTask.Result; if (bytesRead == 0) { OnClosing(); return; } //Emit event try { Read?.Invoke(_receiveBuffer, bytesRead); } catch (Exception ex) { OnError(ex); } ReceiveAsync(); } /// <summary> /// Handles exceptions that the methods <c>NetworkStream.ReadAsync()</c> and <c>NetworkStream.WriteAsync()</c> can throw. /// </summary> private void HandleStreamException(Exception ex) { if (ex is IOException) { if (ex.InnerException is SocketException) { OnError((SocketException)ex.InnerException); return; } // Wrapped ObjectDisposedException and others: we can consider it as not connected OnError(null, SocketError.NotConnected); return; } if (ex is ObjectDisposedException) { // Wrapped ObjectDisposedException and others: we can consider it as not connected OnError(null, SocketError.NotConnected); return; } OnError(ex); } /// <summary> /// Handles the send completed event /// </summary> protected void OnSendCompleted(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { OnError(null, e.SocketError); } OnWriteFlushed(); WriteCompleted?.Invoke(); } /// <summary> /// Handles the continuation for WriteAsync faulted or Task on Stream mode /// </summary> protected void OnSendStreamCallback(Task writeTask) { if (writeTask.Exception != null) { writeTask.Exception.Handle(_ => true); HandleStreamException(writeTask.Exception.InnerException); return; } OnWriteFlushed(); WriteCompleted?.Invoke(); } protected void OnClosing() { _isClosing = true; Closing?.Invoke(); if (_receiveSocketEvent != null) { //It is safe to call SocketAsyncEventArgs.Dispose() more than once _sendSocketEvent.Dispose(); _receiveSocketEvent.Dispose(); } else if (_socketStream != null) { _socketStream.Dispose(); } //dereference to make the byte array GC-able as soon as possible _receiveBuffer = null; } private void OnWriteFlushed() { Interlocked.Exchange(ref _writeFlushCallback, null)?.Invoke(); } /// <summary> /// Sends data asynchronously /// </summary> public void Write(RecyclableMemoryStream stream, Action onBufferFlush) { Interlocked.Exchange(ref _writeFlushCallback, onBufferFlush); if (_isClosing) { OnError(new SocketException((int)SocketError.Shutdown)); OnWriteFlushed(); return; } if (_sendSocketEvent != null) { _sendSocketEvent.BufferList = stream.GetBufferList(); var isWritePending = false; try { isWritePending = _socket.SendAsync(_sendSocketEvent); } catch (ObjectDisposedException) { OnError(null, SocketError.NotConnected); } catch (NullReferenceException) { // Mono can throw a NRE when being disposed concurrently // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/SocketAsyncEventArgs.cs#L184-L185 // https://github.com/mono/mono/blob/b190f213a364a2793cc573e1bd9fae8be72296e4/mcs/class/System/System.Net.Sockets/Socket.cs#L2477-L2478 OnError(null, SocketError.NotConnected); } catch (Exception ex) { OnError(ex); } if (!isWritePending) { OnSendCompleted(this, _sendSocketEvent); } } else { var length = (int)stream.Length; try { _socketStream .WriteAsync(stream.GetBuffer(), 0, length) .ContinueWith(OnSendStreamCallback, TaskContinuationOptions.ExecuteSynchronously); } catch (Exception ex) { HandleStreamException(ex); } } } public void Kill() { _socket.Shutdown(SocketShutdown.Send); } public void Dispose() { if (_socket == null) { return; } _isClosing = true; try { //Try to close it. //Some operations could make the socket to dispose itself _socket.Shutdown(SocketShutdown.Both); } catch { // Shutdown might throw an exception if the socket was not open-open } try { _socket.Dispose(); } catch { //We should not mind if socket's Close method throws an exception } if (_receiveSocketEvent != null) { //It is safe to call SocketAsyncEventArgs.Dispose() more than once //Also checked: .NET 4.0, .NET 4.5 and Mono 3.10 and 3.12 implementations _sendSocketEvent.Dispose(); _receiveSocketEvent.Dispose(); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using log4net.Config; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Land; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups; using OpenSim.Tests.Common; using ArchiveConstants = OpenSim.Framework.Serialization.ArchiveConstants; using TarArchiveReader = OpenSim.Framework.Serialization.TarArchiveReader; using TarArchiveWriter = OpenSim.Framework.Serialization.TarArchiveWriter; using RegionSettings = OpenSim.Framework.RegionSettings; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.CoreModules.World.Archiver.Tests { [TestFixture] public class ArchiverTests : OpenSimTestCase { private Guid m_lastRequestId; private string m_lastErrorMessage; protected SceneHelpers m_sceneHelpers; protected TestScene m_scene; protected ArchiverModule m_archiverModule; protected SerialiserModule m_serialiserModule; protected TaskInventoryItem m_soundItem; private AutoResetEvent m_oarEvent = new AutoResetEvent(false); [SetUp] public override void SetUp() { base.SetUp(); m_archiverModule = new ArchiverModule(); m_serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); m_sceneHelpers = new SceneHelpers(); m_scene = m_sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(m_scene, m_archiverModule, m_serialiserModule, terrainModule); } private void LoadCompleted(Guid requestId, List<UUID> loadedScenes, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on LoadCompleted"); m_oarEvent.Set(); } } private void SaveCompleted(Guid requestId, string errorMessage) { lock (this) { m_lastRequestId = requestId; m_lastErrorMessage = errorMessage; Console.WriteLine("About to pulse ArchiverTests on SaveCompleted"); m_oarEvent.Set(); } } protected SceneObjectPart CreateSceneObjectPart1() { string partName = "My Little Pony"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000015"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); Vector3 groupPosition = new Vector3(10, 20, 30); Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); rotationOffset.Normalize(); // Vector3 offsetPosition = new Vector3(5, 10, 15); return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, Vector3.Zero) { Name = partName }; } protected SceneObjectPart CreateSceneObjectPart2() { string partName = "Action Man"; UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000016"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateCylinder(); Vector3 groupPosition = new Vector3(90, 80, 70); Quaternion rotationOffset = new Quaternion(60, 70, 80, 90); rotationOffset.Normalize(); Vector3 offsetPosition = new Vector3(20, 25, 30); return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName }; } private void CreateTestObjects(Scene scene, out SceneObjectGroup sog1, out SceneObjectGroup sog2, out UUID ncAssetUuid) { SceneObjectPart part1 = CreateSceneObjectPart1(); sog1 = new SceneObjectGroup(part1); scene.AddNewSceneObject(sog1, false); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); ncAssetUuid = UUID.Random(); UUID ncItemUuid = UUID.Random(); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; SceneObjectPart part2 = CreateSceneObjectPart2(); sog2 = new SceneObjectGroup(part2); part2.Inventory.AddInventoryItem(ncItem, true); scene.AddNewSceneObject(sog2, false); } private static void CreateSoundAsset(TarArchiveWriter tar, Assembly assembly, string soundDataResourceName, out byte[] soundData, out UUID soundUuid) { using (Stream resource = assembly.GetManifestResourceStream(soundDataResourceName)) { using (BinaryReader br = new BinaryReader(resource)) { // FIXME: Use the inspector instead soundData = br.ReadBytes(99999999); soundUuid = UUID.Parse("00000000-0000-0000-0000-000000000001"); string soundAssetFileName = ArchiveConstants.ASSETS_PATH + soundUuid + ArchiveConstants.ASSET_TYPE_TO_EXTENSION[(sbyte)AssetType.SoundWAV]; tar.WriteFile(soundAssetFileName, soundData); /* AssetBase soundAsset = AssetHelpers.CreateAsset(soundUuid, soundData); scene.AssetService.Store(soundAsset); asset1FileName = ArchiveConstants.ASSETS_PATH + soundUuid + ".wav"; */ } } } /// <summary> /// Test saving an OpenSim Region Archive. /// </summary> [Test] public void TestSaveOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup sog1; SceneObjectGroup sog2; UUID ncAssetUuid; CreateTestObjects(m_scene, out sog1, out sog2, out ncAssetUuid); MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); m_oarEvent.Reset(); m_archiverModule.ArchiveRegion(archiveWriteStream, requestId); //AssetServerBase assetServer = (AssetServerBase)scene.CommsManager.AssetCache.AssetServer; //while (assetServer.HasWaitingRequests()) // assetServer.ProcessNextRequest(); m_oarEvent.WaitOne(60000); Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); bool gotNcAssetFile = false; string expectedNcAssetFileName = string.Format("{0}_{1}", ncAssetUuid, "notecard.txt"); List<string> foundPaths = new List<string>(); List<string> expectedPaths = new List<string>(); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); Assert.That(fileName, Is.EqualTo(expectedNcAssetFileName)); gotNcAssetFile = true; } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths.Add(filePath); } } Assert.That(gotNcAssetFile, Is.True, "No notecard asset file in archive"); Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test saving an OpenSim Region Archive with the no assets option /// </summary> [Test] public void TestSaveOarNoAssets() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectPart part1 = CreateSceneObjectPart1(); SceneObjectGroup sog1 = new SceneObjectGroup(part1); m_scene.AddNewSceneObject(sog1, false); SceneObjectPart part2 = CreateSceneObjectPart2(); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000"); UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000"); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); SceneObjectGroup sog2 = new SceneObjectGroup(part2); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; part2.Inventory.AddInventoryItem(ncItem, true); m_scene.AddNewSceneObject(sog2, false); MemoryStream archiveWriteStream = new MemoryStream(); Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); Dictionary<string, Object> options = new Dictionary<string, Object>(); options.Add("noassets", true); m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options); // Don't wait for completion - with --noassets save oar happens synchronously // Monitor.Wait(this, 60000); Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); List<string> foundPaths = new List<string>(); List<string> expectedPaths = new List<string>(); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths.Add(ArchiveHelpers.CreateObjectPath(sog2)); string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { Assert.Fail("Asset was found in saved oar of TestSaveOarNoAssets()"); } else if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths.Add(filePath); } } Assert.That(foundPaths, Is.EquivalentTo(expectedPaths)); // TODO: Test presence of more files and contents of files. } /// <summary> /// Test loading an OpenSim Region Archive. /// </summary> [Test] public void TestLoadOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); // Put in a random blank directory to check that this doesn't upset the load process tar.WriteDir("ignoreme"); // Also check that direct entries which will also have a file entry containing that directory doesn't // upset load tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); SceneObjectPart part1 = CreateSceneObjectPart1(); part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f); part1.SitTargetPosition = new Vector3(1, 2, 3); SceneObjectGroup object1 = new SceneObjectGroup(part1); // Let's put some inventory items into our object string soundItemName = "sound-item1"; UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002"); Type type = GetType(); Assembly assembly = type.Assembly; string soundDataResourceName = null; string[] names = assembly.GetManifestResourceNames(); foreach (string name in names) { if (name.EndsWith(".Resources.test-sound.wav")) soundDataResourceName = name; } Assert.That(soundDataResourceName, Is.Not.Null); byte[] soundData; UUID soundUuid; CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid); TaskInventoryItem item1 = new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName }; part1.Inventory.AddInventoryItem(item1, true); m_scene.AddNewSceneObject(object1, false); string object1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1.Name, Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), part1.UUID); tar.WriteFile(ArchiveConstants.OBJECTS_PATH + object1FileName, SceneObjectSerializer.ToXml2Format(object1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(archiveReadStream); m_oarEvent.WaitOne(60000); Assert.That(m_lastErrorMessage, Is.Null); TestLoadedRegion(part1, soundItemName, soundData); } /// <summary> /// Test loading an OpenSim Region Archive where the scene object parts are not ordered by link number (e.g. /// 2 can come after 3). /// </summary> [Test] public void TestLoadOarUnorderedParts() { TestHelpers.InMethod(); UUID ownerId = TestHelpers.ParseTail(0xaaaa); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(1, ownerId, "obj1-", 0x11); SceneObjectPart sop2 = SceneHelpers.CreateSceneObjectPart("obj1-Part2", TestHelpers.ParseTail(0x12), ownerId); SceneObjectPart sop3 = SceneHelpers.CreateSceneObjectPart("obj1-Part3", TestHelpers.ParseTail(0x13), ownerId); // Add the parts so they will be written out in reverse order to the oar sog1.AddPart(sop3); sop3.LinkNum = 3; sog1.AddPart(sop2); sop2.LinkNum = 2; tar.WriteFile( ArchiveConstants.CreateOarObjectPath(sog1.Name, sog1.UUID, sog1.AbsolutePosition), SceneObjectSerializer.ToXml2Format(sog1)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(archiveReadStream); m_oarEvent.WaitOne(60000); Assert.That(m_lastErrorMessage, Is.Null); SceneObjectPart part2 = m_scene.GetSceneObjectPart("obj1-Part2"); Assert.That(part2.LinkNum, Is.EqualTo(2)); SceneObjectPart part3 = m_scene.GetSceneObjectPart("obj1-Part3"); Assert.That(part3.LinkNum, Is.EqualTo(3)); } /// <summary> /// Test loading an OpenSim Region Archive saved with the --publish option. /// </summary> [Test] public void TestLoadPublishedOar() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); SceneObjectPart part1 = CreateSceneObjectPart1(); SceneObjectGroup sog1 = new SceneObjectGroup(part1); m_scene.AddNewSceneObject(sog1, false); SceneObjectPart part2 = CreateSceneObjectPart2(); AssetNotecard nc = new AssetNotecard(); nc.BodyText = "Hello World!"; nc.Encode(); UUID ncAssetUuid = new UUID("00000000-0000-0000-1000-000000000000"); UUID ncItemUuid = new UUID("00000000-0000-0000-1100-000000000000"); AssetBase ncAsset = AssetHelpers.CreateAsset(ncAssetUuid, AssetType.Notecard, nc.AssetData, UUID.Zero); m_scene.AssetService.Store(ncAsset); SceneObjectGroup sog2 = new SceneObjectGroup(part2); TaskInventoryItem ncItem = new TaskInventoryItem { Name = "ncItem", AssetID = ncAssetUuid, ItemID = ncItemUuid }; part2.Inventory.AddInventoryItem(ncItem, true); m_scene.AddNewSceneObject(sog2, false); MemoryStream archiveWriteStream = new MemoryStream(); m_scene.EventManager.OnOarFileSaved += SaveCompleted; Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); m_oarEvent.Reset(); m_archiverModule.ArchiveRegion( archiveWriteStream, requestId, new Dictionary<string, Object>() { { "wipe-owners", Boolean.TrueString } }); m_oarEvent.WaitOne(60000); Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); { UUID estateOwner = TestHelpers.ParseTail(0x4747); UUID objectOwner = TestHelpers.ParseTail(0x15); // Reload to new scene ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); SceneHelpers m_sceneHelpers2 = new SceneHelpers(); TestScene scene2 = m_sceneHelpers2.SetupScene(); SceneHelpers.SetupSceneModules(scene2, archiverModule, serialiserModule, terrainModule); // Make sure there's a valid owner for the owner we saved (this should have been wiped if the code is // behaving correctly UserAccountHelpers.CreateUserWithInventory(scene2, objectOwner); scene2.RegionInfo.EstateSettings.EstateOwner = estateOwner; scene2.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); archiverModule.DearchiveRegion(archiveReadStream); m_oarEvent.WaitOne(60000); Assert.That(m_lastErrorMessage, Is.Null); SceneObjectGroup loadedSog = scene2.GetSceneObjectGroup(part1.Name); Assert.That(loadedSog.OwnerID, Is.EqualTo(estateOwner)); Assert.That(loadedSog.LastOwnerID, Is.EqualTo(estateOwner)); } } /// <summary> /// Test OAR loading where the land parcel is group deeded. /// </summary> /// <remarks> /// In this situation, the owner ID is set to the group ID. /// </remarks> [Test] public void TestLoadOarDeededLand() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID landID = TestHelpers.ParseTail(0x10); MockGroupsServicesConnector groupsService = new MockGroupsServicesConnector(); IConfigSource configSource = new IniConfigSource(); IConfig config = configSource.AddConfig("Groups"); config.Set("Enabled", true); config.Set("Module", "GroupsModule"); config.Set("DebugEnabled", true); SceneHelpers.SetupSceneModules( m_scene, configSource, new object[] { new GroupsModule(), groupsService, new LandManagementModule() }); // Create group in scene for loading // FIXME: For now we'll put up with the issue that we'll get a group ID that varies across tests. UUID groupID = groupsService.CreateGroup(UUID.Zero, "group1", "", true, UUID.Zero, 3, true, true, true, UUID.Zero); // Construct OAR MemoryStream oarStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(oarStream); tar.WriteDir(ArchiveConstants.LANDDATA_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); LandObject lo = new LandObject(groupID, true, m_scene); lo.SetLandBitmap(lo.BasicFullRegionLandBitmap()); LandData ld = lo.LandData; ld.GlobalID = landID; string ldPath = ArchiveConstants.CreateOarLandDataPath(ld); Dictionary<string, object> options = new Dictionary<string, object>(); tar.WriteFile(ldPath, LandDataSerializer.Serialize(ld, options)); tar.Close(); oarStream = new MemoryStream(oarStream.ToArray()); // Load OAR m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(oarStream); m_oarEvent.WaitOne(60000); ILandObject rLo = m_scene.LandChannel.GetLandObject(16, 16); LandData rLd = rLo.LandData; Assert.That(rLd.GlobalID, Is.EqualTo(landID)); Assert.That(rLd.OwnerID, Is.EqualTo(groupID)); Assert.That(rLd.GroupID, Is.EqualTo(groupID)); Assert.That(rLd.IsGroupOwned, Is.EqualTo(true)); } /// <summary> /// Test loading the region settings of an OpenSim Region Archive. /// </summary> [Test] public void TestLoadOarRegionSettings() { TestHelpers.InMethod(); //log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty).CreateControlFile(new ArchiveScenesGroup())); RegionSettings rs = new RegionSettings(); rs.AgentLimit = 17; rs.AllowDamage = true; rs.AllowLandJoinDivide = true; rs.AllowLandResell = true; rs.BlockFly = true; rs.BlockShowInSearch = true; rs.BlockTerraform = true; rs.DisableCollisions = true; rs.DisablePhysics = true; rs.DisableScripts = true; rs.Elevation1NW = 15.9; rs.Elevation1NE = 45.3; rs.Elevation1SE = 49; rs.Elevation1SW = 1.9; rs.Elevation2NW = 4.5; rs.Elevation2NE = 19.2; rs.Elevation2SE = 9.2; rs.Elevation2SW = 2.1; rs.FixedSun = true; rs.SunPosition = 12.0; rs.ObjectBonus = 1.4; rs.RestrictPushing = true; rs.TerrainLowerLimit = 0.4; rs.TerrainRaiseLimit = 17.9; rs.TerrainTexture1 = UUID.Parse("00000000-0000-0000-0000-000000000020"); rs.TerrainTexture2 = UUID.Parse("00000000-0000-0000-0000-000000000040"); rs.TerrainTexture3 = UUID.Parse("00000000-0000-0000-0000-000000000060"); rs.TerrainTexture4 = UUID.Parse("00000000-0000-0000-0000-000000000080"); rs.UseEstateSun = true; rs.WaterHeight = 23; rs.TelehubObject = UUID.Parse("00000000-0000-0000-0000-111111111111"); rs.AddSpawnPoint(SpawnPoint.Parse("1,-2,0.33")); tar.WriteFile(ArchiveConstants.SETTINGS_PATH + "region1.xml", RegionSettingsSerializer.Serialize(rs)); tar.Close(); MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(archiveReadStream); m_oarEvent.WaitOne(60000); Assert.That(m_lastErrorMessage, Is.Null); RegionSettings loadedRs = m_scene.RegionInfo.RegionSettings; Assert.That(loadedRs.AgentLimit, Is.EqualTo(17)); Assert.That(loadedRs.AllowDamage, Is.True); Assert.That(loadedRs.AllowLandJoinDivide, Is.True); Assert.That(loadedRs.AllowLandResell, Is.True); Assert.That(loadedRs.BlockFly, Is.True); Assert.That(loadedRs.BlockShowInSearch, Is.True); Assert.That(loadedRs.BlockTerraform, Is.True); Assert.That(loadedRs.DisableCollisions, Is.True); Assert.That(loadedRs.DisablePhysics, Is.True); Assert.That(loadedRs.DisableScripts, Is.True); Assert.That(loadedRs.Elevation1NW, Is.EqualTo(15.9)); Assert.That(loadedRs.Elevation1NE, Is.EqualTo(45.3)); Assert.That(loadedRs.Elevation1SE, Is.EqualTo(49)); Assert.That(loadedRs.Elevation1SW, Is.EqualTo(1.9)); Assert.That(loadedRs.Elevation2NW, Is.EqualTo(4.5)); Assert.That(loadedRs.Elevation2NE, Is.EqualTo(19.2)); Assert.That(loadedRs.Elevation2SE, Is.EqualTo(9.2)); Assert.That(loadedRs.Elevation2SW, Is.EqualTo(2.1)); Assert.That(loadedRs.FixedSun, Is.True); Assert.AreEqual(12.0, loadedRs.SunPosition); Assert.That(loadedRs.ObjectBonus, Is.EqualTo(1.4)); Assert.That(loadedRs.RestrictPushing, Is.True); Assert.That(loadedRs.TerrainLowerLimit, Is.EqualTo(0.4)); Assert.That(loadedRs.TerrainRaiseLimit, Is.EqualTo(17.9)); Assert.That(loadedRs.TerrainTexture1, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000020"))); Assert.That(loadedRs.TerrainTexture2, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000040"))); Assert.That(loadedRs.TerrainTexture3, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000060"))); Assert.That(loadedRs.TerrainTexture4, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000080"))); Assert.That(loadedRs.UseEstateSun, Is.True); Assert.That(loadedRs.WaterHeight, Is.EqualTo(23)); Assert.AreEqual(UUID.Zero, loadedRs.TelehubObject); // because no object was found with the original UUID Assert.AreEqual(0, loadedRs.SpawnPoints().Count); } /// <summary> /// Test merging an OpenSim Region Archive into an existing scene /// </summary> //[Test] public void TestMergeOar() { TestHelpers.InMethod(); //XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); // string part2Name = "objectMerge"; // PrimitiveBaseShape part2Shape = PrimitiveBaseShape.CreateCylinder(); // Vector3 part2GroupPosition = new Vector3(90, 80, 70); // Quaternion part2RotationOffset = new Quaternion(60, 70, 80, 90); // Vector3 part2OffsetPosition = new Vector3(20, 25, 30); SceneObjectPart part2 = CreateSceneObjectPart2(); // Create an oar file that we can use for the merge { ArchiverModule archiverModule = new ArchiverModule(); SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); Scene scene = m_sceneHelpers.SetupScene(); SceneHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false); // Write out this scene scene.EventManager.OnOarFileSaved += SaveCompleted; m_oarEvent.Reset(); m_archiverModule.ArchiveRegion(archiveWriteStream); m_oarEvent.WaitOne(60000); } { SceneObjectPart part1 = CreateSceneObjectPart1(); m_scene.AddNewSceneObject(new SceneObjectGroup(part1), false); // Merge in the archive we created earlier byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); m_scene.EventManager.OnOarFileLoaded += LoadCompleted; Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); archiveOptions.Add("merge", null); m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(archiveReadStream, Guid.Empty, archiveOptions); m_oarEvent.WaitOne(60000); SceneObjectPart object1Existing = m_scene.GetSceneObjectPart(part1.Name); Assert.That(object1Existing, Is.Not.Null, "object1 was not present after merge"); Assert.That(object1Existing.Name, Is.EqualTo(part1.Name), "object1 names not identical after merge"); Assert.That(object1Existing.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal after merge"); SceneObjectPart object2PartMerged = m_scene.GetSceneObjectPart(part2.Name); Assert.That(object2PartMerged, Is.Not.Null, "object2 was not present after merge"); Assert.That(object2PartMerged.Name, Is.EqualTo(part2.Name), "object2 names not identical after merge"); Assert.That(object2PartMerged.GroupPosition, Is.EqualTo(part2.GroupPosition), "object2 group position not equal after merge"); } } /// <summary> /// Test saving a multi-region OAR. /// </summary> [Test] public void TestSaveMultiRegionOar() { TestHelpers.InMethod(); // Create test regions int WIDTH = 2; int HEIGHT = 2; List<Scene> scenes = new List<Scene>(); // Maps (Directory in OAR file -> scene) Dictionary<string, Scene> regionPaths = new Dictionary<string, Scene>(); // Maps (Scene -> expected object paths) Dictionary<UUID, List<string>> expectedPaths = new Dictionary<UUID, List<string>>(); // List of expected assets List<UUID> expectedAssets = new List<UUID>(); for (uint y = 0; y < HEIGHT; y++) { for (uint x = 0; x < WIDTH; x++) { Scene scene; if (x == 0 && y == 0) { scene = m_scene; // this scene was already created in SetUp() } else { scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y); SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule()); } scenes.Add(scene); string dir = String.Format("{0}_{1}_{2}", x + 1, y + 1, scene.RegionInfo.RegionName.Replace(" ", "_")); regionPaths[dir] = scene; SceneObjectGroup sog1; SceneObjectGroup sog2; UUID ncAssetUuid; CreateTestObjects(scene, out sog1, out sog2, out ncAssetUuid); expectedPaths[scene.RegionInfo.RegionID] = new List<string>(); expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog1)); expectedPaths[scene.RegionInfo.RegionID].Add(ArchiveHelpers.CreateObjectPath(sog2)); expectedAssets.Add(ncAssetUuid); } } // Save OAR MemoryStream archiveWriteStream = new MemoryStream(); Guid requestId = new Guid("00000000-0000-0000-0000-808080808080"); Dictionary<string, Object> options = new Dictionary<string, Object>(); options.Add("all", true); m_scene.EventManager.OnOarFileSaved += SaveCompleted; m_oarEvent.Reset(); m_archiverModule.ArchiveRegion(archiveWriteStream, requestId, options); m_oarEvent.WaitOne(60000); // Check that the OAR contains the expected data Assert.That(m_lastRequestId, Is.EqualTo(requestId)); byte[] archive = archiveWriteStream.ToArray(); MemoryStream archiveReadStream = new MemoryStream(archive); TarArchiveReader tar = new TarArchiveReader(archiveReadStream); Dictionary<UUID, List<string>> foundPaths = new Dictionary<UUID, List<string>>(); List<UUID> foundAssets = new List<UUID>(); foreach (Scene scene in scenes) { foundPaths[scene.RegionInfo.RegionID] = new List<string>(); } string filePath; TarArchiveReader.TarEntryType tarEntryType; byte[] data = tar.ReadEntry(out filePath, out tarEntryType); Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH)); Dictionary<string, object> archiveOptions = new Dictionary<string, object>(); ArchiveReadRequest arr = new ArchiveReadRequest(m_scene, (Stream)null, Guid.Empty, archiveOptions); arr.LoadControlFile(filePath, data, new DearchiveScenesInfo()); Assert.That(arr.ControlFileLoaded, Is.True); while (tar.ReadEntry(out filePath, out tarEntryType) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { // Assets are shared, so this file doesn't belong to any specific region. string fileName = filePath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); if (fileName.EndsWith("_notecard.txt")) foundAssets.Add(UUID.Parse(fileName.Substring(0, fileName.Length - "_notecard.txt".Length))); } else { // This file belongs to one of the regions. Find out which one. Assert.IsTrue(filePath.StartsWith(ArchiveConstants.REGIONS_PATH)); string[] parts = filePath.Split(new Char[] { '/' }, 3); Assert.AreEqual(3, parts.Length); string regionDirectory = parts[1]; string relativePath = parts[2]; Scene scene = regionPaths[regionDirectory]; if (relativePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { foundPaths[scene.RegionInfo.RegionID].Add(relativePath); } } } Assert.AreEqual(scenes.Count, foundPaths.Count); foreach (Scene scene in scenes) { Assert.That(foundPaths[scene.RegionInfo.RegionID], Is.EquivalentTo(expectedPaths[scene.RegionInfo.RegionID])); } Assert.That(foundAssets, Is.EquivalentTo(expectedAssets)); } /// <summary> /// Test loading a multi-region OAR. /// </summary> [Test] public void TestLoadMultiRegionOar() { TestHelpers.InMethod(); // Create an ArchiveScenesGroup with the regions in the OAR. This is needed to generate the control file. int WIDTH = 2; int HEIGHT = 2; for (uint y = 0; y < HEIGHT; y++) { for (uint x = 0; x < WIDTH; x++) { Scene scene; if (x == 0 && y == 0) { scene = m_scene; // this scene was already created in SetUp() } else { scene = m_sceneHelpers.SetupScene(string.Format("Unit test region {0}", (y * WIDTH) + x + 1), UUID.Random(), 1000 + x, 1000 + y); SceneHelpers.SetupSceneModules(scene, new ArchiverModule(), m_serialiserModule, new TerrainModule()); } } } ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup(); m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene) { scenesGroup.AddScene(scene); }); scenesGroup.CalcSceneLocations(); // Generate the OAR file MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); ArchiveWriteRequest writeRequest = new ArchiveWriteRequest(m_scene, (Stream)null, Guid.Empty); writeRequest.MultiRegionFormat = true; tar.WriteFile( ArchiveConstants.CONTROL_FILE_PATH, writeRequest.CreateControlFile(scenesGroup)); SceneObjectPart part1 = CreateSceneObjectPart1(); part1.SitTargetOrientation = new Quaternion(0.2f, 0.3f, 0.4f, 0.5f); part1.SitTargetPosition = new Vector3(1, 2, 3); SceneObjectGroup object1 = new SceneObjectGroup(part1); // Let's put some inventory items into our object string soundItemName = "sound-item1"; UUID soundItemUuid = UUID.Parse("00000000-0000-0000-0000-000000000002"); Type type = GetType(); Assembly assembly = type.Assembly; string soundDataResourceName = null; string[] names = assembly.GetManifestResourceNames(); foreach (string name in names) { if (name.EndsWith(".Resources.test-sound.wav")) soundDataResourceName = name; } Assert.That(soundDataResourceName, Is.Not.Null); byte[] soundData; UUID soundUuid; CreateSoundAsset(tar, assembly, soundDataResourceName, out soundData, out soundUuid); TaskInventoryItem item1 = new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName }; part1.Inventory.AddInventoryItem(item1, true); m_scene.AddNewSceneObject(object1, false); string object1FileName = string.Format( "{0}_{1:000}-{2:000}-{3:000}__{4}.xml", part1.Name, Math.Round(part1.GroupPosition.X), Math.Round(part1.GroupPosition.Y), Math.Round(part1.GroupPosition.Z), part1.UUID); string path = "regions/1_1_Unit_test_region/" + ArchiveConstants.OBJECTS_PATH + object1FileName; tar.WriteFile(path, SceneObjectSerializer.ToXml2Format(object1)); tar.Close(); // Delete the current objects, to test that they're loaded from the OAR and didn't // just remain in the scene. m_sceneHelpers.SceneManager.ForEachScene(delegate(Scene scene) { scene.DeleteAllSceneObjects(); }); // Create a "hole", to test that that the corresponding region isn't loaded from the OAR m_sceneHelpers.SceneManager.CloseScene(SceneManager.Instance.Scenes[1]); // Check thay the OAR file contains the expected data MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); m_scene.EventManager.OnOarFileLoaded += LoadCompleted; m_oarEvent.Reset(); m_archiverModule.DearchiveRegion(archiveReadStream); m_oarEvent.WaitOne(60000); Assert.That(m_lastErrorMessage, Is.Null); Assert.AreEqual(3, m_sceneHelpers.SceneManager.Scenes.Count); TestLoadedRegion(part1, soundItemName, soundData); } private void TestLoadedRegion(SceneObjectPart part1, string soundItemName, byte[] soundData) { SceneObjectPart object1PartLoaded = m_scene.GetSceneObjectPart(part1.Name); Assert.That(object1PartLoaded, Is.Not.Null, "object1 was not loaded"); Assert.That(object1PartLoaded.Name, Is.EqualTo(part1.Name), "object1 names not identical"); Assert.That(object1PartLoaded.GroupPosition, Is.EqualTo(part1.GroupPosition), "object1 group position not equal"); Quaternion qtmp1 = new Quaternion ( (float)Math.Round(object1PartLoaded.RotationOffset.X,5), (float)Math.Round(object1PartLoaded.RotationOffset.Y,5), (float)Math.Round(object1PartLoaded.RotationOffset.Z,5), (float)Math.Round(object1PartLoaded.RotationOffset.W,5)); Quaternion qtmp2 = new Quaternion ( (float)Math.Round(part1.RotationOffset.X,5), (float)Math.Round(part1.RotationOffset.Y,5), (float)Math.Round(part1.RotationOffset.Z,5), (float)Math.Round(part1.RotationOffset.W,5)); Assert.That(qtmp1, Is.EqualTo(qtmp2), "object1 rotation offset not equal"); Assert.That( object1PartLoaded.OffsetPosition, Is.EqualTo(part1.OffsetPosition), "object1 offset position not equal"); Assert.That(object1PartLoaded.SitTargetOrientation, Is.EqualTo(part1.SitTargetOrientation)); Assert.That(object1PartLoaded.SitTargetPosition, Is.EqualTo(part1.SitTargetPosition)); TaskInventoryItem loadedSoundItem = object1PartLoaded.Inventory.GetInventoryItems(soundItemName)[0]; Assert.That(loadedSoundItem, Is.Not.Null, "loaded sound item was null"); AssetBase loadedSoundAsset = m_scene.AssetService.Get(loadedSoundItem.AssetID.ToString()); Assert.That(loadedSoundAsset, Is.Not.Null, "loaded sound asset was null"); Assert.That(loadedSoundAsset.Data, Is.EqualTo(soundData), "saved and loaded sound data do not match"); Assert.Greater(m_scene.LandChannel.AllParcels().Count, 0, "incorrect number of parcels"); } } }
/* * 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.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; //using Cairo; namespace OpenSim.Region.CoreModules.Scripting.VectorRender { public class VectorRenderModule : IRegionModule, IDynamicTextureRender { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_name = "VectorRenderModule"; private Scene m_scene; private IDynamicTextureManager m_textureManager; private Graphics m_graph; private string m_fontName = "Arial"; public VectorRenderModule() { } #region IDynamicTextureRender Members public string GetContentType() { return ("vector"); } public string GetName() { return m_name; } public bool SupportsAsynchronous() { return true; } public byte[] ConvertUrl(string url, string extraParams) { return null; } public byte[] ConvertStream(Stream data, string extraParams) { return null; } public bool AsyncConvertUrl(UUID id, string url, string extraParams) { return false; } public bool AsyncConvertData(UUID id, string bodyData, string extraParams) { Draw(bodyData, id, extraParams); return true; } public void GetDrawStringSize(string text, string fontName, int fontSize, out double xSize, out double ySize) { Font myFont = new Font(fontName, fontSize); SizeF stringSize = new SizeF(); lock (m_graph) { stringSize = m_graph.MeasureString(text, myFont); xSize = stringSize.Width; ySize = stringSize.Height; } } #endregion #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { if (m_scene == null) { m_scene = scene; } if (m_graph == null) { Bitmap bitmap = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb); m_graph = Graphics.FromImage(bitmap); } IConfig cfg = config.Configs["VectorRender"]; if (null != cfg) { m_fontName = cfg.GetString("font_name", m_fontName); } m_log.DebugFormat("[VECTORRENDERMODULE]: using font \"{0}\" for text rendering.", m_fontName); } public void PostInitialise() { m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>(); if (m_textureManager != null) { m_textureManager.RegisterRender(GetContentType(), this); } } public void Close() { } public string Name { get { return m_name; } } public bool IsSharedModule { get { return true; } } #endregion private void Draw(string data, UUID id, string extraParams) { // We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha // we will now support multiple comma seperated params in the form width:256,height:512,alpha:255 int width = 256; int height = 256; int alpha = 255; // 0 is transparent Color bgColour = Color.White; // Default background color char altDataDelim = ';'; char[] paramDelimiter = { ',' }; char[] nvpDelimiter = { ':' }; extraParams = extraParams.Trim(); extraParams = extraParams.ToLower(); string[] nvps = extraParams.Split(paramDelimiter); int temp = -1; foreach (string pair in nvps) { string[] nvp = pair.Split(nvpDelimiter); string name = ""; string value = ""; if (nvp[0] != null) { name = nvp[0].Trim(); } if (nvp.Length == 2) { value = nvp[1].Trim(); } switch (name) { case "width": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { width = 1; } else if (temp > 2048) { width = 2048; } else { width = temp; } } break; case "height": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { height = 1; } else if (temp > 2048) { height = 2048; } else { height = temp; } } break; case "alpha": temp = parseIntParam(value); if (temp != -1) { if (temp < 0) { alpha = 0; } else if (temp > 255) { alpha = 255; } else { alpha = temp; } } // Allow a bitmap w/o the alpha component to be created else if (value.ToLower() == "false") { alpha = 256; } break; case "bgcolour": int hex = 0; if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { bgColour = Color.FromArgb(hex); } else { bgColour = Color.FromName(value); } break; case "altdatadelim": altDataDelim = value.ToCharArray()[0]; break; case "": // blank string has been passed do nothing just use defaults break; default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future // could be either set alpha or just an int if (name == "setalpha") { alpha = 0; // set the texture to have transparent background (maintains backwards compat) } else { // this function used to accept an int on its own that represented both // width and height, this is to maintain backwards compat, could be removed // but would break existing scripts temp = parseIntParam(name); if (temp != -1) { if (temp > 1024) temp = 1024; if (temp < 128) temp = 128; width = temp; height = temp; } } break; } } Bitmap bitmap; if (alpha == 256) { bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); } else { bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); } Graphics graph = Graphics.FromImage(bitmap); // this is really just to save people filling the // background color in their scripts, only do when fully opaque if (alpha >= 255) { graph.FillRectangle(new SolidBrush(bgColour), 0, 0, width, height); } for (int w = 0; w < bitmap.Width; w++) { if (alpha <= 255) { for (int h = 0; h < bitmap.Height; h++) { bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h))); } } } GDIDraw(data, graph, altDataDelim); byte[] imageJ2000 = new byte[0]; try { imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); } catch (Exception) { m_log.Error( "[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } m_textureManager.ReturnData(id, imageJ2000); } private int parseIntParam(string strInt) { int parsed; try { parsed = Convert.ToInt32(strInt); } catch (Exception) { //Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used // m_log.Debug("Problem with Draw. Please verify parameters." + e.ToString()); parsed = -1; } return parsed; } /* private void CairoDraw(string data, System.Drawing.Graphics graph) { using (Win32Surface draw = new Win32Surface(graph.GetHdc())) { Context contex = new Context(draw); contex.Antialias = Antialias.None; //fastest method but low quality contex.LineWidth = 7; char[] lineDelimiter = { ';' }; char[] partsDelimiter = { ',' }; string[] lines = data.Split(lineDelimiter); foreach (string line in lines) { string nextLine = line.Trim(); if (nextLine.StartsWith("MoveTO")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, ref x, ref y); contex.MoveTo(x, y); } else if (nextLine.StartsWith("LineTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, ref x, ref y); contex.LineTo(x, y); contex.Stroke(); } } } graph.ReleaseHdc(); } */ private void GDIDraw(string data, Graphics graph, char dataDelim) { Point startPoint = new Point(0, 0); Point endPoint = new Point(0, 0); Pen drawPen = new Pen(Color.Black, 7); string fontName = m_fontName; float fontSize = 14; Font myFont = new Font(fontName, fontSize); SolidBrush myBrush = new SolidBrush(Color.Black); char[] lineDelimiter = {dataDelim}; char[] partsDelimiter = {','}; string[] lines = data.Split(lineDelimiter); foreach (string line in lines) { string nextLine = line.Trim(); //replace with switch, or even better, do some proper parsing if (nextLine.StartsWith("MoveTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); startPoint.X = (int) x; startPoint.Y = (int) y; } else if (nextLine.StartsWith("LineTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.DrawLine(drawPen, startPoint, endPoint); startPoint.X = endPoint.X; startPoint.Y = endPoint.Y; } else if (nextLine.StartsWith("Text")) { nextLine = nextLine.Remove(0, 4); nextLine = nextLine.Trim(); graph.DrawString(nextLine, myFont, myBrush, startPoint); } else if (nextLine.StartsWith("Image")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; Image image = ImageHttpRequest(nextLine); if (image != null) { graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y); } else { graph.DrawString("URL couldn't be resolved or is", new Font(m_fontName,6), myBrush, startPoint); graph.DrawString("not an image. Please check URL.", new Font(m_fontName, 6), myBrush, new Point(startPoint.X, 12 + startPoint.Y)); graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); } startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("Rectangle")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FillRectangle")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FillPolygon")) { PointF[] points = null; GetParams(partsDelimiter, ref nextLine, 11, ref points); graph.FillPolygon(myBrush, points); } else if (nextLine.StartsWith("Polygon")) { PointF[] points = null; GetParams(partsDelimiter, ref nextLine, 7, ref points); graph.DrawPolygon(drawPen, points); } else if (nextLine.StartsWith("Ellipse")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y); endPoint.X = (int)x; endPoint.Y = (int)y; graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FontSize")) { nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Trim(); fontSize = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); myFont = new Font(fontName, fontSize); } else if (nextLine.StartsWith("FontProp")) { nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Trim(); string[] fprops = nextLine.Split(partsDelimiter); foreach (string prop in fprops) { switch (prop) { case "B": if (!(myFont.Bold)) myFont = new Font(myFont, myFont.Style | FontStyle.Bold); break; case "I": if (!(myFont.Italic)) myFont = new Font(myFont, myFont.Style | FontStyle.Italic); break; case "U": if (!(myFont.Underline)) myFont = new Font(myFont, myFont.Style | FontStyle.Underline); break; case "S": if (!(myFont.Strikeout)) myFont = new Font(myFont, myFont.Style | FontStyle.Strikeout); break; case "R": myFont = new Font(myFont, FontStyle.Regular); break; } } } else if (nextLine.StartsWith("FontName")) { nextLine = nextLine.Remove(0, 8); fontName = nextLine.Trim(); myFont = new Font(fontName, fontSize); } else if (nextLine.StartsWith("PenSize")) { nextLine = nextLine.Remove(0, 7); nextLine = nextLine.Trim(); float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); drawPen.Width = size; } else if (nextLine.StartsWith("PenCap")) { bool start = true, end = true; nextLine = nextLine.Remove(0, 6); nextLine = nextLine.Trim(); string[] cap = nextLine.Split(partsDelimiter); if (cap[0].ToLower() == "start") end = false; else if (cap[0].ToLower() == "end") start = false; else if (cap[0].ToLower() != "both") return; string type = cap[1].ToLower(); if (end) { switch (type) { case "arrow": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; break; case "round": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.RoundAnchor; break; case "diamond": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor; break; case "flat": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.Flat; break; } } if (start) { switch (type) { case "arrow": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; break; case "round": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor; break; case "diamond": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor; break; case "flat": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.Flat; break; } } } else if (nextLine.StartsWith("PenColour")) { nextLine = nextLine.Remove(0, 9); nextLine = nextLine.Trim(); int hex = 0; Color newColour; if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { newColour = Color.FromArgb(hex); } else { // this doesn't fail, it just returns black if nothing is found newColour = Color.FromName(nextLine); } myBrush.Color = newColour; drawPen.Color = newColour; } } } private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y) { line = line.Remove(0, startLength); string[] parts = line.Split(partsDelimiter); if (parts.Length == 2) { string xVal = parts[0].Trim(); string yVal = parts[1].Trim(); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); } else if (parts.Length > 2) { string xVal = parts[0].Trim(); string yVal = parts[1].Trim(); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); line = ""; for (int i = 2; i < parts.Length; i++) { line = line + parts[i].Trim(); line = line + " "; } } } private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref PointF[] points) { line = line.Remove(0, startLength); string[] parts = line.Split(partsDelimiter); if (parts.Length > 1 && parts.Length % 2 == 0) { points = new PointF[parts.Length / 2]; for (int i = 0; i < parts.Length; i = i + 2) { string xVal = parts[i].Trim(); string yVal = parts[i+1].Trim(); float x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); float y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); PointF point = new PointF(x, y); points[i / 2] = point; } } } private Bitmap ImageHttpRequest(string url) { try { WebRequest request = HttpWebRequest.Create(url); //Ckrinke: Comment out for now as 'str' is unused. Bring it back into play later when it is used. //Ckrinke Stream str = null; HttpWebResponse response = (HttpWebResponse)(request).GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Bitmap image = new Bitmap(response.GetResponseStream()); return image; } } catch { } return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using NPoco; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Persistence.Querying; using Umbraco.Cms.Core.Persistence.Repositories; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Strings; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement; using Umbraco.Cms.Infrastructure.PublishedCache.DataSource; using Umbraco.Extensions; using static Umbraco.Cms.Core.Persistence.SqlExtensionsStatics; using Constants = Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Infrastructure.PublishedCache.Persistence { public class NuCacheContentRepository : RepositoryBase, INuCacheContentRepository { private readonly ILogger<NuCacheContentRepository> _logger; private readonly IMemberRepository _memberRepository; private readonly IDocumentRepository _documentRepository; private readonly IMediaRepository _mediaRepository; private readonly IShortStringHelper _shortStringHelper; private readonly UrlSegmentProviderCollection _urlSegmentProviders; private readonly IContentCacheDataSerializerFactory _contentCacheDataSerializerFactory; private readonly IOptions<NuCacheSettings> _nucacheSettings; /// <summary> /// Initializes a new instance of the <see cref="NuCacheContentRepository"/> class. /// </summary> public NuCacheContentRepository( IScopeAccessor scopeAccessor, AppCaches appCaches, ILogger<NuCacheContentRepository> logger, IMemberRepository memberRepository, IDocumentRepository documentRepository, IMediaRepository mediaRepository, IShortStringHelper shortStringHelper, UrlSegmentProviderCollection urlSegmentProviders, IContentCacheDataSerializerFactory contentCacheDataSerializerFactory, IOptions<NuCacheSettings> nucacheSettings) : base(scopeAccessor, appCaches) { _logger = logger; _memberRepository = memberRepository; _documentRepository = documentRepository; _mediaRepository = mediaRepository; _shortStringHelper = shortStringHelper; _urlSegmentProviders = urlSegmentProviders; _contentCacheDataSerializerFactory = contentCacheDataSerializerFactory; _nucacheSettings = nucacheSettings; } public void DeleteContentItem(IContentBase item) => Database.Execute("DELETE FROM cmsContentNu WHERE nodeId=@id", new { id = item.Id }); public void RefreshContent(IContent content) { IContentCacheDataSerializer serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Document); // always refresh the edited data OnRepositoryRefreshed(serializer, content, false); if (content.PublishedState == PublishedState.Unpublishing) { // if unpublishing, remove published data from table Database.Execute("DELETE FROM cmsContentNu WHERE nodeId=@id AND published=1", new { id = content.Id }); } else if (content.PublishedState == PublishedState.Publishing) { // if publishing, refresh the published data OnRepositoryRefreshed(serializer, content, true); } } public void RefreshMedia(IMedia media) { IContentCacheDataSerializer serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); OnRepositoryRefreshed(serializer, media, false); } public void RefreshMember(IMember member) { IContentCacheDataSerializer serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Member); OnRepositoryRefreshed(serializer, member, false); } private void OnRepositoryRefreshed(IContentCacheDataSerializer serializer, IContentBase content, bool published) { // use a custom SQL to update row version on each update // db.InsertOrUpdate(dto); ContentNuDto dto = GetDto(content, published, serializer); Database.InsertOrUpdate( dto, "SET data=@data, dataRaw=@dataRaw, rv=rv+1 WHERE nodeId=@id AND published=@published", new { dataRaw = dto.RawData ?? Array.Empty<byte>(), data = dto.Data, id = dto.NodeId, published = dto.Published }); } public void Rebuild( IReadOnlyCollection<int> contentTypeIds = null, IReadOnlyCollection<int> mediaTypeIds = null, IReadOnlyCollection<int> memberTypeIds = null) { IContentCacheDataSerializer serializer = _contentCacheDataSerializerFactory.Create( ContentCacheDataSerializerEntityType.Document | ContentCacheDataSerializerEntityType.Media | ContentCacheDataSerializerEntityType.Member); RebuildContentDbCache(serializer, _nucacheSettings.Value.SqlPageSize, contentTypeIds); RebuildMediaDbCache(serializer, _nucacheSettings.Value.SqlPageSize, mediaTypeIds); RebuildMemberDbCache(serializer, _nucacheSettings.Value.SqlPageSize, memberTypeIds); } // assumes content tree lock private void RebuildContentDbCache(IContentCacheDataSerializer serializer, int groupSize, IReadOnlyCollection<int> contentTypeIds) { Guid contentObjectType = Constants.ObjectTypes.Document; // remove all - if anything fails the transaction will rollback if (contentTypeIds == null || contentTypeIds.Count == 0) { // must support SQL-CE Database.Execute( @"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode WHERE umbracoNode.nodeObjectType=@objType )", new { objType = contentObjectType }); } else { // assume number of ctypes won't blow IN(...) // must support SQL-CE Database.Execute( $@"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode JOIN {Constants.DatabaseSchema.Tables.Content} ON {Constants.DatabaseSchema.Tables.Content}.nodeId=umbracoNode.id WHERE umbracoNode.nodeObjectType=@objType AND {Constants.DatabaseSchema.Tables.Content}.contentTypeId IN (@ctypes) )", new { objType = contentObjectType, ctypes = contentTypeIds }); } // insert back - if anything fails the transaction will rollback IQuery<IContent> query = SqlContext.Query<IContent>(); if (contentTypeIds != null && contentTypeIds.Count > 0) { query = query.WhereIn(x => x.ContentTypeId, contentTypeIds); // assume number of ctypes won't blow IN(...) } long pageIndex = 0; long processed = 0; long total; do { // the tree is locked, counting and comparing to total is safe IEnumerable<IContent> descendants = _documentRepository.GetPage(query, pageIndex++, groupSize, out total, null, Ordering.By("Path")); var items = new List<ContentNuDto>(); var count = 0; foreach (IContent c in descendants) { // always the edited version items.Add(GetDto(c, false, serializer)); // and also the published version if it makes any sense if (c.Published) { items.Add(GetDto(c, true, serializer)); } count++; } Database.BulkInsertRecords(items); processed += count; } while (processed < total); } // assumes media tree lock private void RebuildMediaDbCache(IContentCacheDataSerializer serializer, int groupSize, IReadOnlyCollection<int> contentTypeIds) { var mediaObjectType = Constants.ObjectTypes.Media; // remove all - if anything fails the transaction will rollback if (contentTypeIds == null || contentTypeIds.Count == 0) { // must support SQL-CE Database.Execute( @"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode WHERE umbracoNode.nodeObjectType=@objType )", new { objType = mediaObjectType }); } else { // assume number of ctypes won't blow IN(...) // must support SQL-CE Database.Execute( $@"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode JOIN {Constants.DatabaseSchema.Tables.Content} ON {Constants.DatabaseSchema.Tables.Content}.nodeId=umbracoNode.id WHERE umbracoNode.nodeObjectType=@objType AND {Constants.DatabaseSchema.Tables.Content}.contentTypeId IN (@ctypes) )", new { objType = mediaObjectType, ctypes = contentTypeIds }); } // insert back - if anything fails the transaction will rollback var query = SqlContext.Query<IMedia>(); if (contentTypeIds != null && contentTypeIds.Count > 0) { query = query.WhereIn(x => x.ContentTypeId, contentTypeIds); // assume number of ctypes won't blow IN(...) } long pageIndex = 0; long processed = 0; long total; do { // the tree is locked, counting and comparing to total is safe var descendants = _mediaRepository.GetPage(query, pageIndex++, groupSize, out total, null, Ordering.By("Path")); var items = descendants.Select(m => GetDto(m, false, serializer)).ToList(); Database.BulkInsertRecords(items); processed += items.Count; } while (processed < total); } // assumes member tree lock private void RebuildMemberDbCache(IContentCacheDataSerializer serializer, int groupSize, IReadOnlyCollection<int> contentTypeIds) { Guid memberObjectType = Constants.ObjectTypes.Member; // remove all - if anything fails the transaction will rollback if (contentTypeIds == null || contentTypeIds.Count == 0) { // must support SQL-CE Database.Execute( @"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode WHERE umbracoNode.nodeObjectType=@objType )", new { objType = memberObjectType }); } else { // assume number of ctypes won't blow IN(...) // must support SQL-CE Database.Execute( $@"DELETE FROM cmsContentNu WHERE cmsContentNu.nodeId IN ( SELECT id FROM umbracoNode JOIN {Constants.DatabaseSchema.Tables.Content} ON {Constants.DatabaseSchema.Tables.Content}.nodeId=umbracoNode.id WHERE umbracoNode.nodeObjectType=@objType AND {Constants.DatabaseSchema.Tables.Content}.contentTypeId IN (@ctypes) )", new { objType = memberObjectType, ctypes = contentTypeIds }); } // insert back - if anything fails the transaction will rollback IQuery<IMember> query = SqlContext.Query<IMember>(); if (contentTypeIds != null && contentTypeIds.Count > 0) { query = query.WhereIn(x => x.ContentTypeId, contentTypeIds); // assume number of ctypes won't blow IN(...) } long pageIndex = 0; long processed = 0; long total; do { IEnumerable<IMember> descendants = _memberRepository.GetPage(query, pageIndex++, groupSize, out total, null, Ordering.By("Path")); ContentNuDto[] items = descendants.Select(m => GetDto(m, false, serializer)).ToArray(); Database.BulkInsertRecords(items); processed += items.Length; } while (processed < total); } // assumes content tree lock public bool VerifyContentDbCache() { // every document should have a corresponding row for edited properties // and if published, may have a corresponding row for published properties Guid contentObjectType = Constants.ObjectTypes.Document; var count = Database.ExecuteScalar<int>( $@"SELECT COUNT(*) FROM umbracoNode JOIN {Constants.DatabaseSchema.Tables.Document} ON umbracoNode.id={Constants.DatabaseSchema.Tables.Document}.nodeId LEFT JOIN cmsContentNu nuEdited ON (umbracoNode.id=nuEdited.nodeId AND nuEdited.published=0) LEFT JOIN cmsContentNu nuPublished ON (umbracoNode.id=nuPublished.nodeId AND nuPublished.published=1) WHERE umbracoNode.nodeObjectType=@objType AND nuEdited.nodeId IS NULL OR ({Constants.DatabaseSchema.Tables.Document}.published=1 AND nuPublished.nodeId IS NULL);", new { objType = contentObjectType }); return count == 0; } // assumes media tree lock public bool VerifyMediaDbCache() { // every media item should have a corresponding row for edited properties Guid mediaObjectType = Constants.ObjectTypes.Media; var count = Database.ExecuteScalar<int>( @"SELECT COUNT(*) FROM umbracoNode LEFT JOIN cmsContentNu ON (umbracoNode.id=cmsContentNu.nodeId AND cmsContentNu.published=0) WHERE umbracoNode.nodeObjectType=@objType AND cmsContentNu.nodeId IS NULL ", new { objType = mediaObjectType }); return count == 0; } // assumes member tree lock public bool VerifyMemberDbCache() { // every member item should have a corresponding row for edited properties var memberObjectType = Constants.ObjectTypes.Member; var count = Database.ExecuteScalar<int>( @"SELECT COUNT(*) FROM umbracoNode LEFT JOIN cmsContentNu ON (umbracoNode.id=cmsContentNu.nodeId AND cmsContentNu.published=0) WHERE umbracoNode.nodeObjectType=@objType AND cmsContentNu.nodeId IS NULL ", new { objType = memberObjectType }); return count == 0; } private ContentNuDto GetDto(IContentBase content, bool published, IContentCacheDataSerializer serializer) { // should inject these in ctor // BUT for the time being we decide not to support ConvertDbToXml/String // var propertyEditorResolver = PropertyEditorResolver.Current; // var dataTypeService = ApplicationContext.Current.Services.DataTypeService; var propertyData = new Dictionary<string, PropertyData[]>(); foreach (IProperty prop in content.Properties) { var pdatas = new List<PropertyData>(); foreach (IPropertyValue pvalue in prop.Values) { // sanitize - properties should be ok but ... never knows if (!prop.PropertyType.SupportsVariation(pvalue.Culture, pvalue.Segment)) { continue; } // note: at service level, invariant is 'null', but here invariant becomes 'string.Empty' var value = published ? pvalue.PublishedValue : pvalue.EditedValue; if (value != null) { pdatas.Add(new PropertyData { Culture = pvalue.Culture ?? string.Empty, Segment = pvalue.Segment ?? string.Empty, Value = value }); } } propertyData[prop.Alias] = pdatas.ToArray(); } var cultureData = new Dictionary<string, CultureVariation>(); // sanitize - names should be ok but ... never knows if (content.ContentType.VariesByCulture()) { ContentCultureInfosCollection infos = content is IContent document ? published ? document.PublishCultureInfos : document.CultureInfos : content.CultureInfos; // ReSharper disable once UseDeconstruction foreach (ContentCultureInfos cultureInfo in infos) { var cultureIsDraft = !published && content is IContent d && d.IsCultureEdited(cultureInfo.Culture); cultureData[cultureInfo.Culture] = new CultureVariation { Name = cultureInfo.Name, UrlSegment = content.GetUrlSegment(_shortStringHelper, _urlSegmentProviders, cultureInfo.Culture), Date = content.GetUpdateDate(cultureInfo.Culture) ?? DateTime.MinValue, IsDraft = cultureIsDraft }; } } // the dictionary that will be serialized var contentCacheData = new ContentCacheDataModel { PropertyData = propertyData, CultureData = cultureData, UrlSegment = content.GetUrlSegment(_shortStringHelper, _urlSegmentProviders) }; var serialized = serializer.Serialize(ReadOnlyContentBaseAdapter.Create(content), contentCacheData, published); var dto = new ContentNuDto { NodeId = content.Id, Published = published, Data = serialized.StringData, RawData = serialized.ByteData }; return dto; } // we want arrays, we want them all loaded, not an enumerable private Sql<ISqlContext> SqlContentSourcesSelect(Func<ISqlContext, Sql<ISqlContext>> joins = null) { var sqlTemplate = SqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.ContentSourcesSelect, tsql => tsql.Select<NodeDto>(x => Alias(x.NodeId, "Id"), x => Alias(x.UniqueId, "Key"), x => Alias(x.Level, "Level"), x => Alias(x.Path, "Path"), x => Alias(x.SortOrder, "SortOrder"), x => Alias(x.ParentId, "ParentId"), x => Alias(x.CreateDate, "CreateDate"), x => Alias(x.UserId, "CreatorId")) .AndSelect<ContentDto>(x => Alias(x.ContentTypeId, "ContentTypeId")) .AndSelect<DocumentDto>(x => Alias(x.Published, "Published"), x => Alias(x.Edited, "Edited")) .AndSelect<ContentVersionDto>(x => Alias(x.Id, "VersionId"), x => Alias(x.Text, "EditName"), x => Alias(x.VersionDate, "EditVersionDate"), x => Alias(x.UserId, "EditWriterId")) .AndSelect<DocumentVersionDto>(x => Alias(x.TemplateId, "EditTemplateId")) .AndSelect<ContentVersionDto>("pcver", x => Alias(x.Id, "PublishedVersionId"), x => Alias(x.Text, "PubName"), x => Alias(x.VersionDate, "PubVersionDate"), x => Alias(x.UserId, "PubWriterId")) .AndSelect<DocumentVersionDto>("pdver", x => Alias(x.TemplateId, "PubTemplateId")) .AndSelect<ContentNuDto>("nuEdit", x => Alias(x.Data, "EditData")) .AndSelect<ContentNuDto>("nuPub", x => Alias(x.Data, "PubData")) .AndSelect<ContentNuDto>("nuEdit", x => Alias(x.RawData, "EditDataRaw")) .AndSelect<ContentNuDto>("nuPub", x => Alias(x.RawData, "PubDataRaw")) .From<NodeDto>()); var sql = sqlTemplate.Sql(); // TODO: I'm unsure how we can format the below into SQL templates also because right.Current and right.Published end up being parameters if (joins != null) sql = sql.Append(joins(sql.SqlContext)); sql = sql .InnerJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId) .InnerJoin<DocumentDto>().On<NodeDto, DocumentDto>((left, right) => left.NodeId == right.NodeId) .InnerJoin<ContentVersionDto>().On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId && right.Current) .InnerJoin<DocumentVersionDto>().On<ContentVersionDto, DocumentVersionDto>((left, right) => left.Id == right.Id) .LeftJoin<ContentVersionDto>(j => j.InnerJoin<DocumentVersionDto>("pdver").On<ContentVersionDto, DocumentVersionDto>((left, right) => left.Id == right.Id && right.Published == true, "pcver", "pdver"), "pcver") .On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId, aliasRight: "pcver") .LeftJoin<ContentNuDto>("nuEdit").On<NodeDto, ContentNuDto>((left, right) => left.NodeId == right.NodeId && right.Published == false, aliasRight: "nuEdit") .LeftJoin<ContentNuDto>("nuPub").On<NodeDto, ContentNuDto>((left, right) => left.NodeId == right.NodeId && right.Published == true, aliasRight: "nuPub"); return sql; } private Sql<ISqlContext> SqlContentSourcesSelectUmbracoNodeJoin(ISqlContext sqlContext) { var syntax = sqlContext.SqlSyntax; var sqlTemplate = sqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.SourcesSelectUmbracoNodeJoin, builder => builder.InnerJoin<NodeDto>("x") .On<NodeDto, NodeDto>((left, right) => left.NodeId == right.NodeId || SqlText<bool>(left.Path, right.Path, (lp, rp) => $"({lp} LIKE {syntax.GetConcat(rp, "',%'")})"), aliasRight: "x")); var sql = sqlTemplate.Sql(); return sql; } private Sql<ISqlContext> SqlWhereNodeId(ISqlContext sqlContext, int id) { var syntax = sqlContext.SqlSyntax; var sqlTemplate = sqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.WhereNodeId, builder => builder.Where<NodeDto>(x => x.NodeId == SqlTemplate.Arg<int>("id"))); var sql = sqlTemplate.Sql(id); return sql; } private Sql<ISqlContext> SqlWhereNodeIdX(ISqlContext sqlContext, int id) { var syntax = sqlContext.SqlSyntax; var sqlTemplate = sqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.WhereNodeIdX, s => s.Where<NodeDto>(x => x.NodeId == SqlTemplate.Arg<int>("id"), "x")); var sql = sqlTemplate.Sql(id); return sql; } private Sql<ISqlContext> SqlOrderByLevelIdSortOrder(ISqlContext sqlContext) { var syntax = sqlContext.SqlSyntax; var sqlTemplate = sqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.OrderByLevelIdSortOrder, s => s.OrderBy<NodeDto>(x => x.Level, x => x.ParentId, x => x.SortOrder)); var sql = sqlTemplate.Sql(); return sql; } private Sql<ISqlContext> SqlObjectTypeNotTrashed(ISqlContext sqlContext, Guid nodeObjectType) { var syntax = sqlContext.SqlSyntax; var sqlTemplate = sqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.ObjectTypeNotTrashedFilter, s => s.Where<NodeDto>(x => x.NodeObjectType == SqlTemplate.Arg<Guid?>("nodeObjectType") && x.Trashed == SqlTemplate.Arg<bool>("trashed"))); var sql = sqlTemplate.Sql(nodeObjectType, false); return sql; } /// <summary> /// Returns a slightly more optimized query to use for the document counting when paging over the content sources /// </summary> /// <param name="scope"></param> /// <returns></returns> private Sql<ISqlContext> SqlContentSourcesCount(Func<ISqlContext, Sql<ISqlContext>> joins = null) { var sqlTemplate = SqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.ContentSourcesCount, tsql => tsql.Select<NodeDto>(x => Alias(x.NodeId, "Id")) .From<NodeDto>() .InnerJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId) .InnerJoin<DocumentDto>().On<NodeDto, DocumentDto>((left, right) => left.NodeId == right.NodeId)); var sql = sqlTemplate.Sql(); if (joins != null) sql = sql.Append(joins(sql.SqlContext)); // TODO: We can't use a template with this one because of the 'right.Current' and 'right.Published' ends up being a parameter so not sure how we can do that sql = sql .InnerJoin<ContentVersionDto>().On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId && right.Current) .InnerJoin<DocumentVersionDto>().On<ContentVersionDto, DocumentVersionDto>((left, right) => left.Id == right.Id) .LeftJoin<ContentVersionDto>(j => j.InnerJoin<DocumentVersionDto>("pdver").On<ContentVersionDto, DocumentVersionDto>((left, right) => left.Id == right.Id && right.Published, "pcver", "pdver"), "pcver") .On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId, aliasRight: "pcver"); return sql; } private Sql<ISqlContext> SqlMediaSourcesSelect(Func<ISqlContext, Sql<ISqlContext>> joins = null) { var sqlTemplate = SqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.MediaSourcesSelect, tsql => tsql.Select<NodeDto>(x => Alias(x.NodeId, "Id"), x => Alias(x.UniqueId, "Key"), x => Alias(x.Level, "Level"), x => Alias(x.Path, "Path"), x => Alias(x.SortOrder, "SortOrder"), x => Alias(x.ParentId, "ParentId"), x => Alias(x.CreateDate, "CreateDate"), x => Alias(x.UserId, "CreatorId")) .AndSelect<ContentDto>(x => Alias(x.ContentTypeId, "ContentTypeId")) .AndSelect<ContentVersionDto>(x => Alias(x.Id, "VersionId"), x => Alias(x.Text, "EditName"), x => Alias(x.VersionDate, "EditVersionDate"), x => Alias(x.UserId, "EditWriterId")) .AndSelect<ContentNuDto>("nuEdit", x => Alias(x.Data, "EditData")) .AndSelect<ContentNuDto>("nuEdit", x => Alias(x.RawData, "EditDataRaw")) .From<NodeDto>()); var sql = sqlTemplate.Sql(); if (joins != null) sql = sql.Append(joins(sql.SqlContext)); // TODO: We can't use a template with this one because of the 'right.Published' ends up being a parameter so not sure how we can do that sql = sql .InnerJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId) .InnerJoin<ContentVersionDto>().On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId && right.Current) .LeftJoin<ContentNuDto>("nuEdit").On<NodeDto, ContentNuDto>((left, right) => left.NodeId == right.NodeId && !right.Published, aliasRight: "nuEdit"); return sql; } private Sql<ISqlContext> SqlMediaSourcesCount(Func<ISqlContext, Sql<ISqlContext>> joins = null) { var sqlTemplate = SqlContext.Templates.Get(Constants.SqlTemplates.NuCacheDatabaseDataSource.MediaSourcesCount, tsql => tsql.Select<NodeDto>(x => Alias(x.NodeId, "Id")).From<NodeDto>()); var sql = sqlTemplate.Sql(); if (joins != null) sql = sql.Append(joins(sql.SqlContext)); // TODO: We can't use a template with this one because of the 'right.Current' ends up being a parameter so not sure how we can do that sql = sql .InnerJoin<ContentDto>().On<NodeDto, ContentDto>((left, right) => left.NodeId == right.NodeId) .InnerJoin<ContentVersionDto>().On<NodeDto, ContentVersionDto>((left, right) => left.NodeId == right.NodeId && right.Current); return sql; } public ContentNodeKit GetContentSource(int id) { var sql = SqlContentSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .Append(SqlWhereNodeId(SqlContext, id)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); var dto = Database.Fetch<ContentSourceDto>(sql).FirstOrDefault(); if (dto == null) return ContentNodeKit.Empty; var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Document); return CreateContentNodeKit(dto, serializer); } public IEnumerable<ContentNodeKit> GetAllContentSources() { var sql = SqlContentSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlContentSourcesCount() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Document); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateContentNodeKit(row, serializer); } } public IEnumerable<ContentNodeKit> GetBranchContentSources(int id) { var sql = SqlContentSourcesSelect(SqlContentSourcesSelectUmbracoNodeJoin) .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .Append(SqlWhereNodeIdX(SqlContext, id)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlContentSourcesCount(SqlContentSourcesSelectUmbracoNodeJoin) .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .Append(SqlWhereNodeIdX(SqlContext, id)); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Document); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateContentNodeKit(row, serializer); } } public IEnumerable<ContentNodeKit> GetTypeContentSources(IEnumerable<int> ids) { if (!ids.Any()) yield break; var sql = SqlContentSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .WhereIn<ContentDto>(x => x.ContentTypeId, ids) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlContentSourcesCount() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Document)) .WhereIn<ContentDto>(x => x.ContentTypeId, ids); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Document); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateContentNodeKit(row, serializer); } } public ContentNodeKit GetMediaSource(IScope scope, int id) { var sql = SqlMediaSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .Append(SqlWhereNodeId(SqlContext, id)) .Append(SqlOrderByLevelIdSortOrder(scope.SqlContext)); var dto = scope.Database.Fetch<ContentSourceDto>(sql).FirstOrDefault(); if (dto == null) return ContentNodeKit.Empty; var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); return CreateMediaNodeKit(dto, serializer); } public ContentNodeKit GetMediaSource(int id) { var sql = SqlMediaSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .Append(SqlWhereNodeId(SqlContext, id)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); var dto = Database.Fetch<ContentSourceDto>(sql).FirstOrDefault(); if (dto == null) return ContentNodeKit.Empty; var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); return CreateMediaNodeKit(dto, serializer); } public IEnumerable<ContentNodeKit> GetAllMediaSources() { var sql = SqlMediaSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlMediaSourcesCount() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateMediaNodeKit(row, serializer); } } public IEnumerable<ContentNodeKit> GetBranchMediaSources(int id) { var sql = SqlMediaSourcesSelect(SqlContentSourcesSelectUmbracoNodeJoin) .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .Append(SqlWhereNodeIdX(SqlContext, id)) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlMediaSourcesCount(SqlContentSourcesSelectUmbracoNodeJoin) .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .Append(SqlWhereNodeIdX(SqlContext, id)); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateMediaNodeKit(row, serializer); } } public IEnumerable<ContentNodeKit> GetTypeMediaSources(IEnumerable<int> ids) { if (!ids.Any()) yield break; var sql = SqlMediaSourcesSelect() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .WhereIn<ContentDto>(x => x.ContentTypeId, ids) .Append(SqlOrderByLevelIdSortOrder(SqlContext)); // Use a more efficient COUNT query var sqlCountQuery = SqlMediaSourcesCount() .Append(SqlObjectTypeNotTrashed(SqlContext, Constants.ObjectTypes.Media)) .WhereIn<ContentDto>(x => x.ContentTypeId, ids); var sqlCount = SqlContext.Sql("SELECT COUNT(*) FROM (").Append(sqlCountQuery).Append(") npoco_tbl"); var serializer = _contentCacheDataSerializerFactory.Create(ContentCacheDataSerializerEntityType.Media); // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. foreach (var row in Database.QueryPaged<ContentSourceDto>(_nucacheSettings.Value.SqlPageSize, sql, sqlCount)) { yield return CreateMediaNodeKit(row, serializer); } } private ContentNodeKit CreateContentNodeKit(ContentSourceDto dto, IContentCacheDataSerializer serializer) { ContentData d = null; ContentData p = null; if (dto.Edited) { if (dto.EditData == null && dto.EditDataRaw == null) { if (Debugger.IsAttached) { throw new InvalidOperationException("Missing cmsContentNu edited content for node " + dto.Id + ", consider rebuilding."); } _logger.LogWarning("Missing cmsContentNu edited content for node {NodeId}, consider rebuilding.", dto.Id); } else { bool published = false; var deserializedContent = serializer.Deserialize(dto, dto.EditData, dto.EditDataRaw, published); d = new ContentData( dto.EditName, deserializedContent.UrlSegment, dto.VersionId, dto.EditVersionDate, dto.EditWriterId, dto.EditTemplateId, published, deserializedContent.PropertyData, deserializedContent.CultureData); } } if (dto.Published) { if (dto.PubData == null && dto.PubDataRaw == null) { if (Debugger.IsAttached) { throw new InvalidOperationException("Missing cmsContentNu published content for node " + dto.Id + ", consider rebuilding."); } _logger.LogWarning("Missing cmsContentNu published content for node {NodeId}, consider rebuilding.", dto.Id); } else { bool published = true; var deserializedContent = serializer.Deserialize(dto, dto.PubData, dto.PubDataRaw, published); p = new ContentData( dto.PubName, deserializedContent.UrlSegment, dto.VersionId, dto.PubVersionDate, dto.PubWriterId, dto.PubTemplateId, published, deserializedContent.PropertyData, deserializedContent.CultureData); } } var n = new ContentNode(dto.Id, dto.Key, dto.Level, dto.Path, dto.SortOrder, dto.ParentId, dto.CreateDate, dto.CreatorId); var s = new ContentNodeKit(n, dto.ContentTypeId, d, p); return s; } private ContentNodeKit CreateMediaNodeKit(ContentSourceDto dto, IContentCacheDataSerializer serializer) { if (dto.EditData == null && dto.EditDataRaw == null) throw new InvalidOperationException("No data for media " + dto.Id); bool published = true; var deserializedMedia = serializer.Deserialize(dto, dto.EditData, dto.EditDataRaw, published); var p = new ContentData( dto.EditName, null, dto.VersionId, dto.EditVersionDate, dto.CreatorId, -1, published, deserializedMedia.PropertyData, deserializedMedia.CultureData); var n = new ContentNode(dto.Id, dto.Key, dto.Level, dto.Path, dto.SortOrder, dto.ParentId, dto.CreateDate, dto.CreatorId); var s = new ContentNodeKit(n, dto.ContentTypeId, null, p); return s; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Reflection; using System.Text; namespace Python.Runtime { /// <summary> /// This file defines objects to support binary interop with the Python /// runtime. Generally, the definitions here need to be kept up to date /// when moving to new Python versions. /// </summary> [Serializable] [AttributeUsage(AttributeTargets.All)] public class DocStringAttribute : Attribute { public DocStringAttribute(string docStr) { DocString = docStr; } public string DocString { get { return docStr; } set { docStr = value; } } private string docStr; } [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class PythonMethodAttribute : Attribute { public PythonMethodAttribute() { } } [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class ModuleFunctionAttribute : Attribute { public ModuleFunctionAttribute() { } } [Serializable] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Delegate)] internal class ForbidPythonThreadsAttribute : Attribute { public ForbidPythonThreadsAttribute() { } } [Serializable] [AttributeUsage(AttributeTargets.Property)] internal class ModulePropertyAttribute : Attribute { public ModulePropertyAttribute() { } } internal static partial class TypeOffset { public static int magic() => ManagedDataOffsets.Magic; } internal static class ManagedDataOffsets { public static int Magic { get; internal set; } public static readonly Dictionary<string, int> NameMapping = new Dictionary<string, int>(); static class DataOffsets { public static readonly int ob_data = 0; public static readonly int ob_dict = 0; static DataOffsets() { FieldInfo[] fields = typeof(DataOffsets).GetFields(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < fields.Length; i++) { fields[i].SetValue(null, -(i * IntPtr.Size) - IntPtr.Size); } } } static ManagedDataOffsets() { NameMapping = TypeOffset.GetOffsets(); FieldInfo[] fields = typeof(DataOffsets).GetFields(BindingFlags.Static | BindingFlags.Public); size = fields.Length * IntPtr.Size; } public static int GetSlotOffset(string name) { return NameMapping[name]; } private static int BaseOffset(IntPtr type) { Debug.Assert(type != IntPtr.Zero); int typeSize = Marshal.ReadInt32(type, TypeOffset.tp_basicsize); Debug.Assert(typeSize > 0); return typeSize; } public static int DataOffset(IntPtr type) { return BaseOffset(type) + DataOffsets.ob_data; } public static int DictOffset(IntPtr type) { return BaseOffset(type) + DataOffsets.ob_dict; } public static int ob_data => DataOffsets.ob_data; public static int ob_dict => DataOffsets.ob_dict; public static int Size { get { return size; } } private static readonly int size; } internal static class OriginalObjectOffsets { static OriginalObjectOffsets() { int size = IntPtr.Size; var n = 0; // Py_TRACE_REFS add two pointers to PyObject_HEAD #if PYTHON_WITH_PYDEBUG _ob_next = 0; _ob_prev = 1 * size; n = 2; #endif ob_refcnt = (n + 0) * size; ob_type = (n + 1) * size; } public static int Size { get { return size; } } private static readonly int size = #if PYTHON_WITH_PYDEBUG 4 * IntPtr.Size; #else 2 * IntPtr.Size; #endif #if PYTHON_WITH_PYDEBUG public static int _ob_next; public static int _ob_prev; #endif public static int ob_refcnt; public static int ob_type; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class ObjectOffset { static ObjectOffset() { #if PYTHON_WITH_PYDEBUG _ob_next = OriginalObjectOffsets._ob_next; _ob_prev = OriginalObjectOffsets._ob_prev; #endif ob_refcnt = OriginalObjectOffsets.ob_refcnt; ob_type = OriginalObjectOffsets.ob_type; size = OriginalObjectOffsets.Size + ManagedDataOffsets.Size; } public static int magic(IntPtr type) { return ManagedDataOffsets.DataOffset(type); } public static int TypeDictOffset(IntPtr type) { return ManagedDataOffsets.DictOffset(type); } public static int Size(IntPtr pyType) { if (IsException(pyType)) { return ExceptionOffset.Size(); } return size; } #if PYTHON_WITH_PYDEBUG public static int _ob_next; public static int _ob_prev; #endif public static int ob_refcnt; public static int ob_type; private static readonly int size; private static bool IsException(IntPtr pyObjectPtr) { var pyObject = new BorrowedReference(pyObjectPtr); var type = Runtime.PyObject_TYPE(pyObject); return Runtime.PyType_IsSameAsOrSubtype(type, ofType: Exceptions.BaseException) || Runtime.PyType_IsSameAsOrSubtype(type, ofType: Runtime.PyTypeType) && Runtime.PyType_IsSubtype(pyObject, Exceptions.BaseException); } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class ExceptionOffset { static ExceptionOffset() { Type type = typeof(ExceptionOffset); FieldInfo[] fi = type.GetFields(BindingFlags.Static | BindingFlags.Public); for (int i = 0; i < fi.Length; i++) { fi[i].SetValue(null, (i * IntPtr.Size) + OriginalObjectOffsets.Size); } size = fi.Length * IntPtr.Size + OriginalObjectOffsets.Size + ManagedDataOffsets.Size; } public static int Size() { return size; } // PyException_HEAD // (start after PyObject_HEAD) public static int dict = 0; public static int args = 0; public static int traceback = 0; public static int context = 0; public static int cause = 0; public static int suppress_context = 0; private static readonly int size; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class BytesOffset { static BytesOffset() { Type type = typeof(BytesOffset); FieldInfo[] fi = type.GetFields(); int size = IntPtr.Size; for (int i = 0; i < fi.Length; i++) { fi[i].SetValue(null, i * size); } } /* The *real* layout of a type object when allocated on the heap */ //typedef struct _heaptypeobject { #if PYTHON_WITH_PYDEBUG /* _PyObject_HEAD_EXTRA defines pointers to support a doubly-linked list of all live heap objects. */ public static int _ob_next = 0; public static int _ob_prev = 0; #endif // PyObject_VAR_HEAD { // PyObject_HEAD { public static int ob_refcnt = 0; public static int ob_type = 0; // } public static int ob_size = 0; /* Number of items in _VAR_iable part */ // } public static int ob_shash = 0; public static int ob_sval = 0; /* start of data */ /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. */ //} PyBytesObject; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal class ModuleDefOffset { static ModuleDefOffset() { Type type = typeof(ModuleDefOffset); FieldInfo[] fi = type.GetFields(); int size = IntPtr.Size; for (int i = 0; i < fi.Length; i++) { fi[i].SetValue(null, (i * size) + TypeOffset.ob_size); } } public static IntPtr AllocModuleDef(string modulename) { byte[] ascii = Encoding.ASCII.GetBytes(modulename); int size = name + ascii.Length + 1; IntPtr ptr = Marshal.AllocHGlobal(size); for (int i = 0; i <= m_free; i += IntPtr.Size) Marshal.WriteIntPtr(ptr, i, IntPtr.Zero); Marshal.Copy(ascii, 0, (IntPtr)(ptr + name), ascii.Length); Marshal.WriteIntPtr(ptr, m_name, (IntPtr)(ptr + name)); Marshal.WriteByte(ptr, name + ascii.Length, 0); return ptr; } public static void FreeModuleDef(IntPtr ptr) { Marshal.FreeHGlobal(ptr); } // typedef struct PyModuleDef{ // typedef struct PyModuleDef_Base { // starts after PyObject_HEAD (TypeOffset.ob_type + 1) public static int m_init = 0; public static int m_index = 0; public static int m_copy = 0; // } PyModuleDef_Base public static int m_name = 0; public static int m_doc = 0; public static int m_size = 0; public static int m_methods = 0; public static int m_reload = 0; public static int m_traverse = 0; public static int m_clear = 0; public static int m_free = 0; // } PyModuleDef public static int name = 0; } /// <summary> /// TypeFlags(): The actual bit values for the Type Flags stored /// in a class. /// Note that the two values reserved for stackless have been put /// to good use as PythonNet specific flags (Managed and Subclass) /// </summary> internal class TypeFlags { public const int HeapType = (1 << 9); public const int BaseType = (1 << 10); public const int Ready = (1 << 12); public const int Readying = (1 << 13); public const int HaveGC = (1 << 14); // 15 and 16 are reserved for stackless public const int HaveStacklessExtension = 0; /* XXX Reusing reserved constants */ public const int Managed = (1 << 15); // PythonNet specific public const int Subclass = (1 << 16); // PythonNet specific public const int HaveIndex = (1 << 17); /* Objects support nb_index in PyNumberMethods */ public const int HaveVersionTag = (1 << 18); public const int ValidVersionTag = (1 << 19); public const int IsAbstract = (1 << 20); public const int HaveNewBuffer = (1 << 21); // TODO: Implement FastSubclass functions public const int IntSubclass = (1 << 23); public const int LongSubclass = (1 << 24); public const int ListSubclass = (1 << 25); public const int TupleSubclass = (1 << 26); public const int StringSubclass = (1 << 27); public const int UnicodeSubclass = (1 << 28); public const int DictSubclass = (1 << 29); public const int BaseExceptionSubclass = (1 << 30); public const int TypeSubclass = (1 << 31); public const int Default = ( HaveStacklessExtension | HaveVersionTag); } // This class defines the function prototypes (delegates) used for low // level integration with the CPython runtime. It also provides name // based lookup of the correct prototype for a particular Python type // slot and utilities for generating method thunks for managed methods. internal class Interop { private static Hashtable pmap; static Interop() { // Here we build a mapping of PyTypeObject slot names to the // appropriate prototype (delegate) type to use for the slot. Type[] items = typeof(Interop).GetNestedTypes(); Hashtable p = new Hashtable(); for (int i = 0; i < items.Length; i++) { Type item = items[i]; p[item.Name] = item; } pmap = new Hashtable(); pmap["tp_dealloc"] = p["DestructorFunc"]; pmap["tp_print"] = p["PrintFunc"]; pmap["tp_getattr"] = p["BinaryFunc"]; pmap["tp_setattr"] = p["ObjObjArgFunc"]; pmap["tp_compare"] = p["ObjObjFunc"]; pmap["tp_repr"] = p["UnaryFunc"]; pmap["tp_hash"] = p["UnaryFunc"]; pmap["tp_call"] = p["TernaryFunc"]; pmap["tp_str"] = p["UnaryFunc"]; pmap["tp_getattro"] = p["BinaryFunc"]; pmap["tp_setattro"] = p["ObjObjArgFunc"]; pmap["tp_traverse"] = p["ObjObjArgFunc"]; pmap["tp_clear"] = p["InquiryFunc"]; pmap["tp_richcompare"] = p["RichCmpFunc"]; pmap["tp_iter"] = p["UnaryFunc"]; pmap["tp_iternext"] = p["UnaryFunc"]; pmap["tp_descr_get"] = p["TernaryFunc"]; pmap["tp_descr_set"] = p["ObjObjArgFunc"]; pmap["tp_init"] = p["ObjObjArgFunc"]; pmap["tp_alloc"] = p["IntArgFunc"]; pmap["tp_new"] = p["TernaryFunc"]; pmap["tp_free"] = p["DestructorFunc"]; pmap["tp_is_gc"] = p["InquiryFunc"]; pmap["nb_add"] = p["BinaryFunc"]; pmap["nb_subtract"] = p["BinaryFunc"]; pmap["nb_multiply"] = p["BinaryFunc"]; pmap["nb_remainder"] = p["BinaryFunc"]; pmap["nb_divmod"] = p["BinaryFunc"]; pmap["nb_power"] = p["TernaryFunc"]; pmap["nb_negative"] = p["UnaryFunc"]; pmap["nb_positive"] = p["UnaryFunc"]; pmap["nb_absolute"] = p["UnaryFunc"]; pmap["nb_nonzero"] = p["InquiryFunc"]; pmap["nb_invert"] = p["UnaryFunc"]; pmap["nb_lshift"] = p["BinaryFunc"]; pmap["nb_rshift"] = p["BinaryFunc"]; pmap["nb_and"] = p["BinaryFunc"]; pmap["nb_xor"] = p["BinaryFunc"]; pmap["nb_or"] = p["BinaryFunc"]; pmap["nb_coerce"] = p["ObjObjFunc"]; pmap["nb_int"] = p["UnaryFunc"]; pmap["nb_long"] = p["UnaryFunc"]; pmap["nb_float"] = p["UnaryFunc"]; pmap["nb_oct"] = p["UnaryFunc"]; pmap["nb_hex"] = p["UnaryFunc"]; pmap["nb_inplace_add"] = p["BinaryFunc"]; pmap["nb_inplace_subtract"] = p["BinaryFunc"]; pmap["nb_inplace_multiply"] = p["BinaryFunc"]; pmap["nb_inplace_remainder"] = p["BinaryFunc"]; pmap["nb_inplace_power"] = p["TernaryFunc"]; pmap["nb_inplace_lshift"] = p["BinaryFunc"]; pmap["nb_inplace_rshift"] = p["BinaryFunc"]; pmap["nb_inplace_and"] = p["BinaryFunc"]; pmap["nb_inplace_xor"] = p["BinaryFunc"]; pmap["nb_inplace_or"] = p["BinaryFunc"]; pmap["nb_floor_divide"] = p["BinaryFunc"]; pmap["nb_true_divide"] = p["BinaryFunc"]; pmap["nb_inplace_floor_divide"] = p["BinaryFunc"]; pmap["nb_inplace_true_divide"] = p["BinaryFunc"]; pmap["nb_index"] = p["UnaryFunc"]; pmap["sq_length"] = p["InquiryFunc"]; pmap["sq_concat"] = p["BinaryFunc"]; pmap["sq_repeat"] = p["IntArgFunc"]; pmap["sq_item"] = p["IntArgFunc"]; pmap["sq_slice"] = p["IntIntArgFunc"]; pmap["sq_ass_item"] = p["IntObjArgFunc"]; pmap["sq_ass_slice"] = p["IntIntObjArgFunc"]; pmap["sq_contains"] = p["ObjObjFunc"]; pmap["sq_inplace_concat"] = p["BinaryFunc"]; pmap["sq_inplace_repeat"] = p["IntArgFunc"]; pmap["mp_length"] = p["InquiryFunc"]; pmap["mp_subscript"] = p["BinaryFunc"]; pmap["mp_ass_subscript"] = p["ObjObjArgFunc"]; pmap["bf_getreadbuffer"] = p["IntObjArgFunc"]; pmap["bf_getwritebuffer"] = p["IntObjArgFunc"]; pmap["bf_getsegcount"] = p["ObjObjFunc"]; pmap["bf_getcharbuffer"] = p["IntObjArgFunc"]; } internal static Type GetPrototype(string name) { return pmap[name] as Type; } internal static Dictionary<IntPtr, Delegate> allocatedThunks = new Dictionary<IntPtr, Delegate>(); internal static ThunkInfo GetThunk(MethodInfo method, string funcType = null) { Type dt; if (funcType != null) dt = typeof(Interop).GetNestedType(funcType) as Type; else dt = GetPrototype(method.Name); if (dt == null) { return ThunkInfo.Empty; } Delegate d = Delegate.CreateDelegate(dt, method); var info = new ThunkInfo(d); allocatedThunks[info.Address] = d; return info; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr UnaryFunc(IntPtr ob); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr BinaryFunc(IntPtr ob, IntPtr arg); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr TernaryFunc(IntPtr ob, IntPtr a1, IntPtr a2); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int InquiryFunc(IntPtr ob); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr IntArgFunc(IntPtr ob, int arg); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr IntIntArgFunc(IntPtr ob, int a1, int a2); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int IntObjArgFunc(IntPtr ob, int a1, IntPtr a2); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int IntIntObjArgFunc(IntPtr o, int a, int b, IntPtr c); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int ObjObjArgFunc(IntPtr o, IntPtr a, IntPtr b); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int ObjObjFunc(IntPtr ob, IntPtr arg); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void DestructorFunc(IntPtr ob); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int PrintFunc(IntPtr ob, IntPtr a, int b); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate IntPtr RichCmpFunc(IntPtr ob, IntPtr a, int b); } internal class ThunkInfo { public readonly Delegate Target; public readonly IntPtr Address; public static readonly ThunkInfo Empty = new ThunkInfo(null); public ThunkInfo(Delegate target) { if (target == null) { return; } Target = target; Address = Marshal.GetFunctionPointerForDelegate(target); } } [StructLayout(LayoutKind.Sequential)] struct PyGC_Node { public IntPtr gc_next; public IntPtr gc_prev; public IntPtr gc_refs; } [StructLayout(LayoutKind.Sequential)] struct PyGC_Head { public PyGC_Node gc; } [StructLayout(LayoutKind.Sequential)] struct PyMethodDef { public IntPtr ml_name; public IntPtr ml_meth; public int ml_flags; public IntPtr ml_doc; } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections; namespace Hotcakes.Shipping.Ups { [Serializable] public class ShipRequest { private bool _AddressVerification; // Note OnCallAir options are not supported yet private PaymentType _BillTo = PaymentType.ShipperUpsAccount; private string _BillToAccountNumber = string.Empty; private string _BillToCountryCode = string.Empty; private int _BillToCreditCardExpirationMonth = 1; private int _BillToCreditCardExpirationYear = 1900; private string _BillToCreditCardNumber = string.Empty; private CreditCardType _BillToCreditCardType = CreditCardType.Amex; private string _BillToPostalCode = string.Empty; private string _BrowserHttpUserAgentString = string.Empty; private bool _COD; private decimal _CODAmount; private CurrencyCode _CODCurrencyCode = CurrencyCode.UsDollar; private CODFundsCode _CODPaymentType = CODFundsCode.AllTypesAccepted; private bool _InvoiceLineTotal; private decimal _InvoiceLineTotalAmount; private CurrencyCode _InvoiceLineTotalCurrency = CurrencyCode.UsDollar; private ShipLabelFormat _LabelFormat = ShipLabelFormat.Gif; private bool _NonValuedDocumentsOnly; private bool _Notification; private string _NotificationEmailAddress = string.Empty; private string _NotificationFromName = string.Empty; private string _NotificationMemo = string.Empty; private NotificationSubjectCode _NotificationSubjectType = NotificationSubjectCode.DefaultCode; private NotificationCode _NotificationType = NotificationCode.ShipNotification; private string _NotificationUndeliverableEmailAddress = string.Empty; private ArrayList _Packages = new ArrayList(10); private string _ReferenceNumber = string.Empty; private ReferenceNumberCode _ReferenceNumberType = ReferenceNumberCode.TransactionReferenceNumber; private bool _SaturdayDelivery; private ServiceType _Service = ServiceType.Standard; private UpsSettings _settings = new UpsSettings(); private Entity _ShipFrom = new Entity(); private string _ShipmentDescription = string.Empty; private Entity _Shipper = new Entity(); private Entity _ShipTo = new Entity(); private int _StockSizeHeight; private int _StockSizeWidth; private string _XmlConfirmRequest = string.Empty; private string _XmlConfirmResponse = string.Empty; public UpsSettings Settings { get { return _settings; } set { _settings = value; } } public string XmlConfirmRequest { get { return _XmlConfirmRequest; } set { _XmlConfirmRequest = value; } } public string XmlConfirmResponse { get { return _XmlConfirmResponse; } set { _XmlConfirmResponse = value; } } public bool AddressVerification { get { return _AddressVerification; } set { _AddressVerification = false; } } public ShipLabelFormat LabelFormat { get { return _LabelFormat; } set { _LabelFormat = value; } } public string BrowserHttpUserAgentString { get { return _BrowserHttpUserAgentString; } set { _BrowserHttpUserAgentString = value; } } public int LabelStockSizeHeight { get { return _StockSizeHeight; } set { _StockSizeHeight = value; } } public int LabelStockSizeWidth { get { return _StockSizeWidth; } set { _StockSizeWidth = value; } } public string ShipmentDescription { get { return _ShipmentDescription; } set { _ShipmentDescription = value; } } public bool NonValuedDocumentsOnly { get { return _NonValuedDocumentsOnly; } set { _NonValuedDocumentsOnly = value; } } public string ReferenceNumber { get { return _ReferenceNumber; } set { _ReferenceNumber = value; } } public ReferenceNumberCode ReferenceNumberType { get { return _ReferenceNumberType; } set { _ReferenceNumberType = value; } } public ServiceType Service { get { return _Service; } set { _Service = value; } } public bool COD { get { return _COD; } set { _COD = value; } } public CODFundsCode CODPaymentType { get { return _CODPaymentType; } set { _CODPaymentType = value; } } public CurrencyCode CODCurrencyCode { get { return _CODCurrencyCode; } set { _CODCurrencyCode = value; } } public decimal CODAmount { get { return _CODAmount; } set { _CODAmount = value; } } public bool InvoiceLineTotal { get { return _InvoiceLineTotal; } set { _InvoiceLineTotal = value; } } public decimal InvoiceLineTotalAmount { get { return _InvoiceLineTotalAmount; } set { _InvoiceLineTotalAmount = value; } } public CurrencyCode InvoiceLineTotalCurrency { get { return _InvoiceLineTotalCurrency; } set { _InvoiceLineTotalCurrency = value; } } public bool SaturdayDelivery { get { return _SaturdayDelivery; } set { _SaturdayDelivery = value; } } public bool Notification { get { return _Notification; } set { _Notification = value; } } public NotificationCode NotificationType { get { return _NotificationType; } set { _NotificationType = value; } } public string NotificationEmailAddress { get { return _NotificationEmailAddress; } set { _NotificationEmailAddress = value; } } public string NotificationUndeliverableEmailAddress { get { return _NotificationUndeliverableEmailAddress; } set { _NotificationUndeliverableEmailAddress = value; } } public string NotificationFromName { get { return _NotificationFromName; } set { _NotificationFromName = value; } } public string NotificationMemo { get { return _NotificationMemo; } set { _NotificationMemo = value; } } public NotificationSubjectCode NotificationSubjectType { get { return _NotificationSubjectType; } set { _NotificationSubjectType = value; } } public PaymentType BillTo { get { return _BillTo; } set { _BillTo = value; } } public string BillToAccountNumber { get { return _BillToAccountNumber; } set { _BillToAccountNumber = value; } } public string BillToCreditCardNumber { get { return _BillToCreditCardNumber; } set { _BillToCreditCardNumber = value; } } public int BillToCreditCardExpirationMonth { get { return _BillToCreditCardExpirationMonth; } set { _BillToCreditCardExpirationMonth = value; if (_BillToCreditCardExpirationMonth < 1) { _BillToCreditCardExpirationMonth = 1; } if (_BillToCreditCardExpirationMonth > 13) { _BillToCreditCardExpirationMonth = 1; } } } public int BillToCreditCardExpirationYear { get { return _BillToCreditCardExpirationYear; } set { _BillToCreditCardExpirationYear = value; // Make sure we've got a four digit date if (_BillToCreditCardExpirationYear < 2000) { _BillToCreditCardExpirationYear += 2000; } } } public CreditCardType BillToCreditCardType { get { return _BillToCreditCardType; } set { _BillToCreditCardType = value; } } public string BillToPostalCode { get { return _BillToPostalCode; } set { _BillToPostalCode = value; } } public string BillToCountryCode { get { return _BillToCountryCode; } set { _BillToCountryCode = value; } } public ArrayList Packages { get { return _Packages; } } public Entity Shipper { get { return _Shipper; } set { _Shipper = value; } } public Entity ShipTo { get { return _ShipTo; } set { _ShipTo = value; } } public Entity ShipFrom { get { return _ShipFrom; } set { _ShipFrom = value; } } public bool AddPackage(ref Package p) { var result = false; _Packages.Add(p); result = true; return result; } public bool ClearPackages() { var result = true; _Packages = new ArrayList(10); result = true; return result; } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System.Collections.Generic; using System.Xml.Linq; using NUnit.Framework.Internal; using NUnit.TestUtilities; namespace NUnit.Framework.Api { public static class SchemaTests { [Test] public static void TestSchemaIsValid() { Assert.Multiple(() => SchemaTestUtils.AssertValidXsd("Test.xsd")); } [Test] public static void TestSchemaMatches() { Assert.Multiple(() => { var controller = new FrameworkController("mock-assembly", Test.IdPrefix, new Dictionary<string, string>()); var loadXml = controller.LoadTests(); var exploreXml = controller.ExploreTests(null); SchemaTestUtils.AssertValidXml(loadXml, "Test.xsd"); SchemaTestUtils.AssertValidXml(exploreXml, "Test.xsd"); }); } [Test] public static void TestSchemaDisallowsDuplicateIds() { SchemaTestUtils.AssertInvalidXml(@" <test-suite id='0' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0'> <test-suite id='1' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0'> <test-case id='0' name='0' fullname='0' runstate='Runnable' seed='0' /> </test-suite> </test-suite>", "Test.xsd"); } [Test] public static void TestResultSchemaIsValid() { Assert.Multiple(() => SchemaTestUtils.AssertValidXsd("TestResult.xsd")); } [Test] public static void TestResultSchemaMatches() { Assert.Multiple(() => { var controller = new FrameworkController("mock-assembly", Test.IdPrefix, new Dictionary<string, string>()); controller.LoadTests(); var frameworkXml = XElement.Parse(controller.RunTests(null)); var fullXml = new XElement("test-run", new XElement("command-line"), new XElement("filter"), frameworkXml, new XAttribute("id", 0), new XAttribute("name", 0), new XAttribute("fullname", 0), new XAttribute("testcasecount", 0), new XAttribute("result", "Passed"), new XAttribute("total", 0), new XAttribute("passed", 0), new XAttribute("failed", 0), new XAttribute("inconclusive", 0), new XAttribute("skipped", 0), new XAttribute("warnings", 0), new XAttribute("asserts", 0), new XAttribute("random-seed", 0)); SchemaTestUtils.AssertValidXml(fullXml.ToString(), "TestResult.xsd"); }); } [Test] public static void MultipleTestsAreAllowedInsideTestRun() { Assert.Multiple(() => { SchemaTestUtils.AssertValidXml(@" <test-run id='0' name='0' fullname='0' testcasecount='0' result='Passed' total='0' passed='0' failed='0' inconclusive='0' skipped='0' warnings='0' asserts='0' random-seed='0'> <command-line /> <filter /> <test-case result='Passed' asserts='0' id='1' name='0' fullname='0' runstate='Runnable' seed='0' /> <test-suite result='Passed' asserts='0' total='0' passed='0' failed='0' warnings='0' inconclusive='0' skipped='0' id='2' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0' /> <test-case result='Passed' asserts='0' id='3' name='0' fullname='0' runstate='Runnable' seed='0' /> </test-run>", "TestResult.xsd"); }); } [Test] public static void TestResultSchemaDisallowsRootElement_Filter() { SchemaTestUtils.AssertInvalidXml("<filter />", "TestResult.xsd"); } [Test] public static void TestResultSchemaDisallowsRootElement_TestSuite() { SchemaTestUtils.AssertInvalidXml(@" <test-suite result='Passed' asserts='0' total='0' passed='0' failed='0' warnings='0' inconclusive='0' skipped='0' id='0' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0' />", "TestResult.xsd"); } [Test] public static void TestResultSchemaDisallowsRootElement_TestCase() { SchemaTestUtils.AssertInvalidXml(@" <test-case result='Passed' asserts='0' id='0' name='0' fullname='0' runstate='Runnable' seed='0' />", "TestResult.xsd"); } [Test] public static void TestResultSchemaDisallowsDuplicateIds() { SchemaTestUtils.AssertInvalidXml(@" <test-run id='0' name='0' fullname='0' testcasecount='0' result='Passed' total='0' passed='0' failed='0' inconclusive='0' skipped='0' asserts='0' random-seed='0'> <command-line /> <filter /> <test-suite id='1' result='Passed' asserts='0' total='0' passed='0' failed='0' warnings='0' inconclusive='0' skipped='0' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0'> <test-case id='0' result='Passed' asserts='0' name='0' fullname='0' runstate='Runnable' seed='0' /> </test-suite> </test-run>", "TestResult.xsd"); SchemaTestUtils.AssertInvalidXml(@" <test-run id='0' name='0' fullname='0' testcasecount='0' result='Passed' total='0' passed='0' failed='0' inconclusive='0' skipped='0' asserts='0' random-seed='0'> <command-line /> <filter /> <test-suite id='1' result='Passed' asserts='0' total='0' passed='0' failed='0' warnings='0' inconclusive='0' skipped='0' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0'> <test-suite id='2' result='Passed' asserts='0' total='0' passed='0' failed='0' warnings='0' inconclusive='0' skipped='0' name='0' fullname='0' runstate='Runnable' type='TestMethod' testcasecount='0'> <test-case id='1' result='Passed' asserts='0' name='0' fullname='0' runstate='Runnable' seed='0' /> </test-suite> </test-suite> </test-run>", "TestResult.xsd"); } [Test] public static void TestFilterSchemaIsValid() { Assert.Multiple(() => SchemaTestUtils.AssertValidXsd("TestFilter.xsd")); } [Test] public static void TestFilterSchemaMatches() { Assert.Multiple(() => { SchemaTestUtils.AssertValidXml(@" <filter> <class>c</class> <or> <not> <class re='1'>c</class> </not> <and> <cat>c</cat> <cat re='1'>c</cat> <id>i</id> <id re='1'>i</id> <method>m</method> <method re='1'>m</method> <name>n</name> <name re='1'>n</name> <namespace>n</namespace> <namespace re='1'>n</namespace> <prop name='p'>v</prop> <prop name='p' re='1'>v</prop> <test>t</test> <test re='1'>t</test> </and> </or> </filter>", "TestFilter.xsd"); }); } [Test] public static void TestFilterSchemaDisallowsRootElement_And() { SchemaTestUtils.AssertInvalidXml("<and><class>x</class></and>", "TestFilter.xsd"); } } }
#region Copyright // // This framework is based on log4j see http://jakarta.apache.org/log4j // Copyright (C) The Apache Software Foundation. All rights reserved. // // This software is published under the terms of the Apache Software // License version 1.1, a copy of which has been included with this // distribution in the LICENSE.txt file. // #endregion using System; using System.Collections; using System.Globalization; using System.Reflection; using log4net.Appender; using log4net.helpers; using log4net.spi; using log4net.Repository; namespace log4net.spi { /// <summary> /// The default implementation of the <see cref="IRepositorySelector"/> interface. /// </summary> /// <remarks> /// Uses attributes defined on the calling assembly to determine how to /// configure the hierarchy for the domain.. /// </remarks> public class DefaultRepositorySelector : IRepositorySelector { #region Public Events /// <summary> /// Event to notify that a logger repository has been created. /// </summary> /// <value> /// Event to notify that a logger repository has been created. /// </value> public event LoggerRepositoryCreationEventHandler LoggerRepositoryCreatedEvent { add { m_loggerRepositoryCreatedEvent += value; } remove { m_loggerRepositoryCreatedEvent -= value; } } #endregion Public Events #region Public Instance Constructors /// <summary> /// Creates a new repository selector. /// </summary> /// <param name="defaultRepositoryType">The type of the repositories to create, must implement <see cref="ILoggerRepository"/></param> /// <exception cref="ArgumentNullException"><paramref name="defaultRepositoryType"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="defaultRepositoryType"/> does not implement <see cref="ILoggerRepository"/>.</exception> public DefaultRepositorySelector(Type defaultRepositoryType) { if (defaultRepositoryType == null) { throw new ArgumentNullException("defaultRepositoryType"); } // Check that the type is a repository if (! (typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType)) ) { throw new ArgumentOutOfRangeException("Parameter: defaultRepositoryType, Value: [" + defaultRepositoryType + "] out of range. Argument must implement the ILoggerRepository interface"); } m_defaultRepositoryType = defaultRepositoryType; LogLog.Debug("DefaultRepositorySelector: defaultRepositoryType [" + m_defaultRepositoryType + "]"); } #endregion Public Instance Constructors #region Implementation of IRepositorySelector /// <summary> /// Gets the <see cref="ILoggerRepository"/> for the specified assembly. /// </summary> /// <param name="domainAssembly">The assembly use to lookup the <see cref="ILoggerRepository"/>.</param> /// <remarks> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and the domain /// to create can be overridden by specifying the <see cref="log4net.Config.DomainAttribute"/> /// attribute on the <paramref name="assembly"/>. /// </para> /// <para> /// The default values are to use the <see cref="log4net.Repository.Hierarchy.Hierarchy"/> /// implementation of the <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the domain. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically configured using /// any <see cref="log4net.Config.ConfiguratorAttribute"/> attributes defined on /// the <paramref name="assembly"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> /// <returns>The <see cref="ILoggerRepository"/> for the assembly</returns> public ILoggerRepository GetRepository(Assembly domainAssembly) { if (domainAssembly == null) { throw new ArgumentNullException("domainAssembly"); } return CreateRepository(domainAssembly, m_defaultRepositoryType); } /// <summary> /// Get the <see cref="ILoggerRepository"/> for the specified domain /// </summary> /// <param name="domain">the domain to use to lookup to the <see cref="ILoggerRepository"/></param> /// <returns>The <see cref="ILoggerRepository"/> for the domain</returns> /// <exception cref="ArgumentNullException">throw if <paramref name="domain"/> is null</exception> /// <exception cref="LogException">throw if the <paramref name="domain"/> does not exist</exception> public ILoggerRepository GetRepository(string domain) { if (domain == null) { throw new ArgumentNullException("domain"); } lock(this) { // Lookup in map ILoggerRepository rep = m_domain2repositoryMap[domain] as ILoggerRepository; if (rep == null) { throw new LogException("Domain ["+domain+"] is NOT defined."); } return rep; } } /// <summary> /// Create a new repository for the assembly specified /// </summary> /// <param name="domainAssembly">the assembly to use to create the domain to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the domain /// specified such that a call to <see cref="GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the domain to create can be overridden by specifying the /// <see cref="log4net.Config.DomainAttribute"/> attribute on the /// <paramref name="assembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the domain. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="domainAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="domainAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.DomainAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="domainAssembly"/> is null.</exception> public ILoggerRepository CreateRepository(Assembly domainAssembly, Type repositoryType) { return CreateRepository(domainAssembly, repositoryType, DEFAULT_DOMAIN_NAME, true); } /// <summary> /// Create a new repository for the assembly specified /// </summary> /// <param name="domainAssembly">the assembly to use to create the domain to associate with the <see cref="ILoggerRepository"/>.</param> /// <param name="repositoryType">The type of repository to create, must implement <see cref="ILoggerRepository"/>.</param> /// <param name="domainName">The name to assign to the created repository</param> /// <param name="readAssemblyAttributes">Set to <c>true</c> to read and apply the assembly attributes</param> /// <returns>The repository created.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the domain /// specified such that a call to <see cref="GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// <para> /// The type of the <see cref="ILoggerRepository"/> created and /// the domain to create can be overridden by specifying the /// <see cref="log4net.Config.DomainAttribute"/> attribute on the /// <paramref name="assembly"/>. The default values are to use the /// <paramref name="repositoryType"/> implementation of the /// <see cref="ILoggerRepository"/> interface and to use the /// <see cref="AssemblyName.Name"/> as the name of the domain. /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be automatically /// configured using any <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes defined on the <paramref name="domainAssembly"/>. /// </para> /// <para> /// If a repository for the <paramref name="domainAssembly"/> already exists /// that repository will be returned. An error will not be raised and that /// repository may be of a different type to that specified in <paramref name="repositoryType"/>. /// Also the <see cref="log4net.Config.DomainAttribute"/> attribute on the /// assembly may be used to override the repository type specified in /// <paramref name="repositoryType"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="domainAssembly"/> is null.</exception> public ILoggerRepository CreateRepository(Assembly domainAssembly, Type repositoryType, string domainName, bool readAssemblyAttributes) { if (domainAssembly == null) { throw new ArgumentNullException("domainAssembly"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { // Lookup in map ILoggerRepository rep = m_assembly2repositoryMap[domainAssembly] as ILoggerRepository; if (rep == null) { // Not found, therefore create LogLog.Debug("DefaultRepositorySelector: Creating repository for assembly [" + domainAssembly + "]"); // Must specify defaults string domain = domainName; Type actualRepositoryType = repositoryType; if (readAssemblyAttributes) { // Get the domain and type from the assembly attributes GetInfoForAssembly(domainAssembly, ref domain, ref actualRepositoryType); } LogLog.Debug("DefaultRepositorySelector: Assembly [" + domainAssembly + "] using domain [" + domain + "] and repository type [" + actualRepositoryType + "]"); // Lookup the domain in the map (as this may already be defined) rep = m_domain2repositoryMap[domain] as ILoggerRepository; if (rep == null) { // Create the repository rep = CreateRepository(domain, actualRepositoryType); if (readAssemblyAttributes) { // Look for aliasing attributes LoadAliases(domainAssembly, rep); // Look for plugins defined on the assembly LoadPlugins(domainAssembly, rep); // Configure the repository using the assembly attributes ConfigureRepository(domainAssembly, rep); } } else { LogLog.Debug("DefaultRepositorySelector: domain [" + domain + "] already exisits, using repository type [" + rep.GetType().FullName + "]"); if (readAssemblyAttributes) { // Look for plugins defined on the assembly LoadPlugins(domainAssembly, rep); } } m_assembly2repositoryMap[domainAssembly] = rep; } return rep; } } /// <summary> /// Create a new repository for the domain specified /// </summary> /// <param name="domain">the domain to associate with the <see cref="ILoggerRepository"/></param> /// <param name="repositoryType">the type of repository to create, must implement <see cref="ILoggerRepository"/>. /// If this param is null then the default repository type is used.</param> /// <returns>the repository created</returns> /// <remarks> /// The <see cref="ILoggerRepository"/> created will be associated with the domain /// specified such that a call to <see cref="GetRepository(string)"/> with the /// same domain specified will return the same repository instance. /// </remarks> /// <exception cref="ArgumentNullException">throw if <paramref name="domain"/> is null</exception> /// <exception cref="LogException">throw if the <paramref name="domain"/> already exists</exception> public ILoggerRepository CreateRepository(string domain, Type repositoryType) { if (domain == null) { throw new ArgumentNullException("domain"); } // If the type is not set then use the default type if (repositoryType == null) { repositoryType = m_defaultRepositoryType; } lock(this) { ILoggerRepository rep = null; // First check that the domain does not exist rep = m_domain2repositoryMap[domain] as ILoggerRepository; if (rep != null) { throw new LogException("Domain [" + domain + "] is already defined. Domains cannot be redefined."); } else { // Lookup an alias before trying to create the new domain ILoggerRepository aliasedRepository = m_alias2repositoryMap[domain] as ILoggerRepository; if (aliasedRepository != null) { // Found an alias // Check repository type if (aliasedRepository.GetType() == repositoryType) { // Repository type is compatable LogLog.Debug("DefaultRepositorySelector: Aliasing domain [" + domain + "] to existing repository [" + aliasedRepository.Name + "]"); rep = aliasedRepository; // Store in map m_domain2repositoryMap[domain] = rep; } else { // Invalid repository type for alias LogLog.Error("DefaultRepositorySelector: Failed to alias domain [" + domain + "] to existing repository ["+aliasedRepository.Name+"]. Requested repository type ["+repositoryType.FullName+"] is not compatable with existing type [" + aliasedRepository.GetType().FullName + "]"); // We now drop through to create the domain without aliasing } } // If we could not find an alias if (rep == null) { LogLog.Debug("DefaultRepositorySelector: Creating repository for domain [" + domain + "] using type [" + repositoryType + "]"); // Call the no arg constructor for the repositoryType rep = (ILoggerRepository) repositoryType.GetConstructor(SystemInfo.EmptyTypes).Invoke(BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture); // Set the name of the repository rep.Name = domain; // Store in map m_domain2repositoryMap[domain] = rep; // Notify listeners that the repository has been created FireLoggerRepositoryCreatedEvent(rep); } } return rep; } } /// <summary> /// Copy the list of <see cref="ILoggerRepository"/> objects /// </summary> /// <returns>an array of all known <see cref="ILoggerRepository"/> objects</returns> public ILoggerRepository[] GetAllRepositories() { lock(this) { ICollection reps = m_domain2repositoryMap.Values; ILoggerRepository[] all = new ILoggerRepository[reps.Count]; reps.CopyTo(all, 0); return all; } } #endregion Implementation of IRepositorySelector #region Public Instance Methods /// <summary> /// Alias a domain to an existing repository. /// </summary> /// <param name="domain">The domain to alias.</param> /// <param name="repository">The repository that the domain is aliased to.</param> /// <remarks> /// <para> /// Aliases a domain to an existing repository. /// </para> /// <para> /// The domain specified will be aliased to the repository when created. /// The domain must not already exist. /// </para> /// <para> /// When the domain is created it must utilise the same reporitory type as /// the domain it is aliased to, otherwise the aliasing will fail. /// </para> /// </remarks> public void AliasRepository(string domain, ILoggerRepository repository) { if (domain == null) { throw new ArgumentNullException("domain"); } if (repository == null) { throw new ArgumentNullException("repository"); } lock(this) { // Check if the domain is already aliased if (m_alias2repositoryMap.Contains(domain)) { // Check if this is a duplicate of the current alias if (repository != ((ILoggerRepository)m_alias2repositoryMap[domain])) { // Cannot redefine existing alias throw new InvalidOperationException("Domain [" + domain + "] is already aliased to repository [" + ((ILoggerRepository)m_alias2repositoryMap[domain]).Name + "]. Aliases cannot be redefined."); } } // Check if the domain is already mapped to a repository else if (m_domain2repositoryMap.Contains(domain)) { // Check if this is a duplicate of the current mapping if ( repository != ((ILoggerRepository)m_domain2repositoryMap[domain]) ) { // Cannot define alias for already mapped domain throw new InvalidOperationException("Domain [" + domain + "] already exists and cannot be aliased to repository [" + repository.Name + "]."); } } else { // Set the alias m_alias2repositoryMap[domain] = repository; } } } #endregion Public Instance Methods #region Protected Instance Methods /// <summary> /// Notifies the registered listeners that the repository has been created. /// </summary> /// <param name="repository">The repository that has been created</param> protected void FireLoggerRepositoryCreatedEvent(ILoggerRepository repository) { if (m_loggerRepositoryCreatedEvent != null) { m_loggerRepositoryCreatedEvent(this, new LoggerRepositoryCreationEventArgs(repository)); } } #endregion Protected Instance Methods #region Private Instance Methods /// <summary> /// Get the domain and repository type for the specified assembly /// </summary> /// <param name="assembly">the assembly that has a <see cref="log4net.Config.DomainAttribute"/></param> /// <param name="domain">in/out param to hold the domain to use for the assembly, caller should set this to the default value before calling</param> /// <param name="repositoryType">in/out param to hold the type of the repository to create for the domain, caller should set this to the default value before calling</param> private void GetInfoForAssembly(Assembly assembly, ref string domain, ref Type repositoryType) { if (assembly == null) { throw new ArgumentNullException("assembly"); } LogLog.Debug("DefaultRepositorySelector: Assembly [" + assembly.FullName + "] Loaded From [" + SystemInfo.AssemblyLocationInfo(assembly) + "]"); // Look for the DomainAttribute on the assembly object[] domainAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.DomainAttribute), false); if (domainAttributes == null || domainAttributes.Length == 0) { // This is not a problem, but its nice to know what is going on. LogLog.Debug("DefaultRepositorySelector: Assembly [" + assembly + "] does not have a DomainAttribute specified."); } else { if (domainAttributes.Length > 1) { LogLog.Error("DefaultRepositorySelector: Assembly [" + assembly + "] has multiple log4net.Config.DomainAttribute assembly attributes. Only using first occurrence."); } log4net.Config.DomainAttribute domAttr = domainAttributes[0] as log4net.Config.DomainAttribute; if (domAttr == null) { LogLog.Error("DefaultRepositorySelector: Assembly [" + assembly + "] has a DomainAttribute but it does not!."); } else { // If the Name property is set then override the default if (domAttr.Name != null) { domain = domAttr.Name; } // If the RepositoryType property is set then override the default if (domAttr.RepositoryType != null) { // Check that the type is a repository if (typeof(ILoggerRepository).IsAssignableFrom(domAttr.RepositoryType)) { repositoryType = domAttr.RepositoryType; } else { LogLog.Error("DefaultRepositorySelector: Repository Type [" + domAttr.RepositoryType + "] must implement the ILoggerRepository interface."); } } } } } /// <summary> /// Configure the repository using information from the assembly /// </summary> /// <param name="assembly">The assembly containing <see cref="log4net.Config.ConfiguratorAttribute"/> /// attributes which define the configuration for the repository</param> /// <param name="repository">the repository to configure</param> private void ConfigureRepository(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the Configurator attributes (eg. DOMConfiguratorAttribute) on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.ConfiguratorAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { // Delegate to the attribute the job of configuring the repository foreach(log4net.Config.ConfiguratorAttribute configAttr in configAttributes) { configAttr.Configure(assembly, repository); } } } /// <summary> /// Load the attribute defined plugins on the assembly /// </summary> /// <param name="assembly">the assembly that contains the attributes</param> /// <param name="repository">the repository to alias to</param> private void LoadPlugins(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the PluginAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.PluginAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Plugin.IPluginFactory configAttr in configAttributes) { try { // Create the plugin and add it to the repository repository.PluginMap.Add(configAttr.CreatePlugin()); } catch(Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to create plugin. Attribute [" + configAttr.ToString() + "]", ex); } } } } /// <summary> /// Load the attribute defined aliases on the assembly /// </summary> /// <param name="assembly">the assembly that contains the attributes</param> /// <param name="repository">the repository to alias to</param> private void LoadAliases(Assembly assembly, ILoggerRepository repository) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (repository == null) { throw new ArgumentNullException("repository"); } // Look for the AliasDomainAttribute on the assembly object[] configAttributes = Attribute.GetCustomAttributes(assembly, typeof(log4net.Config.AliasDomainAttribute), false); if (configAttributes != null && configAttributes.Length > 0) { foreach(log4net.Config.AliasDomainAttribute configAttr in configAttributes) { try { AliasRepository(configAttr.Name, repository); } catch(Exception ex) { LogLog.Error("DefaultRepositorySelector: Failed to alias domain [" + configAttr.Name + "]", ex); } } } } #endregion Private Instance Methods #region Private Static Fields private const string DEFAULT_DOMAIN_NAME = "log4net-default-domain"; #endregion Private Static Fields #region Private Instance Fields private IDictionary m_domain2repositoryMap = new Hashtable(); private IDictionary m_assembly2repositoryMap = new Hashtable(); private IDictionary m_alias2repositoryMap = new Hashtable(); private Type m_defaultRepositoryType; private event LoggerRepositoryCreationEventHandler m_loggerRepositoryCreatedEvent; #endregion Private Instance Fields } }
// 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. // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Buffers.Text { public static partial class Utf16Parser { internal static partial class Hex { #region Byte public unsafe static bool TryParseByte(char* text, int length, out byte value) { if (length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.ByteOverflowLengthHex) { // Length is less than or equal to Parsers.ByteOverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.ByteOverflowLengthHex; overflow is only possible after Parsers.ByteOverflowLengthHex // digits. There may be no overflow after Parsers.ByteOverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.ByteOverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.ByteOverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } // If we try to append a digit to anything larger than byte.MaxValue / 0x10, there will be overflow if (parsedValue > byte.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = (byte)(parsedValue); return true; } public unsafe static bool TryParseByte(char* text, int length, out byte value, out int charactersConsumed) { if (length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.ByteOverflowLengthHex) { // Length is less than or equal to Parsers.ByteOverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.ByteOverflowLengthHex; overflow is only possible after Parsers.ByteOverflowLengthHex // digits. There may be no overflow after Parsers.ByteOverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.ByteOverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.ByteOverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } // If we try to append a digit to anything larger than byte.MaxValue / 0x10, there will be overflow if (parsedValue > byte.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = length; value = (byte)(parsedValue); return true; } public static bool TryParseByte(ReadOnlySpan<char> text, out byte value) { if (text.Length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.ByteOverflowLengthHex) { // Length is less than or equal to Parsers.ByteOverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.ByteOverflowLengthHex; overflow is only possible after Parsers.ByteOverflowLengthHex // digits. There may be no overflow after Parsers.ByteOverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.ByteOverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.ByteOverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (byte)(parsedValue); return true; } // If we try to append a digit to anything larger than byte.MaxValue / 0x10, there will be overflow if (parsedValue > byte.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = (byte)(parsedValue); return true; } public static bool TryParseByte(ReadOnlySpan<char> text, out byte value, out int charactersConsumed) { if (text.Length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.ByteOverflowLengthHex) { // Length is less than or equal to Parsers.ByteOverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.ByteOverflowLengthHex; overflow is only possible after Parsers.ByteOverflowLengthHex // digits. There may be no overflow after Parsers.ByteOverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.ByteOverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.ByteOverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (byte)(parsedValue); return true; } // If we try to append a digit to anything larger than byte.MaxValue / 0x10, there will be overflow if (parsedValue > byte.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = text.Length; value = (byte)(parsedValue); return true; } #endregion #region UInt16 public unsafe static bool TryParseUInt16(char* text, int length, out ushort value) { if (length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.Int16OverflowLengthHex) { // Length is less than or equal to Parsers.Int16OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int16OverflowLengthHex; overflow is only possible after Parsers.Int16OverflowLengthHex // digits. There may be no overflow after Parsers.Int16OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int16OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int16OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } // If we try to append a digit to anything larger than ushort.MaxValue / 0x10, there will be overflow if (parsedValue > ushort.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = (ushort)(parsedValue); return true; } public unsafe static bool TryParseUInt16(char* text, int length, out ushort value, out int charactersConsumed) { if (length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.Int16OverflowLengthHex) { // Length is less than or equal to Parsers.Int16OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int16OverflowLengthHex; overflow is only possible after Parsers.Int16OverflowLengthHex // digits. There may be no overflow after Parsers.Int16OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int16OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int16OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } // If we try to append a digit to anything larger than ushort.MaxValue / 0x10, there will be overflow if (parsedValue > ushort.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = length; value = (ushort)(parsedValue); return true; } public static bool TryParseUInt16(ReadOnlySpan<char> text, out ushort value) { if (text.Length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.Int16OverflowLengthHex) { // Length is less than or equal to Parsers.Int16OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int16OverflowLengthHex; overflow is only possible after Parsers.Int16OverflowLengthHex // digits. There may be no overflow after Parsers.Int16OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int16OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int16OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = (ushort)(parsedValue); return true; } // If we try to append a digit to anything larger than ushort.MaxValue / 0x10, there will be overflow if (parsedValue > ushort.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = (ushort)(parsedValue); return true; } public static bool TryParseUInt16(ReadOnlySpan<char> text, out ushort value, out int charactersConsumed) { if (text.Length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.Int16OverflowLengthHex) { // Length is less than or equal to Parsers.Int16OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int16OverflowLengthHex; overflow is only possible after Parsers.Int16OverflowLengthHex // digits. There may be no overflow after Parsers.Int16OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int16OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int16OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = (ushort)(parsedValue); return true; } // If we try to append a digit to anything larger than ushort.MaxValue / 0x10, there will be overflow if (parsedValue > ushort.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = text.Length; value = (ushort)(parsedValue); return true; } #endregion #region UInt32 public unsafe static bool TryParseUInt32(char* text, int length, out uint value) { if (length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.Int32OverflowLengthHex) { // Length is less than or equal to Parsers.Int32OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int32OverflowLengthHex; overflow is only possible after Parsers.Int32OverflowLengthHex // digits. There may be no overflow after Parsers.Int32OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int32OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int32OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } // If we try to append a digit to anything larger than uint.MaxValue / 0x10, there will be overflow if (parsedValue > uint.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = parsedValue; return true; } public unsafe static bool TryParseUInt32(char* text, int length, out uint value, out int charactersConsumed) { if (length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (length <= Parsers.Int32OverflowLengthHex) { // Length is less than or equal to Parsers.Int32OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int32OverflowLengthHex; overflow is only possible after Parsers.Int32OverflowLengthHex // digits. There may be no overflow after Parsers.Int32OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int32OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int32OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } // If we try to append a digit to anything larger than uint.MaxValue / 0x10, there will be overflow if (parsedValue > uint.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = length; value = parsedValue; return true; } public static bool TryParseUInt32(ReadOnlySpan<char> text, out uint value) { if (text.Length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.Int32OverflowLengthHex) { // Length is less than or equal to Parsers.Int32OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int32OverflowLengthHex; overflow is only possible after Parsers.Int32OverflowLengthHex // digits. There may be no overflow after Parsers.Int32OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int32OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int32OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } // If we try to append a digit to anything larger than uint.MaxValue / 0x10, there will be overflow if (parsedValue > uint.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = parsedValue; return true; } public static bool TryParseUInt32(ReadOnlySpan<char> text, out uint value, out int charactersConsumed) { if (text.Length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } uint parsedValue = nextDigit; if (text.Length <= Parsers.Int32OverflowLengthHex) { // Length is less than or equal to Parsers.Int32OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int32OverflowLengthHex; overflow is only possible after Parsers.Int32OverflowLengthHex // digits. There may be no overflow after Parsers.Int32OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int32OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int32OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } // If we try to append a digit to anything larger than uint.MaxValue / 0x10, there will be overflow if (parsedValue > uint.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = text.Length; value = parsedValue; return true; } #endregion #region UInt64 public unsafe static bool TryParseUInt64(char* text, int length, out ulong value) { if (length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } ulong parsedValue = nextDigit; if (length <= Parsers.Int64OverflowLengthHex) { // Length is less than or equal to Parsers.Int64OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int64OverflowLengthHex; overflow is only possible after Parsers.Int64OverflowLengthHex // digits. There may be no overflow after Parsers.Int64OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int64OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int64OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } // If we try to append a digit to anything larger than ulong.MaxValue / 0x10, there will be overflow if (parsedValue > ulong.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = parsedValue; return true; } public unsafe static bool TryParseUInt64(char* text, int length, out ulong value, out int charactersConsumed) { if (length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } ulong parsedValue = nextDigit; if (length <= Parsers.Int64OverflowLengthHex) { // Length is less than or equal to Parsers.Int64OverflowLengthHex; overflow is not possible for (int index = 1; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int64OverflowLengthHex; overflow is only possible after Parsers.Int64OverflowLengthHex // digits. There may be no overflow after Parsers.Int64OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int64OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int64OverflowLengthHex; index < length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } // If we try to append a digit to anything larger than ulong.MaxValue / 0x10, there will be overflow if (parsedValue > ulong.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = length; value = parsedValue; return true; } public static bool TryParseUInt64(ReadOnlySpan<char> text, out ulong value) { if (text.Length < 1) { value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = default; return false; } ulong parsedValue = nextDigit; if (text.Length <= Parsers.Int64OverflowLengthHex) { // Length is less than or equal to Parsers.Int64OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int64OverflowLengthHex; overflow is only possible after Parsers.Int64OverflowLengthHex // digits. There may be no overflow after Parsers.Int64OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int64OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int64OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { value = parsedValue; return true; } // If we try to append a digit to anything larger than ulong.MaxValue / 0x10, there will be overflow if (parsedValue > ulong.MaxValue / 0x10) { value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } value = parsedValue; return true; } public static bool TryParseUInt64(ReadOnlySpan<char> text, out ulong value, out int charactersConsumed) { if (text.Length < 1) { charactersConsumed = 0; value = default; return false; } char nextCharacter; byte nextDigit; // Cache Parsers.s_HexLookup in order to avoid static constructor checks byte[] hexLookup = Parsers.HexLookup; // Parse the first digit separately. If invalid here, we need to return false. nextCharacter = text[0]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = 0; value = default; return false; } ulong parsedValue = nextDigit; if (text.Length <= Parsers.Int64OverflowLengthHex) { // Length is less than or equal to Parsers.Int64OverflowLengthHex; overflow is not possible for (int index = 1; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } } else { // Length is greater than Parsers.Int64OverflowLengthHex; overflow is only possible after Parsers.Int64OverflowLengthHex // digits. There may be no overflow after Parsers.Int64OverflowLengthHex if there are leading zeroes. for (int index = 1; index < Parsers.Int64OverflowLengthHex; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } parsedValue = (parsedValue << 4) + nextDigit; } for (int index = Parsers.Int64OverflowLengthHex; index < text.Length; index++) { nextCharacter = text[index]; nextDigit = hexLookup[(byte)nextCharacter]; if (nextDigit == 0xFF || (nextCharacter >> 8) != 0) { charactersConsumed = index; value = parsedValue; return true; } // If we try to append a digit to anything larger than ulong.MaxValue / 0x10, there will be overflow if (parsedValue > ulong.MaxValue / 0x10) { charactersConsumed = 0; value = default; return false; } parsedValue = (parsedValue << 4) + nextDigit; } } charactersConsumed = text.Length; value = parsedValue; return true; } #endregion } } }
using AxoCover.Common.Events; using AxoCover.Common.Extensions; using AxoCover.Models.Editor; using AxoCover.Models.Extensions; using AxoCover.Models.Telemetry; using AxoCover.Models.Testing.Data; using AxoCover.Models.Testing.Data.CoverageReport; using AxoCover.Models.Testing.Discovery; using AxoCover.Models.Testing.Execution; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AxoCover.Models.Testing.Results { public class CoverageProvider : ICoverageProvider { public event EventHandler CoverageUpdated; private const string _anonymousGroupName = "Anonymous"; private readonly ITestRunner _testRunner; private readonly ITelemetryManager _telemetryManager; private readonly IEditorContext _editorContext; private CoverageSession _report; private Dictionary<int, TestMethod[]> _trackedMethods = new Dictionary<int, TestMethod[]>(); private static readonly Regex _methodNameRegex = new Regex("^(?<returnType>[^ ]*) [^:]*::(?<methodName>[^\\(]*)\\((?<argumentList>[^\\)]*)\\)$", RegexOptions.Compiled); private readonly Regex _visitorNameRegex = new Regex("^[^ ]* (?<visitorName>[^:]*::[^\\(]*)\\([^\\)]*\\)$", RegexOptions.Compiled); public string ReportPath => _report?.FilePath; public CoverageProvider(ITestProvider testProvider, ITestRunner testRunner, ITelemetryManager telemetryManager, IEditorContext editorContext) { _testRunner = testRunner; _telemetryManager = telemetryManager; _testRunner.TestsFinished += OnTestsFinished; _editorContext = editorContext; _editorContext.SolutionClosing += OnSolutionClosing; } public bool TryOpenCoverageReport(string reportPath) { try { _report = GenericExtensions.ParseXml<CoverageSession>(reportPath); CoverageUpdated?.Invoke(this, EventArgs.Empty); return true; } catch { return false; } } private void OnSolutionClosing(object sender, EventArgs e) { _report = null; _trackedMethods = new Dictionary<int, TestMethod[]>(); } private void OnTestsFinished(object sender, EventArgs<TestReport> e) { if (e.Value.CoverageReport != null) { _report = e.Value.CoverageReport; var testMethods = e.Value.TestResults .Select(p => p.Method) .GroupBy(p => (p.Kind == CodeItemKind.Data ? p.Parent.FullName : p.FullName).CleanPath(true)) .ToDictionary(p => p.Key, p => p.ToArray()); _trackedMethods = _report.Modules .SelectMany(p => p.TrackedMethods) .Select(p => new { Id = p.Id, NameMatch = _visitorNameRegex.Match(p.Name), Name = p.Name }) .DoIf(p => !p.NameMatch.Success, p => _telemetryManager.UploadExceptionAsync(new Exception("Could not parse tracked method name: " + p.Name))) .Where(p => p.NameMatch.Success) .ToDictionary(p => p.Id, p => testMethods.TryGetValue(p.NameMatch.Groups["visitorName"].Value.Replace("::", ".")) ?? new TestMethod[0]); CoverageUpdated?.Invoke(this, EventArgs.Empty); } } public async Task<FileCoverage> GetFileCoverageAsync(string filePath) { if (filePath == null) throw new ArgumentNullException(nameof(filePath)); var report = _report; var trackedMethods = _trackedMethods; return await Task.Run(() => GetFileCoverage(report, trackedMethods, filePath)); } private static FileCoverage GetFileCoverage(CoverageSession report, Dictionary<int, TestMethod[]> trackedMethods, string filePath) { if (report != null) { foreach (var module in report.Modules) { var file = module.Files .FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Equals(p.FullPath, filePath)); if (file == null) continue; var methods = module.Classes .SelectMany(p => p.Methods) .Where(p => p.FileRef != null && p.FileRef.Id == file.Id) .ToArray(); var sequenceGroups = methods .SelectMany(p => p.SequencePoints) .SelectMany(p => Enumerable .Range(p.StartLine, p.EndLine - p.StartLine + 1) .Select(q => new { LineNumber = q - 1, VisitCount = p.VisitCount, Start = q == p.StartLine ? p.StartColumn - 1 : 0, End = q == p.EndLine ? p.EndColumn - 1 : int.MaxValue, Visitors = p.TrackedMethodRefs })) .GroupBy(p => p.LineNumber) .ToDictionary(p => p.Key); var branchGroups = methods .SelectMany(p => p.BranchPoints) .GroupBy(p => p.StartLine) .ToDictionary(p => p.Key - 1); var affectedLines = sequenceGroups .Select(p => p.Key) .Concat(branchGroups.Select(p => p.Key)) .Distinct(); var lineCoverages = new Dictionary<int, LineCoverage>(); foreach (var affectedLine in affectedLines) { var sequenceGroup = sequenceGroups.TryGetValue(affectedLine); var branchGroup = branchGroups.TryGetValue(affectedLine); var visitCount = sequenceGroup.Max(p => p.VisitCount); var sequenceState = sequenceGroup.All(p => p.VisitCount > 0) ? CoverageState.Covered : (sequenceGroup.All(p => p.VisitCount == 0) ? CoverageState.Uncovered : CoverageState.Mixed); var unvisitedSections = sequenceGroup .Where(p => p.VisitCount == 0) .Select(p => new LineSection(p.Start, p.End)) .ToArray(); var branchesVisited = branchGroup? .GroupBy(p => p.Offset) .Select(p => p .OrderBy(q => q.Path) .Select(q => q.VisitCount > 0) .ToArray()) .ToArray() ?? new bool[0][]; var branchPoints = branchesVisited.SelectMany(p => p).ToArray(); var branchState = branchPoints.All(p => p) ? CoverageState.Covered : (branchPoints.All(p => !p) ? CoverageState.Uncovered : CoverageState.Mixed); var lineVisitors = new HashSet<TestMethod>(sequenceGroup .SelectMany(p => p.Visitors) .Select(p => p.Id) .Distinct() .Where(p => trackedMethods.ContainsKey(p)) .SelectMany(p => trackedMethods[p])); var branchVisitors = branchGroup? .GroupBy(p => p.Offset) .Select(p => p .OrderBy(q => q.Path) .Select(q => new HashSet<TestMethod>(q.TrackedMethodRefs .Where(r => trackedMethods.ContainsKey(r.Id)) .SelectMany(r => trackedMethods[r.Id]))) .ToArray()) .ToArray() ?? new HashSet<TestMethod>[0][]; var lineCoverage = new LineCoverage(visitCount, sequenceState, branchState, branchesVisited, unvisitedSections, lineVisitors, branchVisitors); lineCoverages.Add(affectedLine, lineCoverage); } return new FileCoverage(lineCoverages); } } return FileCoverage.Empty; } public async Task<CoverageItem> GetCoverageAsync() { var report = _report; return await Task.Run(() => GetCoverage(report)); } private static CoverageItem GetCoverage(CoverageSession report) { if (report == null) return null; var solutionResult = new CoverageItem(null, Resources.Assemblies, CodeItemKind.Solution); foreach (var moduleReport in report.Modules) { if (!moduleReport.Classes.Any()) continue; var projectResult = new CoverageItem(solutionResult, moduleReport.ModuleName, CodeItemKind.Project); var results = new Dictionary<string, CoverageItem>() { { "", projectResult } }; foreach (var classReport in moduleReport.Classes) { if (classReport.Methods.Length == 0) continue; var classResult = AddResultItem(results, CodeItemKind.Class, PreparePath(classReport.FullName), classReport.Summary ?? new Summary()); foreach (var methodReport in classReport.Methods) { if (methodReport.SequencePoints.Length == 0) continue; var sourceFile = methodReport.FileRef != null ? moduleReport.Files.Where(p => p.Id == methodReport.FileRef.Id).Select(p => p.FullPath).FirstOrDefault() : null; var sourceLine = methodReport.SequencePoints.Select(p => p.StartLine).FirstOrDefault(); var methodNameMatch = _methodNameRegex.Match(methodReport.Name); if (!methodNameMatch.Success) continue; var returnType = methodNameMatch.Groups["returnType"].Value; var methodName = methodNameMatch.Groups["methodName"].Value; var argumentList = methodNameMatch.Groups["argumentList"].Value; var name = $"{methodName}({argumentList}) : {returnType}"; var methodResult = AddResultItem(results, CodeItemKind.Method, PreparePath(classResult.FullName + "." + methodName.Replace(".", "-")), methodReport.Summary ?? new Summary(), name); methodResult.SourceFile = sourceFile; methodResult.SourceLine = sourceLine; } var firstSource = classResult.Children .Where(p => p.SourceFile != null) .OrderBy(p => p.SourceLine) .FirstOrDefault(); if (firstSource != null) { classResult.SourceFile = firstSource.SourceFile; classResult.SourceLine = firstSource.SourceLine; } } } return solutionResult; } private static string PreparePath(string itemPath) { var nameParts = itemPath.Replace('/', '.').SplitPath(false); var result = string.Empty; var isInsideAnonymousGroup = false; foreach(var namePart in nameParts) { if(!isInsideAnonymousGroup && namePart.StartsWith("<")) { result += "." + _anonymousGroupName; isInsideAnonymousGroup = true; } result += "." + namePart; } return result.TrimStart('.'); } private static CoverageItem AddResultItem(Dictionary<string, CoverageItem> items, CodeItemKind itemKind, string itemPath, Summary summary, string displayName = null) { var nameParts = itemPath.SplitPath(false); var parentName = string.Join(".", nameParts.Take(nameParts.Length - 1)).TrimEnd('.'); //Remove dot for .ctor and .cctor var itemName = nameParts[nameParts.Length - 1]; CoverageItem parent; if (!items.TryGetValue(parentName, out parent)) { if(parentName.EndsWith("." + _anonymousGroupName) || parentName == _anonymousGroupName) { parent = AddResultItem(items, CodeItemKind.Group, parentName, new Summary()); } else if (itemKind == CodeItemKind.Method) { parent = AddResultItem(items, CodeItemKind.Class, parentName, new Summary()); } else { parent = AddResultItem(items, CodeItemKind.Namespace, parentName, new Summary()); } } var item = new CoverageItem(parent, itemName, itemKind, summary, displayName); //Methods cannot be a parent so adding them is unnecessary - also overloads would result in key already exists exceptions if (itemKind != CodeItemKind.Method) { items.Add(itemPath, item); } return item; } } }
// 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.IO; using System.Runtime.Serialization; // For SR using System.Text; namespace System.Xml { // This wrapper does not support seek. // Constructors consume/emit byte order mark. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. // ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration // ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration // during construction. internal class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private const int BufferLength = 128; // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; private Encoding _encoding; private Encoder _enc; private Decoder _dec; private bool _isReading; private Stream _stream; private char[] _chars; private byte[] _bytes; private int _byteOffset; private int _byteCount; private byte[] _byteBuffer = new byte[1]; // Reading constructor public EncodingStreamWrapper(Stream stream, Encoding encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); _encodingCode = e; _encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) { switch (e) { case SupportedEncoding.UTF8: return s_validatingUTF8; case SupportedEncoding.UTF16LE: return s_validatingUTF16; case SupportedEncoding.UTF16BE: return s_validatingBEUTF16; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static Encoding GetSafeEncoding(SupportedEncoding e) { switch (e) { case SupportedEncoding.UTF8: return s_safeUTF8; case SupportedEncoding.UTF16LE: return s_safeUTF16; case SupportedEncoding.UTF16BE: return s_safeBEUTF16; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static string GetEncodingName(SupportedEncoding enc) { switch (enc) { case SupportedEncoding.UTF8: return "utf-8"; case SupportedEncoding.UTF16LE: return "utf-16LE"; case SupportedEncoding.UTF16BE: return "utf-16BE"; default: throw new XmlException(SR.XmlEncodingNotSupported); } } private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; else if (encoding.WebName == s_validatingUTF16.WebName) return SupportedEncoding.UTF16LE; else if (encoding.WebName == s_validatingBEUTF16.WebName) return SupportedEncoding.UTF16BE; else throw new XmlException(SR.XmlEncodingNotSupported); } // Writing constructor public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { _isReading = false; _encoding = encoding; _stream = stream; // Set the encoding code _encodingCode = GetSupportedEncoding(encoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); // Emit BOM if (emitBOM) { ReadOnlySpan<byte> bom = _encoding.Preamble; if (bom.Length > 0) _stream.Write(bom); } } } private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); int b3 = _stream.ReadByte(); int b4 = _stream.ReadByte(); // Premature end of stream if (b4 == -1) throw new XmlException(SR.UnexpectedEndOfFile); int preserve; SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: _bytes[0] = (byte)b4; break; case 2: _bytes[0] = (byte)b3; _bytes[1] = (byte)b4; break; case 4: _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _bytes[2] = (byte)b3; _bytes[3] = (byte)b4; break; } _byteCount = preserve; return e; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding e = SupportedEncoding.UTF8; // Default preserve = 0; if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM { e = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian { e = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian { e = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM { e = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0x00 || b4 != '?')) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM { e = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != '?' || b4 != 0x00)) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM { // Encoding error if (notOutOfBand && b3 != 0xBF) throw new XmlException(SR.XmlBadBOM); preserve = 1; } else // Assume UTF8 { preserve = 4; } return e; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes, _byteOffset + _byteCount, count); if (read == 0) break; _byteCount += read; count -= read; } } private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) _chars = new char[BufferLength]; } private void EnsureByteBuffer() { if (_bytes != null) return; _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte quot = 0; int encEq = -1; int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" int i = 0; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?" { if (quot != 0) { if (buffer[i] == quot) { quot = 0; } continue; } if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"') { quot = buffer[i]; } else if (buffer[i] == (byte)'=') { if (eq == 1) { encEq = i; break; } eq++; } else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "=" { break; } } // No encoding found if (encEq == -1) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } if (encEq < 28) // Earliest second "=" can appear throw new XmlException(SR.XmlMalformedDecl); // Back off whitespace for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ; // Check for encoding attribute if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1)) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } // Move ahead of whitespace for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ; // Find the quotes if (buffer[i] != '\'' && buffer[i] != '"') throw new XmlException(SR.XmlMalformedDecl); quot = buffer[i]; int q = i; for (i = q + 1; buffer[i] != quot && i < max; ++i) ; if (buffer[i] != quot) throw new XmlException(SR.XmlMalformedDecl); int encStart = q + 1; int encCount = i - encStart; // lookup the encoding SupportedEncoding declEnc = e; if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart)) { declEnc = SupportedEncoding.UTF8; } else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16LE; } else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16BE; } else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart)) { if (e == SupportedEncoding.UTF8) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length)); } else { ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } if (e != declEnc) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] == buffer[offset + i]) continue; if (key[i] != Char.ToLowerInvariant((char)buffer[offset + i])) return false; } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) return false; } return true; } private static bool IsWhitespace(byte ch) { return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); try { int preserve; ArraySegment<byte> seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); offset += 4 - preserve; count -= 4 - preserve; // Fastpath: UTF-8 char[] chars; byte[] bytes; Encoding localEnc; if (declEnc == SupportedEncoding.UTF8) { // Fastpath: No declaration if (buffer[offset + 1] != '?' || buffer[offset] != '<') { seg = new ArraySegment<byte>(buffer, offset, count); return seg; } CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc); seg = new ArraySegment<byte>(buffer, offset, count); return seg; } // Convert to UTF-8 localEnc = GetSafeEncoding(declEnc); int inputCount = Math.Min(count, BufferLength * 2); chars = new char[localEnc.GetMaxCharCount(inputCount)]; int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0); bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)]; int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0); // Check for declaration if (bytes[1] == '?' && bytes[0] == '<') { CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count))); return seg; } catch (DecoderFallbackException e) { throw new XmlException(SR.XmlInvalidBytes, e); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc)); } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) return false; return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) return false; return _stream.CanWrite; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (_stream.CanWrite) { Flush(); } _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) return _stream.ReadByte(); if (Read(_byteBuffer, 0, 1) == 0) return -1; return _byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) return 0; // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void CleanupCharBreak() { int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } } // Add format exceptions // Do we need to modify the stream position/Seek to account for the buffer? // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. }
// // EditPackagesDialog.cs: Allows you to add and remove pkg-config packages to the project // // Authors: // Marcos David Marin Amador <MarcosMarin@gmail.com> // // Copyright (C) 2007 Marcos David Marin Amador // // // This source code is licenced under The 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.IO; using System.Collections.Generic; using MonoDevelop.Projects; using MonoDevelop.Ide; using MonoDevelop.Components; namespace CBinding { public partial class EditPackagesDialog : Gtk.Dialog { private Gtk.ListStore normalPackageListStore = new Gtk.ListStore (typeof(bool), typeof(string), typeof(string)); private Gtk.ListStore projectPackageListStore = new Gtk.ListStore (typeof(bool), typeof(string), typeof(string)); private Gtk.ListStore selectedPackageListStore = new Gtk.ListStore (typeof(string), typeof(string)); private CProject project; private ProjectPackageCollection selectedPackages = new ProjectPackageCollection (); private List<Package> packagesOfProjects; private List<Package> packages = new List<Package> (); // Column IDs const int NormalPackageToggleID = 0; const int NormalPackageNameID = 1; const int NormalPackageVersionID = 2; const int ProjectPackageToggleID = 0; const int ProjectPackageNameID = 1; const int ProjectPackageVersionID = 2; const int SelectedPackageNameID = 0; const int SelectedPackageVersionID = 1; public EditPackagesDialog(CProject project) { this.Build(); this.project = project; selectedPackages.Project = project; selectedPackages.AddRange (project.Packages); Gtk.CellRendererText textRenderer = new Gtk.CellRendererText (); CellRendererImage pixbufRenderer = new CellRendererImage (); pixbufRenderer.StockId = "md-package"; normalPackageListStore.DefaultSortFunc = NormalPackageCompareNodes; projectPackageListStore.DefaultSortFunc = ProjectPackageCompareNodes; selectedPackageListStore.DefaultSortFunc = SelectedPackageCompareNodes; normalPackageListStore.SetSortColumnId (NormalPackageNameID, Gtk.SortType.Ascending); projectPackageListStore.SetSortColumnId (ProjectPackageNameID, Gtk.SortType.Ascending); selectedPackageListStore.SetSortColumnId (SelectedPackageNameID, Gtk.SortType.Ascending); normalPackageTreeView.SearchColumn = NormalPackageNameID; projectPackageTreeView.SearchColumn = ProjectPackageNameID; selectedPackageTreeView.SearchColumn = SelectedPackageNameID; // <!-- Normal packages --> Gtk.CellRendererToggle normalPackageToggleRenderer = new Gtk.CellRendererToggle (); normalPackageToggleRenderer.Activatable = true; normalPackageToggleRenderer.Toggled += OnNormalPackageToggled; normalPackageToggleRenderer.Xalign = 0; Gtk.TreeViewColumn normalPackageColumn = new Gtk.TreeViewColumn (); normalPackageColumn.Title = "Package"; normalPackageColumn.PackStart (pixbufRenderer, false); normalPackageColumn.PackStart (textRenderer, true); normalPackageColumn.AddAttribute (textRenderer, "text", NormalPackageNameID); normalPackageTreeView.Model = normalPackageListStore; normalPackageTreeView.HeadersVisible = true; normalPackageTreeView.AppendColumn ("", normalPackageToggleRenderer, "active", NormalPackageToggleID); normalPackageTreeView.AppendColumn (normalPackageColumn); normalPackageTreeView.AppendColumn ("Version", textRenderer, "text", NormalPackageVersionID); // <!-- Project packages --> Gtk.CellRendererToggle projectPackageToggleRenderer = new Gtk.CellRendererToggle (); projectPackageToggleRenderer.Activatable = true; projectPackageToggleRenderer.Toggled += OnProjectPackageToggled; projectPackageToggleRenderer.Xalign = 0; Gtk.TreeViewColumn projectPackageColumn = new Gtk.TreeViewColumn (); projectPackageColumn.Title = "Package"; projectPackageColumn.PackStart (pixbufRenderer, false); projectPackageColumn.PackStart (textRenderer, true); projectPackageColumn.AddAttribute (textRenderer, "text", ProjectPackageNameID); projectPackageTreeView.Model = projectPackageListStore; projectPackageTreeView.HeadersVisible = true; projectPackageTreeView.AppendColumn ("", projectPackageToggleRenderer, "active", ProjectPackageToggleID); projectPackageTreeView.AppendColumn (projectPackageColumn); projectPackageTreeView.AppendColumn ("Version", textRenderer, "text", ProjectPackageVersionID); // <!-- Selected packages --> Gtk.TreeViewColumn selectedPackageColumn = new Gtk.TreeViewColumn (); selectedPackageColumn.Title = "Package"; selectedPackageColumn.PackStart (pixbufRenderer, false); selectedPackageColumn.PackStart (textRenderer, true); selectedPackageColumn.AddAttribute (textRenderer, "text", SelectedPackageNameID); selectedPackageTreeView.Model = selectedPackageListStore; selectedPackageTreeView.HeadersVisible = true; selectedPackageTreeView.AppendColumn (selectedPackageColumn); selectedPackageTreeView.AppendColumn ("Version", textRenderer, "text", SelectedPackageVersionID); // Fill up the project tree view packagesOfProjects = GetPackagesOfProjects (project); foreach (Package p in packagesOfProjects) { if (p.Name == project.Name) continue; packages.Add (p); string version = p.Version; bool inProject = selectedPackages.Contains (p); if (!IsPackageInStore (projectPackageListStore, p.Name, version, ProjectPackageNameID, ProjectPackageVersionID)) { projectPackageListStore.AppendValues (inProject, p.Name, version); if (inProject) selectedPackageListStore.AppendValues (p.Name, version); } } // Fill up the normal tree view foreach (string dir in ScanDirs ()) { if (Directory.Exists (dir)) { DirectoryInfo di = new DirectoryInfo (dir); FileInfo[] availablePackages = di.GetFiles ("*.pc"); foreach (FileInfo f in availablePackages) { if (!IsValidPackage (f.FullName)) { continue; } Package package = new Package (f.FullName); packages.Add (package); string name = package.Name; string version = package.Version; bool inProject = selectedPackages.Contains (package); if (!IsPackageInStore (normalPackageListStore, name, version, NormalPackageNameID, NormalPackageVersionID)) { normalPackageListStore.AppendValues (inProject, name, version); if (inProject) selectedPackageListStore.AppendValues (name, version); } } } } } private List<Package> GetPackagesOfProjects (Project project) { List<Package> packages = new List<Package>(); Package package; foreach (SolutionFolderItem c in project.ParentFolder.Items) { if (null != c && c is CProject) { CProject cproj = (CProject)c; CProjectConfiguration conf = (CProjectConfiguration)cproj.GetConfiguration (IdeApp.Workspace.ActiveConfiguration); if (conf.CompileTarget != CBinding.CompileTarget.Bin) { cproj.WriteMDPkgPackage (conf.Selector); package = new Package (cproj); packages.Add (package); } } } return packages; } private bool IsPackageInStore (Gtk.ListStore store, string pname, string pversion, int pname_col, int pversion_col) { Gtk.TreeIter search_iter; bool has_elem = store.GetIterFirst (out search_iter); if (has_elem) { while (true) { string name = (string)store.GetValue (search_iter, pname_col); string version = (string)store.GetValue (search_iter, pversion_col); if (name == pname && version == pversion) return true; if (!store.IterNext (ref search_iter)) break; } } return false; } private string[] ScanDirs () { List<string> dirs = new List<string> (); string pkg_var = Environment.GetEnvironmentVariable ("PKG_CONFIG_PATH"); string[] pkg_paths; dirs.Add ("/usr/lib/pkgconfig"); dirs.Add ("/usr/lib64/pkgconfig"); dirs.Add ("/usr/share/pkgconfig"); dirs.Add ("/usr/local/lib/pkgconfig"); dirs.Add ("/usr/local/share/pkgconfig"); dirs.Add ("/usr/lib/x86_64-linux-gnu/pkgconfig"); if (pkg_var == null) return dirs.ToArray (); pkg_paths = pkg_var.Split (':'); foreach (string dir in pkg_paths) { if (string.IsNullOrEmpty (dir)) continue; string dirPath = System.IO.Path.GetFullPath (dir); if (!dirs.Contains (dirPath) && !string.IsNullOrEmpty (dir)) { dirs.Add (dir); } } return dirs.ToArray (); } private void OnOkButtonClick (object sender, EventArgs e) { // Use this instead of clear, since clear seems to not update the packages tree while (project.Packages.Count > 0) { project.Packages.RemoveAt (0); } project.Packages.AddRange (selectedPackages); Destroy (); } private void OnCancelButtonClick (object sender, EventArgs e) { Destroy (); } private void OnRemoveButtonClick (object sender, EventArgs e) { Gtk.TreeIter iter; selectedPackageTreeView.Selection.GetSelected (out iter); if (!selectedPackageListStore.IterIsValid (iter)) return; string package = (string)selectedPackageListStore.GetValue (iter, SelectedPackageNameID); bool isProject = false; foreach (Package p in selectedPackages) { if (p.Name == package) { isProject = p.IsProject; selectedPackages.Remove (p); break; } } selectedPackageListStore.Remove (ref iter); if (!isProject) { Gtk.TreeIter search_iter; bool has_elem = normalPackageListStore.GetIterFirst (out search_iter); if (has_elem) { while (true) { string current = (string)normalPackageListStore.GetValue (search_iter, NormalPackageNameID); if (current.Equals (package)) { normalPackageListStore.SetValue (search_iter, NormalPackageToggleID, false); break; } if (!normalPackageListStore.IterNext (ref search_iter)) break; } } } else { Gtk.TreeIter search_iter; bool has_elem = projectPackageListStore.GetIterFirst (out search_iter); if (has_elem) { while (true) { string current = (string)projectPackageListStore.GetValue (search_iter, ProjectPackageNameID); if (current.Equals (package)) { projectPackageListStore.SetValue (search_iter, ProjectPackageToggleID, false); break; } if (!projectPackageListStore.IterNext (ref search_iter)) break; } } } } private void OnNormalPackageToggled (object sender, Gtk.ToggledArgs args) { Gtk.TreeIter iter; bool old = true; string name; string version; if (normalPackageListStore.GetIter (out iter, new Gtk.TreePath (args.Path))) { old = (bool)normalPackageListStore.GetValue (iter, NormalPackageToggleID); normalPackageListStore.SetValue (iter, NormalPackageToggleID, !old); } name = (string)normalPackageListStore.GetValue (iter, NormalPackageNameID); version = (string)normalPackageListStore.GetValue(iter, NormalPackageVersionID); if (old == false) { selectedPackageListStore.AppendValues (name, version); foreach (Package package in packages) { if (package.Name == name && package.Version == version) { selectedPackages.Add (package); break; } } } else { Gtk.TreeIter search_iter; bool has_elem = selectedPackageListStore.GetIterFirst (out search_iter); if (has_elem) { while (true) { string current = (string)selectedPackageListStore.GetValue (search_iter, SelectedPackageNameID); if (current.Equals (name)) { selectedPackageListStore.Remove (ref search_iter); foreach (Package p in selectedPackages) { if (p.Name == name) { selectedPackages.Remove (p); break; } } break; } if (!selectedPackageListStore.IterNext (ref search_iter)) break; } } } } private void OnProjectPackageToggled (object sender, Gtk.ToggledArgs args) { Gtk.TreeIter iter; bool old = true; string name; string version; if (projectPackageListStore.GetIter (out iter, new Gtk.TreePath (args.Path))) { old = (bool)projectPackageListStore.GetValue (iter, ProjectPackageToggleID); projectPackageListStore.SetValue (iter, ProjectPackageToggleID, !old); } name = (string)projectPackageListStore.GetValue (iter, ProjectPackageNameID); version = (string)projectPackageListStore.GetValue(iter, ProjectPackageVersionID); if (old == false) { selectedPackageListStore.AppendValues (name, version); foreach (Package p in packagesOfProjects) { if (p.Name == name) { selectedPackages.Add (p); break; } } } else { Gtk.TreeIter search_iter; bool has_elem = selectedPackageListStore.GetIterFirst (out search_iter); if (has_elem) { while (true) { string current = (string)selectedPackageListStore.GetValue (search_iter, SelectedPackageNameID); if (current.Equals (name)) { selectedPackageListStore.Remove (ref search_iter); foreach (Package p in selectedPackages) { if (p.Name == name) { selectedPackages.Remove (p); break; } } break; } if (!selectedPackageListStore.IterNext (ref search_iter)) break; } } } } private bool IsValidPackage (string package) { bool valid = false; try { using (StreamReader reader = new StreamReader (package)) { string line; while ((line = reader.ReadLine ()) != null) { if (line.StartsWith ("Libs:", true, null) && line.Contains (" -l")) { valid = true; break; } } } } catch { // Invalid file, permission error, broken symlink } return valid; } int NormalPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b) { string name1 = (string)model.GetValue (a, NormalPackageNameID); string name2 = (string)model.GetValue (b, NormalPackageNameID); return string.Compare (name1, name2, true); } int ProjectPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b) { string name1 = (string)model.GetValue (a, ProjectPackageNameID); string name2 = (string)model.GetValue (b, ProjectPackageNameID); return string.Compare (name1, name2, true); } int SelectedPackageCompareNodes (Gtk.TreeModel model, Gtk.TreeIter a, Gtk.TreeIter b) { string name1 = (string)model.GetValue (a, SelectedPackageNameID); string name2 = (string)model.GetValue (b, SelectedPackageNameID); return string.Compare (name1, name2, true); } protected virtual void OnSelectedPackagesTreeViewCursorChanged (object sender, System.EventArgs e) { removeButton.Sensitive = true; } protected virtual void OnRemoveButtonClicked (object sender, System.EventArgs e) { removeButton.Sensitive = false; } protected virtual void OnDetailsButtonClicked (object sender, System.EventArgs e) { Gtk.TreeIter iter; Gtk.Widget active_tab = notebook1.Children [notebook1.Page]; string tab_label = notebook1.GetTabLabelText (active_tab); string name = string.Empty; string version = string.Empty; Package package = null; if (tab_label == "System Packages") { normalPackageTreeView.Selection.GetSelected (out iter); name = (string)normalPackageListStore.GetValue (iter, NormalPackageNameID); version = (string)normalPackageListStore.GetValue (iter, NormalPackageVersionID); } else if (tab_label == "Project Packages") { projectPackageTreeView.Selection.GetSelected (out iter); name = (string)projectPackageListStore.GetValue (iter, ProjectPackageNameID); version = (string)projectPackageListStore.GetValue (iter, ProjectPackageVersionID); } else { return; } foreach (Package p in packages) { if (p.Name == name && p.Version == version) { package = p; break; } } if (package == null) return; PackageDetails details = new PackageDetails (package); details.Modal = true; details.Show (); } protected virtual void OnNonSelectedPackageCursorChanged (object o, EventArgs e) { Gtk.TreeIter iter; Gtk.Widget active_tab = notebook1.Children [notebook1.Page]; Gtk.Widget active_label = notebook1.GetTabLabel (active_tab); bool sensitive = false; if (active_label == this.labelSystemPackages) { normalPackageTreeView.Selection.GetSelected (out iter); if (normalPackageListStore.IterIsValid (iter)) sensitive = true; } else if (active_label == this.labelProjectPackages) { projectPackageTreeView.Selection.GetSelected (out iter); if (projectPackageListStore.IterIsValid (iter)) sensitive = true; } else { return; } detailsButton.Sensitive = sensitive; } protected virtual void OnNotebook1SwitchPage (object o, Gtk.SwitchPageArgs args) { Gtk.TreeIter iter; Gtk.Widget active_tab = notebook1.Children [notebook1.Page]; switch(notebook1.GetTabLabelText (active_tab)) { case "System Packages": normalPackageTreeView.Selection.GetSelected (out iter); detailsButton.Sensitive = normalPackageListStore.IterIsValid (iter); break; case "Project Packages": projectPackageTreeView.Selection.GetSelected (out iter); detailsButton.Sensitive = projectPackageListStore.IterIsValid (iter); break; } } } }
using System; using System.Text; ///<summary> ///System.Test.UnicodeEncoding.GetByteCount(System.Char[],System.Int32,System.Int32) [v-zuolan] ///</summary> public class UnicodeEncodingGetByteCount { public static int Main() { UnicodeEncodingGetByteCount testObj = new UnicodeEncodingGetByteCount(); TestLibrary.TestFramework.BeginTestCase("for field of System.Test.UnicodeEncoding"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("Positive"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("Positive"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Helper Method //Create a None-Surrogate-Char Array. public Char[] GetCharArray(int length) { if (length <= 0) return new Char[] { }; Char[] charArray = new Char[length]; int i = 0; while (i < length) { Char temp = TestLibrary.Generator.GetChar(-55); if (!Char.IsSurrogate(temp)) { charArray[i] = temp; i++; } } return charArray; } //Convert Char Array to String public String ToString(Char[] chars) { String str = "{"; for (int i = 0;i < chars.Length; i++) { str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]); if (i != chars.Length - 1) str = str + ","; } str = str + "}"; return str; } #endregion #region Positive Test Logic public bool PosTest1() { bool retVal = true; Char[] chars = new Char[] { } ; UnicodeEncoding uEncoding = new UnicodeEncoding(); int expectedValue = 0; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method with a empty char array."); try { actualValue = uEncoding.GetByteCount(chars,0,0); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Char[] chars = GetCharArray(10); UnicodeEncoding uEncoding = new UnicodeEncoding(); int expectedValue = 20; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method with max length of the char array."); try { actualValue = uEncoding.GetByteCount(chars, 0, chars.Length); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(chars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e + "when chars is:" + ToString(chars)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; Char[] chars = GetCharArray(1); UnicodeEncoding uEncoding = new UnicodeEncoding(); int expectedValue = 2; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method with one char array."); try { actualValue = uEncoding.GetByteCount(chars, 0, 1); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(chars)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e + "when chars is:" + ToString(chars)); retVal = false; } return retVal; } #endregion #region Negative Test Logic public bool NegTest1() { bool retVal = true; //Char[] chars = new Char[]{}; UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method with null"); try { actualValue = uEncoding.GetByteCount(null,0,0); TestLibrary.TestFramework.LogError("007", "No ArgumentNullException throw out expected."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; Char[] chars = GetCharArray(10); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; TestLibrary.TestFramework.BeginScenario("NegTest2:Invoke the method with index out of range."); try { actualValue = uEncoding.GetByteCount(chars, 10, 1); TestLibrary.TestFramework.LogError("009", "No ArgumentOutOfRangeException throw out expected when chars is:" + ToString(chars)); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception:" + e + " when chars is:" + ToString(chars)); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; Char[] chars = GetCharArray(10); UnicodeEncoding uEncoding = new UnicodeEncoding(); int actualValue; TestLibrary.TestFramework.BeginScenario("NegTest3:Invoke the method with count out of range."); try { actualValue = uEncoding.GetByteCount(chars, 5, -1); TestLibrary.TestFramework.LogError("011", "No ArgumentOutOfRangeException throw out expected when chars is:" + ToString(chars)); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception:" + e + " when chars is:" + ToString(chars)); retVal = false; } return retVal; } #endregion }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; namespace MongoDB.Messaging.Logging { /// <summary> /// A logger class for starting log messages. /// </summary> public sealed class Logger : ILogger { private static ILogWriter _logWriter; private static readonly ObjectPool<LogBuilder> _objectPool; // only create if used #if !PORTABLE private static readonly ThreadLocal<IPropertyContext> _threadProperties; #endif #if !PORTABLE && !NETSTANDARD1_3 && !NETSTANDARD1_5 && !NETSTANDARD1_6 private static readonly Lazy<IPropertyContext> _asyncProperties; #endif private static readonly Lazy<IPropertyContext> _globalProperties; private readonly Lazy<IPropertyContext> _properties; /// <summary> /// Initializes the <see cref="Logger"/> class. /// </summary> static Logger() { _globalProperties = new Lazy<IPropertyContext>(CreateGlobal); #if !PORTABLE _threadProperties = new ThreadLocal<IPropertyContext>(CreateLocal); _logWriter = new TraceLogWriter(); #else _logWriter = new DelegateLogWriter(); #endif #if !PORTABLE && !NETSTANDARD1_3 && !NETSTANDARD1_5 && !NETSTANDARD1_6 _asyncProperties = new Lazy<IPropertyContext>(CreateAsync); #endif _objectPool = new ObjectPool<LogBuilder>(() => new LogBuilder(_logWriter, _objectPool), 25); } /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> public Logger() { _properties = new Lazy<IPropertyContext>(() => new PropertyContext()); } /// <summary> /// Gets the global property context. All values are copied to each log on write. /// </summary> /// <value> /// The global property context. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static IPropertyContext GlobalProperties { get { return _globalProperties.Value; } } #if !PORTABLE /// <summary> /// Gets the thread-local property context. All values are copied to each log on write. /// </summary> /// <value> /// The thread-local property context. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static IPropertyContext ThreadProperties { get { return _threadProperties.Value; } } #endif #if !PORTABLE && !NETSTANDARD1_3 && !NETSTANDARD1_5 && !NETSTANDARD1_6 /// <summary> /// Gets the property context that maintains state across asynchronous tasks and call contexts. All values are copied to each log on write. /// </summary> /// <value> /// The asynchronous property context. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static IPropertyContext AsyncProperties { get { return _asyncProperties.Value; } } #endif /// <summary> /// Gets the logger initial default properties. All values are copied to each log. /// </summary> /// <value> /// The logger initial default properties. /// </value> [DebuggerBrowsable(DebuggerBrowsableState.Never)] public IPropertyContext Properties { get { return _properties.Value; } } /// <summary> /// Gets the logger name. /// </summary> /// <value> /// The logger name. /// </value> public string Name { get; set; } /// <summary> /// Start a fluent <see cref="LogBuilder" /> with the specified <see cref="LogLevel" />. /// </summary> /// <param name="logLevel">The log level.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns> /// A fluent Logger instance. /// </returns> public static ILogBuilder Log(LogLevel logLevel, [CallerFilePath]string callerFilePath = null) { return CreateBuilder(logLevel, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogBuilder" /> with the specified <see cref="LogLevel" />. /// </summary> /// <param name="logLevel">The log level.</param> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Log(LogLevel logLevel) { return CreateBuilder(logLevel); } /// <summary> /// Start a fluent <see cref="LogBuilder" /> with the computed <see cref="LogLevel" />. /// </summary> /// <param name="logLevelFactory">The log level factory.</param> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns> /// A fluent Logger instance. /// </returns> public static ILogBuilder Log(Func<LogLevel> logLevelFactory, [CallerFilePath]string callerFilePath = null) { var logLevel = (logLevelFactory != null) ? logLevelFactory() : LogLevel.Debug; return CreateBuilder(logLevel, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogBuilder" /> with the computed <see cref="LogLevel" />. /// </summary> /// <param name="logLevelFactory">The log level factory.</param> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Log(Func<LogLevel> logLevelFactory) { var logLevel = (logLevelFactory != null) ? logLevelFactory() : LogLevel.Debug; return CreateBuilder(logLevel); } /// <summary> /// Start a fluent <see cref="LogLevel.Trace"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Trace([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Trace, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Trace" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Trace() { return CreateBuilder(LogLevel.Trace); } /// <summary> /// Start a fluent <see cref="LogLevel.Debug"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Debug([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Debug, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Debug" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Debug() { return CreateBuilder(LogLevel.Debug); } /// <summary> /// Start a fluent <see cref="LogLevel.Info"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Info([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Info, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Info" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Info() { return CreateBuilder(LogLevel.Info); } /// <summary> /// Start a fluent <see cref="LogLevel.Warn"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Warn([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Warn, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Warn" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Warn() { return CreateBuilder(LogLevel.Warn); } /// <summary> /// Start a fluent <see cref="LogLevel.Error"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Error([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Error, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Error" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Error() { return CreateBuilder(LogLevel.Error); } /// <summary> /// Start a fluent <see cref="LogLevel.Fatal"/> logger. /// </summary> /// <param name="callerFilePath">The full path of the source file that contains the caller. This is the file path at the time of compile.</param> /// <returns>A fluent Logger instance.</returns> public static ILogBuilder Fatal([CallerFilePath]string callerFilePath = null) { return CreateBuilder(LogLevel.Fatal, callerFilePath); } /// <summary> /// Start a fluent <see cref="LogLevel.Fatal" /> logger. /// </summary> /// <returns> /// A fluent Logger instance. /// </returns> ILogBuilder ILogger.Fatal() { return CreateBuilder(LogLevel.Fatal); } /// <summary> /// Registers a <see langword="delegate"/> to write logs to. /// </summary> /// <param name="writer">The <see langword="delegate"/> to write logs to.</param> public static void RegisterWriter(Action<LogData> writer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); var logWriter = new DelegateLogWriter(writer); RegisterWriter(logWriter); } /// <summary> /// Registers a ILogWriter to write logs to. /// </summary> /// <param name="writer">The ILogWriter to write logs to.</param> public static void RegisterWriter<TWriter>(TWriter writer) where TWriter : ILogWriter { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (writer.Equals(_logWriter)) return; var current = _logWriter; if (Interlocked.CompareExchange(ref _logWriter, writer, current) != current) return; // clear object pool _objectPool.Clear(); } /// <summary> /// Creates a new <see cref="ILogger"/> using the specified fluent <paramref name="builder"/> action. /// </summary> /// <param name="builder">The builder.</param> /// <returns></returns> public static ILogger CreateLogger(Action<LoggerCreateBuilder> builder) { var factory = new Logger(); var factoryBuilder = new LoggerCreateBuilder(factory); builder(factoryBuilder); return factory; } /// <summary> /// Creates a new <see cref="ILogger"/> using the caller file name as the logger name. /// </summary> /// <returns></returns> public static ILogger CreateLogger([CallerFilePath]string callerFilePath = null) { return new Logger { Name = GetName(callerFilePath) }; } /// <summary> /// Creates a new <see cref="ILogger" /> using the specified type as the logger name. /// </summary> /// <param name="type">The type to use as the logger name.</param> /// <returns></returns> public static ILogger CreateLogger(Type type) { return new Logger { Name = type.FullName }; } /// <summary> /// Creates a new <see cref="ILogger" /> using the specified type as the logger name. /// </summary> /// <typeparam name="T">The type to use as the logger name.</typeparam> /// <returns></returns> public static ILogger CreateLogger<T>() { return CreateLogger(typeof(T)); } private static ILogBuilder CreateBuilder(LogLevel logLevel, string callerFilePath) { string name = GetName(callerFilePath); var builder = _objectPool.Allocate(); builder .Reset() .Level(logLevel) .Logger(name); MergeProperties(builder); return builder; } private ILogBuilder CreateBuilder(LogLevel logLevel) { var builder = _objectPool.Allocate(); builder .Reset() .Level(logLevel); MergeProperties(builder); MergeDefaults(builder); return builder; } private static string GetName(string path) { path = GetFileName(path); if (path == null) return null; int i; if ((i = path.LastIndexOf('.')) != -1) return path.Substring(0, i); return path; } private static string GetFileName(string path) { if (path == null) return path; int length = path.Length; for (int i = length; --i >= 0;) { char ch = path[i]; if (ch == '\\' || ch == '/' || ch == ':') return path.Substring(i + 1, length - i - 1); } return path; } #if !PORTABLE private static IPropertyContext CreateLocal() { var propertyContext = new PropertyContext(); propertyContext.Set("ThreadId", Thread.CurrentThread.ManagedThreadId); return propertyContext; } #endif #if !PORTABLE && !NETSTANDARD1_3 && !NETSTANDARD1_5 && !NETSTANDARD1_6 private static IPropertyContext CreateAsync() { var propertyContext = new AsynchronousContext(); return propertyContext; } #endif private static IPropertyContext CreateGlobal() { var propertyContext = new PropertyContext(); #if !PORTABLE && !NETSTANDARD1_3 propertyContext.Set("MachineName", Environment.MachineName); #endif return propertyContext; } private static void MergeProperties(ILogBuilder builder) { // copy global properties to current builder only if it has been created if (_globalProperties.IsValueCreated) _globalProperties.Value.Apply(builder); #if !PORTABLE // copy thread-local properties to current builder only if it has been created if (_threadProperties.IsValueCreated) _threadProperties.Value.Apply(builder); #endif #if !PORTABLE && !NETSTANDARD1_3 && !NETSTANDARD1_5 && !NETSTANDARD1_6 // copy async properties to current builder only if it has been created if (_asyncProperties.IsValueCreated) _asyncProperties.Value.Apply(builder); #endif } private ILogBuilder MergeDefaults(ILogBuilder builder) { // copy logger name if (!String.IsNullOrEmpty(Name)) builder.Logger(Name); // copy properties to current builder if (_properties.IsValueCreated) _properties.Value.Apply(builder); return builder; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Xunit; using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier< Microsoft.NetFramework.Analyzers.DoNotUseInsecureDtdProcessingAnalyzer, Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; namespace Microsoft.NetFramework.Analyzers.UnitTests { public partial class DoNotUseInsecureDtdProcessingAnalyzerTests { private static DiagnosticResult GetCA3075DataTableReadXmlSchemaCSharpResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXmlSchema"); #pragma warning restore RS0030 // Do not used banned APIs private static DiagnosticResult GetCA3075DataTableReadXmlSchemaBasicResultAt(int line, int column) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(DoNotUseInsecureDtdProcessingAnalyzer.RuleDoNotUseDtdProcessingOverloads).WithLocation(line, column).WithArguments("ReadXmlSchema"); #pragma warning restore RS0030 // Do not used banned APIs [Fact] public async Task UseDataTableReadXmlSchemaShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.IO; using System.Xml; using System.Data; namespace TestNamespace { public class UseXmlReaderForDataTableReadXmlSchema { public void TestMethod(Stream stream) { DataTable table = new DataTable(); table.ReadXmlSchema(stream); } } } ", GetCA3075DataTableReadXmlSchemaCSharpResultAt(13, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.IO Imports System.Xml Imports System.Data Namespace TestNamespace Public Class UseXmlReaderForDataTableReadXmlSchema Public Sub TestMethod(stream As Stream) Dim table As New DataTable() table.ReadXmlSchema(stream) End Sub End Class End Namespace", GetCA3075DataTableReadXmlSchemaBasicResultAt(10, 13) ); } [Fact] public async Task UseDataTableReadXmlSchemaInGetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { public DataTable Test { get { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); return dt; } } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(11, 13) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Public ReadOnly Property Test() As DataTable Get Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) Return dt End Get End Property End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(9, 13) ); } [Fact] public async Task UseDataTableReadXmlSchemaInSetShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { DataTable privateDoc; public DataTable GetDoc { set { if (value == null) { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); privateDoc = dt; } else privateDoc = value; } } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private privateDoc As DataTable Public WriteOnly Property GetDoc() As DataTable Set If value Is Nothing Then Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) privateDoc = dt Else privateDoc = value End If End Set End Property End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(11, 17) ); } [Fact] public async Task UseDataTableReadXmlSchemaInTryBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); } catch (Exception) { throw; } finally { } } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(13, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) Catch generatedExceptionName As Exception Throw Finally End Try End Sub End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(10, 13) ); } [Fact] public async Task UseDataTableReadXmlSchemaInCatchBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); } finally { } } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(14, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) Finally End Try End Sub End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(11, 13) ); } [Fact] public async Task UseDataTableReadXmlSchemaInFinallyBlockShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System; using System.Data; class TestClass { private void TestMethod() { try { } catch (Exception) { throw; } finally { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); } } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(15, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System Imports System.Data Class TestClass Private Sub TestMethod() Try Catch generatedExceptionName As Exception Throw Finally Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) End Try End Sub End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(13, 13) ); } [Fact] public async Task UseDataTableReadXmlSchemaInAsyncAwaitShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Threading.Tasks; using System.Data; class TestClass { private async Task TestMethod() { await Task.Run(() => { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); }); } private async void TestMethod2() { await TestMethod(); } }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(12, 17) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Threading.Tasks Imports System.Data Class TestClass Private Async Function TestMethod() As Task Await Task.Run(Function() Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) End Function) End Function Private Async Sub TestMethod2() Await TestMethod() End Sub End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(10, 9) ); } [Fact] public async Task UseDataTableReadXmlSchemaInDelegateShouldGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Data; class TestClass { delegate void Del(); Del d = delegate () { var src = """"; DataTable dt = new DataTable(); dt.ReadXmlSchema(src); }; }", GetCA3075DataTableReadXmlSchemaCSharpResultAt(11, 9) ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Data Class TestClass Private Delegate Sub Del() Private d As Del = Sub() Dim src = """" Dim dt As New DataTable() dt.ReadXmlSchema(src) End Sub End Class", GetCA3075DataTableReadXmlSchemaBasicResultAt(10, 5) ); } [Fact] public async Task UseDataTableReadXmlSchemaWithXmlReaderShouldNotGenerateDiagnostic() { await VerifyCSharpAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" using System.Xml; using System.Data; namespace TestNamespace { public class UseXmlReaderForDataTableReadXmlSchema { public void TestMethod(XmlReader reader) { DataTable table = new DataTable(); table.ReadXmlSchema(reader); } } } " ); await VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies.NetFramework.Net472.Default, @" Imports System.Xml Imports System.Data Namespace TestNamespace Public Class UseXmlReaderForDataTableReadXmlSchema Public Sub TestMethod(reader As XmlReader) Dim table As New DataTable() table.ReadXmlSchema(reader) End Sub End Class End Namespace"); } } }
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 PyriteCloudAdmin.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) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.IO; using SharpDX.Direct3D11; using SharpDX.IO; namespace SharpDX.Toolkit.Graphics { /// <summary> /// A Texture 2D front end to <see cref="SharpDX.Direct3D11.Texture2D"/>. /// </summary> public class Texture2D : Texture2DBase { internal Texture2D(GraphicsDevice device, Texture2DDescription description2D, params DataBox[] dataBoxes) : base(device, description2D, dataBoxes) { Initialize(Resource); } internal Texture2D(GraphicsDevice device, Direct3D11.Texture2D texture) : base(device, texture) { Initialize(Resource); } internal override RenderTargetView GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipMapSlice) { throw new System.NotSupportedException(); } /// <summary> /// Makes a copy of this texture. /// </summary> /// <remarks> /// This method doesn't copy the content of the texture. /// </remarks> /// <returns> /// A copy of this texture. /// </returns> public override Texture Clone() { return new Texture2D(GraphicsDevice, this.Description); } /// <summary> /// Creates a new texture from a <see cref="Texture2DDescription"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="description">The description.</param> /// <returns> /// A new instance of <see cref="Texture2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, Texture2DDescription description) { return new Texture2D(device, description); } /// <summary> /// Creates a new texture from a <see cref="Direct3D11.Texture2D"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="texture">The native texture <see cref="Direct3D11.Texture2D"/>.</param> /// <returns> /// A new instance of <see cref="Texture2D"/> class. /// </returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, Direct3D11.Texture2D texture) { return new Texture2D(device, texture); } /// <summary> /// Creates a new <see cref="Texture2D" /> with a single mipmap. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, int width, int height, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default) { return New(device, width, height, false, format, flags, arraySize, usage); } /// <summary> /// Creates a new <see cref="Texture2D" />. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default) { return new Texture2D(device, NewDescription(width, height, format, flags | TextureFlags.ShaderResource, mipCount, arraySize, usage)); } /// <summary> /// Creates a new <see cref="Texture2D" /> with a single level of mipmap. /// </summary> /// <typeparam name="T">Type of the pixel data to upload to the texture.</typeparam> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="usage">The usage.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="textureData">The texture data for a single mipmap and a single array slice. See remarks</param> /// <returns>A new instance of <see cref="Texture2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> /// <remarks> /// Each value in textureData is a pixel in the destination texture. /// </remarks> public unsafe static Texture2D New<T>(GraphicsDevice device, int width, int height, PixelFormat format, T[] textureData, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) where T : struct { return New(device, width, height, 1, format, new [] { GetDataBox(format, width, height, 1, textureData, (IntPtr)Interop.Fixed(textureData)) }, flags, 1, usage); } /// <summary> /// Creates a new <see cref="Texture2D" />. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="format">Describes the format to use.</param> /// <param name="mipCount">Number of mipmaps, set to true to have all mipmaps, set to an int >=1 for a particular mipmap count.</param> /// <param name="textureData">Texture data through an array of <see cref="DataBox"/> </param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="arraySize">Size of the texture 2D array, default to 1.</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, int width, int height, MipMapCount mipCount, PixelFormat format, DataBox[] textureData, TextureFlags flags = TextureFlags.ShaderResource, int arraySize = 1, ResourceUsage usage = ResourceUsage.Default) { return new Texture2D(device, NewDescription(width, height, format, flags | TextureFlags.ShaderResource, mipCount, arraySize, usage), textureData); } /// <summary> /// Creates a new <see cref="Texture2D" /> directly from an <see cref="Image"/>. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="image">An image in CPU memory.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">The usage.</param> /// <returns>A new instance of <see cref="Texture2D" /> class.</returns> /// <msdn-id>ff476521</msdn-id> /// <unmanaged>HRESULT ID3D11Device::CreateTexture2D([In] const D3D11_TEXTURE2D_DESC* pDesc,[In, Buffer, Optional] const D3D11_SUBRESOURCE_DATA* pInitialData,[Out, Fast] ID3D11Texture2D** ppTexture2D)</unmanaged> /// <unmanaged-short>ID3D11Device::CreateTexture2D</unmanaged-short> public static Texture2D New(GraphicsDevice device, Image image, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { if (image == null) throw new ArgumentNullException("image"); if (image.Description.Dimension != TextureDimension.Texture2D) throw new ArgumentException("Invalid image. Must be 2D", "image"); return new Texture2D(device, CreateTextureDescriptionFromImage(image, flags | TextureFlags.ShaderResource, usage), image.ToDataBox()); } /// <summary> /// Loads a 2D texture from a stream. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="stream">The stream to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 2D</exception> /// <returns>A texture</returns> public static new Texture2D Load(GraphicsDevice device, Stream stream, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { var texture = Texture.Load(device, stream, flags | TextureFlags.ShaderResource, usage); if (!(texture is Texture2D)) throw new ArgumentException(string.Format("Texture is not type of [Texture2D] but [{0}]", texture.GetType().Name)); return (Texture2D)texture; } /// <summary> /// Loads a 2D texture from a stream. /// </summary> /// <param name="device">The <see cref="GraphicsDevice"/>.</param> /// <param name="filePath">The file to load the texture from.</param> /// <param name="flags">Sets the texture flags (for unordered access...etc.)</param> /// <param name="usage">Usage of the resource. Default is <see cref="ResourceUsage.Immutable"/> </param> /// <exception cref="ArgumentException">If the texture is not of type 2D</exception> /// <returns>A texture</returns> public static new Texture2D Load(GraphicsDevice device, string filePath, TextureFlags flags = TextureFlags.ShaderResource, ResourceUsage usage = ResourceUsage.Immutable) { using (var stream = new NativeFileStream(filePath, NativeFileMode.Open, NativeFileAccess.Read)) return Load(device, stream, flags | TextureFlags.ShaderResource, usage); } } }
// // 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 Encog.MathUtil.Randomize; using Encog.Neural.Flat; using Encog.Neural.Networks; using Encog.Util; namespace Encog.Neural.Prune { /// <summary> /// Prune a neural network selectively. This class allows you to either add or /// remove neurons from layers of a neural network. You can also randomize or /// stimulate neurons. /// No provision is given for removing an entire layer. Removing a layer requires /// a totally new set of weights between the layers before and after the removed /// one. This essentially makes any remaining weights useless. At this point you /// are better off just creating a new network of the desired dimensions. /// </summary> /// public class PruneSelective { /// <summary> /// The network to prune. /// </summary> /// private readonly BasicNetwork _network; /// <summary> /// Construct an object prune the neural network. /// </summary> /// /// <param name="network">The network to prune.</param> public PruneSelective(BasicNetwork network) { _network = network; } /// <value>The network that is being processed.</value> public BasicNetwork Network { get { return _network; } } /// <summary> /// Change the neuron count for the network. If the count is increased then a /// zero-weighted neuron is added, which will not affect the output of the /// neural network. If the neuron count is decreased, then the weakest neuron /// will be removed. /// This method cannot be used to remove a bias neuron. /// </summary> /// /// <param name="layer">The layer to adjust.</param> /// <param name="neuronCount">The new neuron count for this layer.</param> public void ChangeNeuronCount(int layer, int neuronCount) { if (neuronCount == 0) { throw new NeuralNetworkError("Can't decrease to zero neurons."); } int currentCount = _network.GetLayerNeuronCount(layer); // is there anything to do? if (neuronCount == currentCount) { return; } if (neuronCount > currentCount) { IncreaseNeuronCount(layer, neuronCount); } else { DecreaseNeuronCount(layer, neuronCount); } } /// <summary> /// Internal function to decrease the neuron count of a layer. /// </summary> /// /// <param name="layer">The layer to affect.</param> /// <param name="neuronCount">The new neuron count.</param> private void DecreaseNeuronCount(int layer, int neuronCount) { // create an array to hold the least significant neurons, which will be // removed int lostNeuronCount = _network.GetLayerNeuronCount(layer) - neuronCount; int[] lostNeuron = FindWeakestNeurons(layer, lostNeuronCount); // finally, actually prune the neurons that the previous steps // determined to remove for (int i = 0; i < lostNeuronCount; i++) { Prune(layer, lostNeuron[i] - i); } } /// <summary> /// Determine the significance of the neuron. The higher the return value, /// the more significant the neuron is. /// </summary> /// /// <param name="layer">The layer to query.</param> /// <param name="neuron">The neuron to query.</param> /// <returns>How significant is this neuron.</returns> public double DetermineNeuronSignificance(int layer, int neuron) { _network.ValidateNeuron(layer, neuron); // calculate the bias significance double result = 0; // calculate the inbound significance if (layer > 0) { int prevLayer = layer - 1; int prevCount = _network .GetLayerTotalNeuronCount(prevLayer); for (int i = 0; i < prevCount; i++) { result += _network.GetWeight(prevLayer, i, neuron); } } // calculate the outbound significance if (layer < _network.LayerCount - 1) { int nextLayer = layer + 1; int nextCount = _network.GetLayerNeuronCount(nextLayer); for (int i = 0; i < nextCount; i++) { result += _network.GetWeight(layer, neuron, i); } } return Math.Abs(result); } /// <summary> /// Find the weakest neurons on a layer. Considers both weight and bias. /// </summary> /// /// <param name="layer">The layer to search.</param> /// <param name="count">The number of neurons to find.</param> /// <returns>An array of the indexes of the weakest neurons.</returns> private int[] FindWeakestNeurons(int layer, int count) { // create an array to hold the least significant neurons, which will be // returned var lostNeuronSignificance = new double[count]; var lostNeuron = new int[count]; // init the potential lost neurons to the first ones, we will find // better choices if we can for (int i = 0; i < count; i++) { lostNeuron[i] = i; lostNeuronSignificance[i] = DetermineNeuronSignificance(layer, i); } // now loop over the remaining neurons and see if any are better ones to // remove for (int i = count; i < _network.GetLayerNeuronCount(layer); i++) { double significance = DetermineNeuronSignificance(layer, i); // is this neuron less significant than one already chosen? for (int j = 0; j < count; j++) { if (lostNeuronSignificance[j] > significance) { lostNeuron[j] = i; lostNeuronSignificance[j] = significance; break; } } } return lostNeuron; } /// <summary> /// Internal function to increase the neuron count. This will add a /// zero-weight neuron to this layer. /// </summary> /// /// <param name="targetLayer">The layer to increase.</param> /// <param name="neuronCount">The new neuron count.</param> private void IncreaseNeuronCount(int targetLayer, int neuronCount) { // check for errors if (targetLayer > _network.LayerCount) { throw new NeuralNetworkError("Invalid layer " + targetLayer); } if (neuronCount <= 0) { throw new NeuralNetworkError("Invalid neuron count " + neuronCount); } int oldNeuronCount = _network .GetLayerNeuronCount(targetLayer); int increaseBy = neuronCount - oldNeuronCount; if (increaseBy <= 0) { throw new NeuralNetworkError( "New neuron count is either a decrease or no change: " + neuronCount); } // access the flat network FlatNetwork flat = _network.Structure.Flat; double[] oldWeights = flat.Weights; // first find out how many connections there will be after this prune. int connections = oldWeights.Length; // are connections added from the previous layer? if (targetLayer > 0) { int inBoundConnections = _network .GetLayerTotalNeuronCount(targetLayer - 1); connections += inBoundConnections*increaseBy; } // are there connections added from the next layer? if (targetLayer < (_network.LayerCount - 1)) { int outBoundConnections = _network .GetLayerNeuronCount(targetLayer + 1); connections += outBoundConnections*increaseBy; } // increase layer count int flatLayer = _network.LayerCount - targetLayer - 1; flat.LayerCounts[flatLayer] += increaseBy; flat.LayerFeedCounts[flatLayer] += increaseBy; // allocate new weights now that we know how big the new weights will be var newWeights = new double[connections]; // construct the new weights int weightsIndex = 0; int oldWeightsIndex = 0; for (int fromLayer = flat.LayerCounts.Length - 2; fromLayer >= 0; fromLayer--) { int fromNeuronCount = _network .GetLayerTotalNeuronCount(fromLayer); int toNeuronCount = _network .GetLayerNeuronCount(fromLayer + 1); int toLayer = fromLayer + 1; for (int toNeuron = 0; toNeuron < toNeuronCount; toNeuron++) { for (int fromNeuron = 0; fromNeuron < fromNeuronCount; fromNeuron++) { if ((toLayer == targetLayer) && (toNeuron >= oldNeuronCount)) { newWeights[weightsIndex++] = 0; } else if ((fromLayer == targetLayer) && (fromNeuron > oldNeuronCount)) { newWeights[weightsIndex++] = 0; } else { newWeights[weightsIndex++] = _network.Flat.Weights[oldWeightsIndex++]; } } } } // swap in the new weights flat.Weights = newWeights; // reindex ReindexNetwork(); } /// <summary> /// Prune one of the neurons from this layer. Remove all entries in this /// weight matrix and other layers. This method cannot be used to remove a /// bias neuron. /// </summary> /// /// <param name="targetLayer">The neuron to prune. Zero specifies the first neuron.</param> /// <param name="neuron">The neuron to prune.</param> public void Prune(int targetLayer, int neuron) { // check for errors _network.ValidateNeuron(targetLayer, neuron); // don't empty a layer if (_network.GetLayerNeuronCount(targetLayer) <= 1) { throw new NeuralNetworkError( "A layer must have at least a single neuron. If you want to remove the entire layer you must create a new network."); } // access the flat network FlatNetwork flat = _network.Structure.Flat; double[] oldWeights = flat.Weights; // first find out how many connections there will be after this prune. int connections = oldWeights.Length; // are connections removed from the previous layer? if (targetLayer > 0) { int inBoundConnections = _network .GetLayerTotalNeuronCount(targetLayer - 1); connections -= inBoundConnections; } // are there connections removed from the next layer? if (targetLayer < (_network.LayerCount - 1)) { int outBoundConnections = _network .GetLayerNeuronCount(targetLayer + 1); connections -= outBoundConnections; } // allocate new weights now that we know how big the new weights will be var newWeights = new double[connections]; // construct the new weights int weightsIndex = 0; for (int fromLayer = flat.LayerCounts.Length - 2; fromLayer >= 0; fromLayer--) { int fromNeuronCount = _network .GetLayerTotalNeuronCount(fromLayer); int toNeuronCount = _network .GetLayerNeuronCount(fromLayer + 1); int toLayer = fromLayer + 1; for (int toNeuron = 0; toNeuron < toNeuronCount; toNeuron++) { for (int fromNeuron = 0; fromNeuron < fromNeuronCount; fromNeuron++) { bool skip = false; if ((toLayer == targetLayer) && (toNeuron == neuron)) { skip = true; } else if ((fromLayer == targetLayer) && (fromNeuron == neuron)) { skip = true; } if (!skip) { newWeights[weightsIndex++] = _network.GetWeight( fromLayer, fromNeuron, toNeuron); } } } } // swap in the new weights flat.Weights = newWeights; // decrease layer count int flatLayer = _network.LayerCount - targetLayer - 1; flat.LayerCounts[flatLayer]--; flat.LayerFeedCounts[flatLayer]--; // reindex ReindexNetwork(); } /// <param name="low">The low-end of the range.</param> /// <param name="high">The high-end of the range.</param> /// <param name="targetLayer">The target layer.</param> /// <param name="neuron">The target neuron.</param> public void RandomizeNeuron(double low, double high, int targetLayer, int neuron) { RandomizeNeuron(targetLayer, neuron, true, low, high, false, 0.0d); } /// <summary> /// Assign random values to the network. The range will be the min/max of /// existing neurons. /// </summary> /// /// <param name="targetLayer">The target layer.</param> /// <param name="neuron">The target neuron.</param> public void RandomizeNeuron(int targetLayer, int neuron) { FlatNetwork flat = _network.Structure.Flat; double low = EngineArray.Min(flat.Weights); double high = EngineArray.Max(flat.Weights); RandomizeNeuron(targetLayer, neuron, true, low, high, false, 0.0d); } /// <summary> /// Used internally to randomize a neuron. Usually called from /// randomizeNeuron or stimulateNeuron. /// </summary> /// /// <param name="targetLayer">The target layer.</param> /// <param name="neuron">The target neuron.</param> /// <param name="useRange">True if range randomization should be used.</param> /// <param name="low">The low-end of the range.</param> /// <param name="high">The high-end of the range.</param> /// <param name="usePercent">True if percent stimulation should be used.</param> /// <param name="percent">The percent to stimulate by.</param> private void RandomizeNeuron(int targetLayer, int neuron, bool useRange, double low, double high, bool usePercent, double percent) { IRandomizer d; if (useRange) { d = new RangeRandomizer(low, high); } else { d = new Distort(percent); } // check for errors _network.ValidateNeuron(targetLayer, neuron); // access the flat network FlatNetwork flat = _network.Structure.Flat; // allocate new weights now that we know how big the new weights will be var newWeights = new double[flat.Weights.Length]; // construct the new weights int weightsIndex = 0; for (int fromLayer = flat.LayerCounts.Length - 2; fromLayer >= 0; fromLayer--) { int fromNeuronCount = _network .GetLayerTotalNeuronCount(fromLayer); int toNeuronCount = _network .GetLayerNeuronCount(fromLayer + 1); int toLayer = fromLayer + 1; for (int toNeuron = 0; toNeuron < toNeuronCount; toNeuron++) { for (int fromNeuron = 0; fromNeuron < fromNeuronCount; fromNeuron++) { bool randomize = false; if ((toLayer == targetLayer) && (toNeuron == neuron)) { randomize = true; } else if ((fromLayer == targetLayer) && (fromNeuron == neuron)) { randomize = true; } double weight = _network.GetWeight(fromLayer, fromNeuron, toNeuron); if (randomize) { weight = d.Randomize(weight); } newWeights[weightsIndex++] = weight; } } } // swap in the new weights flat.Weights = newWeights; } /// <summary> /// Creat new index values for the network. /// </summary> /// private void ReindexNetwork() { FlatNetwork flat = _network.Structure.Flat; int neuronCount = 0; int weightCount = 0; for (int i = 0; i < flat.LayerCounts.Length; i++) { if (i > 0) { int from = flat.LayerFeedCounts[i - 1]; int to = flat.LayerCounts[i]; weightCount += from*to; } flat.LayerIndex[i] = neuronCount; flat.WeightIndex[i] = weightCount; neuronCount += flat.LayerCounts[i]; } flat.LayerOutput = new double[neuronCount]; flat.LayerSums = new double[neuronCount]; flat.ClearContext(); flat.InputCount = flat.LayerFeedCounts[flat.LayerCounts.Length - 1]; flat.OutputCount = flat.LayerFeedCounts[0]; } /// <summary> /// Stimulate the specified neuron by the specified percent. This is used to /// randomize the weights and bias values for weak neurons. /// </summary> /// /// <param name="percent">The percent to randomize by.</param> /// <param name="targetLayer">The layer that the neuron is on.</param> /// <param name="neuron">The neuron to randomize.</param> public void StimulateNeuron(double percent, int targetLayer, int neuron) { RandomizeNeuron(targetLayer, neuron, false, 0, 0, true, percent); } /// <summary> /// Stimulate weaker neurons on a layer. Find the weakest neurons and then /// randomize them by the specified percent. /// </summary> /// /// <param name="layer">The layer to stimulate.</param> /// <param name="count">The number of weak neurons to stimulate.</param> /// <param name="percent">The percent to stimulate by.</param> public void StimulateWeakNeurons(int layer, int count, double percent) { int[] weak = FindWeakestNeurons(layer, count); foreach (int element in weak) { StimulateNeuron(percent, layer, element); } } } }
using UnityEngine; using UnityEditor; #if !UNITY_4_7 using UnityEngine.Rendering; #endif using ProBuilder2.Common; using ProBuilder2.EditorCommon; using System.Collections; using System.Linq; #if PB_DEBUG using Parabox.Debug; #endif public class pb_Preferences { private static bool prefsLoaded = false; static Color pbDefaultFaceColor; static Color pbDefaultEdgeColor; static Color pbDefaultSelectedVertexColor; static Color pbDefaultVertexColor; static bool defaultOpenInDockableWindow; static Material pbDefaultMaterial; static Vector2 settingsScroll = Vector2.zero; static bool pbShowEditorNotifications; static bool pbForceConvex = false; static bool pbDragCheckLimit = false; static bool pbForceVertexPivot = true; static bool pbForceGridPivot = true; static bool pbPerimeterEdgeBridgeOnly; static bool pbPBOSelectionOnly; static bool pbCloseShapeWindow = false; static bool pbUVEditorFloating = true; // static bool pbShowSceneToolbar = true; static bool pbStripProBuilderOnBuild = true; static bool pbDisableAutoUV2Generation = false; static bool pbShowSceneInfo = false; static bool pbUniqueModeShortcuts = false; static bool pbIconGUI = false; static bool pbShiftOnlyTooltips = false; static bool pbDrawAxisLines = true; static bool pbMeshesAreAssets = false; static bool pbElementSelectIsHamFisted = false; static bool pbDragSelectWholeElement = false; #if !UNITY_4_7 static ShadowCastingMode pbShadowCastingMode = ShadowCastingMode.On; #endif static ColliderType defaultColliderType = ColliderType.BoxCollider; static SceneToolbarLocation pbToolbarLocation = SceneToolbarLocation.UpperCenter; static EntityType pbDefaultEntity = EntityType.Detail; static float pbUVGridSnapValue; static float pbVertexHandleSize; static pb_Shortcut[] defaultShortcuts; [PreferenceItem (pb_Constant.PRODUCT_NAME)] public static void PreferencesGUI () { // Load the preferences if (!prefsLoaded) { LoadPrefs(); prefsLoaded = true; OnWindowResize(); } settingsScroll = EditorGUILayout.BeginScrollView(settingsScroll, GUILayout.MaxHeight(200)); EditorGUI.BeginChangeCheck(); /** * GENERAL SETTINGS */ GUILayout.Label("General Settings", EditorStyles.boldLabel); pbStripProBuilderOnBuild = EditorGUILayout.Toggle(new GUIContent("Strip PB Scripts on Build", "If true, when building an executable all ProBuilder scripts will be stripped from your built product."), pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = EditorGUILayout.Toggle(new GUIContent("Disable Auto UV2 Generation", "Disables automatic generation of UV2 channel. If Unity is sluggish when working with large ProBuilder objects, disabling UV2 generation will improve performance. Use `Actions/Generate UV2` or `Actions/Generate Scene UV2` to build lightmap UVs prior to baking."), pbDisableAutoUV2Generation); pbShowSceneInfo = EditorGUILayout.Toggle(new GUIContent("Show Scene Info", "Displays the selected object vertex and triangle counts in the scene view."), pbShowSceneInfo); pbShowEditorNotifications = EditorGUILayout.Toggle("Show Editor Notifications", pbShowEditorNotifications); /** * TOOLBAR SETTINGS */ GUILayout.Label("Toolbar Settings", EditorStyles.boldLabel); pbIconGUI = EditorGUILayout.Toggle(new GUIContent("Use Icon GUI", "Toggles the ProBuilder window interface between text and icon versions."), pbIconGUI); pbShiftOnlyTooltips = EditorGUILayout.Toggle(new GUIContent("Shift Key Tooltips", "Tooltips will only show when the Shift key is held"), pbShiftOnlyTooltips); pbToolbarLocation = (SceneToolbarLocation) EditorGUILayout.EnumPopup("Toolbar Location", pbToolbarLocation); pbUniqueModeShortcuts = EditorGUILayout.Toggle(new GUIContent("Unique Mode Shortcuts", "When off, the G key toggles between Object and Element modes and H enumerates the element modes. If on, G, H, J, and K are shortcuts to Object, Vertex, Edge, and Face modes respectively."), pbUniqueModeShortcuts); defaultOpenInDockableWindow = EditorGUILayout.Toggle("Open in Dockable Window", defaultOpenInDockableWindow); /** * DEFAULT SETTINGS */ GUILayout.Label("Defaults", EditorStyles.boldLabel); pbDefaultMaterial = (Material) EditorGUILayout.ObjectField("Default Material", pbDefaultMaterial, typeof(Material), false); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Entity"); pbDefaultEntity = ((EntityType)EditorGUILayout.EnumPopup( (EntityType)pbDefaultEntity )); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Default Collider"); defaultColliderType = ((ColliderType)EditorGUILayout.EnumPopup( (ColliderType)defaultColliderType )); GUILayout.EndHorizontal(); if((ColliderType)defaultColliderType == ColliderType.MeshCollider) pbForceConvex = EditorGUILayout.Toggle("Force Convex Mesh Collider", pbForceConvex); #if !UNITY_4_7 GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Shadow Casting Mode"); pbShadowCastingMode = (ShadowCastingMode) EditorGUILayout.EnumPopup(pbShadowCastingMode); GUILayout.EndHorizontal(); #endif /** * MISC. SETTINGS */ GUILayout.Label("Misc. Settings", EditorStyles.boldLabel); pbDragCheckLimit = EditorGUILayout.Toggle(new GUIContent("Limit Drag Check to Selection", "If true, when drag selecting faces, only currently selected pb-Objects will be tested for matching faces. If false, all pb_Objects in the scene will be checked. The latter may be slower in large scenes."), pbDragCheckLimit); pbPBOSelectionOnly = EditorGUILayout.Toggle(new GUIContent("Only PBO are Selectable", "If true, you will not be able to select non probuilder objects in Geometry and Texture mode"), pbPBOSelectionOnly); pbCloseShapeWindow = EditorGUILayout.Toggle(new GUIContent("Close shape window after building", "If true the shape window will close after hitting the build button"), pbCloseShapeWindow); pbDrawAxisLines = EditorGUILayout.Toggle(new GUIContent("Dimension Overlay Lines", "When the Dimensions Overlay is on, this toggle shows or hides the axis lines."), pbDrawAxisLines); GUILayout.Space(4); /** * GEOMETRY EDITING SETTINGS */ GUILayout.Label("Geometry Editing Settings", EditorStyles.boldLabel); pbElementSelectIsHamFisted = !EditorGUILayout.Toggle(new GUIContent("Precise Element Selection", "When enabled you will be able to select object faces when in Vertex of Edge mode by clicking the center of a face. When disabled, edge and vertex selection will always be restricted to the nearest element."), !pbElementSelectIsHamFisted); pbDragSelectWholeElement = EditorGUILayout.Toggle("Precise Drag Select", pbDragSelectWholeElement); pbDefaultFaceColor = EditorGUILayout.ColorField("Selected Face Color", pbDefaultFaceColor); pbDefaultEdgeColor = EditorGUILayout.ColorField("Edge Wireframe Color", pbDefaultEdgeColor); pbDefaultVertexColor = EditorGUILayout.ColorField("Vertex Color", pbDefaultVertexColor); pbDefaultSelectedVertexColor = EditorGUILayout.ColorField("Selected Vertex Color", pbDefaultSelectedVertexColor); pbVertexHandleSize = EditorGUILayout.Slider("Vertex Handle Size", pbVertexHandleSize, 0f, 3f); pbForceVertexPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Vertex Point", "If true, new objects will automatically have their pivot point set to a vertex instead of the center."), pbForceVertexPivot); pbForceGridPivot = EditorGUILayout.Toggle(new GUIContent("Force Pivot to Grid", "If true, newly instantiated pb_Objects will be snapped to the nearest point on grid. If ProGrids is present, the snap value will be used, otherwise decimals are simply rounded to whole numbers."), pbForceGridPivot); pbPerimeterEdgeBridgeOnly = EditorGUILayout.Toggle(new GUIContent("Bridge Perimeter Edges Only", "If true, only edges on the perimeters of an object may be bridged. If false, you may bridge any between any two edges you like."), pbPerimeterEdgeBridgeOnly); GUILayout.Space(4); GUILayout.Label("Experimental", EditorStyles.boldLabel); pbMeshesAreAssets = EditorGUILayout.Toggle(new GUIContent("Meshes Are Assets", "Experimental! Instead of storing mesh data in the scene, this toggle creates a Mesh cache in the Project that ProBuilder will use."), pbMeshesAreAssets); GUILayout.Space(4); /** * UV EDITOR SETTINGS */ GUILayout.Label("UV Editing Settings", EditorStyles.boldLabel); pbUVGridSnapValue = EditorGUILayout.FloatField("UV Snap Increment", pbUVGridSnapValue); pbUVGridSnapValue = Mathf.Clamp(pbUVGridSnapValue, .015625f, 2f); pbUVEditorFloating = EditorGUILayout.Toggle(new GUIContent("Editor window floating", "If true UV Editor window will open as a floating window"), pbUVEditorFloating); EditorGUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Shortcut Settings", EditorStyles.boldLabel); if(GUI.Button(resetRect, "Use defaults")) ResetToDefaults(); ShortcutSelectPanel(); ShortcutEditPanel(); // Save the preferences if (EditorGUI.EndChangeCheck()) SetPrefs(); } public static void OnWindowResize() { int pad = 10, buttonWidth = 100, buttonHeight = 20; resetRect = new Rect(Screen.width-pad-buttonWidth, Screen.height-pad-buttonHeight, buttonWidth, buttonHeight); } public static void ResetToDefaults() { if(EditorUtility.DisplayDialog("Delete ProBuilder editor preferences?", "Are you sure you want to delete these?, this action cannot be undone.", "Yes", "No")) { EditorPrefs.DeleteKey(pb_Constant.pbDefaultFaceColor); EditorPrefs.DeleteKey(pb_Constant.pbDefaultEditLevel); EditorPrefs.DeleteKey(pb_Constant.pbDefaultSelectionMode); EditorPrefs.DeleteKey(pb_Constant.pbHandleAlignment); EditorPrefs.DeleteKey(pb_Constant.pbVertexColorTool); EditorPrefs.DeleteKey(pb_Constant.pbToolbarLocation); EditorPrefs.DeleteKey(pb_Constant.pbDefaultEntity); EditorPrefs.DeleteKey(pb_Constant.pbDefaultFaceColor); EditorPrefs.DeleteKey(pb_Constant.pbDefaultEdgeColor); EditorPrefs.DeleteKey(pb_Constant.pbDefaultSelectedVertexColor); EditorPrefs.DeleteKey(pb_Constant.pbDefaultVertexColor); EditorPrefs.DeleteKey(pb_Constant.pbDefaultOpenInDockableWindow); EditorPrefs.DeleteKey(pb_Constant.pbEditorPrefVersion); EditorPrefs.DeleteKey(pb_Constant.pbEditorShortcutsVersion); EditorPrefs.DeleteKey(pb_Constant.pbDefaultCollider); EditorPrefs.DeleteKey(pb_Constant.pbForceConvex); EditorPrefs.DeleteKey(pb_Constant.pbVertexColorPrefs); EditorPrefs.DeleteKey(pb_Constant.pbShowEditorNotifications); EditorPrefs.DeleteKey(pb_Constant.pbDragCheckLimit); EditorPrefs.DeleteKey(pb_Constant.pbForceVertexPivot); EditorPrefs.DeleteKey(pb_Constant.pbForceGridPivot); EditorPrefs.DeleteKey(pb_Constant.pbManifoldEdgeExtrusion); EditorPrefs.DeleteKey(pb_Constant.pbPerimeterEdgeBridgeOnly); EditorPrefs.DeleteKey(pb_Constant.pbPBOSelectionOnly); EditorPrefs.DeleteKey(pb_Constant.pbCloseShapeWindow); EditorPrefs.DeleteKey(pb_Constant.pbUVEditorFloating); EditorPrefs.DeleteKey(pb_Constant.pbUVMaterialPreview); EditorPrefs.DeleteKey(pb_Constant.pbShowSceneToolbar); EditorPrefs.DeleteKey(pb_Constant.pbNormalizeUVsOnPlanarProjection); EditorPrefs.DeleteKey(pb_Constant.pbStripProBuilderOnBuild); EditorPrefs.DeleteKey(pb_Constant.pbDisableAutoUV2Generation); EditorPrefs.DeleteKey(pb_Constant.pbShowSceneInfo); EditorPrefs.DeleteKey(pb_Constant.pbEnableBackfaceSelection); EditorPrefs.DeleteKey(pb_Constant.pbVertexPaletteDockable); EditorPrefs.DeleteKey(pb_Constant.pbExtrudeAsGroup); EditorPrefs.DeleteKey(pb_Constant.pbUniqueModeShortcuts); EditorPrefs.DeleteKey(pb_Constant.pbMaterialEditorFloating); EditorPrefs.DeleteKey(pb_Constant.pbShapeWindowFloating); EditorPrefs.DeleteKey(pb_Constant.pbIconGUI); EditorPrefs.DeleteKey(pb_Constant.pbShiftOnlyTooltips); EditorPrefs.DeleteKey(pb_Constant.pbDrawAxisLines); EditorPrefs.DeleteKey(pb_Constant.pbCollapseVertexToFirst); EditorPrefs.DeleteKey(pb_Constant.pbMeshesAreAssets); EditorPrefs.DeleteKey(pb_Constant.pbElementSelectIsHamFisted); EditorPrefs.DeleteKey(pb_Constant.pbDragSelectWholeElement); EditorPrefs.DeleteKey(pb_Constant.pbFillHoleSelectsEntirePath); EditorPrefs.DeleteKey(pb_Constant.pbDetachToNewObject); EditorPrefs.DeleteKey(pb_Constant.pbPreserveFaces); EditorPrefs.DeleteKey(pb_Constant.pbVertexHandleSize); EditorPrefs.DeleteKey(pb_Constant.pbUVGridSnapValue); EditorPrefs.DeleteKey(pb_Constant.pbUVWeldDistance); EditorPrefs.DeleteKey(pb_Constant.pbWeldDistance); EditorPrefs.DeleteKey(pb_Constant.pbExtrudeDistance); EditorPrefs.DeleteKey(pb_Constant.pbBevelAmount); EditorPrefs.DeleteKey(pb_Constant.pbEdgeSubdivisions); EditorPrefs.DeleteKey(pb_Constant.pbDefaultShortcuts); EditorPrefs.DeleteKey(pb_Constant.pbDefaultMaterial); EditorPrefs.DeleteKey(pb_Constant.pbGrowSelectionUsingAngle); EditorPrefs.DeleteKey(pb_Constant.pbGrowSelectionAngle); EditorPrefs.DeleteKey(pb_Constant.pbGrowSelectionAngleIterative); EditorPrefs.DeleteKey(pb_Constant.pbShowDetail); EditorPrefs.DeleteKey(pb_Constant.pbShowOccluder); EditorPrefs.DeleteKey(pb_Constant.pbShowMover); EditorPrefs.DeleteKey(pb_Constant.pbShowCollider); EditorPrefs.DeleteKey(pb_Constant.pbShowTrigger); EditorPrefs.DeleteKey(pb_Constant.pbShowNoDraw); #if !UNITY_4_7 EditorPrefs.DeleteKey(pb_Constant.pbShadowCastingMode); #endif } LoadPrefs(); } static int shortcutIndex = 0; static Rect selectBox = new Rect(130, 253, 183, 142); static Rect resetRect = new Rect(0,0,0,0); static Vector2 shortcutScroll = Vector2.zero; static int CELL_HEIGHT = 20; static void ShortcutSelectPanel() { GUILayout.Space(4); GUI.contentColor = Color.white; GUI.Box(selectBox, ""); GUIStyle labelStyle = GUIStyle.none; if(EditorGUIUtility.isProSkin) labelStyle.normal.textColor = new Color(1f, 1f, 1f, .8f); labelStyle.alignment = TextAnchor.MiddleLeft; labelStyle.contentOffset = new Vector2(4f, 0f); shortcutScroll = EditorGUILayout.BeginScrollView(shortcutScroll, false, true, GUILayout.MaxWidth(183), GUILayout.MaxHeight(156)); for(int n = 1; n < defaultShortcuts.Length; n++) { if(n == shortcutIndex) { GUI.backgroundColor = new Color(0.23f, .49f, .89f, 1f); labelStyle.normal.background = EditorGUIUtility.whiteTexture; Color oc = labelStyle.normal.textColor; labelStyle.normal.textColor = Color.white; GUILayout.Box(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT)); labelStyle.normal.background = null; labelStyle.normal.textColor = oc; GUI.backgroundColor = Color.white; } else { if(GUILayout.Button(defaultShortcuts[n].action, labelStyle, GUILayout.MinHeight(CELL_HEIGHT), GUILayout.MaxHeight(CELL_HEIGHT))) { shortcutIndex = n; } } } EditorGUILayout.EndScrollView(); } static Rect keyRect = new Rect(324, 248, 168, 18); static Rect keyInputRect = new Rect(356, 248, 133, 18); static Rect descriptionTitleRect = new Rect(324, 300, 168, 200); static Rect descriptionRect = new Rect(324, 320, 168, 200); static Rect modifiersRect = new Rect(324, 270, 168, 18); static Rect modifiersInputRect = new Rect(383, 270, 107, 18); static void ShortcutEditPanel() { // descriptionTitleRect = EditorGUI.RectField(new Rect(240,150,200,50), descriptionTitleRect); GUI.Label(keyRect, "Key"); KeyCode key = defaultShortcuts[shortcutIndex].key; key = (KeyCode) EditorGUI.EnumPopup(keyInputRect, key); defaultShortcuts[shortcutIndex].key = key; GUI.Label(modifiersRect, "Modifiers"); // EnumMaskField returns a bit-mask where the flags correspond to the indices of the enum, not the enum values, // so this isn't technically correct. EventModifiers em = (EventModifiers) (((int)defaultShortcuts[shortcutIndex].eventModifiers) * 2); em = (EventModifiers)EditorGUI.EnumMaskField(modifiersInputRect, em); defaultShortcuts[shortcutIndex].eventModifiers = (EventModifiers) (((int)em) / 2); GUI.Label(descriptionTitleRect, "Description", EditorStyles.boldLabel); GUI.Label(descriptionRect, defaultShortcuts[shortcutIndex].description, EditorStyles.wordWrappedLabel); } static void LoadPrefs() { pbStripProBuilderOnBuild = pb_Preferences_Internal.GetBool(pb_Constant.pbStripProBuilderOnBuild); pbDisableAutoUV2Generation = pb_Preferences_Internal.GetBool(pb_Constant.pbDisableAutoUV2Generation); pbShowSceneInfo = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneInfo); defaultOpenInDockableWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbDefaultOpenInDockableWindow); pbDragCheckLimit = pb_Preferences_Internal.GetBool(pb_Constant.pbDragCheckLimit); pbForceConvex = pb_Preferences_Internal.GetBool(pb_Constant.pbForceConvex); pbForceGridPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceGridPivot); pbForceVertexPivot = pb_Preferences_Internal.GetBool(pb_Constant.pbForceVertexPivot); pbPerimeterEdgeBridgeOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPerimeterEdgeBridgeOnly); pbPBOSelectionOnly = pb_Preferences_Internal.GetBool(pb_Constant.pbPBOSelectionOnly); pbCloseShapeWindow = pb_Preferences_Internal.GetBool(pb_Constant.pbCloseShapeWindow); pbUVEditorFloating = pb_Preferences_Internal.GetBool(pb_Constant.pbUVEditorFloating); // pbShowSceneToolbar = pb_Preferences_Internal.GetBool(pb_Constant.pbShowSceneToolbar); pbShowEditorNotifications = pb_Preferences_Internal.GetBool(pb_Constant.pbShowEditorNotifications); pbUniqueModeShortcuts = pb_Preferences_Internal.GetBool(pb_Constant.pbUniqueModeShortcuts); pbIconGUI = pb_Preferences_Internal.GetBool(pb_Constant.pbIconGUI); pbShiftOnlyTooltips = pb_Preferences_Internal.GetBool(pb_Constant.pbShiftOnlyTooltips); pbDrawAxisLines = pb_Preferences_Internal.GetBool(pb_Constant.pbDrawAxisLines); pbMeshesAreAssets = pb_Preferences_Internal.GetBool(pb_Constant.pbMeshesAreAssets); pbElementSelectIsHamFisted = pb_Preferences_Internal.GetBool(pb_Constant.pbElementSelectIsHamFisted); pbDragSelectWholeElement = pb_Preferences_Internal.GetBool(pb_Constant.pbDragSelectWholeElement); pbDefaultFaceColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultFaceColor ); pbDefaultEdgeColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultEdgeColor ); pbDefaultSelectedVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultSelectedVertexColor ); pbDefaultVertexColor = pb_Preferences_Internal.GetColor( pb_Constant.pbDefaultVertexColor ); pbUVGridSnapValue = pb_Preferences_Internal.GetFloat(pb_Constant.pbUVGridSnapValue); pbVertexHandleSize = pb_Preferences_Internal.GetFloat(pb_Constant.pbVertexHandleSize); defaultColliderType = pb_Preferences_Internal.GetEnum<ColliderType>(pb_Constant.pbDefaultCollider); pbToolbarLocation = pb_Preferences_Internal.GetEnum<SceneToolbarLocation>(pb_Constant.pbToolbarLocation); pbDefaultEntity = pb_Preferences_Internal.GetEnum<EntityType>(pb_Constant.pbDefaultEntity); #if !UNITY_4_7 pbShadowCastingMode = pb_Preferences_Internal.GetEnum<ShadowCastingMode>(pb_Constant.pbShadowCastingMode); #endif pbDefaultMaterial = pb_Preferences_Internal.GetMaterial(pb_Constant.pbDefaultMaterial); defaultShortcuts = pb_Preferences_Internal.GetShortcuts().ToArray(); } public static void SetPrefs() { EditorPrefs.SetBool (pb_Constant.pbStripProBuilderOnBuild, pbStripProBuilderOnBuild); EditorPrefs.SetBool (pb_Constant.pbDisableAutoUV2Generation, pbDisableAutoUV2Generation); EditorPrefs.SetBool (pb_Constant.pbShowSceneInfo, pbShowSceneInfo); EditorPrefs.SetInt (pb_Constant.pbToolbarLocation, (int)pbToolbarLocation); EditorPrefs.SetInt (pb_Constant.pbDefaultEntity, (int)pbDefaultEntity); EditorPrefs.SetString (pb_Constant.pbDefaultFaceColor, pbDefaultFaceColor.ToString()); EditorPrefs.SetString (pb_Constant.pbDefaultEdgeColor, pbDefaultEdgeColor.ToString()); EditorPrefs.SetString (pb_Constant.pbDefaultSelectedVertexColor, pbDefaultSelectedVertexColor.ToString()); EditorPrefs.SetString (pb_Constant.pbDefaultVertexColor, pbDefaultVertexColor.ToString()); EditorPrefs.SetBool (pb_Constant.pbDefaultOpenInDockableWindow, defaultOpenInDockableWindow); EditorPrefs.SetString (pb_Constant.pbDefaultShortcuts, pb_Shortcut.ShortcutsToString(defaultShortcuts)); string matPath = pbDefaultMaterial != null ? AssetDatabase.GetAssetPath(pbDefaultMaterial) : ""; EditorPrefs.SetString (pb_Constant.pbDefaultMaterial, matPath); EditorPrefs.SetInt (pb_Constant.pbDefaultCollider, (int) defaultColliderType); #if !UNITY_4_7 EditorPrefs.SetInt (pb_Constant.pbShadowCastingMode, (int) pbShadowCastingMode); #endif EditorPrefs.SetBool (pb_Constant.pbShowEditorNotifications, pbShowEditorNotifications); EditorPrefs.SetBool (pb_Constant.pbForceConvex, pbForceConvex); EditorPrefs.SetBool (pb_Constant.pbDragCheckLimit, pbDragCheckLimit); EditorPrefs.SetBool (pb_Constant.pbForceVertexPivot, pbForceVertexPivot); EditorPrefs.SetBool (pb_Constant.pbForceGridPivot, pbForceGridPivot); EditorPrefs.SetBool (pb_Constant.pbPerimeterEdgeBridgeOnly, pbPerimeterEdgeBridgeOnly); EditorPrefs.SetBool (pb_Constant.pbPBOSelectionOnly, pbPBOSelectionOnly); EditorPrefs.SetBool (pb_Constant.pbCloseShapeWindow, pbCloseShapeWindow); EditorPrefs.SetBool (pb_Constant.pbUVEditorFloating, pbUVEditorFloating); EditorPrefs.SetBool (pb_Constant.pbUniqueModeShortcuts, pbUniqueModeShortcuts); EditorPrefs.SetBool (pb_Constant.pbIconGUI, pbIconGUI); EditorPrefs.SetBool (pb_Constant.pbShiftOnlyTooltips, pbShiftOnlyTooltips); EditorPrefs.SetBool (pb_Constant.pbDrawAxisLines, pbDrawAxisLines); EditorPrefs.SetBool (pb_Constant.pbMeshesAreAssets, pbMeshesAreAssets); EditorPrefs.SetBool (pb_Constant.pbElementSelectIsHamFisted, pbElementSelectIsHamFisted); EditorPrefs.SetBool (pb_Constant.pbDragSelectWholeElement, pbDragSelectWholeElement); EditorPrefs.SetFloat (pb_Constant.pbVertexHandleSize, pbVertexHandleSize); EditorPrefs.SetFloat (pb_Constant.pbUVGridSnapValue, pbUVGridSnapValue); if(pb_Editor.instance != null) pb_Editor.instance.OnEnable(); SceneView.RepaintAll(); } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.Data; namespace WebsitePanel.EnterpriseServer.Base.Reports { public partial class OverusageReport { #region BandwidthOverusageRow Extension Functions public partial class BandwidthOverusageRow { /// <summary> /// Creates a <see cref="BandwidthOverusageRow"/> using the <see cref="OverusageReport"/> /// DataSet from a row that contains information about bandwidth usage. /// </summary> /// <param name="report">Instance of <see cref="OverusageReport"/> class.</param> /// <param name="hostingSpaceDataRow">DataRow with bandwidth information.</param> /// <returns><see cref="BandwidthOverusageRow"/>.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or either <paramref name="hostingSpaceDataRow"/> is <code>null</code>.</exception> public static BandwidthOverusageRow CreateFromHostingSpaceDataRow(OverusageReport report, DataRow hostingSpaceDataRow) { if (report == null) { throw new ArgumentNullException("report"); } if (hostingSpaceDataRow == null) { throw new ArgumentNullException("hostingSpaceDataRow"); } BandwidthOverusageRow row = report.BandwidthOverusage.NewBandwidthOverusageRow(); row.HostingSpaceId = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceDataRow["PackageID"].ToString(), 0); row.Allocated = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceDataRow["QuotaValue"].ToString(), 0); row.Used = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceDataRow["Bandwidth"].ToString(), 0); row.Usage = (row.Used - row.Allocated); return row; } /// <summary> /// Creates <see cref="BandwidthOverusageRow"/> using <see cref="PackageInfo"/> as a data source. /// </summary> /// <param name="report">Current <see cref="OverusageReport"/> dataset.</param> /// <param name="packageInfo"><see cref="PackageInfo"/> instance.</param> /// <returns><see cref="BandwidthOverusageRow"/> instance.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or either <paramref name="packageInfo"/> is <code>null</code>.</exception> public static BandwidthOverusageRow CreateFromPackageInfo(OverusageReport report, PackageInfo packageInfo) { if (report == null) { throw new ArgumentNullException("report"); } if (packageInfo == null) { throw new ArgumentNullException("packageInfo"); } BandwidthOverusageRow row = report.BandwidthOverusage.NewBandwidthOverusageRow(); row.HostingSpaceId = packageInfo.PackageId; row.Allocated = packageInfo.BandWidthQuota; row.Used = packageInfo.BandWidth; row.Usage = (row.Used - row.Allocated); return row; } } #endregion #region OverusageDetailsRow Extension methods public partial class OverusageDetailsRow { /// <summary> /// Creates <see cref="OverusageDetailsRow"/> using the information about Hosting Space disk space. /// </summary> /// <param name="report"><see cref="OverusageReport"/> data set. Current report.</param> /// <param name="packageDiskspaceRow"><see cref="DataRow"/> containing the Hosting Space disk space information.</param> /// <param name="hostingSpaceId">Hosting Space id.</param> /// <param name="overusageType">Type of overusage, can be Diskspace, Bandwidth, etc.</param> /// <returns>An instance of <see cref="OverusageDetailsRow"/>.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/>, <paramref name="packageDiskspaceRow"/> or <paramref name="overusageType"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">When <paramref name="hostingSpaceId"/> less then 1.</exception> public static OverusageDetailsRow CreateFromPackageDiskspaceRow(OverusageReport report, DataRow packageDiskspaceRow, long hostingSpaceId, string overusageType) { if (report == null) { throw new ArgumentNullException("report"); } if (packageDiskspaceRow == null) { throw new ArgumentNullException("packageDiskspaceRow"); } if (String.IsNullOrEmpty(overusageType)) { throw new ArgumentNullException("overusageType"); } if (hostingSpaceId < 1) { throw new ArgumentOutOfRangeException( "hostingSpaceId" , String.Format( "Hosting Space Id cannot be less then 1, however it is {0}." , hostingSpaceId ) ); } OverusageDetailsRow row = report.OverusageDetails.NewOverusageDetailsRow(); row.HostingSpaceId = hostingSpaceId; row.OverusageType = overusageType; row.ResourceGroupName = OverusageReportUtils.GetStringOrDefault(packageDiskspaceRow, "GroupName", "Files"); row.Used = OverusageReportUtils.GetLongValueOrDefault(packageDiskspaceRow["Diskspace"].ToString(), 0); row.Allowed = 0; return row; } /// <summary> /// Creates <see cref="OverusageDetailsRow"/> using information about Hosting Space bandwidth. /// </summary> /// <param name="report">Current <see cref="OverusageReport"/> instance.</param> /// <param name="bandwidthRow"><see cref="DataRow"/> containing information about Hosting Space bandwidth.</param> /// <param name="hostingSpaceId">Hosting Space Id.</param> /// <param name="overusageType">Type of overusage. Diskspace, Bandwidth, etc.</param> /// <returns><see cref="OverusageDetailsRow"/> filled from <paramref name="bandwidthRow"/>.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/>, <paramref name="bandwidthRow"/> or <paramref name="overusageType"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">When <paramref name="hostingSpaceId"/> less then 1.</exception> public static OverusageDetailsRow CreateFromBandwidthRow(OverusageReport report, DataRow bandwidthRow, long hostingSpaceId, string overusageType) { if (report == null) { throw new ArgumentNullException("report"); } if (bandwidthRow == null) { throw new ArgumentNullException("bandwidthRow"); } if (String.IsNullOrEmpty(overusageType)) { throw new ArgumentNullException("overusageType"); } if (hostingSpaceId < 1) { throw new ArgumentOutOfRangeException( "hostingSpaceId" , String.Format( "Hosting Space Id cannot be less then 1, however it is {0}." , hostingSpaceId ) ); } OverusageDetailsRow row = report.OverusageDetails.NewOverusageDetailsRow(); row.HostingSpaceId = hostingSpaceId; row.OverusageType = overusageType; row.ResourceGroupName = OverusageReportUtils.GetStringOrDefault(bandwidthRow, "GroupName", "Files"); row.Used = OverusageReportUtils.GetLongValueOrDefault(bandwidthRow["MegaBytesSent"].ToString(), 0); row.AdditionalField = OverusageReportUtils.GetLongValueOrDefault(bandwidthRow["MegaBytesReceived"].ToString(), 0); row.Allowed = 0; return row; } } #endregion #region HostingSpaceRow Extension functions public partial class HostingSpaceRow { /// <summary> /// Returns a package id /// </summary> /// <param name="hostingSpaceRow"><see cref="DataRow"/> containing information about Hosting Space</param> /// <returns>Hosting space ID.</returns> /// <exception cref="ArgumentOutOfRangeException">When DataRow does not contain PackageID field or this field contains value less then 1.</exception> public static long GetPackageId(DataRow hostingSpaceRow) { long hostingSpaceId = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["PackageID"].ToString(), 0); if (hostingSpaceId < 1) { throw new ArgumentOutOfRangeException( "hostingSpaceId" , String.Format( "PackageID field is either empty or contains incorrect value. Received package ID value: {0}." , hostingSpaceId ) ); } return hostingSpaceId; } /// <summary> /// Creates <see cref="HostingSpaceRow"/> using <see cref="PackageInfo"/>. /// </summary> /// <param name="report">Current <see cref="OverusageReport"/>.</param> /// <param name="packageInfo">Information about Hosting Space</param> /// <param name="userInfo">Information about user <paramref name="packageInfo"/> belongs to.</param> /// <param name="serverInfo">Information about server. Physical storage of a hosting space described in <paramref name="packageInfo"/></param> /// <param name="isDiskspaceOverused">Indicates whether disk space is overused.</param> /// <param name="isBandwidthOverused">Indicates whether bandwidht is overused.</param> /// <param name="packageFullTree">File system -like path of the location of a hosting space described in <paramref name="packageInfo"/></param> /// <returns><see cref="HostingSpaceRow"/> instance.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/>, <paramref name="packageInfo"/>, <paramref name="userInfo"/> or <paramref name="serverInfo"/> is null.</exception> public static HostingSpaceRow CreateFromPackageInfo(OverusageReport report, PackageInfo packageInfo, UserInfo userInfo, ServerInfo serverInfo,bool isDiskspaceOverused, bool isBandwidthOverused, string packageFullTree) { if (report == null) { throw new ArgumentNullException("report"); } if (packageInfo == null) { throw new ArgumentNullException("packageInfo"); } if (userInfo == null) { throw new ArgumentNullException("userInfo"); } if (serverInfo == null) { throw new ArgumentNullException("serverInfo"); } HostingSpaceRow row = report.HostingSpace.NewHostingSpaceRow(); row.IsBandwidthOverused = isBandwidthOverused; row.IsDiskspaceOverused = isDiskspaceOverused; row.HostingSpaceName = packageInfo.PackageName; row.UserEmail = userInfo.Username; row.UserName = userInfo.Email; row.ChildSpaceQuantity = 1; row.UserId = packageInfo.UserId; row.HostingSpaceId = packageInfo.PackageId; row.Status = packageInfo.StatusId.ToString(); row.HostingSpaceFullTreeName = packageFullTree; row.HostingSpaceCreationDate = packageInfo.PurchaseDate; row.Location = serverInfo.ServerName; return row; } /// <summary> /// Creating <see cref="HostingSpaceRow"/> from DataRow containing data about Hosting Space /// </summary> /// <param name="report">Current <see cref="OverusageReport"/></param> /// <param name="hostingSpaceRow"><see cref="DataRow"/> containing information about Hosting Space.</param> /// <param name="isDiskspaceOverused">Indicates whether disk space is overused.</param> /// <param name="isBandwidthOverused">Indicates whether bandwidth is overusaed.</param> /// <param name="packageFullTree">File system -like path to hosting space described by <paramref name="hostingSpaceRow"/></param> /// <returns><see cref="HostingSpaceRow"/> instance.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or <paramref name="hostingSpaceRow"/> is null.</exception> public static HostingSpaceRow CreateFromHostingSpacesRow(OverusageReport report, DataRow hostingSpaceRow, bool isDiskspaceOverused, bool isBandwidthOverused, string packageFullTree) { if (report == null) { throw new ArgumentNullException("report"); } if (hostingSpaceRow == null) { throw new ArgumentNullException("hostingSpaceRow"); } HostingSpaceRow row = report.HostingSpace.NewHostingSpaceRow(); row.IsBandwidthOverused = isBandwidthOverused; row.IsDiskspaceOverused = isDiskspaceOverused; row.HostingSpaceName = OverusageReportUtils.GetStringOrDefault(hostingSpaceRow, "PackageName", String.Empty); row.UserEmail = OverusageReportUtils.GetStringOrDefault(hostingSpaceRow, "Email", String.Empty); row.UserName = OverusageReportUtils.GetStringOrDefault(hostingSpaceRow, "Username", String.Empty); row.UserId = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["UserId"].ToString(), 0); row.HostingSpaceId = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["PackageID"].ToString(), 0); row.ChildSpaceQuantity = (int)OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["PackagesNumber"].ToString(), 0); row.Status = hostingSpaceRow["StatusID"].ToString(); row.HostingSpaceFullTreeName = packageFullTree; return row; } /// <summary> /// Verify whether <paramref name="hostingSpacesRow"/> contains child spaces. /// </summary> /// <param name="hostingSpacesRow"><see cref="DataRow"/> containing information about Hosting Space.</param> /// <returns>True it Hosting space contains child spaces. Otherwise, False.</returns> /// <exception cref="ArgumentNullException">When <paramref name="hostingSpacesRow"/> is null.</exception> public static bool IsContainChildSpaces(DataRow hostingSpacesRow) { if (hostingSpacesRow == null) { throw new ArgumentNullException("hostingSpacesRow"); } return OverusageReportUtils.GetLongValueOrDefault(hostingSpacesRow["PackagesNumber"].ToString(), 0) > 0; } /// <summary> /// Verify is disk space is overused by a Hosting Space. /// </summary> /// <param name="hostingSpacesRow"><see cref="DataRow"/> containing information about Hosting Space.</param> /// <returns>True, if Hosting Space overuses disk space quota. Otherwise, False.</returns> /// <exception cref="ArgumentNullException">When <paramref name="hostingSpacesRow"/> is null.</exception> public static bool VerifyIfDiskspaceOverused(DataRow hostingSpacesRow) { if (hostingSpacesRow == null) { throw new ArgumentNullException("hostingSpacesRow"); } long allocated = OverusageReportUtils.GetLongValueOrDefault(hostingSpacesRow["QuotaValue"].ToString(), 0), used = OverusageReportUtils.GetLongValueOrDefault(hostingSpacesRow["Diskspace"].ToString(), 0); return (used > allocated); } /// <summary> /// Vefiry if bandwidth is overused by Hosting Space /// </summary> /// <param name="hostingSpacesRow"><see cref="DataRow"/> containing bandwidth information about Hosting Space.</param> /// <returns>True, if bandwidth is overused by a Hosting Space. Otherwise, False.</returns> /// <exception cref="ArgumentNullException">When <paramref name="hostingSpacesRow"/> is null.</exception> public static bool VerifyIfBandwidthOverused(DataRow hostingSpacesRow) { if (hostingSpacesRow == null) { throw new ArgumentNullException("hostingSpacesRow"); } long allocated = OverusageReportUtils.GetLongValueOrDefault(hostingSpacesRow["QuotaValue"].ToString(), 0), used = OverusageReportUtils.GetLongValueOrDefault(hostingSpacesRow["Bandwidth"].ToString(), 0); return (used > allocated); } } #endregion #region DiskspaceOverusageRow extension functions public partial class DiskspaceOverusageRow { /// <summary> /// Creates <see cref="DiskspaceOverusageRow"/> from Hosting Space row. /// </summary> /// <param name="report">Current <paramref name="OverusageReport"/></param> /// <param name="hostingSpaceRow"><see cref="DataRow"/> containing Hosting Space information.</param> /// <returns><see cref="DiskspaceOverusageRow"/> instance.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or <paramref name="hostingSpaceRow"/> is null.</exception> public static DiskspaceOverusageRow CreateFromHostingSpacesRow(OverusageReport report, DataRow hostingSpaceRow) { if (report == null) { throw new ArgumentNullException("report"); } if (hostingSpaceRow == null) { throw new ArgumentNullException("hostingSpaceRow"); } DiskspaceOverusageRow row = report.DiskspaceOverusage.NewDiskspaceOverusageRow(); row.HostingSpaceId = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["PackageID"].ToString(), 0); row.Allocated = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["QuotaValue"].ToString(), 0); row.Used = OverusageReportUtils.GetLongValueOrDefault(hostingSpaceRow["Diskspace"].ToString(), 0); row.Usage = (row.Used - row.Allocated); return row; } /// <summary> /// Creates <see cref="DiskspaceOverusageRow"/> using <see cref="PackageInfo"/> information. /// </summary> /// <param name="report">Current <see cref="OverusageReport"/></param> /// <param name="packageInfo">Hosting Space information.</param> /// <returns><see cref="DiskspaceOverusageRow"/> instance.</returns> /// <exception cref="ArgumentNullException">When <paramref name="report"/> or <paramref name="packageInfo"/> is null.</exception> public static DiskspaceOverusageRow CreateFromPackageInfo(OverusageReport report, PackageInfo packageInfo) { if (report == null) { throw new ArgumentNullException("report"); } if (packageInfo == null) { throw new ArgumentNullException("packageInfo"); } DiskspaceOverusageRow row = report.DiskspaceOverusage.NewDiskspaceOverusageRow(); row.HostingSpaceId = packageInfo.PackageId; row.Allocated = packageInfo.DiskSpaceQuota; row.Used = packageInfo.DiskSpace; row.Usage = (row.Used - row.Allocated); return row; } } #endregion } }
using System; using System.Collections.Generic; using JetBrains.Annotations; using JetBrains.DocumentModel; using JetBrains.ProjectModel; using JetBrains.ReSharper.Feature.Services.CodeCompletion; using JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.LookupItems; using JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.LookupItems.Impl; using JetBrains.ReSharper.Feature.Services.CodeCompletion.Infrastructure.Match; using JetBrains.ReSharper.Feature.Services.CSharp.CodeCompletion.Infrastructure; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.Features.Intellisense.CodeCompletion.CSharp.Rules; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AnimatorUsages; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.CSharp.Util.Literals; using JetBrains.ReSharper.Psi.Resources; using JetBrains.ReSharper.Psi.Tree; using JetBrains.TextControl; using JetBrains.UI.Icons; namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.CodeCompletion { [Language(typeof(CSharpLanguage))] public class UnityProjectSettingsCompletionProvider : CSharpItemsProviderBase<CSharpCodeCompletionContext> { protected override bool IsAvailable(CSharpCodeCompletionContext context) { return context.BasicContext.CodeCompletionType == CodeCompletionType.BasicCompletion; } protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector) { var ranges = context.CompletionRanges; IEnumerable<string> completionItems = null; // scene completion if (IsSpecificArgumentInSpecificMethod(context, out var argumentLiteral, IsLoadSceneMethod, IsCorrespondingArgument("sceneName"))) { var cache = context.NodeInFile.GetSolution().GetComponent<UnityProjectSettingsCache>(); completionItems = cache.GetAllPossibleSceneNames(); } // animator state completion else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, IsPlayAnimationMethod, IsCorrespondingArgument("stateName"))) { var container = context.NodeInFile.GetSolution().GetComponent<AnimatorScriptUsagesElementContainer>(); completionItems = container.GetStateNames(); } // tag completion, tag == "..." else if (IsTagEquality(context, out argumentLiteral)) { var cache = context.NodeInFile.GetSolution().GetComponent<UnityProjectSettingsCache>(); completionItems = cache.GetAllTags(); } // tag completion, CompareTag("...") else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, ExpressionReferenceUtils.IsCompareTagMethod, IsCorrespondingArgument("tag"))) { var cache = context.NodeInFile.GetSolution().GetComponent<UnityProjectSettingsCache>(); completionItems = cache.GetAllTags(); } // layer completion else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, ExpressionReferenceUtils.IsLayerMaskNameToLayerMethod, IsCorrespondingArgument("layerName")) || IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, ExpressionReferenceUtils.IsLayerMaskGetMaskMethod, (_, __) => true)) { var cache = context.NodeInFile.GetSolution().GetComponent<UnityProjectSettingsCache>(); completionItems = cache.GetAllLayers(); } // input completion else if (IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, ExpressionReferenceUtils.IsInputButtonMethod, IsCorrespondingArgument("buttonName")) || IsSpecificArgumentInSpecificMethod(context, out argumentLiteral, ExpressionReferenceUtils.IsInputAxisMethod, IsCorrespondingArgument("axisName"))) { var cache = context.NodeInFile.GetSolution().GetComponent<UnityProjectSettingsCache>(); completionItems = cache.GetAllInput(); } var any = false; if (argumentLiteral != null) { var offset = argumentLiteral.GetDocumentRange().EndOffset; ranges = ranges.WithInsertRange(ranges.InsertRange.SetEndTo(offset)).WithReplaceRange(ranges.ReplaceRange.SetEndTo(offset)); } if (completionItems != null) { foreach (var sceneName in completionItems) { any = true; var item = new StringLiteralItem($"\"{sceneName}\""); item.InitializeRanges(ranges, context.BasicContext); collector.Add(item); } } return any; } private bool IsSpecificArgumentInSpecificMethod(CSharpCodeCompletionContext context, out ICSharpLiteralExpression stringLiteral, Func<IInvocationExpression, bool> methodChecker, Func<IArgumentList, ICSharpArgument, bool> argumentChecker) { stringLiteral = null; var nodeInFile = context.NodeInFile as ITokenNode; if (nodeInFile == null) return false; var possibleInvocationExpression = nodeInFile.Parent; if (possibleInvocationExpression is ICSharpLiteralExpression literalExpression) { if (!literalExpression.Literal.IsAnyStringLiteral()) return false; var argument = CSharpArgumentNavigator.GetByValue(literalExpression); var argumentList = ArgumentListNavigator.GetByArgument(argument); if (argument == null || argumentList == null) return false; if (argumentChecker(argumentList, argument)) { stringLiteral = literalExpression; possibleInvocationExpression = InvocationExpressionNavigator.GetByArgument(argument); } } if (possibleInvocationExpression is IInvocationExpression invocationExpression) { if (methodChecker(invocationExpression)) { return true; } } stringLiteral = null; return false; } private Func<IArgumentList, ICSharpArgument, bool> IsCorrespondingArgument(string argumentName) { return (argumentList, argument) => argument.IsNamedArgument && argument.NameIdentifier.Name.Equals(argumentName) || !argument.IsNamedArgument && argumentList.Arguments[0] == argument; } private bool IsLoadSceneMethod(IInvocationExpression invocationExpression) { return invocationExpression.InvocationExpressionReference.IsSceneManagerSceneRelatedMethod() || invocationExpression.InvocationExpressionReference.IsEditorSceneManagerSceneRelatedMethod(); } private static bool IsPlayAnimationMethod([NotNull] IInvocationExpression invocationExpression) { return invocationExpression.InvocationExpressionReference.IsAnimatorPlayMethod(); } private bool IsTagEquality(CSharpCodeCompletionContext context, out ICSharpLiteralExpression stringLiteral) { stringLiteral = null; var nodeInFile = context.NodeInFile; var eqExpression = nodeInFile.NextSibling as IEqualityExpression ?? nodeInFile.PrevSibling as IEqualityExpression; var possibleLiteral = context.NodeInFile.Parent; if (possibleLiteral is ICSharpLiteralExpression literalExpression) { stringLiteral = literalExpression; eqExpression = possibleLiteral.Parent as IEqualityExpression; } if (eqExpression != null) { return (eqExpression.LeftOperand as IReferenceExpression).IsTagProperty() || (eqExpression.RightOperand as IReferenceExpression).IsTagProperty(); } stringLiteral = null; return false; } private sealed class StringLiteralItem : TextLookupItemBase { public StringLiteralItem([NotNull] string text) { Text = text; } public override IconId Image => PsiSymbolsThemedIcons.Const.Id; public override MatchingResult Match(PrefixMatcher prefixMatcher) { var matchingResult = prefixMatcher.Match(Text); if (matchingResult == null) return null; return new MatchingResult(matchingResult.MatchedIndices, matchingResult.AdjustedScore - 100, matchingResult.OriginalScore); } public override void Accept( ITextControl textControl, DocumentRange nameRange, LookupItemInsertType insertType, Suffix suffix, ISolution solution, bool keepCaretStill) { base.Accept(textControl, nameRange, LookupItemInsertType.Replace, suffix, solution, keepCaretStill); } } } }
using Gaming.Game; using Gaming.Graphics; using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.VectorMath; //#define USE_GLSL using System; using System.Collections.Generic; namespace RockBlaster { public class Playfield : GameObject { [GameDataList("RockList")] private List<Entity> m_RockList = new List<Entity>(); private List<Entity> m_SequenceEntityList = new List<Entity>(); [GameData("PlayerList")] private List<Player> m_PlayerList = new List<Player>(); //Model3D m_Ship = new Model3D("..\\..\\GameData\\ShipTris.dae"); #region GameObjectStuff public Playfield() { } public static new GameObject Load(String PathName) { return GameObject.Load(PathName); } #endregion GameObjectStuff public List<Entity> RockList { get { return m_RockList; } } public List<Player> PlayerList { get { return m_PlayerList; } } public void StartOnePlayerGame() { m_SequenceEntityList.Add(new SequenceEntity(new Vector2(20, 20))); m_RockList.Add(new Rock(m_RockList, 40)); m_RockList.Add(new Rock(m_RockList, 40)); m_PlayerList.Add(new Player(0, 0, Keys.Z, Keys.X, Keys.OemPeriod, Keys.OemQuestion)); m_PlayerList[0].Position = new Vector2(Entity.GameWidth / 2, Entity.GameHeight / 2); } internal void StartTwoPlayerGame() { m_SequenceEntityList.Add(new SequenceEntity(new Vector2(20, 20))); m_RockList.Add(new Rock(m_RockList, 0)); m_RockList.Add(new Rock(m_RockList, 0)); m_RockList.Add(new Rock(m_RockList, 0)); m_PlayerList.Add(new Player(0, 0, Keys.Z, Keys.X, Keys.V, Keys.B)); m_PlayerList[0].Position = new Vector2(Entity.GameWidth / 4, Entity.GameHeight / 2); m_PlayerList.Add(new Player(1, 1, Keys.N, Keys.M, Keys.OemPeriod, Keys.OemQuestion)); m_PlayerList[1].Position = new Vector2(Entity.GameWidth / 4 * 3, Entity.GameHeight / 2); } internal void StartFourPlayerGame() { m_SequenceEntityList.Add(new SequenceEntity(new Vector2(20, 20))); m_RockList.Add(new Rock(m_RockList, 0)); m_RockList.Add(new Rock(m_RockList, 0)); m_RockList.Add(new Rock(m_RockList, 0)); m_PlayerList.Add(new Player(0, -1, Keys.Z, Keys.X, Keys.V, Keys.B)); m_PlayerList[0].Position = new Vector2(Entity.GameWidth / 4, Entity.GameHeight / 4 * 3); m_PlayerList.Add(new Player(1, -1, Keys.N, Keys.M, Keys.OemPeriod, Keys.OemQuestion)); m_PlayerList[1].Position = new Vector2(Entity.GameWidth / 4 * 3, Entity.GameHeight / 4 * 3); m_PlayerList.Add(new Player(2, 0, Keys.Q, Keys.Q, Keys.Q, Keys.Q)); m_PlayerList[2].Position = new Vector2(Entity.GameWidth / 4, Entity.GameHeight / 4); m_PlayerList.Add(new Player(3, 1, Keys.Q, Keys.Q, Keys.Q, Keys.Q)); m_PlayerList[3].Position = new Vector2(Entity.GameWidth / 4 * 3, Entity.GameHeight / 4); } public void Draw(Graphics2D currentRenderer) { foreach (Rock aRock in m_RockList) { aRock.Draw(currentRenderer); } foreach (Player aPlayer in m_PlayerList) { aPlayer.DrawBullets(currentRenderer); } foreach (SequenceEntity aSequenceEntity in m_SequenceEntityList) { aSequenceEntity.Draw(currentRenderer); } foreach (Player aPlayer in m_PlayerList) { aPlayer.Draw(currentRenderer); } GameImageSequence hud = (GameImageSequence)DataAssetCache.Instance.GetAsset(typeof(GameImageSequence), (m_PlayerList.Count).ToString() + "PlayerHUD"); currentRenderer.Render(hud.GetImageByIndex(0), 400, 300); foreach (Player aPlayer in m_PlayerList) { aPlayer.DrawScore(currentRenderer); } #if false Gl.glMatrixMode(Gl.GL_PROJECTION); // Select The Projection Matrix Gl.glLoadIdentity(); // Reset The Projection Matrix Glu.gluPerspective(45, Entity.GameWidth / (double)Entity.GameHeight, 0.1, 100); // Calculate The Aspect Ratio Of The Window Gl.glMatrixMode(Gl.GL_MODELVIEW); // Select The Modelview Matrix float scale = .08f; Gl.glLoadIdentity(); // Reset The Current Modelview Matrix Gl.glLightf(Gl.GL_LIGHT0, Gl.GL_CONSTANT_ATTENUATION, 0.0f); Gl.glLightf(Gl.GL_LIGHT0, Gl.GL_LINEAR_ATTENUATION, 0.0f); Gl.glLightf(Gl.GL_LIGHT0, Gl.GL_QUADRATIC_ATTENUATION, 0.0002f); float[] position = new float[] { -10.5f, 10.0f, 20.0f, 1.0f }; Gl.glScalef(scale, scale, scale); Gl.glTranslatef(0, 0, -160); // Move Left 1.5 Units And Into The Screen 6.0 Gl.glLightfv(Gl.GL_LIGHT0, Gl.GL_POSITION, position); Gl.glTranslatef((float)m_Player.Position.x - 200, (float)m_Player.Position.y - 200, 0); Gl.glRotatef((float)((m_Player.m_Rotation - Math.PI / 2) / Math.PI * 180), 0, 0, 1); // Rotate The Triangle On The Y axis ( NEW ) Gl.glShadeModel(Gl.GL_FLAT); Gl.glClearDepth(1); // Depth Buffer Setup Gl.glEnable(Gl.GL_DEPTH_TEST); // Enables Depth Testing Gl.glDepthFunc(Gl.GL_LEQUAL); // The Type Of Depth Testing To Do Gl.glDisable(Gl.GL_CULL_FACE); #endif #if USE_GLSL String[] vertexSource = System.IO.File.ReadAllLines("..\\..\\GameData\\marble.vert"); vertexSource = new string[] { "void main(void) { gl_Position = ftransform(); } " }; vertexSource = new string[] { "varying vec3 normal, lightDir, eyeVec; void main() { normal = gl_NormalMatrix * gl_Normal; vec3 vVertex = vec3(gl_ModelViewMatrix * gl_Vertex); lightDir = vec3(gl_LightSource[0].position.xyz - vVertex); eyeVec = -vVertex; gl_Position = ftransform(); }" }; int vertexShader = Gl.glCreateShader(Gl.GL_VERTEX_SHADER); Gl.glShaderSource(vertexShader, vertexSource.Length, vertexSource, null); Gl.glCompileShader(vertexShader); int goodCompile; Gl.glGetShaderiv(vertexShader, Gl.GL_COMPILE_STATUS, out goodCompile); String[] fragmentSource = System.IO.File.ReadAllLines("..\\..\\GameData\\marble.frag"); fragmentSource = new string[] { "void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); }" }; fragmentSource = new string[] { "varying vec3 normal, lightDir, eyeVec; void main (void) { vec4 final_color = (gl_FrontLightModelProduct.sceneColor * gl_FrontMaterial.ambient) + (gl_LightSource[0].ambient * gl_FrontMaterial.ambient); vec3 N = normalize(normal); vec3 L = normalize(lightDir); float lambertTerm = dot(N,L); if(lambertTerm > 0.0) { final_color += gl_LightSource[0].diffuse * gl_FrontMaterial.diffuse * lambertTerm; vec3 E = normalize(eyeVec); vec3 R = reflect(-L, N); float specular = pow( max(dot(R, E), 0.0), gl_FrontMaterial.shininess ); final_color += gl_LightSource[0].specular * gl_FrontMaterial.specular * specular; } gl_FragColor = final_color; }" }; int fragmentShader = Gl.glCreateShader(Gl.GL_FRAGMENT_SHADER); Gl.glShaderSource(fragmentShader, fragmentSource.Length, fragmentSource, null); Gl.glCompileShader(fragmentShader); Gl.glGetShaderiv(fragmentShader, Gl.GL_COMPILE_STATUS, out goodCompile); int shaderProgram; shaderProgram = Gl.glCreateProgram(); Gl.glAttachShader(shaderProgram, fragmentShader); Gl.glAttachShader(shaderProgram, vertexShader); Gl.glLinkProgram(shaderProgram); Gl.glGetProgramiv(shaderProgram, Gl.GL_LINK_STATUS, out goodCompile); System.Text.StringBuilder infoLog = new System.Text.StringBuilder(); int length; Gl.glGetShaderInfoLog(shaderProgram, 500, out length, infoLog); Gl.glUseProgram(shaderProgram); #endif //m_Ship.Render(); #if USE_GLSL Gl.glUseProgram(0); Gl.glDetachShader(shaderProgram, fragmentShader); Gl.glDetachShader(shaderProgram, vertexShader); Gl.glDeleteShader(fragmentShader); Gl.glDeleteShader(vertexShader); Gl.glDeleteProgram(shaderProgram); #endif } public void CollidePlayersWithOtherPlayersBullets() { foreach (Player aPlayer in m_PlayerList) { foreach (Player bPlayer in m_PlayerList) { if (aPlayer != bPlayer) { foreach (Bullet aBullet in aPlayer.m_BulletList) { Vector2 BulletRelBPlayer = aBullet.Position - bPlayer.Position; double BothRadius = bPlayer.Radius + aBullet.Radius; double BothRadiusSqrd = BothRadius * BothRadius; if (BulletRelBPlayer.LengthSquared < BothRadiusSqrd) { Vector2 addVelocity = aBullet.Velocity; addVelocity *= .7; bPlayer.Velocity = bPlayer.Velocity + addVelocity; bPlayer.m_LastPlayerToShot = aPlayer; aBullet.GiveDamage(); } } } } } } public void CollideRocksAndPlayersAndBullets() { foreach (Player aPlayer in m_PlayerList) { foreach (Rock aRock in m_RockList) { { Vector2 playerRelRock = aPlayer.Position - aRock.Position; double BothRadius = aRock.Radius + aPlayer.Radius; double BothRadiusSqrd = BothRadius * BothRadius; if (playerRelRock.LengthSquared < BothRadiusSqrd) { aRock.TakeDamage(aPlayer.GiveDamage(), aPlayer); aPlayer.TakeDamage(20, null); } } foreach (Bullet aBullet in aPlayer.m_BulletList) { Vector2 BulletRelRock = aBullet.Position - aRock.Position; double BothRadius = aRock.Radius + aBullet.Radius; double BothRadiusSqrd = BothRadius * BothRadius; if (BulletRelRock.LengthSquared < BothRadiusSqrd) { aRock.TakeDamage(aBullet.GiveDamage(), aPlayer); if (m_PlayerList.Count == 1) { aPlayer.m_Score += 2; } } } } } } protected void RemoveDeadStuff(List<Entity> listToRemoveFrom) { List<Entity> RemoveList = new List<Entity>(); foreach (Entity aEntity in listToRemoveFrom) { if (aEntity.Damage >= aEntity.MaxDamage) { RemoveList.Add(aEntity); } } foreach (Entity aEntity in RemoveList) { aEntity.Destroying(); listToRemoveFrom.Remove(aEntity); } } public void Update(double NumSecondsPassed) { int numBigRocks = 0; foreach (Rock aRock in m_RockList) { aRock.Update(NumSecondsPassed); if (aRock.scaleRatio == 1) { numBigRocks++; } } if (m_RockList.Count < 20 && numBigRocks < 1 && m_PlayerList.Count > 1) { m_RockList.Add(new Rock(m_RockList, 0)); } foreach (SequenceEntity aSequenceEntity in m_SequenceEntityList) { aSequenceEntity.Update(NumSecondsPassed); } foreach (Player aPlayer in m_PlayerList) { aPlayer.Update(NumSecondsPassed); } RemoveDeadStuff(m_RockList); CollideRocksAndPlayersAndBullets(); CollidePlayersWithOtherPlayersBullets(); RemoveDeadStuff(m_RockList); foreach (Player aPlayer in m_PlayerList) { RemoveDeadStuff(aPlayer.m_BulletList); } RemoveDeadStuff(m_SequenceEntityList); } } }
namespace Entropy { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblIterations = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.chkDisplayMotion = new System.Windows.Forms.CheckBox(); this.btnStart = new System.Windows.Forms.Button(); this.cmbSeed = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.cmbGrid = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.cmbParticles = new System.Windows.Forms.ComboBox(); this.label8 = new System.Windows.Forms.Label(); this.cmbMaxInitVx = new System.Windows.Forms.ComboBox(); this.label9 = new System.Windows.Forms.Label(); this.cmbMaxInitVy = new System.Windows.Forms.ComboBox(); this.btnReset = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.btnLoad = new System.Windows.Forms.Button(); this.btnLoadMin = new System.Windows.Forms.Button(); this.lblEntropy = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.histogramY = new Entropy.Histogram(); this.histogramX = new Entropy.Histogram(); this.canvas = new Entropy.DrawingCanvas(); this.SuspendLayout(); // // lblIterations // this.lblIterations.AutoSize = true; this.lblIterations.Location = new System.Drawing.Point(598, 291); this.lblIterations.Name = "lblIterations"; this.lblIterations.Size = new System.Drawing.Size(16, 13); this.lblIterations.TabIndex = 2; this.lblIterations.Text = "---"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(520, 170); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(76, 13); this.label4.TabIndex = 2; this.label4.Text = "Random seed:"; // // chkDisplayMotion // this.chkDisplayMotion.AutoSize = true; this.chkDisplayMotion.CheckAlign = System.Drawing.ContentAlignment.MiddleRight; this.chkDisplayMotion.Checked = true; this.chkDisplayMotion.CheckState = System.Windows.Forms.CheckState.Checked; this.chkDisplayMotion.Location = new System.Drawing.Point(519, 200); this.chkDisplayMotion.Name = "chkDisplayMotion"; this.chkDisplayMotion.Size = new System.Drawing.Size(94, 17); this.chkDisplayMotion.TabIndex = 4; this.chkDisplayMotion.Text = "Display motion"; this.chkDisplayMotion.UseVisualStyleBackColor = true; // // btnStart // this.btnStart.Location = new System.Drawing.Point(601, 232); this.btnStart.Name = "btnStart"; this.btnStart.Size = new System.Drawing.Size(57, 24); this.btnStart.TabIndex = 3; this.btnStart.Text = "Start"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // cmbSeed // this.cmbSeed.FormattingEnabled = true; this.cmbSeed.Location = new System.Drawing.Point(600, 167); this.cmbSeed.Name = "cmbSeed"; this.cmbSeed.Size = new System.Drawing.Size(47, 21); this.cmbSeed.TabIndex = 5; this.cmbSeed.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(520, 291); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 2; this.label5.Text = "Iterations:"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(520, 48); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(29, 13); this.label6.TabIndex = 2; this.label6.Text = "Grid:"; // // cmbGrid // this.cmbGrid.FormattingEnabled = true; this.cmbGrid.Items.AddRange(new object[] { "10", "15", "25", "50", "75", "100", "150", "250"}); this.cmbGrid.Location = new System.Drawing.Point(600, 45); this.cmbGrid.Name = "cmbGrid"; this.cmbGrid.Size = new System.Drawing.Size(47, 21); this.cmbGrid.TabIndex = 5; this.cmbGrid.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged); // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(520, 79); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(50, 13); this.label7.TabIndex = 2; this.label7.Text = "Particles:"; // // cmbParticles // this.cmbParticles.FormattingEnabled = true; this.cmbParticles.Items.AddRange(new object[] { "10", "15", "25", "50", "75", "100", "150", "250", "500", "750", "1000", "1500", "2500", "5000", "7500", "10000"}); this.cmbParticles.Location = new System.Drawing.Point(600, 76); this.cmbParticles.Name = "cmbParticles"; this.cmbParticles.Size = new System.Drawing.Size(47, 21); this.cmbParticles.TabIndex = 5; this.cmbParticles.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(520, 109); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(61, 13); this.label8.TabIndex = 2; this.label8.Text = "Max init Vx:"; // // cmbMaxInitVx // this.cmbMaxInitVx.FormattingEnabled = true; this.cmbMaxInitVx.Items.AddRange(new object[] { "10", "15", "20", "25", "50", "75", "100", "150", "200", "250", "500", "750", "1000"}); this.cmbMaxInitVx.Location = new System.Drawing.Point(600, 106); this.cmbMaxInitVx.Name = "cmbMaxInitVx"; this.cmbMaxInitVx.Size = new System.Drawing.Size(47, 21); this.cmbMaxInitVx.TabIndex = 5; this.cmbMaxInitVx.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged); // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(520, 139); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(61, 13); this.label9.TabIndex = 2; this.label9.Text = "Max init Vy:"; // // cmbMaxInitVy // this.cmbMaxInitVy.FormattingEnabled = true; this.cmbMaxInitVy.Items.AddRange(new object[] { "10", "15", "20", "25", "50", "75", "100", "150", "200", "250", "500", "750", "1000"}); this.cmbMaxInitVy.Location = new System.Drawing.Point(600, 136); this.cmbMaxInitVy.Name = "cmbMaxInitVy"; this.cmbMaxInitVy.Size = new System.Drawing.Size(47, 21); this.cmbMaxInitVy.TabIndex = 5; this.cmbMaxInitVy.SelectedIndexChanged += new System.EventHandler(this.cmb_SelectedIndexChanged); // // btnReset // this.btnReset.Enabled = false; this.btnReset.Location = new System.Drawing.Point(670, 232); this.btnReset.Name = "btnReset"; this.btnReset.Size = new System.Drawing.Size(57, 24); this.btnReset.TabIndex = 3; this.btnReset.Text = "Reset"; this.btnReset.UseVisualStyleBackColor = true; this.btnReset.Click += new System.EventHandler(this.btnReset_Click); // // btnSave // this.btnSave.Enabled = false; this.btnSave.Location = new System.Drawing.Point(601, 258); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(57, 24); this.btnSave.TabIndex = 3; this.btnSave.Text = "Save"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnLoad // this.btnLoad.Location = new System.Drawing.Point(670, 258); this.btnLoad.Name = "btnLoad"; this.btnLoad.Size = new System.Drawing.Size(57, 24); this.btnLoad.TabIndex = 3; this.btnLoad.Text = "Load"; this.btnLoad.UseVisualStyleBackColor = true; this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click); // // btnLoadMin // this.btnLoadMin.Enabled = false; this.btnLoadMin.Location = new System.Drawing.Point(671, 313); this.btnLoadMin.Name = "btnLoadMin"; this.btnLoadMin.Size = new System.Drawing.Size(57, 24); this.btnLoadMin.TabIndex = 8; this.btnLoadMin.Text = "Load"; this.btnLoadMin.UseVisualStyleBackColor = true; this.btnLoadMin.Click += new System.EventHandler(this.btnLoad_Click); // // lblEntropy // this.lblEntropy.AutoSize = true; this.lblEntropy.Location = new System.Drawing.Point(599, 319); this.lblEntropy.Name = "lblEntropy"; this.lblEntropy.Size = new System.Drawing.Size(16, 13); this.lblEntropy.TabIndex = 6; this.lblEntropy.Text = "---"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(521, 319); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(39, 13); this.label1.TabIndex = 7; this.label1.Text = "S(min):"; // // histogramY // this.histogramY.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.histogramY.Horizontal = false; this.histogramY.Location = new System.Drawing.Point(26, 29); this.histogramY.Name = "histogramY"; this.histogramY.Size = new System.Drawing.Size(75, 400); this.histogramY.TabIndex = 1; // // histogramX // this.histogramX.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.histogramX.Horizontal = true; this.histogramX.Location = new System.Drawing.Point(100, 428); this.histogramX.Name = "histogramX"; this.histogramX.Size = new System.Drawing.Size(400, 75); this.histogramX.TabIndex = 1; // // canvas // this.canvas.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.canvas.Location = new System.Drawing.Point(100, 29); this.canvas.Name = "canvas"; this.canvas.ScaleFactor = 0D; this.canvas.Size = new System.Drawing.Size(400, 400); this.canvas.TabIndex = 0; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(759, 531); this.Controls.Add(this.btnLoadMin); this.Controls.Add(this.lblEntropy); this.Controls.Add(this.label1); this.Controls.Add(this.cmbParticles); this.Controls.Add(this.cmbGrid); this.Controls.Add(this.cmbMaxInitVy); this.Controls.Add(this.cmbMaxInitVx); this.Controls.Add(this.cmbSeed); this.Controls.Add(this.chkDisplayMotion); this.Controls.Add(this.btnLoad); this.Controls.Add(this.btnReset); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnStart); this.Controls.Add(this.label7); this.Controls.Add(this.label9); this.Controls.Add(this.label5); this.Controls.Add(this.label8); this.Controls.Add(this.label6); this.Controls.Add(this.label4); this.Controls.Add(this.lblIterations); this.Controls.Add(this.histogramY); this.Controls.Add(this.histogramX); this.Controls.Add(this.canvas); this.DoubleBuffered = true; this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(775, 570); this.MinimumSize = new System.Drawing.Size(775, 570); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Entropy"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private DrawingCanvas canvas; private Histogram histogramX; private Histogram histogramY; private System.Windows.Forms.Label lblIterations; private System.Windows.Forms.Label label4; private System.Windows.Forms.CheckBox chkDisplayMotion; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.ComboBox cmbSeed; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.ComboBox cmbGrid; private System.Windows.Forms.Label label7; private System.Windows.Forms.ComboBox cmbParticles; private System.Windows.Forms.Label label8; private System.Windows.Forms.ComboBox cmbMaxInitVx; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox cmbMaxInitVy; private System.Windows.Forms.Button btnReset; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnLoad; private System.Windows.Forms.Button btnLoadMin; private System.Windows.Forms.Label lblEntropy; private System.Windows.Forms.Label label1; } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; namespace Microsoft.Azure.Commands.Management.Storage { /// <summary> /// Lists all storage services underneath the subscription. /// </summary> [Cmdlet(VerbsCommon.Set, StorageAccountNounStr, SupportsShouldProcess = true, DefaultParameterSetName = StorageEncryptionParameterSet), OutputType(typeof(PSStorageAccount))] public class SetAzureStorageAccountCommand : StorageAccountBaseCmdlet { /// <summary> /// Storage Encryption parameter set name /// </summary> private const string StorageEncryptionParameterSet = "StorageEncryption"; /// <summary> /// Keyvault Encryption parameter set name /// </summary> private const string KeyvaultEncryptionParameterSet = "KeyvaultEncryption"; [Parameter( Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Resource Group Name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Name.")] [Alias(StorageAccountNameAlias, AccountNameAlias)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(HelpMessage = "Force to Set the Account")] public SwitchParameter Force { get { return force; } set { force = value; } } private bool force = false; [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] [ValidateSet(AccountTypeString.StandardLRS, AccountTypeString.StandardZRS, AccountTypeString.StandardGRS, AccountTypeString.StandardRAGRS, AccountTypeString.PremiumLRS, IgnoreCase = true)] public string SkuName { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Access Tier.")] [ValidateSet(AccountAccessTier.Hot, AccountAccessTier.Cool, IgnoreCase = true)] public string AccessTier { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Custom Domain.")] [ValidateNotNull] public string CustomDomainName { get; set; } [Parameter( Mandatory = false, HelpMessage = "To Use Sub Domain.")] [ValidateNotNullOrEmpty] public bool? UseSubDomain { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will enable encryption.")] public EncryptionSupportServiceEnum? EnableEncryptionService { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will disable encryption.")] public EncryptionSupportServiceEnum? DisableEncryptionService { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Tags.")] [AllowEmptyCollection] [ValidateNotNull] [Alias(TagsAlias)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account EnableHttpsTrafficOnly.")] public bool EnableHttpsTrafficOnly { get { return enableHttpsTrafficOnly.Value; } set { enableHttpsTrafficOnly = value; } } private bool? enableHttpsTrafficOnly = null; [Parameter(HelpMessage = "Whether to set Storage Account Encryption KeySource to Microsoft.Storage or not.", Mandatory = false, ParameterSetName = StorageEncryptionParameterSet)] public SwitchParameter StorageEncryption { get { return storageEncryption; } set { storageEncryption = value; } } private bool storageEncryption = false; [Parameter(HelpMessage = "Whether to set Storage Account encryption keySource to Microsoft.Keyvault or not. " + "If you specify KeyName, KeyVersion and KeyvaultUri, Storage Account Encryption KeySource will also be set to Microsoft.Keyvault weather this parameter is set or not.", Mandatory = false, ParameterSetName = KeyvaultEncryptionParameterSet)] public SwitchParameter KeyvaultEncryption { get { return keyvaultEncryption; } set { keyvaultEncryption = value; } } private bool keyvaultEncryption = false; [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyName", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyName { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVersion", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVersion { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVaultUri", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVaultUri { get; set; } [Parameter( Mandatory = false, HelpMessage = "Generate and assign a new Storage Account Identity for this storage account for use with key management services like Azure KeyVault.")] public SwitchParameter AssignIdentity { get; set; } [Parameter(HelpMessage = "Storage Account NetworkRule", Mandatory = false)] [ValidateNotNullOrEmpty] public PSNetworkRuleSet NetworkRuleSet { get; set; } [Parameter( Mandatory = false, HelpMessage = "Upgrade Storage Account Kind to StorageV2.")] public SwitchParameter UpgradeToStorageV2 { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (ShouldProcess(this.Name, "Set Storage Account")) { if (this.force || this.AccessTier == null || ShouldContinue("Changing the access tier may result in additional charges. See (http://go.microsoft.com/fwlink/?LinkId=786482) to learn more.", "")) { StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters(); if (this.SkuName != null) { updateParameters.Sku = new Sku(ParseSkuName(this.SkuName)); } if (this.Tag != null) { Dictionary<string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag, validate: true); updateParameters.Tags = tagDictionary ?? new Dictionary<string, string>(); } if (this.CustomDomainName != null) { updateParameters.CustomDomain = new CustomDomain() { Name = CustomDomainName, UseSubDomain = UseSubDomain }; } else if (UseSubDomain != null) { throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName.")); } if (this.AccessTier != null) { updateParameters.AccessTier = ParseAccessTier(AccessTier); } if (enableHttpsTrafficOnly != null) { updateParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent) { updateParameters.Identity = new Identity(); } if (this.EnableEncryptionService != null || this.DisableEncryptionService != null || StorageEncryption || (ParameterSetName == KeyvaultEncryptionParameterSet)) { if (ParameterSetName == KeyvaultEncryptionParameterSet) { keyvaultEncryption = true; } updateParameters.Encryption = ParseEncryption(EnableEncryptionService, DisableEncryptionService, StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri); } if (NetworkRuleSet != null) { updateParameters.NetworkRuleSet = PSNetworkRuleSet.ParseStorageNetworkRule(NetworkRuleSet); } if (UpgradeToStorageV2.IsPresent) { updateParameters.Kind = Kind.StorageV2; } var updatedAccountResponse = this.StorageClient.StorageAccounts.Update( this.ResourceGroupName, this.Name, updateParameters); var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); WriteStorageAccount(storageAccount); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.FSharp.Collections; using Microsoft.FSharp.Core; using Microsoft.FSharp.Reflection; using Orleans.Serialization.Buffers; using Orleans.Serialization.Cloning; using Orleans.Serialization.Codecs; using Orleans.Serialization.GeneratedCodeHelpers; using Orleans.Serialization.Serializers; using Orleans.Serialization.WireProtocol; namespace Orleans.Serialization { [RegisterSerializer] public sealed class FSharpOptionCodec<T> : GeneralizedReferenceTypeSurrogateCodec<FSharpOption<T>, FSharpOptionSurrogate<T>>, IDerivedTypeCodec { public FSharpOptionCodec(IValueSerializer<FSharpOptionSurrogate<T>> surrogateSerializer) : base(surrogateSerializer) { } public override FSharpOption<T> ConvertFromSurrogate(ref FSharpOptionSurrogate<T> surrogate) { if (surrogate.IsNone) { return FSharpOption<T>.None; } else { return FSharpOption<T>.Some(surrogate.Value); } } public override void ConvertToSurrogate(FSharpOption<T> value, ref FSharpOptionSurrogate<T> surrogate) { if (value is null || FSharpOption<T>.get_IsNone(value)) { surrogate.IsNone = true; } else { surrogate.Value = value.Value; } } } [GenerateSerializer] public struct FSharpOptionSurrogate<T> { [Id(0)] public bool IsNone { get; set; } [Id(1)] public T Value { get; set; } } [RegisterCopier] public sealed class FSharpOptionCopier<T> : IDeepCopier<FSharpOption<T>>, IDerivedTypeCopier { private IDeepCopier<T> _valueCopier; public FSharpOptionCopier(IDeepCopier<T> valueCopier) { _valueCopier = OrleansGeneratedCodeHelper.UnwrapService(this, valueCopier); } public FSharpOption<T> DeepCopy(FSharpOption<T> input, CopyContext context) { if (context.TryGetCopy<FSharpOption<T>>(input, out var result)) { return result; } if (FSharpOption<T>.get_IsNone(input)) { result = input; } else { result = FSharpOption<T>.Some(_valueCopier.DeepCopy(input.Value, context)); } context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpValueOptionCodec<T> : IFieldCodec<FSharpValueOption<T>> { private readonly IFieldCodec<T> _valueCodec; public FSharpValueOptionCodec(IFieldCodec<T> item1Codec) { _valueCodec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); } void IFieldCodec<FSharpValueOption<T>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpValueOption<T> value) { ReferenceCodec.MarkValueField(writer.Session); writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpValueOption<T>), WireType.TagDelimited); BoolCodec.WriteField(ref writer, 0, typeof(bool), value.IsSome); if (value.IsSome) { _valueCodec.WriteField(ref writer, 1, typeof(T), value.Value); } writer.WriteEndObject(); } FSharpValueOption<T> IFieldCodec<FSharpValueOption<T>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } ReferenceCodec.MarkValueField(reader.Session); var isSome = false; T result = default; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: isSome = BoolCodec.ReadValue(ref reader, header); break; case 1: result = _valueCodec.ReadValue(ref reader, header); break; default: reader.ConsumeUnknownField(header); break; } } if (isSome) { return FSharpValueOption<T>.Some(result); } return FSharpValueOption<T>.None; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public sealed class FSharpValueOptionCopier<T> : IDeepCopier<FSharpValueOption<T>> { private IDeepCopier<T> _valueCopier; public FSharpValueOptionCopier(IDeepCopier<T> valueCopier) { _valueCopier = OrleansGeneratedCodeHelper.UnwrapService(this, valueCopier); } public FSharpValueOption<T> DeepCopy(FSharpValueOption<T> input, CopyContext context) { if (input.IsNone) { return input; } else { return FSharpValueOption<T>.Some(_valueCopier.DeepCopy(input.Value, context)); } } } [RegisterSerializer] public class FSharpChoiceCodec<T1, T2> : IFieldCodec<FSharpChoice<T1, T2>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T1); private static readonly Type ElementType2 = typeof(T2); private readonly IFieldCodec<T1> _item1Codec; private readonly IFieldCodec<T2> _item2Codec; public FSharpChoiceCodec(IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); } void IFieldCodec<FSharpChoice<T1, T2>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpChoice<T1, T2> value) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpChoice<T1, T2>), WireType.TagDelimited); switch (value) { case FSharpChoice<T1, T2>.Choice1Of2 c1: Int32Codec.WriteField(ref writer, 0, typeof(int), 1); _item1Codec.WriteField(ref writer, 1, ElementType1, c1.Item); break; case FSharpChoice<T1, T2>.Choice2Of2 c2: Int32Codec.WriteField(ref writer, 0, typeof(int), 2); _item2Codec.WriteField(ref writer, 1, ElementType2, c2.Item); break; } writer.WriteEndObject(); } FSharpChoice<T1, T2> IFieldCodec<FSharpChoice<T1, T2>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<FSharpChoice<T1, T2>, TInput>(ref reader, field); } if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); FSharpChoice<T1, T2> result = default; var tag = 0; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: tag = Int32Codec.ReadValue(ref reader, header); break; case 1: result = tag switch { 1 => FSharpChoice<T1, T2>.NewChoice1Of2(_item1Codec.ReadValue(ref reader, header)), 2 => FSharpChoice<T1, T2>.NewChoice2Of2(_item2Codec.ReadValue(ref reader, header)), _ => throw new NotSupportedException($"Unexpected choice {tag}") }; break; default: reader.ConsumeUnknownField(header); break; } } ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpChoiceCopier<T1, T2> : IDeepCopier<FSharpChoice<T1, T2>>, IDerivedTypeCopier { private readonly IDeepCopier<T1> _copier1; private readonly IDeepCopier<T2> _copier2; public FSharpChoiceCopier(IDeepCopier<T1> copier1, IDeepCopier<T2> copier2) { _copier1 = copier1; _copier2 = copier2; } public FSharpChoice<T1, T2> DeepCopy(FSharpChoice<T1, T2> input, CopyContext context) { if (context.TryGetCopy(input, out FSharpChoice<T1, T2> result)) { return result; } result = input switch { FSharpChoice<T1, T2>.Choice1Of2 c1 => FSharpChoice<T1, T2>.NewChoice1Of2(_copier1.DeepCopy(c1.Item, context)), FSharpChoice<T1, T2>.Choice2Of2 c2 => FSharpChoice<T1, T2>.NewChoice2Of2(_copier2.DeepCopy(c2.Item, context)), _ => throw new NotSupportedException($"Type {input.GetType()} is not supported"), }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpChoiceCodec<T1, T2, T3> : IFieldCodec<FSharpChoice<T1, T2, T3>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T1); private static readonly Type ElementType2 = typeof(T2); private static readonly Type ElementType3 = typeof(T3); private readonly IFieldCodec<T1> _item1Codec; private readonly IFieldCodec<T2> _item2Codec; private readonly IFieldCodec<T3> _item3Codec; public FSharpChoiceCodec( IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec, IFieldCodec<T3> item3Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec); } void IFieldCodec<FSharpChoice<T1, T2, T3>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpChoice<T1, T2, T3> value) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpChoice<T1, T2, T3>), WireType.TagDelimited); switch (value) { case FSharpChoice<T1, T2, T3>.Choice1Of3 c1: Int32Codec.WriteField(ref writer, 0, typeof(int), 1); _item1Codec.WriteField(ref writer, 1, ElementType1, c1.Item); break; case FSharpChoice<T1, T2, T3>.Choice2Of3 c2: Int32Codec.WriteField(ref writer, 0, typeof(int), 2); _item2Codec.WriteField(ref writer, 1, ElementType2, c2.Item); break; case FSharpChoice<T1, T2, T3>.Choice3Of3 c3: Int32Codec.WriteField(ref writer, 0, typeof(int), 3); _item3Codec.WriteField(ref writer, 1, ElementType3, c3.Item); break; } writer.WriteEndObject(); } FSharpChoice<T1, T2, T3> IFieldCodec<FSharpChoice<T1, T2, T3>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<FSharpChoice<T1, T2, T3>, TInput>(ref reader, field); } if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); FSharpChoice<T1, T2, T3> result = default; var tag = 0; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: tag = Int32Codec.ReadValue(ref reader, header); break; case 1: result = tag switch { 1 => FSharpChoice<T1, T2, T3>.NewChoice1Of3(_item1Codec.ReadValue(ref reader, header)), 2 => FSharpChoice<T1, T2, T3>.NewChoice2Of3(_item2Codec.ReadValue(ref reader, header)), 3 => FSharpChoice<T1, T2, T3>.NewChoice3Of3(_item3Codec.ReadValue(ref reader, header)), _ => throw new NotSupportedException($"Unexpected choice {tag}") }; break; default: reader.ConsumeUnknownField(header); break; } } ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpChoiceCopier<T1, T2, T3> : IDeepCopier<FSharpChoice<T1, T2, T3>>, IDerivedTypeCopier { private readonly IDeepCopier<T1> _copier1; private readonly IDeepCopier<T2> _copier2; private readonly IDeepCopier<T3> _copier3; public FSharpChoiceCopier( IDeepCopier<T1> copier1, IDeepCopier<T2> copier2, IDeepCopier<T3> copier3) { _copier1 = copier1; _copier2 = copier2; _copier3 = copier3; } public FSharpChoice<T1, T2, T3> DeepCopy(FSharpChoice<T1, T2, T3> input, CopyContext context) { if (context.TryGetCopy(input, out FSharpChoice<T1, T2, T3> result)) { return result; } result = input switch { FSharpChoice<T1, T2, T3>.Choice1Of3 c1 => FSharpChoice<T1, T2, T3>.NewChoice1Of3(_copier1.DeepCopy(c1.Item, context)), FSharpChoice<T1, T2, T3>.Choice2Of3 c2 => FSharpChoice<T1, T2, T3>.NewChoice2Of3(_copier2.DeepCopy(c2.Item, context)), FSharpChoice<T1, T2, T3>.Choice3Of3 c3 => FSharpChoice<T1, T2, T3>.NewChoice3Of3(_copier3.DeepCopy(c3.Item, context)), _ => throw new NotSupportedException($"Type {input.GetType()} is not supported"), }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpChoiceCodec<T1, T2, T3, T4> : IFieldCodec<FSharpChoice<T1, T2, T3, T4>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T1); private static readonly Type ElementType2 = typeof(T2); private static readonly Type ElementType3 = typeof(T3); private static readonly Type ElementType4 = typeof(T4); private readonly IFieldCodec<T1> _item1Codec; private readonly IFieldCodec<T2> _item2Codec; private readonly IFieldCodec<T3> _item3Codec; private readonly IFieldCodec<T4> _item4Codec; public FSharpChoiceCodec( IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec, IFieldCodec<T3> item3Codec, IFieldCodec<T4> item4Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec); _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec); } void IFieldCodec<FSharpChoice<T1, T2, T3, T4>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpChoice<T1, T2, T3, T4> value) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpChoice<T1, T2, T3, T4>), WireType.TagDelimited); switch (value) { case FSharpChoice<T1, T2, T3, T4>.Choice1Of4 c1: Int32Codec.WriteField(ref writer, 0, typeof(int), 1); _item1Codec.WriteField(ref writer, 1, ElementType1, c1.Item); break; case FSharpChoice<T1, T2, T3, T4>.Choice2Of4 c2: Int32Codec.WriteField(ref writer, 0, typeof(int), 2); _item2Codec.WriteField(ref writer, 1, ElementType2, c2.Item); break; case FSharpChoice<T1, T2, T3, T4>.Choice3Of4 c3: Int32Codec.WriteField(ref writer, 0, typeof(int), 3); _item3Codec.WriteField(ref writer, 1, ElementType3, c3.Item); break; case FSharpChoice<T1, T2, T3, T4>.Choice4Of4 c4: Int32Codec.WriteField(ref writer, 0, typeof(int), 4); _item4Codec.WriteField(ref writer, 1, ElementType4, c4.Item); break; } writer.WriteEndObject(); } FSharpChoice<T1, T2, T3, T4> IFieldCodec<FSharpChoice<T1, T2, T3, T4>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<FSharpChoice<T1, T2, T3, T4>, TInput>(ref reader, field); } if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); FSharpChoice<T1, T2, T3, T4> result = default; var tag = 0; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: tag = Int32Codec.ReadValue(ref reader, header); break; case 1: result = tag switch { 1 => FSharpChoice<T1, T2, T3, T4>.NewChoice1Of4(_item1Codec.ReadValue(ref reader, header)), 2 => FSharpChoice<T1, T2, T3, T4>.NewChoice2Of4(_item2Codec.ReadValue(ref reader, header)), 3 => FSharpChoice<T1, T2, T3, T4>.NewChoice3Of4(_item3Codec.ReadValue(ref reader, header)), 4 => FSharpChoice<T1, T2, T3, T4>.NewChoice4Of4(_item4Codec.ReadValue(ref reader, header)), _ => throw new NotSupportedException($"Unexpected choice {tag}") }; break; default: reader.ConsumeUnknownField(header); break; } } ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpChoiceCopier<T1, T2, T3, T4> : IDeepCopier<FSharpChoice<T1, T2, T3, T4>>, IDerivedTypeCopier { private readonly IDeepCopier<T1> _copier1; private readonly IDeepCopier<T2> _copier2; private readonly IDeepCopier<T3> _copier3; private readonly IDeepCopier<T4> _copier4; public FSharpChoiceCopier( IDeepCopier<T1> copier1, IDeepCopier<T2> copier2, IDeepCopier<T3> copier3, IDeepCopier<T4> copier4) { _copier1 = copier1; _copier2 = copier2; _copier3 = copier3; _copier4 = copier4; } public FSharpChoice<T1, T2, T3, T4> DeepCopy(FSharpChoice<T1, T2, T3, T4> input, CopyContext context) { if (context.TryGetCopy(input, out FSharpChoice<T1, T2, T3, T4> result)) { return result; } result = input switch { FSharpChoice<T1, T2, T3, T4>.Choice1Of4 c1 => FSharpChoice<T1, T2, T3, T4>.NewChoice1Of4(_copier1.DeepCopy(c1.Item, context)), FSharpChoice<T1, T2, T3, T4>.Choice2Of4 c2 => FSharpChoice<T1, T2, T3, T4>.NewChoice2Of4(_copier2.DeepCopy(c2.Item, context)), FSharpChoice<T1, T2, T3, T4>.Choice3Of4 c3 => FSharpChoice<T1, T2, T3, T4>.NewChoice3Of4(_copier3.DeepCopy(c3.Item, context)), FSharpChoice<T1, T2, T3, T4>.Choice4Of4 c4 => FSharpChoice<T1, T2, T3, T4>.NewChoice4Of4(_copier4.DeepCopy(c4.Item, context)), _ => throw new NotSupportedException($"Type {input.GetType()} is not supported"), }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpChoiceCodec<T1, T2, T3, T4, T5> : IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T1); private static readonly Type ElementType2 = typeof(T2); private static readonly Type ElementType3 = typeof(T3); private static readonly Type ElementType4 = typeof(T4); private static readonly Type ElementType5 = typeof(T5); private readonly IFieldCodec<T1> _item1Codec; private readonly IFieldCodec<T2> _item2Codec; private readonly IFieldCodec<T3> _item3Codec; private readonly IFieldCodec<T4> _item4Codec; private readonly IFieldCodec<T5> _item5Codec; public FSharpChoiceCodec( IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec, IFieldCodec<T3> item3Codec, IFieldCodec<T4> item4Codec, IFieldCodec<T5> item5Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec); _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec); _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec); } void IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpChoice<T1, T2, T3, T4, T5> value) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpChoice<T1, T2, T3, T4, T5>), WireType.TagDelimited); switch (value) { case FSharpChoice<T1, T2, T3, T4, T5>.Choice1Of5 c1: Int32Codec.WriteField(ref writer, 0, typeof(int), 1); _item1Codec.WriteField(ref writer, 1, ElementType1, c1.Item); break; case FSharpChoice<T1, T2, T3, T4, T5>.Choice2Of5 c2: Int32Codec.WriteField(ref writer, 0, typeof(int), 2); _item2Codec.WriteField(ref writer, 1, ElementType2, c2.Item); break; case FSharpChoice<T1, T2, T3, T4, T5>.Choice3Of5 c3: Int32Codec.WriteField(ref writer, 0, typeof(int), 3); _item3Codec.WriteField(ref writer, 1, ElementType3, c3.Item); break; case FSharpChoice<T1, T2, T3, T4, T5>.Choice4Of5 c4: Int32Codec.WriteField(ref writer, 0, typeof(int), 4); _item4Codec.WriteField(ref writer, 1, ElementType4, c4.Item); break; case FSharpChoice<T1, T2, T3, T4, T5>.Choice5Of5 c5: Int32Codec.WriteField(ref writer, 0, typeof(int), 5); _item5Codec.WriteField(ref writer, 1, ElementType5, c5.Item); break; } writer.WriteEndObject(); } FSharpChoice<T1, T2, T3, T4, T5> IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<FSharpChoice<T1, T2, T3, T4, T5>, TInput>(ref reader, field); } if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); FSharpChoice<T1, T2, T3, T4, T5> result = default; var tag = 0; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: tag = Int32Codec.ReadValue(ref reader, header); break; case 1: result = tag switch { 1 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice1Of5(_item1Codec.ReadValue(ref reader, header)), 2 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice2Of5(_item2Codec.ReadValue(ref reader, header)), 3 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice3Of5(_item3Codec.ReadValue(ref reader, header)), 4 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice4Of5(_item4Codec.ReadValue(ref reader, header)), 5 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice5Of5(_item5Codec.ReadValue(ref reader, header)), _ => throw new NotSupportedException($"Unexpected choice {tag}") }; break; default: reader.ConsumeUnknownField(header); break; } } ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpChoiceCopier<T1, T2, T3, T4, T5> : IDeepCopier<FSharpChoice<T1, T2, T3, T4, T5>>, IDerivedTypeCopier { private readonly IDeepCopier<T1> _copier1; private readonly IDeepCopier<T2> _copier2; private readonly IDeepCopier<T3> _copier3; private readonly IDeepCopier<T4> _copier4; private readonly IDeepCopier<T5> _copier5; public FSharpChoiceCopier( IDeepCopier<T1> copier1, IDeepCopier<T2> copier2, IDeepCopier<T3> copier3, IDeepCopier<T4> copier4, IDeepCopier<T5> copier5) { _copier1 = copier1; _copier2 = copier2; _copier3 = copier3; _copier4 = copier4; _copier5 = copier5; } public FSharpChoice<T1, T2, T3, T4, T5> DeepCopy(FSharpChoice<T1, T2, T3, T4, T5> input, CopyContext context) { if (context.TryGetCopy(input, out FSharpChoice<T1, T2, T3, T4, T5> result)) { return result; } result = input switch { FSharpChoice<T1, T2, T3, T4, T5>.Choice1Of5 c1 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice1Of5(_copier1.DeepCopy(c1.Item, context)), FSharpChoice<T1, T2, T3, T4, T5>.Choice2Of5 c2 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice2Of5(_copier2.DeepCopy(c2.Item, context)), FSharpChoice<T1, T2, T3, T4, T5>.Choice3Of5 c3 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice3Of5(_copier3.DeepCopy(c3.Item, context)), FSharpChoice<T1, T2, T3, T4, T5>.Choice4Of5 c4 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice4Of5(_copier4.DeepCopy(c4.Item, context)), FSharpChoice<T1, T2, T3, T4, T5>.Choice5Of5 c5 => FSharpChoice<T1, T2, T3, T4, T5>.NewChoice5Of5(_copier5.DeepCopy(c5.Item, context)), _ => throw new NotSupportedException($"Type {input.GetType()} is not supported"), }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpChoiceCodec<T1, T2, T3, T4, T5, T6> : IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5, T6>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T1); private static readonly Type ElementType2 = typeof(T2); private static readonly Type ElementType3 = typeof(T3); private static readonly Type ElementType4 = typeof(T4); private static readonly Type ElementType5 = typeof(T5); private static readonly Type ElementType6 = typeof(T6); private readonly IFieldCodec<T1> _item1Codec; private readonly IFieldCodec<T2> _item2Codec; private readonly IFieldCodec<T3> _item3Codec; private readonly IFieldCodec<T4> _item4Codec; private readonly IFieldCodec<T5> _item5Codec; private readonly IFieldCodec<T6> _item6Codec; public FSharpChoiceCodec( IFieldCodec<T1> item1Codec, IFieldCodec<T2> item2Codec, IFieldCodec<T3> item3Codec, IFieldCodec<T4> item4Codec, IFieldCodec<T5> item5Codec, IFieldCodec<T6> item6Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); _item3Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item3Codec); _item4Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item4Codec); _item5Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item5Codec); _item6Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item6Codec); } void IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5, T6>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpChoice<T1, T2, T3, T4, T5, T6> value) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value)) { return; } writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpChoice<T1, T2, T3, T4, T5, T6>), WireType.TagDelimited); switch (value) { case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice1Of6 c1: Int32Codec.WriteField(ref writer, 0, typeof(int), 1); _item1Codec.WriteField(ref writer, 1, ElementType1, c1.Item); break; case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice2Of6 c2: Int32Codec.WriteField(ref writer, 0, typeof(int), 2); _item2Codec.WriteField(ref writer, 1, ElementType2, c2.Item); break; case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice3Of6 c3: Int32Codec.WriteField(ref writer, 0, typeof(int), 3); _item3Codec.WriteField(ref writer, 1, ElementType3, c3.Item); break; case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice4Of6 c4: Int32Codec.WriteField(ref writer, 0, typeof(int), 4); _item4Codec.WriteField(ref writer, 1, ElementType4, c4.Item); break; case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice5Of6 c5: Int32Codec.WriteField(ref writer, 0, typeof(int), 5); _item5Codec.WriteField(ref writer, 1, ElementType5, c5.Item); break; case FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice6Of6 c6: Int32Codec.WriteField(ref writer, 0, typeof(int), 6); _item6Codec.WriteField(ref writer, 1, ElementType6, c6.Item); break; } writer.WriteEndObject(); } FSharpChoice<T1, T2, T3, T4, T5, T6> IFieldCodec<FSharpChoice<T1, T2, T3, T4, T5, T6>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType == WireType.Reference) { return ReferenceCodec.ReadReference<FSharpChoice<T1, T2, T3, T4, T5, T6>, TInput>(ref reader, field); } if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session); FSharpChoice<T1, T2, T3, T4, T5, T6> result = default; var tag = 0; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: tag = Int32Codec.ReadValue(ref reader, header); break; case 1: result = tag switch { 1 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice1Of6(_item1Codec.ReadValue(ref reader, header)), 2 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice2Of6(_item2Codec.ReadValue(ref reader, header)), 3 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice3Of6(_item3Codec.ReadValue(ref reader, header)), 4 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice4Of6(_item4Codec.ReadValue(ref reader, header)), 5 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice5Of6(_item5Codec.ReadValue(ref reader, header)), 6 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice6Of6(_item6Codec.ReadValue(ref reader, header)), _ => throw new NotSupportedException($"Unexpected choice {tag}") }; break; default: reader.ConsumeUnknownField(header); break; } } ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId); return result; } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpChoiceCopier<T1, T2, T3, T4, T5, T6> : IDeepCopier<FSharpChoice<T1, T2, T3, T4, T5, T6>>, IDerivedTypeCopier { private readonly IDeepCopier<T1> _copier1; private readonly IDeepCopier<T2> _copier2; private readonly IDeepCopier<T3> _copier3; private readonly IDeepCopier<T4> _copier4; private readonly IDeepCopier<T5> _copier5; private readonly IDeepCopier<T6> _copier6; public FSharpChoiceCopier( IDeepCopier<T1> copier1, IDeepCopier<T2> copier2, IDeepCopier<T3> copier3, IDeepCopier<T4> copier4, IDeepCopier<T5> copier5, IDeepCopier<T6> copier6) { _copier1 = copier1; _copier2 = copier2; _copier3 = copier3; _copier4 = copier4; _copier5 = copier5; _copier6 = copier6; } public FSharpChoice<T1, T2, T3, T4, T5, T6> DeepCopy(FSharpChoice<T1, T2, T3, T4, T5, T6> input, CopyContext context) { if (context.TryGetCopy(input, out FSharpChoice<T1, T2, T3, T4, T5, T6> result)) { return result; } result = input switch { FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice1Of6 c1 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice1Of6(_copier1.DeepCopy(c1.Item, context)), FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice2Of6 c2 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice2Of6(_copier2.DeepCopy(c2.Item, context)), FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice3Of6 c3 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice3Of6(_copier3.DeepCopy(c3.Item, context)), FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice4Of6 c4 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice4Of6(_copier4.DeepCopy(c4.Item, context)), FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice5Of6 c5 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice5Of6(_copier5.DeepCopy(c5.Item, context)), FSharpChoice<T1, T2, T3, T4, T5, T6>.Choice6Of6 c6 => FSharpChoice<T1, T2, T3, T4, T5, T6>.NewChoice6Of6(_copier6.DeepCopy(c6.Item, context)), _ => throw new NotSupportedException($"Type {input.GetType()} is not supported"), }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpRefCodec<T> : GeneralizedReferenceTypeSurrogateCodec<FSharpRef<T>, FSharpRefSurrogate<T>> { public FSharpRefCodec(IValueSerializer<FSharpRefSurrogate<T>> surrogateSerializer) : base(surrogateSerializer) { } public override FSharpRef<T> ConvertFromSurrogate(ref FSharpRefSurrogate<T> surrogate) { return new FSharpRef<T>(surrogate.Value); } public override void ConvertToSurrogate(FSharpRef<T> value, ref FSharpRefSurrogate<T> surrogate) { surrogate.Value = value.Value; } } [GenerateSerializer] public struct FSharpRefSurrogate<T> { [Id(0)] public T Value { get; set; } } [RegisterCopier] public class FSharpRefCopier<T> : IDeepCopier<FSharpRef<T>> { private readonly IDeepCopier<T> _copier; public FSharpRefCopier(IDeepCopier<T> copier) => _copier = copier; public FSharpRef<T> DeepCopy(FSharpRef<T> input, CopyContext context) { if (context.TryGetCopy<FSharpRef<T>>(input, out var result)) { return result; } result = input switch { not null => new FSharpRef<T>(_copier.DeepCopy(input.Value, context)), null => null }; context.RecordCopy(input, result); return result; } } [RegisterSerializer] public class FSharpListCodec<T> : GeneralizedReferenceTypeSurrogateCodec<FSharpList<T>, FSharpListSurrogate<T>> { public FSharpListCodec(IValueSerializer<FSharpListSurrogate<T>> surrogateSerializer) : base(surrogateSerializer) { } public override FSharpList<T> ConvertFromSurrogate(ref FSharpListSurrogate<T> surrogate) { if (surrogate.Value is null) return null; return ListModule.OfSeq(surrogate.Value); } public override void ConvertToSurrogate(FSharpList<T> value, ref FSharpListSurrogate<T> surrogate) { if (value is null) return; surrogate.Value = new(ListModule.ToSeq(value)); } } [GenerateSerializer] public struct FSharpListSurrogate<T> { [Id(0)] public List<T> Value { get; set; } } [RegisterCopier] public class FSharpListCopier<T> : IDeepCopier<FSharpList<T>> { private readonly IDeepCopier<T> _copier; public FSharpListCopier(IDeepCopier<T> copier) => _copier = copier; public FSharpList<T> DeepCopy(FSharpList<T> input, CopyContext context) { if (context.TryGetCopy<FSharpList<T>>(input, out var result)) { return result; } result = ListModule.OfSeq(CopyElements(input, context)); context.RecordCopy(input, result); return result; IEnumerable<T> CopyElements(FSharpList<T> list, CopyContext context) { foreach (var element in list) { yield return _copier.DeepCopy(element, context); } } } } [RegisterSerializer] public class FSharpSetCodec<T> : GeneralizedReferenceTypeSurrogateCodec<FSharpSet<T>, FSharpSetSurrogate<T>> { public FSharpSetCodec(IValueSerializer<FSharpSetSurrogate<T>> surrogateSerializer) : base(surrogateSerializer) { } public override FSharpSet<T> ConvertFromSurrogate(ref FSharpSetSurrogate<T> surrogate) { if (surrogate.Value is null) return null; return new FSharpSet<T>(surrogate.Value); } public override void ConvertToSurrogate(FSharpSet<T> value, ref FSharpSetSurrogate<T> surrogate) { if (value is null) return; surrogate.Value = value.ToList(); } } [GenerateSerializer] public struct FSharpSetSurrogate<T> { [Id(0)] public List<T> Value { get; set; } } [RegisterCopier] public class FSharpSetCopier<T> : IDeepCopier<FSharpSet<T>> { private readonly IDeepCopier<T> _copier; public FSharpSetCopier(IDeepCopier<T> copier) => _copier = copier; public FSharpSet<T> DeepCopy(FSharpSet<T> input, CopyContext context) { if (context.TryGetCopy<FSharpSet<T>>(input, out var result)) { return result; } result = SetModule.OfSeq(CopyElements(input, context)); context.RecordCopy(input, result); return result; IEnumerable<T> CopyElements(FSharpSet<T> vals, CopyContext context) { foreach (var element in vals) { yield return _copier.DeepCopy(element, context); } } } } [RegisterSerializer] public class FSharpMapCodec<TKey, TValue> : GeneralizedReferenceTypeSurrogateCodec<FSharpMap<TKey, TValue>, FSharpMapSurrogate<TKey, TValue>> { public FSharpMapCodec(IValueSerializer<FSharpMapSurrogate<TKey, TValue>> surrogateSerializer) : base(surrogateSerializer) { } public override FSharpMap<TKey, TValue> ConvertFromSurrogate(ref FSharpMapSurrogate<TKey, TValue> surrogate) { if (surrogate.Value is null) return null; return new FSharpMap<TKey, TValue>(surrogate.Value); } public override void ConvertToSurrogate(FSharpMap<TKey, TValue> value, ref FSharpMapSurrogate<TKey, TValue> surrogate) { if (value is null) return; surrogate.Value = new(value.Count); surrogate.Value.AddRange(MapModule.ToSeq(value)); } } [GenerateSerializer] public struct FSharpMapSurrogate<TKey, TValue> { [Id(0)] public List<Tuple<TKey, TValue>> Value { get; set; } } [RegisterCopier] public class FSharpMapCopier<TKey, TValue> : IDeepCopier<FSharpMap<TKey, TValue>> { private readonly IDeepCopier<TKey> _keyCopier; private readonly IDeepCopier<TValue> _valueCopier; public FSharpMapCopier(IDeepCopier<TKey> keyCopier, IDeepCopier<TValue> valueCopier) { _keyCopier = keyCopier; _valueCopier = valueCopier; } public FSharpMap<TKey, TValue> DeepCopy(FSharpMap<TKey, TValue> input, CopyContext context) { if (context.TryGetCopy<FSharpMap<TKey, TValue>>(input, out var result)) { return result; } result = MapModule.OfSeq(CopyElements(input, context)); context.RecordCopy(input, result); return result; IEnumerable<Tuple<TKey, TValue>> CopyElements(FSharpMap<TKey, TValue> vals, CopyContext context) { foreach (var element in vals) { yield return Tuple.Create(_keyCopier.DeepCopy(element.Key, context), _valueCopier.DeepCopy(element.Value, context)); } } } } [RegisterSerializer] public class FSharpResultCodec<T, TError> : IFieldCodec<FSharpResult<T, TError>>, IDerivedTypeCodec { private static readonly Type ElementType1 = typeof(T); private static readonly Type ElementType2 = typeof(TError); private readonly IFieldCodec<T> _item1Codec; private readonly IFieldCodec<TError> _item2Codec; public FSharpResultCodec(IFieldCodec<T> item1Codec, IFieldCodec<TError> item2Codec) { _item1Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item1Codec); _item2Codec = OrleansGeneratedCodeHelper.UnwrapService(this, item2Codec); } void IFieldCodec<FSharpResult<T, TError>>.WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, FSharpResult<T, TError> value) { writer.WriteFieldHeader(fieldIdDelta, expectedType, typeof(FSharpResult<T, TError>), WireType.TagDelimited); if (value.IsError) { BoolCodec.WriteField(ref writer, 0, typeof(bool), true); _item2Codec.WriteField(ref writer, 1, typeof(TError), value.ErrorValue); } else { BoolCodec.WriteField(ref writer, 0, typeof(bool), true); _item1Codec.WriteField(ref writer, 1, typeof(T), value.ResultValue); } writer.WriteEndObject(); } FSharpResult<T, TError> IFieldCodec<FSharpResult<T, TError>>.ReadValue<TInput>(ref Reader<TInput> reader, Field field) { if (field.WireType != WireType.TagDelimited) { ThrowUnsupportedWireTypeException(); } ReferenceCodec.MarkValueField(reader.Session); var isError = false; uint fieldId = 0; while (true) { var header = reader.ReadFieldHeader(); if (header.IsEndBaseOrEndObject) { break; } fieldId += header.FieldIdDelta; switch (fieldId) { case 0: isError = BoolCodec.ReadValue(ref reader, header); break; case 1: if (isError) { return FSharpResult<T, TError>.NewError(_item2Codec.ReadValue(ref reader, header)); } else { return FSharpResult<T, TError>.NewOk(_item1Codec.ReadValue(ref reader, header)); } default: reader.ConsumeUnknownField(header); break; } } throw new NotSupportedException("Cannot deserialize instance without value field"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowUnsupportedWireTypeException() => throw new UnsupportedWireTypeException( $"Only a {nameof(WireType)} value of {WireType.TagDelimited} is supported"); } [RegisterCopier] public class FSharpResultCopier<T, TError> : IDeepCopier<FSharpResult<T, TError>>, IDerivedTypeCopier { private readonly IDeepCopier<T> _copier1; private readonly IDeepCopier<TError> _copier2; public FSharpResultCopier(IDeepCopier<T> copier1, IDeepCopier<TError> copier2) { _copier1 = copier1; _copier2 = copier2; } public FSharpResult<T, TError> DeepCopy(FSharpResult<T, TError> input, CopyContext context) { if (input.IsError) { return FSharpResult<T, TError>.NewError(_copier2.DeepCopy(input.ErrorValue, context)); } else { return FSharpResult<T, TError>.NewOk(_copier1.DeepCopy(input.ResultValue, context)); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using ASP.NETWebAPI.Areas.HelpPage.ModelDescriptions; using ASP.NETWebAPI.Areas.HelpPage.Models; namespace ASP.NETWebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//------------------------------------------------------------------------------ // <copyright file="IisTraceListener.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Text; using System.Web; using System.Web.Hosting; using System.Web.UI; using System.Diagnostics; using System.Globalization; using System.Security.Permissions; namespace System.Web { [HostProtection(Synchronization=true)] public sealed class IisTraceListener : TraceListener { public IisTraceListener() { // only supported on IIS version 7 and later HttpContext context = HttpContext.Current; if (context != null) { if (!HttpRuntime.UseIntegratedPipeline && !(context.WorkerRequest is ISAPIWorkerRequestInProcForIIS7)) { throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_7)); } } } // the listener apis public override void Write(string message) { if (Filter != null && !Filter.ShouldTrace(null, String.Empty, TraceEventType.Verbose, 0, message, null, null, null)) return; HttpContext context = HttpContext.Current; if (context != null) { context.WorkerRequest.RaiseTraceEvent(IntegratedTraceType.TraceWrite, message); } } public override void Write(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, String.Empty, TraceEventType.Verbose, 0, message, null, null, null)) return; HttpContext context = HttpContext.Current; if (context != null) { context.WorkerRequest.RaiseTraceEvent(IntegratedTraceType.TraceWrite, message); } } public override void WriteLine(string message) { if (Filter != null && !Filter.ShouldTrace(null, String.Empty, TraceEventType.Verbose, 0, message, null, null, null)) return; HttpContext context = HttpContext.Current; if (context != null) { context.WorkerRequest.RaiseTraceEvent(IntegratedTraceType.TraceWrite, message); } } public override void WriteLine(string message, string category) { if (Filter != null && !Filter.ShouldTrace(null, String.Empty, TraceEventType.Verbose, 0, message, null, null, null)) return; HttpContext context = HttpContext.Current; if (context != null) { context.WorkerRequest.RaiseTraceEvent(IntegratedTraceType.TraceWrite, message); } } public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; HttpContext context = HttpContext.Current; if (context != null) { string datastring = String.Empty; if (data != null) { datastring = data.ToString(); } context.WorkerRequest.RaiseTraceEvent(Convert(eventType), AppendTraceOptions(eventCache, datastring)); } } public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { HttpContext context = HttpContext.Current; if (context == null) return; if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; StringBuilder sb = new StringBuilder(); if (data != null) { for (int i=0; i< data.Length; i++) { if (i != 0) sb.Append(", "); if (data[i] != null) sb.Append(data[i].ToString()); } } if (context != null) { context.WorkerRequest.RaiseTraceEvent(Convert(eventType), AppendTraceOptions(eventCache, sb.ToString())); } } public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType severity, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, severity, id, message, null, null, null)) return; HttpContext context = HttpContext.Current; if (context == null) return; context.WorkerRequest.RaiseTraceEvent(Convert(severity), AppendTraceOptions(eventCache, message)); } public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType severity, int id, string format, params object[] args) { TraceEvent(eventCache, source, severity, id, String.Format(CultureInfo.InvariantCulture, format, args)); } // append trace options to message and return the result private String AppendTraceOptions(TraceEventCache eventCache, String message) { if (eventCache == null || TraceOutputOptions == TraceOptions.None) { return message; } StringBuilder sb = new StringBuilder(message, 1024); if (IsEnabled(TraceOptions.ProcessId)) { sb.Append("\r\nProcessId="); sb.Append(eventCache.ProcessId); } if (IsEnabled(TraceOptions.LogicalOperationStack)) { sb.Append("\r\nLogicalOperationStack="); bool first = true; foreach (Object obj in eventCache.LogicalOperationStack) { if (!first) { sb.Append(", "); } else { first = false; } sb.Append(obj); } } if (IsEnabled(TraceOptions.ThreadId)) { sb.Append("\r\nThreadId="); sb.Append(eventCache.ThreadId); } if (IsEnabled(TraceOptions.DateTime)) { sb.Append("\r\nDateTime="); sb.Append(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); } if (IsEnabled(TraceOptions.Timestamp)) { sb.Append("\r\nTimestamp="); sb.Append(eventCache.Timestamp); } if (IsEnabled(TraceOptions.Callstack)) { sb.Append("\r\nCallstack="); sb.Append(eventCache.Callstack); } return sb.ToString(); } private bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } private IntegratedTraceType Convert(TraceEventType tet) { switch (tet) { case TraceEventType.Critical: return IntegratedTraceType.DiagCritical; case TraceEventType.Error: return IntegratedTraceType.DiagError; case TraceEventType.Warning: return IntegratedTraceType.DiagWarning; case TraceEventType.Information: return IntegratedTraceType.DiagInfo; case TraceEventType.Verbose: return IntegratedTraceType.DiagVerbose; case TraceEventType.Start: return IntegratedTraceType.DiagStart; case TraceEventType.Stop: return IntegratedTraceType.DiagStop; case TraceEventType.Suspend: return IntegratedTraceType.DiagSuspend; case TraceEventType.Resume: return IntegratedTraceType.DiagResume; case TraceEventType.Transfer: return IntegratedTraceType.DiagTransfer; } // Default to verbose logging return IntegratedTraceType.DiagVerbose; } } }
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Marten.Linq; using Microsoft.AspNetCore.Http; namespace Marten.AspNetCore { public static class QueryableExtensions { /// <summary> /// Write the JSON contents of a single document response from the Linq query to the HttpContext response, with status code 200 if found or /// 404 if not found /// </summary> /// <param name="queryable"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <param name="onFoundStatus"></param> /// <typeparam name="T"></typeparam> public static async Task WriteSingle<T>(this IQueryable<T> queryable, HttpContext context, string contentType = "application/json", int onFoundStatus = 200) { var stream = new MemoryStream(); var found = await queryable.StreamJsonFirstOrDefault(stream, context.RequestAborted).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Write the JSON content of a Linq query as a JSON array to the HttpContext response /// </summary> /// <param name="queryable"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="T"></typeparam> public static async Task WriteArray<T>(this IQueryable<T> queryable, HttpContext context, string contentType = "application/json") { var stream = new MemoryStream(); await queryable.StreamJsonArray(stream, context.RequestAborted).ConfigureAwait(false); context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } /// <summary> /// Quickly write the JSON for a document by Id to an HttpContext. Will also handle status code mechanics /// </summary> /// <param name="json"></param> /// <param name="id"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="T"></typeparam> public static async Task WriteById<T>(this IJsonLoader json, string id, HttpContext context, string contentType = "application/json") where T : class { var stream = new MemoryStream(); var found = await json.StreamById<T>(id, stream).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Quickly write the JSON for a document by Id to an HttpContext. Will also handle status code mechanics /// </summary> /// <param name="json"></param> /// <param name="id"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="T"></typeparam> public static async Task WriteById<T>(this IJsonLoader json, Guid id, HttpContext context, string contentType = "application/json") where T : class { var stream = new MemoryStream(); var found = await json.StreamById<T>(id, stream).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Quickly write the JSON for a document by Id to an HttpContext. Will also handle status code mechanics /// </summary> /// <param name="json"></param> /// <param name="id"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="T"></typeparam> public static async Task WriteById<T>(this IJsonLoader json, int id, HttpContext context, string contentType = "application/json") where T : class { var stream = new MemoryStream(); var found = await json.StreamById<T>(id, stream).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Quickly write the JSON for a document by Id to an HttpContext. Will also handle status code mechanics /// </summary> /// <param name="json"></param> /// <param name="id"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="T"></typeparam> public static async Task WriteById<T>(this IJsonLoader json, long id, HttpContext context, string contentType = "application/json") where T : class { var stream = new MemoryStream(); var found = await json.StreamById<T>(id, stream).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Write a single document returned from a compiled query to the /// given HttpContext /// </summary> /// <param name="session"></param> /// <param name="query"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="TDoc"></typeparam> /// <typeparam name="TOut"></typeparam> public static async Task WriteOne<TDoc, TOut>(this IQuerySession session, ICompiledQuery<TDoc, TOut> query, HttpContext context, string contentType = "application/json") { var stream = new MemoryStream(); var found = await session.StreamJsonOne(query, stream, context.RequestAborted).ConfigureAwait(false); if (found) { context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } else { context.Response.StatusCode = 404; context.Response.ContentLength = 0; } } /// <summary> /// Write an array of documents as a JSON array from a compiled query /// to the HttpContext /// </summary> /// <param name="session"></param> /// <param name="query"></param> /// <param name="context"></param> /// <param name="contentType"></param> /// <typeparam name="TDoc"></typeparam> /// <typeparam name="TOut"></typeparam> public static async Task WriteArray<TDoc, TOut>(this IQuerySession session, ICompiledQuery<TDoc, TOut> query, HttpContext context, string contentType = "application/json") { var stream = new MemoryStream(); await session.StreamJsonMany(query, stream, context.RequestAborted).ConfigureAwait(false); context.Response.StatusCode = 200; context.Response.ContentLength = stream.Length; context.Response.ContentType = contentType; stream.Position = 0; await stream.CopyToAsync(context.Response.Body).ConfigureAwait(false); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Grid Subjects Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class TTTGDataSet : EduHubDataSet<TTTG> { /// <inheritdoc /> public override string Name { get { return "TTTG"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal TTTGDataSet(EduHubContext Context) : base(Context) { Index_GKEY = new Lazy<Dictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedDictionary(i => i.GKEY)); Index_IDENT = new Lazy<NullDictionary<int?, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.IDENT)); Index_R1ROOM = new Lazy<NullDictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.R1ROOM)); Index_R2ROOM = new Lazy<NullDictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.R2ROOM)); Index_SUBJ = new Lazy<NullDictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.SUBJ)); Index_T1TEACH = new Lazy<NullDictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.T1TEACH)); Index_T2TEACH = new Lazy<NullDictionary<string, IReadOnlyList<TTTG>>>(() => this.ToGroupedNullDictionary(i => i.T2TEACH)); Index_TID = new Lazy<Dictionary<int, TTTG>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="TTTG" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="TTTG" /> fields for each CSV column header</returns> internal override Action<TTTG, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<TTTG, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "GKEY": mapper[i] = (e, v) => e.GKEY = v; break; case "SUBJ": mapper[i] = (e, v) => e.SUBJ = v; break; case "CLASS": mapper[i] = (e, v) => e.CLASS = v == null ? (short?)null : short.Parse(v); break; case "FIRST_CLASS": mapper[i] = (e, v) => e.FIRST_CLASS = v == null ? (short?)null : short.Parse(v); break; case "NSET": mapper[i] = (e, v) => e.NSET = v == null ? (short?)null : short.Parse(v); break; case "IDENT": mapper[i] = (e, v) => e.IDENT = v == null ? (int?)null : int.Parse(v); break; case "CLASS_SIZE": mapper[i] = (e, v) => e.CLASS_SIZE = v == null ? (short?)null : short.Parse(v); break; case "MAXIMUM": mapper[i] = (e, v) => e.MAXIMUM = v == null ? (short?)null : short.Parse(v); break; case "MINIMUM": mapper[i] = (e, v) => e.MINIMUM = v == null ? (short?)null : short.Parse(v); break; case "MINLINE": mapper[i] = (e, v) => e.MINLINE = v == null ? (short?)null : short.Parse(v); break; case "MAXLINE": mapper[i] = (e, v) => e.MAXLINE = v == null ? (short?)null : short.Parse(v); break; case "MCOLOUR": mapper[i] = (e, v) => e.MCOLOUR = v == null ? (short?)null : short.Parse(v); break; case "GCOLOUR": mapper[i] = (e, v) => e.GCOLOUR = v == null ? (int?)null : int.Parse(v); break; case "UNITS": mapper[i] = (e, v) => e.UNITS = v == null ? (short?)null : short.Parse(v); break; case "T1TEACH": mapper[i] = (e, v) => e.T1TEACH = v; break; case "T2TEACH": mapper[i] = (e, v) => e.T2TEACH = v; break; case "R1ROOM": mapper[i] = (e, v) => e.R1ROOM = v; break; case "R2ROOM": mapper[i] = (e, v) => e.R2ROOM = v; break; case "RESOURCES01": mapper[i] = (e, v) => e.RESOURCES01 = v; break; case "RESOURCES02": mapper[i] = (e, v) => e.RESOURCES02 = v; break; case "RESOURCES03": mapper[i] = (e, v) => e.RESOURCES03 = v; break; case "RESOURCES04": mapper[i] = (e, v) => e.RESOURCES04 = v; break; case "RESOURCES05": mapper[i] = (e, v) => e.RESOURCES05 = v; break; case "RESOURCES06": mapper[i] = (e, v) => e.RESOURCES06 = v; break; case "RESOURCES07": mapper[i] = (e, v) => e.RESOURCES07 = v; break; case "RESOURCES08": mapper[i] = (e, v) => e.RESOURCES08 = v; break; case "RESOURCES09": mapper[i] = (e, v) => e.RESOURCES09 = v; break; case "LAB": mapper[i] = (e, v) => e.LAB = v; break; case "FROW": mapper[i] = (e, v) => e.FROW = v == null ? (short?)null : short.Parse(v); break; case "FCOL": mapper[i] = (e, v) => e.FCOL = v == null ? (short?)null : short.Parse(v); break; case "HROW": mapper[i] = (e, v) => e.HROW = v == null ? (short?)null : short.Parse(v); break; case "HCOL": mapper[i] = (e, v) => e.HCOL = v == null ? (short?)null : short.Parse(v); break; case "BLOCK": mapper[i] = (e, v) => e.BLOCK = v; break; case "LOCK": mapper[i] = (e, v) => e.LOCK = v == null ? (short?)null : short.Parse(v); break; case "TCHAIN": mapper[i] = (e, v) => e.TCHAIN = v == null ? (short?)null : short.Parse(v); break; case "LCHAIN": mapper[i] = (e, v) => e.LCHAIN = v == null ? (short?)null : short.Parse(v); break; case "TIED_COL": mapper[i] = (e, v) => e.TIED_COL = v == null ? (short?)null : short.Parse(v); break; case "LINK_COL": mapper[i] = (e, v) => e.LINK_COL = v == null ? (short?)null : short.Parse(v); break; case "MAX_ROW_CLASSES": mapper[i] = (e, v) => e.MAX_ROW_CLASSES = v == null ? (short?)null : short.Parse(v); break; case "ROW_GROUP": mapper[i] = (e, v) => e.ROW_GROUP = v; break; case "DOUBLE_PERIODS": mapper[i] = (e, v) => e.DOUBLE_PERIODS = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="TTTG" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="TTTG" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="TTTG" /> entities</param> /// <returns>A merged <see cref="IEnumerable{TTTG}"/> of entities</returns> internal override IEnumerable<TTTG> ApplyDeltaEntities(IEnumerable<TTTG> Entities, List<TTTG> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.GKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.GKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<TTTG>>> Index_GKEY; private Lazy<NullDictionary<int?, IReadOnlyList<TTTG>>> Index_IDENT; private Lazy<NullDictionary<string, IReadOnlyList<TTTG>>> Index_R1ROOM; private Lazy<NullDictionary<string, IReadOnlyList<TTTG>>> Index_R2ROOM; private Lazy<NullDictionary<string, IReadOnlyList<TTTG>>> Index_SUBJ; private Lazy<NullDictionary<string, IReadOnlyList<TTTG>>> Index_T1TEACH; private Lazy<NullDictionary<string, IReadOnlyList<TTTG>>> Index_T2TEACH; private Lazy<Dictionary<int, TTTG>> Index_TID; #endregion #region Index Methods /// <summary> /// Find TTTG by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByGKEY(string GKEY) { return Index_GKEY.Value[GKEY]; } /// <summary> /// Attempt to find TTTG by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGKEY(string GKEY, out IReadOnlyList<TTTG> Value) { return Index_GKEY.Value.TryGetValue(GKEY, out Value); } /// <summary> /// Attempt to find TTTG by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByGKEY(string GKEY) { IReadOnlyList<TTTG> value; if (Index_GKEY.Value.TryGetValue(GKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by IDENT field /// </summary> /// <param name="IDENT">IDENT value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByIDENT(int? IDENT) { return Index_IDENT.Value[IDENT]; } /// <summary> /// Attempt to find TTTG by IDENT field /// </summary> /// <param name="IDENT">IDENT value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByIDENT(int? IDENT, out IReadOnlyList<TTTG> Value) { return Index_IDENT.Value.TryGetValue(IDENT, out Value); } /// <summary> /// Attempt to find TTTG by IDENT field /// </summary> /// <param name="IDENT">IDENT value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByIDENT(int? IDENT) { IReadOnlyList<TTTG> value; if (Index_IDENT.Value.TryGetValue(IDENT, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by R1ROOM field /// </summary> /// <param name="R1ROOM">R1ROOM value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByR1ROOM(string R1ROOM) { return Index_R1ROOM.Value[R1ROOM]; } /// <summary> /// Attempt to find TTTG by R1ROOM field /// </summary> /// <param name="R1ROOM">R1ROOM value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByR1ROOM(string R1ROOM, out IReadOnlyList<TTTG> Value) { return Index_R1ROOM.Value.TryGetValue(R1ROOM, out Value); } /// <summary> /// Attempt to find TTTG by R1ROOM field /// </summary> /// <param name="R1ROOM">R1ROOM value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByR1ROOM(string R1ROOM) { IReadOnlyList<TTTG> value; if (Index_R1ROOM.Value.TryGetValue(R1ROOM, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by R2ROOM field /// </summary> /// <param name="R2ROOM">R2ROOM value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByR2ROOM(string R2ROOM) { return Index_R2ROOM.Value[R2ROOM]; } /// <summary> /// Attempt to find TTTG by R2ROOM field /// </summary> /// <param name="R2ROOM">R2ROOM value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByR2ROOM(string R2ROOM, out IReadOnlyList<TTTG> Value) { return Index_R2ROOM.Value.TryGetValue(R2ROOM, out Value); } /// <summary> /// Attempt to find TTTG by R2ROOM field /// </summary> /// <param name="R2ROOM">R2ROOM value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByR2ROOM(string R2ROOM) { IReadOnlyList<TTTG> value; if (Index_R2ROOM.Value.TryGetValue(R2ROOM, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindBySUBJ(string SUBJ) { return Index_SUBJ.Value[SUBJ]; } /// <summary> /// Attempt to find TTTG by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySUBJ(string SUBJ, out IReadOnlyList<TTTG> Value) { return Index_SUBJ.Value.TryGetValue(SUBJ, out Value); } /// <summary> /// Attempt to find TTTG by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindBySUBJ(string SUBJ) { IReadOnlyList<TTTG> value; if (Index_SUBJ.Value.TryGetValue(SUBJ, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by T1TEACH field /// </summary> /// <param name="T1TEACH">T1TEACH value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByT1TEACH(string T1TEACH) { return Index_T1TEACH.Value[T1TEACH]; } /// <summary> /// Attempt to find TTTG by T1TEACH field /// </summary> /// <param name="T1TEACH">T1TEACH value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByT1TEACH(string T1TEACH, out IReadOnlyList<TTTG> Value) { return Index_T1TEACH.Value.TryGetValue(T1TEACH, out Value); } /// <summary> /// Attempt to find TTTG by T1TEACH field /// </summary> /// <param name="T1TEACH">T1TEACH value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByT1TEACH(string T1TEACH) { IReadOnlyList<TTTG> value; if (Index_T1TEACH.Value.TryGetValue(T1TEACH, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by T2TEACH field /// </summary> /// <param name="T2TEACH">T2TEACH value used to find TTTG</param> /// <returns>List of related TTTG entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> FindByT2TEACH(string T2TEACH) { return Index_T2TEACH.Value[T2TEACH]; } /// <summary> /// Attempt to find TTTG by T2TEACH field /// </summary> /// <param name="T2TEACH">T2TEACH value used to find TTTG</param> /// <param name="Value">List of related TTTG entities</param> /// <returns>True if the list of related TTTG entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByT2TEACH(string T2TEACH, out IReadOnlyList<TTTG> Value) { return Index_T2TEACH.Value.TryGetValue(T2TEACH, out Value); } /// <summary> /// Attempt to find TTTG by T2TEACH field /// </summary> /// <param name="T2TEACH">T2TEACH value used to find TTTG</param> /// <returns>List of related TTTG entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTTG> TryFindByT2TEACH(string T2TEACH) { IReadOnlyList<TTTG> value; if (Index_T2TEACH.Value.TryGetValue(T2TEACH, out value)) { return value; } else { return null; } } /// <summary> /// Find TTTG by TID field /// </summary> /// <param name="TID">TID value used to find TTTG</param> /// <returns>Related TTTG entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public TTTG FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find TTTG by TID field /// </summary> /// <param name="TID">TID value used to find TTTG</param> /// <param name="Value">Related TTTG entity</param> /// <returns>True if the related TTTG entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out TTTG Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find TTTG by TID field /// </summary> /// <param name="TID">TID value used to find TTTG</param> /// <returns>Related TTTG entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public TTTG TryFindByTID(int TID) { TTTG value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a TTTG table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[TTTG]( [TID] int IDENTITY NOT NULL, [GKEY] varchar(8) NOT NULL, [SUBJ] varchar(5) NULL, [CLASS] smallint NULL, [FIRST_CLASS] smallint NULL, [NSET] smallint NULL, [IDENT] int NULL, [CLASS_SIZE] smallint NULL, [MAXIMUM] smallint NULL, [MINIMUM] smallint NULL, [MINLINE] smallint NULL, [MAXLINE] smallint NULL, [MCOLOUR] smallint NULL, [GCOLOUR] int NULL, [UNITS] smallint NULL, [T1TEACH] varchar(4) NULL, [T2TEACH] varchar(4) NULL, [R1ROOM] varchar(4) NULL, [R2ROOM] varchar(4) NULL, [RESOURCES01] varchar(4) NULL, [RESOURCES02] varchar(4) NULL, [RESOURCES03] varchar(4) NULL, [RESOURCES04] varchar(4) NULL, [RESOURCES05] varchar(4) NULL, [RESOURCES06] varchar(4) NULL, [RESOURCES07] varchar(4) NULL, [RESOURCES08] varchar(4) NULL, [RESOURCES09] varchar(4) NULL, [LAB] varchar(5) NULL, [FROW] smallint NULL, [FCOL] smallint NULL, [HROW] smallint NULL, [HCOL] smallint NULL, [BLOCK] varchar(1) NULL, [LOCK] smallint NULL, [TCHAIN] smallint NULL, [LCHAIN] smallint NULL, [TIED_COL] smallint NULL, [LINK_COL] smallint NULL, [MAX_ROW_CLASSES] smallint NULL, [ROW_GROUP] varchar(2) NULL, [DOUBLE_PERIODS] smallint NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [TTTG_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [TTTG_Index_GKEY] ON [dbo].[TTTG] ( [GKEY] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_IDENT] ON [dbo].[TTTG] ( [IDENT] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_R1ROOM] ON [dbo].[TTTG] ( [R1ROOM] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_R2ROOM] ON [dbo].[TTTG] ( [R2ROOM] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_SUBJ] ON [dbo].[TTTG] ( [SUBJ] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_T1TEACH] ON [dbo].[TTTG] ( [T1TEACH] ASC ); CREATE NONCLUSTERED INDEX [TTTG_Index_T2TEACH] ON [dbo].[TTTG] ( [T2TEACH] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_IDENT') ALTER INDEX [TTTG_Index_IDENT] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_R1ROOM') ALTER INDEX [TTTG_Index_R1ROOM] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_R2ROOM') ALTER INDEX [TTTG_Index_R2ROOM] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_SUBJ') ALTER INDEX [TTTG_Index_SUBJ] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_T1TEACH') ALTER INDEX [TTTG_Index_T1TEACH] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_T2TEACH') ALTER INDEX [TTTG_Index_T2TEACH] ON [dbo].[TTTG] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_TID') ALTER INDEX [TTTG_Index_TID] ON [dbo].[TTTG] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_IDENT') ALTER INDEX [TTTG_Index_IDENT] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_R1ROOM') ALTER INDEX [TTTG_Index_R1ROOM] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_R2ROOM') ALTER INDEX [TTTG_Index_R2ROOM] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_SUBJ') ALTER INDEX [TTTG_Index_SUBJ] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_T1TEACH') ALTER INDEX [TTTG_Index_T1TEACH] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_T2TEACH') ALTER INDEX [TTTG_Index_T2TEACH] ON [dbo].[TTTG] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTTG]') AND name = N'TTTG_Index_TID') ALTER INDEX [TTTG_Index_TID] ON [dbo].[TTTG] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TTTG"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="TTTG"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TTTG> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[TTTG] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the TTTG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the TTTG data set</returns> public override EduHubDataSetDataReader<TTTG> GetDataSetDataReader() { return new TTTGDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the TTTG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the TTTG data set</returns> public override EduHubDataSetDataReader<TTTG> GetDataSetDataReader(List<TTTG> Entities) { return new TTTGDataReader(new EduHubDataSetLoadedReader<TTTG>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class TTTGDataReader : EduHubDataSetDataReader<TTTG> { public TTTGDataReader(IEduHubDataSetReader<TTTG> Reader) : base (Reader) { } public override int FieldCount { get { return 45; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // GKEY return Current.GKEY; case 2: // SUBJ return Current.SUBJ; case 3: // CLASS return Current.CLASS; case 4: // FIRST_CLASS return Current.FIRST_CLASS; case 5: // NSET return Current.NSET; case 6: // IDENT return Current.IDENT; case 7: // CLASS_SIZE return Current.CLASS_SIZE; case 8: // MAXIMUM return Current.MAXIMUM; case 9: // MINIMUM return Current.MINIMUM; case 10: // MINLINE return Current.MINLINE; case 11: // MAXLINE return Current.MAXLINE; case 12: // MCOLOUR return Current.MCOLOUR; case 13: // GCOLOUR return Current.GCOLOUR; case 14: // UNITS return Current.UNITS; case 15: // T1TEACH return Current.T1TEACH; case 16: // T2TEACH return Current.T2TEACH; case 17: // R1ROOM return Current.R1ROOM; case 18: // R2ROOM return Current.R2ROOM; case 19: // RESOURCES01 return Current.RESOURCES01; case 20: // RESOURCES02 return Current.RESOURCES02; case 21: // RESOURCES03 return Current.RESOURCES03; case 22: // RESOURCES04 return Current.RESOURCES04; case 23: // RESOURCES05 return Current.RESOURCES05; case 24: // RESOURCES06 return Current.RESOURCES06; case 25: // RESOURCES07 return Current.RESOURCES07; case 26: // RESOURCES08 return Current.RESOURCES08; case 27: // RESOURCES09 return Current.RESOURCES09; case 28: // LAB return Current.LAB; case 29: // FROW return Current.FROW; case 30: // FCOL return Current.FCOL; case 31: // HROW return Current.HROW; case 32: // HCOL return Current.HCOL; case 33: // BLOCK return Current.BLOCK; case 34: // LOCK return Current.LOCK; case 35: // TCHAIN return Current.TCHAIN; case 36: // LCHAIN return Current.LCHAIN; case 37: // TIED_COL return Current.TIED_COL; case 38: // LINK_COL return Current.LINK_COL; case 39: // MAX_ROW_CLASSES return Current.MAX_ROW_CLASSES; case 40: // ROW_GROUP return Current.ROW_GROUP; case 41: // DOUBLE_PERIODS return Current.DOUBLE_PERIODS; case 42: // LW_DATE return Current.LW_DATE; case 43: // LW_TIME return Current.LW_TIME; case 44: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SUBJ return Current.SUBJ == null; case 3: // CLASS return Current.CLASS == null; case 4: // FIRST_CLASS return Current.FIRST_CLASS == null; case 5: // NSET return Current.NSET == null; case 6: // IDENT return Current.IDENT == null; case 7: // CLASS_SIZE return Current.CLASS_SIZE == null; case 8: // MAXIMUM return Current.MAXIMUM == null; case 9: // MINIMUM return Current.MINIMUM == null; case 10: // MINLINE return Current.MINLINE == null; case 11: // MAXLINE return Current.MAXLINE == null; case 12: // MCOLOUR return Current.MCOLOUR == null; case 13: // GCOLOUR return Current.GCOLOUR == null; case 14: // UNITS return Current.UNITS == null; case 15: // T1TEACH return Current.T1TEACH == null; case 16: // T2TEACH return Current.T2TEACH == null; case 17: // R1ROOM return Current.R1ROOM == null; case 18: // R2ROOM return Current.R2ROOM == null; case 19: // RESOURCES01 return Current.RESOURCES01 == null; case 20: // RESOURCES02 return Current.RESOURCES02 == null; case 21: // RESOURCES03 return Current.RESOURCES03 == null; case 22: // RESOURCES04 return Current.RESOURCES04 == null; case 23: // RESOURCES05 return Current.RESOURCES05 == null; case 24: // RESOURCES06 return Current.RESOURCES06 == null; case 25: // RESOURCES07 return Current.RESOURCES07 == null; case 26: // RESOURCES08 return Current.RESOURCES08 == null; case 27: // RESOURCES09 return Current.RESOURCES09 == null; case 28: // LAB return Current.LAB == null; case 29: // FROW return Current.FROW == null; case 30: // FCOL return Current.FCOL == null; case 31: // HROW return Current.HROW == null; case 32: // HCOL return Current.HCOL == null; case 33: // BLOCK return Current.BLOCK == null; case 34: // LOCK return Current.LOCK == null; case 35: // TCHAIN return Current.TCHAIN == null; case 36: // LCHAIN return Current.LCHAIN == null; case 37: // TIED_COL return Current.TIED_COL == null; case 38: // LINK_COL return Current.LINK_COL == null; case 39: // MAX_ROW_CLASSES return Current.MAX_ROW_CLASSES == null; case 40: // ROW_GROUP return Current.ROW_GROUP == null; case 41: // DOUBLE_PERIODS return Current.DOUBLE_PERIODS == null; case 42: // LW_DATE return Current.LW_DATE == null; case 43: // LW_TIME return Current.LW_TIME == null; case 44: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // GKEY return "GKEY"; case 2: // SUBJ return "SUBJ"; case 3: // CLASS return "CLASS"; case 4: // FIRST_CLASS return "FIRST_CLASS"; case 5: // NSET return "NSET"; case 6: // IDENT return "IDENT"; case 7: // CLASS_SIZE return "CLASS_SIZE"; case 8: // MAXIMUM return "MAXIMUM"; case 9: // MINIMUM return "MINIMUM"; case 10: // MINLINE return "MINLINE"; case 11: // MAXLINE return "MAXLINE"; case 12: // MCOLOUR return "MCOLOUR"; case 13: // GCOLOUR return "GCOLOUR"; case 14: // UNITS return "UNITS"; case 15: // T1TEACH return "T1TEACH"; case 16: // T2TEACH return "T2TEACH"; case 17: // R1ROOM return "R1ROOM"; case 18: // R2ROOM return "R2ROOM"; case 19: // RESOURCES01 return "RESOURCES01"; case 20: // RESOURCES02 return "RESOURCES02"; case 21: // RESOURCES03 return "RESOURCES03"; case 22: // RESOURCES04 return "RESOURCES04"; case 23: // RESOURCES05 return "RESOURCES05"; case 24: // RESOURCES06 return "RESOURCES06"; case 25: // RESOURCES07 return "RESOURCES07"; case 26: // RESOURCES08 return "RESOURCES08"; case 27: // RESOURCES09 return "RESOURCES09"; case 28: // LAB return "LAB"; case 29: // FROW return "FROW"; case 30: // FCOL return "FCOL"; case 31: // HROW return "HROW"; case 32: // HCOL return "HCOL"; case 33: // BLOCK return "BLOCK"; case 34: // LOCK return "LOCK"; case 35: // TCHAIN return "TCHAIN"; case 36: // LCHAIN return "LCHAIN"; case 37: // TIED_COL return "TIED_COL"; case 38: // LINK_COL return "LINK_COL"; case 39: // MAX_ROW_CLASSES return "MAX_ROW_CLASSES"; case 40: // ROW_GROUP return "ROW_GROUP"; case 41: // DOUBLE_PERIODS return "DOUBLE_PERIODS"; case 42: // LW_DATE return "LW_DATE"; case 43: // LW_TIME return "LW_TIME"; case 44: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "GKEY": return 1; case "SUBJ": return 2; case "CLASS": return 3; case "FIRST_CLASS": return 4; case "NSET": return 5; case "IDENT": return 6; case "CLASS_SIZE": return 7; case "MAXIMUM": return 8; case "MINIMUM": return 9; case "MINLINE": return 10; case "MAXLINE": return 11; case "MCOLOUR": return 12; case "GCOLOUR": return 13; case "UNITS": return 14; case "T1TEACH": return 15; case "T2TEACH": return 16; case "R1ROOM": return 17; case "R2ROOM": return 18; case "RESOURCES01": return 19; case "RESOURCES02": return 20; case "RESOURCES03": return 21; case "RESOURCES04": return 22; case "RESOURCES05": return 23; case "RESOURCES06": return 24; case "RESOURCES07": return 25; case "RESOURCES08": return 26; case "RESOURCES09": return 27; case "LAB": return 28; case "FROW": return 29; case "FCOL": return 30; case "HROW": return 31; case "HCOL": return 32; case "BLOCK": return 33; case "LOCK": return 34; case "TCHAIN": return 35; case "LCHAIN": return 36; case "TIED_COL": return 37; case "LINK_COL": return 38; case "MAX_ROW_CLASSES": return 39; case "ROW_GROUP": return 40; case "DOUBLE_PERIODS": return 41; case "LW_DATE": return 42; case "LW_TIME": return 43; case "LW_USER": return 44; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using Microsoft.Xna.Framework; using VelcroPhysics.Collision.ContactSystem; using VelcroPhysics.Collision.Shapes; using VelcroPhysics.Shared; using VelcroPhysics.Shared.Optimization; using VelcroPhysics.Utilities; namespace VelcroPhysics.Collision.Narrowphase { public static class EPCollider { public static void Collide(ref Manifold manifold, EdgeShape edgeA, ref Transform xfA, PolygonShape polygonB, ref Transform xfB) { // Algorithm: // 1. Classify v1 and v2 // 2. Classify polygon centroid as front or back // 3. Flip normal if necessary // 4. Initialize normal range to [-pi, pi] about face normal // 5. Adjust normal range according to adjacent edges // 6. Visit each separating axes, only accept axes within the range // 7. Return if _any_ axis indicates separation // 8. Clip bool front; Vector2 lowerLimit, upperLimit; Vector2 normal; Vector2 normal0 = Vector2.Zero; Vector2 normal2 = Vector2.Zero; Transform xf = MathUtils.MulT(xfA, xfB); Vector2 centroidB = MathUtils.Mul(ref xf, polygonB.MassData.Centroid); Vector2 v0 = edgeA.Vertex0; Vector2 v1 = edgeA._vertex1; Vector2 v2 = edgeA._vertex2; Vector2 v3 = edgeA.Vertex3; bool hasVertex0 = edgeA.HasVertex0; bool hasVertex3 = edgeA.HasVertex3; Vector2 edge1 = v2 - v1; edge1.Normalize(); Vector2 normal1 = new Vector2(edge1.Y, -edge1.X); float offset1 = Vector2.Dot(normal1, centroidB - v1); float offset0 = 0.0f, offset2 = 0.0f; bool convex1 = false, convex2 = false; // Is there a preceding edge? if (hasVertex0) { Vector2 edge0 = v1 - v0; edge0.Normalize(); normal0 = new Vector2(edge0.Y, -edge0.X); convex1 = MathUtils.Cross(edge0, edge1) >= 0.0f; offset0 = Vector2.Dot(normal0, centroidB - v0); } // Is there a following edge? if (hasVertex3) { Vector2 edge2 = v3 - v2; edge2.Normalize(); normal2 = new Vector2(edge2.Y, -edge2.X); convex2 = MathUtils.Cross(edge1, edge2) > 0.0f; offset2 = Vector2.Dot(normal2, centroidB - v2); } // Determine front or back collision. Determine collision normal limits. if (hasVertex0 && hasVertex3) { if (convex1 && convex2) { front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; if (front) { normal = normal1; lowerLimit = normal0; upperLimit = normal2; } else { normal = -normal1; lowerLimit = -normal1; upperLimit = -normal1; } } else if (convex1) { front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); if (front) { normal = normal1; lowerLimit = normal0; upperLimit = normal1; } else { normal = -normal1; lowerLimit = -normal2; upperLimit = -normal1; } } else if (convex2) { front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); if (front) { normal = normal1; lowerLimit = normal1; upperLimit = normal2; } else { normal = -normal1; lowerLimit = -normal1; upperLimit = -normal0; } } else { front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; if (front) { normal = normal1; lowerLimit = normal1; upperLimit = normal1; } else { normal = -normal1; lowerLimit = -normal2; upperLimit = -normal0; } } } else if (hasVertex0) { if (convex1) { front = offset0 >= 0.0f || offset1 >= 0.0f; if (front) { normal = normal1; lowerLimit = normal0; upperLimit = -normal1; } else { normal = -normal1; lowerLimit = normal1; upperLimit = -normal1; } } else { front = offset0 >= 0.0f && offset1 >= 0.0f; if (front) { normal = normal1; lowerLimit = normal1; upperLimit = -normal1; } else { normal = -normal1; lowerLimit = normal1; upperLimit = -normal0; } } } else if (hasVertex3) { if (convex2) { front = offset1 >= 0.0f || offset2 >= 0.0f; if (front) { normal = normal1; lowerLimit = -normal1; upperLimit = normal2; } else { normal = -normal1; lowerLimit = -normal1; upperLimit = normal1; } } else { front = offset1 >= 0.0f && offset2 >= 0.0f; if (front) { normal = normal1; lowerLimit = -normal1; upperLimit = normal1; } else { normal = -normal1; lowerLimit = -normal2; upperLimit = normal1; } } } else { front = offset1 >= 0.0f; if (front) { normal = normal1; lowerLimit = -normal1; upperLimit = -normal1; } else { normal = -normal1; lowerLimit = normal1; upperLimit = normal1; } } // Get polygonB in frameA Vector2[] normals = new Vector2[Settings.MaxPolygonVertices]; Vector2[] vertices = new Vector2[Settings.MaxPolygonVertices]; int count = polygonB.Vertices.Count; for (int i = 0; i < polygonB.Vertices.Count; ++i) { vertices[i] = MathUtils.Mul(ref xf, polygonB.Vertices[i]); normals[i] = MathUtils.Mul(xf.q, polygonB.Normals[i]); } float radius = polygonB.Radius + edgeA.Radius; manifold.PointCount = 0; //Velcro: ComputeEdgeSeparation() was manually inlined here EPAxis edgeAxis; edgeAxis.Type = EPAxisType.EdgeA; edgeAxis.Index = front ? 0 : 1; edgeAxis.Separation = Settings.MaxFloat; for (int i = 0; i < count; ++i) { float s = Vector2.Dot(normal, vertices[i] - v1); if (s < edgeAxis.Separation) { edgeAxis.Separation = s; } } // If no valid normal can be found than this edge should not collide. if (edgeAxis.Type == EPAxisType.Unknown) { return; } if (edgeAxis.Separation > radius) { return; } //Velcro: ComputePolygonSeparation() was manually inlined here EPAxis polygonAxis; polygonAxis.Type = EPAxisType.Unknown; polygonAxis.Index = -1; polygonAxis.Separation = -Settings.MaxFloat; Vector2 perp = new Vector2(-normal.Y, normal.X); for (int i = 0; i < count; ++i) { Vector2 n = -normals[i]; float s1 = Vector2.Dot(n, vertices[i] - v1); float s2 = Vector2.Dot(n, vertices[i] - v2); float s = Math.Min(s1, s2); if (s > radius) { // No collision polygonAxis.Type = EPAxisType.EdgeB; polygonAxis.Index = i; polygonAxis.Separation = s; break; } // Adjacency if (Vector2.Dot(n, perp) >= 0.0f) { if (Vector2.Dot(n - upperLimit, normal) < -Settings.AngularSlop) { continue; } } else { if (Vector2.Dot(n - lowerLimit, normal) < -Settings.AngularSlop) { continue; } } if (s > polygonAxis.Separation) { polygonAxis.Type = EPAxisType.EdgeB; polygonAxis.Index = i; polygonAxis.Separation = s; } } if (polygonAxis.Type != EPAxisType.Unknown && polygonAxis.Separation > radius) { return; } // Use hysteresis for jitter reduction. const float k_relativeTol = 0.98f; const float k_absoluteTol = 0.001f; EPAxis primaryAxis; if (polygonAxis.Type == EPAxisType.Unknown) { primaryAxis = edgeAxis; } else if (polygonAxis.Separation > k_relativeTol * edgeAxis.Separation + k_absoluteTol) { primaryAxis = polygonAxis; } else { primaryAxis = edgeAxis; } FixedArray2<ClipVertex> ie = new FixedArray2<ClipVertex>(); ReferenceFace rf; if (primaryAxis.Type == EPAxisType.EdgeA) { manifold.Type = ManifoldType.FaceA; // Search for the polygon normal that is most anti-parallel to the edge normal. int bestIndex = 0; float bestValue = Vector2.Dot(normal, normals[0]); for (int i = 1; i < count; ++i) { float value = Vector2.Dot(normal, normals[i]); if (value < bestValue) { bestValue = value; bestIndex = i; } } int i1 = bestIndex; int i2 = i1 + 1 < count ? i1 + 1 : 0; ie.Value0.V = vertices[i1]; ie.Value0.ID.ContactFeature.IndexA = 0; ie.Value0.ID.ContactFeature.IndexB = (byte)i1; ie.Value0.ID.ContactFeature.TypeA = ContactFeatureType.Face; ie.Value0.ID.ContactFeature.TypeB = ContactFeatureType.Vertex; ie.Value1.V = vertices[i2]; ie.Value1.ID.ContactFeature.IndexA = 0; ie.Value1.ID.ContactFeature.IndexB = (byte)i2; ie.Value1.ID.ContactFeature.TypeA = ContactFeatureType.Face; ie.Value1.ID.ContactFeature.TypeB = ContactFeatureType.Vertex; if (front) { rf.i1 = 0; rf.i2 = 1; rf.v1 = v1; rf.v2 = v2; rf.Normal = normal1; } else { rf.i1 = 1; rf.i2 = 0; rf.v1 = v2; rf.v2 = v1; rf.Normal = -normal1; } } else { manifold.Type = ManifoldType.FaceB; ie.Value0.V = v1; ie.Value0.ID.ContactFeature.IndexA = 0; ie.Value0.ID.ContactFeature.IndexB = (byte)primaryAxis.Index; ie.Value0.ID.ContactFeature.TypeA = ContactFeatureType.Vertex; ie.Value0.ID.ContactFeature.TypeB = ContactFeatureType.Face; ie.Value1.V = v2; ie.Value1.ID.ContactFeature.IndexA = 0; ie.Value1.ID.ContactFeature.IndexB = (byte)primaryAxis.Index; ie.Value1.ID.ContactFeature.TypeA = ContactFeatureType.Vertex; ie.Value1.ID.ContactFeature.TypeB = ContactFeatureType.Face; rf.i1 = primaryAxis.Index; rf.i2 = rf.i1 + 1 < count ? rf.i1 + 1 : 0; rf.v1 = vertices[rf.i1]; rf.v2 = vertices[rf.i2]; rf.Normal = normals[rf.i1]; } rf.SideNormal1 = new Vector2(rf.Normal.Y, -rf.Normal.X); rf.SideNormal2 = -rf.SideNormal1; rf.SideOffset1 = Vector2.Dot(rf.SideNormal1, rf.v1); rf.SideOffset2 = Vector2.Dot(rf.SideNormal2, rf.v2); // Clip incident edge against extruded edge1 side edges. FixedArray2<ClipVertex> clipPoints1; FixedArray2<ClipVertex> clipPoints2; int np; // Clip to box side 1 np = Collision.ClipSegmentToLine(out clipPoints1, ref ie, rf.SideNormal1, rf.SideOffset1, rf.i1); if (np < Settings.MaxManifoldPoints) { return; } // Clip to negative box side 1 np = Collision.ClipSegmentToLine(out clipPoints2, ref clipPoints1, rf.SideNormal2, rf.SideOffset2, rf.i2); if (np < Settings.MaxManifoldPoints) { return; } // Now clipPoints2 contains the clipped points. if (primaryAxis.Type == EPAxisType.EdgeA) { manifold.LocalNormal = rf.Normal; manifold.LocalPoint = rf.v1; } else { manifold.LocalNormal = polygonB.Normals[rf.i1]; manifold.LocalPoint = polygonB.Vertices[rf.i1]; } int pointCount = 0; for (int i = 0; i < Settings.MaxManifoldPoints; ++i) { float separation = Vector2.Dot(rf.Normal, clipPoints2[i].V - rf.v1); if (separation <= radius) { ManifoldPoint cp = manifold.Points[pointCount]; if (primaryAxis.Type == EPAxisType.EdgeA) { cp.LocalPoint = MathUtils.MulT(ref xf, clipPoints2[i].V); cp.Id = clipPoints2[i].ID; } else { cp.LocalPoint = clipPoints2[i].V; cp.Id.ContactFeature.TypeA = clipPoints2[i].ID.ContactFeature.TypeB; cp.Id.ContactFeature.TypeB = clipPoints2[i].ID.ContactFeature.TypeA; cp.Id.ContactFeature.IndexA = clipPoints2[i].ID.ContactFeature.IndexB; cp.Id.ContactFeature.IndexB = clipPoints2[i].ID.ContactFeature.IndexA; } manifold.Points[pointCount] = cp; ++pointCount; } } manifold.PointCount = pointCount; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Diagnostics.Tracing { [System.FlagsAttribute] public enum EventActivityOptions { None = 0, Disable = 2, Recursive = 4, Detachable = 8, } [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class EventAttribute : System.Attribute { public EventAttribute(int eventId) { } public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } } public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } set { } } public int EventId { get { throw null; } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } } public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } } public string? Message { get { throw null; } set { } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } } public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } } public System.Diagnostics.Tracing.EventTask Task { get { throw null; } set { } } public byte Version { get { throw null; } set { } } } public enum EventChannel : byte { None = (byte)0, Admin = (byte)16, Operational = (byte)17, Analytic = (byte)18, Debug = (byte)19, } public enum EventCommand { Disable = -3, Enable = -2, SendManifest = -1, Update = 0, } public partial class EventCommandEventArgs : System.EventArgs { internal EventCommandEventArgs() { } public System.Collections.Generic.IDictionary<string, string?>? Arguments { get { throw null; } } public System.Diagnostics.Tracing.EventCommand Command { get { throw null; } } public bool DisableEvent(int eventId) { throw null; } public bool EnableEvent(int eventId) { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=false)] public partial class EventDataAttribute : System.Attribute { public EventDataAttribute() { } public string? Name { get { throw null; } set { } } } [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public partial class EventFieldAttribute : System.Attribute { public EventFieldAttribute() { } public System.Diagnostics.Tracing.EventFieldFormat Format { get { throw null; } set { } } public System.Diagnostics.Tracing.EventFieldTags Tags { get { throw null; } set { } } } public enum EventFieldFormat { Default = 0, String = 2, Boolean = 3, Hexadecimal = 4, Xml = 11, Json = 12, HResult = 15, } [System.FlagsAttribute] public enum EventFieldTags { None = 0, } [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public partial class EventIgnoreAttribute : System.Attribute { public EventIgnoreAttribute() { } } [System.FlagsAttribute] public enum EventKeywords : long { All = (long)-1, None = (long)0, MicrosoftTelemetry = (long)562949953421312, WdiContext = (long)562949953421312, WdiDiagnostic = (long)1125899906842624, Sqm = (long)2251799813685248, AuditFailure = (long)4503599627370496, CorrelationHint = (long)4503599627370496, AuditSuccess = (long)9007199254740992, EventLogClassic = (long)36028797018963968, } public enum EventLevel { LogAlways = 0, Critical = 1, Error = 2, Warning = 3, Informational = 4, Verbose = 5, } public abstract partial class EventListener : System.IDisposable { protected EventListener() { } public event System.EventHandler<System.Diagnostics.Tracing.EventSourceCreatedEventArgs>? EventSourceCreated { add { } remove { } } public event System.EventHandler<System.Diagnostics.Tracing.EventWrittenEventArgs>? EventWritten { add { } remove { } } public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { } public virtual void Dispose() { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { } public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string?>? arguments) { } protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; } protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { } protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { } } [System.FlagsAttribute] public enum EventManifestOptions { None = 0, Strict = 1, AllCultures = 2, OnlyIfNeededForRegistration = 4, AllowEventSourceOverride = 8, } public enum EventOpcode { Info = 0, Start = 1, Stop = 2, DataCollectionStart = 3, DataCollectionStop = 4, Extension = 5, Reply = 6, Resume = 7, Suspend = 8, Send = 9, Receive = 240, } public partial class EventSource : System.IDisposable { protected EventSource() { } protected EventSource(bool throwOnEventWriteErrors) { } protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { } protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[]? traits) { } public EventSource(string eventSourceName) { } public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { } public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[]? traits) { } public System.Exception? ConstructionException { get { throw null; } } public static System.Guid CurrentThreadActivityId { get { throw null; } } public System.Guid Guid { get { throw null; } } public string Name { get { throw null; } } public System.Diagnostics.Tracing.EventSourceSettings Settings { get { throw null; } } public event System.EventHandler<System.Diagnostics.Tracing.EventCommandEventArgs>? EventCommandExecuted { add { } remove { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~EventSource() { } public static string? GenerateManifest(System.Type eventSourceType, string? assemblyPathToIncludeInManifest) { throw null; } public static string? GenerateManifest(System.Type eventSourceType, string? assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { throw null; } public static System.Guid GetGuid(System.Type eventSourceType) { throw null; } public static string GetName(System.Type eventSourceType) { throw null; } public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { throw null; } public string? GetTrait(string key) { throw null; } public bool IsEnabled() { throw null; } public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { throw null; } public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { throw null; } protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { } public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string?>? commandArguments) { } public static void SetCurrentThreadActivityId(System.Guid activityId) { } public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { throw null; } public override string ToString() { throw null; } public void Write(string? eventName) { } public void Write(string? eventName, System.Diagnostics.Tracing.EventSourceOptions options) { } protected void WriteEvent(int eventId) { } protected void WriteEvent(int eventId, byte[]? arg1) { } protected void WriteEvent(int eventId, int arg1) { } protected void WriteEvent(int eventId, int arg1, int arg2) { } protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { } protected void WriteEvent(int eventId, int arg1, string? arg2) { } protected void WriteEvent(int eventId, long arg1) { } protected void WriteEvent(int eventId, long arg1, byte[]? arg2) { } protected void WriteEvent(int eventId, long arg1, long arg2) { } protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { } protected void WriteEvent(int eventId, long arg1, string? arg2) { } protected void WriteEvent(int eventId, params object?[] args) { } protected void WriteEvent(int eventId, string? arg1) { } protected void WriteEvent(int eventId, string? arg1, int arg2) { } protected void WriteEvent(int eventId, string? arg1, int arg2, int arg3) { } protected void WriteEvent(int eventId, string? arg1, long arg2) { } protected void WriteEvent(int eventId, string? arg1, string? arg2) { } protected void WriteEvent(int eventId, string? arg1, string? arg2, string? arg3) { } [System.CLSCompliantAttribute(false)] protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { } protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object?[] args) { } [System.CLSCompliantAttribute(false)] protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { } public void Write<T>(string? eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { } public void Write<T>(string? eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { } public void Write<T>(string? eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { } public void Write<T>(string? eventName, T data) { } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] protected internal partial struct EventData { private int _dummyPrimitive; public System.IntPtr DataPointer { get { throw null; } set { } } public int Size { get { throw null; } set { } } } } [System.AttributeUsageAttribute(System.AttributeTargets.Class)] public sealed partial class EventSourceAttribute : System.Attribute { public EventSourceAttribute() { } public string? Guid { get { throw null; } set { } } public string? LocalizationResources { get { throw null; } set { } } public string? Name { get { throw null; } set { } } } public partial class EventSourceCreatedEventArgs : System.EventArgs { public EventSourceCreatedEventArgs() { } public System.Diagnostics.Tracing.EventSource? EventSource { get { throw null; } } } public partial class EventSourceException : System.Exception { public EventSourceException() { } protected EventSourceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public EventSourceException(string? message) { } public EventSourceException(string? message, System.Exception? innerException) { } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct EventSourceOptions { private int _dummyPrimitive; public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } } public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } } public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } } } [System.FlagsAttribute] public enum EventSourceSettings { Default = 0, ThrowOnEventWriteErrors = 1, EtwManifestEventFormat = 4, EtwSelfDescribingEventFormat = 8, } [System.FlagsAttribute] public enum EventTags { None = 0, } public enum EventTask { None = 0, } public partial class EventWrittenEventArgs : System.EventArgs { internal EventWrittenEventArgs() { } public System.Guid ActivityId { get { throw null; } } public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } } public int EventId { get { throw null; } } public string? EventName { get { throw null; } } public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } } public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } } public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } } public string? Message { get { throw null; } } public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } } public long OSThreadId { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection<object?>? Payload { get { throw null; } } public System.Collections.ObjectModel.ReadOnlyCollection<string>? PayloadNames { get { throw null; } } public System.Guid RelatedActivityId { get { throw null; } } public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } } public System.Diagnostics.Tracing.EventTask Task { get { throw null; } } public System.DateTime TimeStamp { get { throw null; } } public byte Version { get { throw null; } } } [System.AttributeUsageAttribute(System.AttributeTargets.Method)] public sealed partial class NonEventAttribute : System.Attribute { public NonEventAttribute() { } } }
// // CTFontDescriptor.cs: Implements the managed CTFontDescriptor // // Authors: Mono Team // Marek Safar (marek.safar@gmail.com) // // Copyright 2010 Novell, Inc // Copyright 2011, 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; using MonoMac.CoreFoundation; using MonoMac.CoreGraphics; using MonoMac.Foundation; namespace MonoMac.CoreText { [Since (3,2)] public enum CTFontOrientation : uint { Default = 0, Horizontal = 1, Vertical = 2, } [Since (3,2)] public enum CTFontFormat : uint { Unrecognized = 0, OpenTypePostScript = 1, OpenTypeTrueType = 2, TrueType = 3, PostScript = 4, Bitmap = 5, } [Since (3,2)] public enum CTFontPriority : uint { System = 10000, Network = 20000, Computer = 30000, User = 40000, Dynamic = 50000, Process = 60000, } public enum CTFontDescriptorMatchingState : uint { Started, Finished, WillBeginQuerying, Stalled, WillBeginDownloading, Downloading, DownloadingFinished, Matched, FailedWithError } [Since (3,2)] public static class CTFontDescriptorAttributeKey { public static readonly NSString Url; public static readonly NSString Name; public static readonly NSString DisplayName; public static readonly NSString FamilyName; public static readonly NSString StyleName; public static readonly NSString Traits; public static readonly NSString Variation; public static readonly NSString Size; public static readonly NSString Matrix; public static readonly NSString CascadeList; public static readonly NSString CharacterSet; public static readonly NSString Languages; public static readonly NSString BaselineAdjust; public static readonly NSString MacintoshEncodings; public static readonly NSString Features; public static readonly NSString FeatureSettings; public static readonly NSString FixedAdvance; public static readonly NSString FontOrientation; public static readonly NSString FontFormat; public static readonly NSString RegistrationScope; public static readonly NSString Priority; public static readonly NSString Enabled; static CTFontDescriptorAttributeKey () { var handle = Dlfcn.dlopen (Constants.CoreTextLibrary, 0); if (handle == IntPtr.Zero) return; try { Url = Dlfcn.GetStringConstant (handle, "kCTFontURLAttribute"); Name = Dlfcn.GetStringConstant (handle, "kCTFontNameAttribute"); DisplayName = Dlfcn.GetStringConstant (handle, "kCTFontDisplayNameAttribute"); FamilyName = Dlfcn.GetStringConstant (handle, "kCTFontFamilyNameAttribute"); StyleName = Dlfcn.GetStringConstant (handle, "kCTFontStyleNameAttribute"); Traits = Dlfcn.GetStringConstant (handle, "kCTFontTraitsAttribute"); Variation = Dlfcn.GetStringConstant (handle, "kCTFontVariationAttribute"); Size = Dlfcn.GetStringConstant (handle, "kCTFontSizeAttribute"); Matrix = Dlfcn.GetStringConstant (handle, "kCTFontMatrixAttribute"); CascadeList = Dlfcn.GetStringConstant (handle, "kCTFontCascadeListAttribute"); CharacterSet = Dlfcn.GetStringConstant (handle, "kCTFontCharacterSetAttribute"); Languages = Dlfcn.GetStringConstant (handle, "kCTFontLanguagesAttribute"); BaselineAdjust = Dlfcn.GetStringConstant (handle, "kCTFontBaselineAdjustAttribute"); MacintoshEncodings = Dlfcn.GetStringConstant (handle, "kCTFontMacintoshEncodingsAttribute"); Features = Dlfcn.GetStringConstant (handle, "kCTFontFeaturesAttribute"); FeatureSettings = Dlfcn.GetStringConstant (handle, "kCTFontFeatureSettingsAttribute"); FixedAdvance = Dlfcn.GetStringConstant (handle, "kCTFontFixedAdvanceAttribute"); FontOrientation = Dlfcn.GetStringConstant (handle, "kCTFontOrientationAttribute"); FontFormat = Dlfcn.GetStringConstant (handle, "kCTFontFormatAttribute"); RegistrationScope = Dlfcn.GetStringConstant (handle, "kCTFontRegistrationScopeAttribute"); Priority = Dlfcn.GetStringConstant (handle, "kCTFontPriorityAttribute"); Enabled = Dlfcn.GetStringConstant (handle, "kCTFontEnabledAttribute"); } finally { Dlfcn.dlclose (handle); } } } [Since (3,2)] public class CTFontDescriptorAttributes { public CTFontDescriptorAttributes () : this (new NSMutableDictionary ()) { } public CTFontDescriptorAttributes (NSDictionary dictionary) { if (dictionary == null) throw new ArgumentNullException ("dictionary"); Dictionary = dictionary; } public NSDictionary Dictionary {get; private set;} public NSUrl Url { get {return (NSUrl) Dictionary [CTFontDescriptorAttributeKey.Url];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Url, value);} } public string Name { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.Name);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Name, value);} } public string DisplayName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.DisplayName, value);} } public string FamilyName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FamilyName, value);} } public string StyleName { get {return Adapter.GetStringValue (Dictionary, CTFontDescriptorAttributeKey.StyleName);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.StyleName, value);} } public CTFontTraits Traits { get { var traits = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Traits]; if (traits == null) return null; return new CTFontTraits (traits); } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Traits, value == null ? null : value.Dictionary); } } public CTFontVariation Variation { get { var variation = (NSDictionary) Dictionary [CTFontDescriptorAttributeKey.Variation]; return variation == null ? null : new CTFontVariation (variation); } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Variation, value == null ? null : value.Dictionary); } } public float? Size { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.Size);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Size, value);} } public unsafe CGAffineTransform? Matrix { get { var d = (NSData) Dictionary [CTFontDescriptorAttributeKey.Matrix]; if (d == null) return null; return (CGAffineTransform) Marshal.PtrToStructure (d.Bytes, typeof (CGAffineTransform)); } set { if (!value.HasValue) Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, (NSObject) null); else { byte[] data = new byte [Marshal.SizeOf (typeof (CGAffineTransform))]; fixed (byte* p = data) { Marshal.StructureToPtr (value.Value, (IntPtr) p, false); } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Matrix, NSData.FromArray (data)); } } } public IEnumerable<CTFontDescriptor> CascadeList { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.CascadeList, d => new CTFontDescriptor (d, false)); } set {Adapter.SetNativeValue (Dictionary, CTFontDescriptorAttributeKey.CascadeList, value);} } public NSCharacterSet CharacterSet { get {return (NSCharacterSet) Dictionary [CTFontDescriptorAttributeKey.CharacterSet];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.CharacterSet, value);} } public IEnumerable<string> Languages { get {return Adapter.GetStringArray (Dictionary, CTFontDescriptorAttributeKey.Languages);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Languages, value);} } public float? BaselineAdjust { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.BaselineAdjust, value);} } public float? MacintoshEncodings { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.MacintoshEncodings, value);} } public IEnumerable<CTFontFeatures> Features { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features, d => new CTFontFeatures ((NSDictionary) Runtime.GetNSObject (d))); } set { List<CTFontFeatures> v; if (value == null || (v = new List<CTFontFeatures> (value)).Count == 0) { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null); return; } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary))); } } public IEnumerable<CTFontFeatureSettings> FeatureSettings { get { return Adapter.GetNativeArray (Dictionary, CTFontDescriptorAttributeKey.Features, d => new CTFontFeatureSettings ((NSDictionary) Runtime.GetNSObject (d))); } set { List<CTFontFeatureSettings> v; if (value == null || (v = new List<CTFontFeatureSettings> (value)).Count == 0) { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Features, (NSObject) null); return; } Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FeatureSettings, NSArray.FromNSObjects (v.ConvertAll (e => (NSObject) e.Dictionary))); } } public float? FixedAdvance { get {return Adapter.GetSingleValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance);} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FixedAdvance, value);} } public CTFontOrientation? FontOrientation { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontOrientation); return !value.HasValue ? null : (CTFontOrientation?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontOrientation, value.HasValue ? (uint?) value.Value : null); } } public CTFontFormat? FontFormat { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.FontFormat); return !value.HasValue ? null : (CTFontFormat?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.FontFormat, value.HasValue ? (uint?) value.Value : null); } } // TODO: docs mention CTFontManagerScope values, but I don't see any such enumeration. public NSNumber RegistrationScope { get {return (NSNumber) Dictionary [CTFontDescriptorAttributeKey.RegistrationScope];} set {Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.RegistrationScope, value);} } public CTFontPriority? Priority { get { var value = Adapter.GetUInt32Value (Dictionary, CTFontDescriptorAttributeKey.Priority); return !value.HasValue ? null : (CTFontPriority?) value.Value; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Priority, value.HasValue ? (uint?) value.Value : null); } } public bool Enabled { get { var value = (NSNumber) Dictionary [CTFontDescriptorAttributeKey.Enabled]; if (value == null) return false; return value.Int32Value != 0; } set { Adapter.SetValue (Dictionary, CTFontDescriptorAttributeKey.Enabled, value ? new NSNumber (1) : null); } } } [Since (3,2)] public class CTFontDescriptor : INativeObject, IDisposable { internal IntPtr handle; internal CTFontDescriptor (IntPtr handle) : this (handle, false) { } internal CTFontDescriptor (IntPtr handle, bool owns) { if (handle == IntPtr.Zero) throw ConstructorError.ArgumentNull (this, "handle"); this.handle = handle; if (!owns) CFObject.CFRetain (handle); } ~CTFontDescriptor () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } public IntPtr Handle { get {return handle;} } protected virtual void Dispose (bool disposing) { if (handle != IntPtr.Zero){ CFObject.CFRelease (handle); handle = IntPtr.Zero; } } #region Descriptor Creation [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateWithNameAndSize (IntPtr name, float size); public CTFontDescriptor (string name, float size) { if (name == null) throw ConstructorError.ArgumentNull (this, "name"); using (CFString n = name) handle = CTFontDescriptorCreateWithNameAndSize (n.Handle, size); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateWithAttributes (IntPtr attributes); public CTFontDescriptor (CTFontDescriptorAttributes attributes) { if (attributes == null) throw ConstructorError.ArgumentNull (this, "attributes"); handle = CTFontDescriptorCreateWithAttributes (attributes.Dictionary.Handle); if (handle == IntPtr.Zero) throw ConstructorError.Unknown (this); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithAttributes (IntPtr original, IntPtr attributes); public CTFontDescriptor WithAttributes (NSDictionary attributes) { if (attributes == null) throw new ArgumentNullException ("attributes"); return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Handle)); } static CTFontDescriptor CreateDescriptor (IntPtr h) { if (h == IntPtr.Zero) return null; return new CTFontDescriptor (h, true); } public CTFontDescriptor WithAttributes (CTFontDescriptorAttributes attributes) { if (attributes == null) throw new ArgumentNullException ("attributes"); return CreateDescriptor (CTFontDescriptorCreateCopyWithAttributes (handle, attributes.Dictionary.Handle)); } // TODO: is there a better type to use for variationIdentifier? // uint perhaps? "This is the four character code of the variation axis" [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithVariation (IntPtr original, IntPtr variationIdentifier, float variationValue); public CTFontDescriptor WithVariation (uint variationIdentifier, float variationValue) { using (var id = new NSNumber (variationIdentifier)) return CreateDescriptor (CTFontDescriptorCreateCopyWithVariation (handle, id.Handle, variationValue)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateCopyWithFeature (IntPtr original, IntPtr featureTypeIdentifier, IntPtr featureSelectorIdentifier); [Obsolete] public CTFontDescriptor WithFeature (NSNumber featureTypeIdentifier, NSNumber featureSelectorIdentifier) { if (featureTypeIdentifier == null) throw new ArgumentNullException ("featureTypeIdentifier"); if (featureSelectorIdentifier == null) throw new ArgumentNullException ("featureSelectorIdentifier"); return CreateDescriptor (CTFontDescriptorCreateCopyWithFeature (handle, featureTypeIdentifier.Handle, featureSelectorIdentifier.Handle)); } public CTFontDescriptor WithFeature (CTFontFeatureAllTypographicFeatures.Selector featureSelector) { return WithFeature (FontFeatureGroup.AllTypographicFeatures, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureLigatures.Selector featureSelector) { return WithFeature (FontFeatureGroup.Ligatures, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCursiveConnection.Selector featureSelector) { return WithFeature (FontFeatureGroup.CursiveConnection, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureLetterCase.Selector featureSelector) { return WithFeature (FontFeatureGroup.LetterCase, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureVerticalSubstitutionConnection.Selector featureSelector) { return WithFeature (FontFeatureGroup.VerticalSubstitution, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureLinguisticRearrangementConnection.Selector featureSelector) { return WithFeature (FontFeatureGroup.LinguisticRearrangement, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureNumberSpacing.Selector featureSelector) { return WithFeature (FontFeatureGroup.NumberSpacing, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureSmartSwash.Selector featureSelector) { return WithFeature (FontFeatureGroup.SmartSwash, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureDiacritics.Selector featureSelector) { return WithFeature (FontFeatureGroup.Diacritics, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureVerticalPosition.Selector featureSelector) { return WithFeature (FontFeatureGroup.VerticalPosition, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureFractions.Selector featureSelector) { return WithFeature (FontFeatureGroup.Fractions, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureOverlappingCharacters.Selector featureSelector) { return WithFeature (FontFeatureGroup.OverlappingCharacters, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureTypographicExtras.Selector featureSelector) { return WithFeature (FontFeatureGroup.TypographicExtras, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureMathematicalExtras.Selector featureSelector) { return WithFeature (FontFeatureGroup.MathematicalExtras, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureOrnamentSets.Selector featureSelector) { return WithFeature (FontFeatureGroup.OrnamentSets, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCharacterAlternatives.Selector featureSelector) { return WithFeature (FontFeatureGroup.CharacterAlternatives, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureDesignComplexity.Selector featureSelector) { return WithFeature (FontFeatureGroup.DesignComplexity, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureStyleOptions.Selector featureSelector) { return WithFeature (FontFeatureGroup.StyleOptions, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCharacterShape.Selector featureSelector) { return WithFeature (FontFeatureGroup.CharacterShape, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureNumberCase.Selector featureSelector) { return WithFeature (FontFeatureGroup.NumberCase, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureTextSpacing.Selector featureSelector) { return WithFeature (FontFeatureGroup.TextSpacing, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureTransliteration.Selector featureSelector) { return WithFeature (FontFeatureGroup.Transliteration, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureAnnotation.Selector featureSelector) { return WithFeature (FontFeatureGroup.Annotation, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureKanaSpacing.Selector featureSelector) { return WithFeature (FontFeatureGroup.KanaSpacing, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureIdeographicSpacing.Selector featureSelector) { return WithFeature (FontFeatureGroup.IdeographicSpacing, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureUnicodeDecomposition.Selector featureSelector) { return WithFeature (FontFeatureGroup.UnicodeDecomposition, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureRubyKana.Selector featureSelector) { return WithFeature (FontFeatureGroup.RubyKana, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCJKSymbolAlternatives.Selector featureSelector) { return WithFeature (FontFeatureGroup.CJKSymbolAlternatives, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureIdeographicAlternatives.Selector featureSelector) { return WithFeature (FontFeatureGroup.IdeographicAlternatives, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCJKVerticalRomanPlacement.Selector featureSelector) { return WithFeature (FontFeatureGroup.CJKVerticalRomanPlacement, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureItalicCJKRoman.Selector featureSelector) { return WithFeature (FontFeatureGroup.ItalicCJKRoman, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCaseSensitiveLayout.Selector featureSelector) { return WithFeature (FontFeatureGroup.CaseSensitiveLayout, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureAlternateKana.Selector featureSelector) { return WithFeature (FontFeatureGroup.AlternateKana, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureStylisticAlternatives.Selector featureSelector) { return WithFeature (FontFeatureGroup.StylisticAlternatives, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureContextualAlternates.Selector featureSelector) { return WithFeature (FontFeatureGroup.ContextualAlternates, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureLowerCase.Selector featureSelector) { return WithFeature (FontFeatureGroup.LowerCase, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureUpperCase.Selector featureSelector) { return WithFeature (FontFeatureGroup.UpperCase, (int) featureSelector); } public CTFontDescriptor WithFeature (CTFontFeatureCJKRomanSpacing.Selector featureSelector) { return WithFeature (FontFeatureGroup.CJKRomanSpacing, (int) featureSelector); } CTFontDescriptor WithFeature (FontFeatureGroup featureGroup, int featureSelector) { using (NSNumber t = new NSNumber ((int) featureGroup), f = new NSNumber (featureSelector)) { return CreateDescriptor (CTFontDescriptorCreateCopyWithFeature (handle, t.Handle, f.Handle)); } } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptors (IntPtr descriptor, IntPtr mandatoryAttributes); public CTFontDescriptor[] GetMatchingFontDescriptors (NSSet mandatoryAttributes) { var cfArrayRef = CTFontDescriptorCreateMatchingFontDescriptors (handle, mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle); if (cfArrayRef == IntPtr.Zero) return new CTFontDescriptor [0]; var matches = NSArray.ArrayFromHandle (cfArrayRef, fd => new CTFontDescriptor (cfArrayRef, false)); CFObject.CFRelease (cfArrayRef); return matches; } public CTFontDescriptor[] GetMatchingFontDescriptors (params NSString[] mandatoryAttributes) { NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes); return GetMatchingFontDescriptors (attrs); } public CTFontDescriptor[] GetMatchingFontDescriptors () { NSSet attrs = null; return GetMatchingFontDescriptors (attrs); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCreateMatchingFontDescriptor (IntPtr descriptor, IntPtr mandatoryAttributes); public CTFontDescriptor GetMatchingFontDescriptor (NSSet mandatoryAttributes) { return CreateDescriptor (CTFontDescriptorCreateMatchingFontDescriptors (handle, mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle)); } public CTFontDescriptor GetMatchingFontDescriptor (params NSString[] mandatoryAttributes) { NSSet attrs = NSSet.MakeNSObjectSet (mandatoryAttributes); return GetMatchingFontDescriptor (attrs); } public CTFontDescriptor GetMatchingFontDescriptor () { NSSet attrs = null; return GetMatchingFontDescriptor (attrs); } #endregion #region Descriptor Accessors [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyAttributes (IntPtr descriptor); public CTFontDescriptorAttributes GetAttributes() { var cfDictRef = CTFontDescriptorCopyAttributes (handle); if (cfDictRef == IntPtr.Zero) return null; var dict = (NSDictionary) Runtime.GetNSObject (cfDictRef); dict.Release (); return new CTFontDescriptorAttributes (dict); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyAttribute (IntPtr descriptor, IntPtr attribute); public NSObject GetAttribute (NSString attribute) { if (attribute == null) throw new ArgumentNullException ("attribute"); return Runtime.GetNSObject (CTFontDescriptorCopyAttribute (handle, attribute.Handle)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, IntPtr language); public NSObject GetLocalizedAttribute (NSString attribute) { return Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, IntPtr.Zero)); } [DllImport (Constants.CoreTextLibrary)] static extern IntPtr CTFontDescriptorCopyLocalizedAttribute (IntPtr descriptor, IntPtr attribute, out IntPtr language); public NSObject GetLocalizedAttribute (NSString attribute, out NSString language) { IntPtr lang; var o = Runtime.GetNSObject (CTFontDescriptorCopyLocalizedAttribute (handle, attribute.Handle, out lang)); language = (NSString) Runtime.GetNSObject (lang); if (lang != IntPtr.Zero) CFObject.CFRelease (lang); return o; } #endregion [DllImport (Constants.CoreTextLibrary)] static extern bool CTFontDescriptorMatchFontDescriptorsWithProgressHandler (IntPtr descriptors, IntPtr mandatoryAttributes, Func<CTFontDescriptorMatchingState, IntPtr, bool> progressHandler); [Since (6,0)] public static bool MatchFontDescriptors (CTFontDescriptor[] descriptors, NSSet mandatoryAttributes, Func<CTFontDescriptorMatchingState, IntPtr, bool> progressHandler) { var ma = mandatoryAttributes == null ? IntPtr.Zero : mandatoryAttributes.Handle; // FIXME: SIGSEGV probably due to mandatoryAttributes mismatch using (var ar = CFArray.FromNativeObjects (descriptors)) { return CTFontDescriptorMatchFontDescriptorsWithProgressHandler (ar.Handle, ma, progressHandler); } } } }
using System; using System.Collections; using System.Collections.Generic; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.Symbology; using gView.Framework.UI; using gView.Framework.IO; using gView.Framework.system; using gView.MapServer; using System.IO; namespace gView.Framework.Carto { public enum DrawPhase { All = 7, Geography = 4, Selection = 2, Graphics = 1 } //public delegate void DatasetAddedEvent(IMap sender,IDataset dataset); public delegate void LayerAddedEvent(IMap sender, ILayer layer); public delegate void LayerRemovedEvent(IMap sender, ILayer layer); public delegate void NewBitmapEvent(System.Drawing.Image image); public delegate void DoRefreshMapViewEvent(); public delegate void StartRefreshMapEvent(IMap sender); public delegate void DrawingLayerEvent(string layerName); public delegate void TOCChangedEvent(IMap sender); public delegate void NewExtentRenderedEvent(IMap sender, IEnvelope extent); public delegate void DrawingLayerFinishedEvent(IMap sender, ITimeEvent timeEvent); public interface IMap : IDisposable, IClone, IMetadata, IDataCopyright { event LayerAddedEvent LayerAdded; event LayerRemovedEvent LayerRemoved; event NewBitmapEvent NewBitmap; event DoRefreshMapViewEvent DoRefreshMapView; event DrawingLayerEvent DrawingLayer; event TOCChangedEvent TOCChanged; event NewExtentRenderedEvent NewExtentRendered; event DrawingLayerFinishedEvent DrawingLayerFinished; event StartRefreshMapEvent StartRefreshMap; event EventHandler MapRenamed; void AddDataset(IDataset dataset, int order); void RemoveDataset(IDataset dataset); void RemoveAllDatasets(); void AddLayer(ILayer layer); void AddLayer(ILayer layer, int pos); void RemoveLayer(ILayer layer); IDataset this[int datasetIndex] { get; } IDataset this[IDatasetElement element] { get; } IEnumerable<IDataset> Datasets { get; } string Name { get; set; } List<IDatasetElement> Elements(string aliasname); List<IDatasetElement> MapElements { get; } List<IDatasetElement> ActiveLayers { get; } IDatasetElement DatasetElementByClass(IClass cls); string ActiveLayerNames { get; set; } void ClearSelection(); ITOC TOC { get; } bool RefreshMap(DrawPhase phase, ICancelTracker cancelTracker); ISelectionEnvironment SelectionEnvironment { get; } void HighlightGeometry(IGeometry geometry, int milliseconds); IDisplay Display { get; } void Release(); ISpatialReference LayerDefaultSpatialReference { get; set; } void Compress(); } /* public interface IDataView { string Name { get; set; } IMap Map { get; set; } } */ //public delegate bool LayerIsVisibleHook(string layername,bool defaultValue); public delegate void BeforeRenderLayersEvent(IServiceMap sender, List<ILayer> layers); public interface IServiceMap : IMetadata, IServiceRequestContext, IDisposable { //event LayerIsVisibleHook OverrideLayerIsVisible; event BeforeRenderLayersEvent BeforeRenderLayers; string Name { get; } IDisplay Display { get; } ITOC TOC { get; } List<IDatasetElement> MapElements { get; } void Release(); bool Render(); System.Drawing.Bitmap Legend(); System.Drawing.Bitmap MapImage { get; } bool SaveImage(string path, System.Drawing.Imaging.ImageFormat format); bool SaveImage(Stream ms, System.Drawing.Imaging.ImageFormat format); void ReleaseImage(); float ScaleSymbolFactor { get; set; } } public delegate void MapScaleChangedEvent(IDisplay sender); public delegate void RenderOverlayImageEvent(System.Drawing.Bitmap image, bool clearOld); // Projective > 0 // Geographic < 0 public enum GeoUnits { Unknown = 0, Inches = 1, Feet = 2, Yards = 3, Miles = 4, NauticalMiles = 5, Millimeters = 6, Centimeters = 7, Decimeters = 8, Meters = 9, Kilometers = 10, DecimalDegrees = -1, DegreesMinutesSeconds = -2 } public interface IDisplay { event MapScaleChangedEvent MapScaleChanged; event RenderOverlayImageEvent RenderOverlayImage; IEnvelope Envelope { get; } IEnvelope Limit { get; set; } void ZoomTo(IEnvelope envelope); double refScale { get; set; } double mapScale { get; set; } int iWidth { get; set; } int iHeight { get; set; } double dpm { get; } double dpi { get; set; } System.Drawing.Image Bitmap { get; } System.Drawing.Graphics GraphicsContext { get; } System.Drawing.Color BackgroundColor { get; set; } System.Drawing.Color TransparentColor { get; set; } bool MakeTransparent { get; set; } void World2Image(ref double x, ref double y); void Image2World(ref double x, ref double y); ISpatialReference SpatialReference { get; set; } IGeometricTransformer GeometricTransformer { get; set; } void Draw(ISymbol symbol, IGeometry geometry); void DrawOverlay(IGraphicsContainer container, bool clearOld); void ClearOverlay(); IGraphicsContainer GraphicsContainer { get; } ILabelEngine LabelEngine { get; } GeoUnits MapUnits { get; set; } GeoUnits DisplayUnits { get; set; } IScreen Screen { get; } IMap Map { get; } IDisplayTransformation DisplayTransformation { get; } } public interface IDisplayTransformation { bool UseTransformation { get; } double DisplayRotation { get; set; } void Transform(IDisplay display, ref double x, ref double y); void InvTransform(IDisplay display, ref double x, ref double y); IEnvelope TransformedBounds(IDisplay display); } public interface IScreen { float LargeFontsFactor { get; } } public enum LabelAppendResult { Succeeded = 0, Overlap = 1, Outside = 2, WrongArguments = 3 } public interface ILabelEngine { void Init(IDisplay display, bool directDraw); LabelAppendResult TryAppend(IDisplay display, ITextSymbol symbol, IGeometry geometry, bool chechForOverlap); LabelAppendResult TryAppend(IDisplay display, List<IAnnotationPolygonCollision> aPolygons, IGeometry geometry, bool checkForOverlap); void Draw(IDisplay display, ICancelTracker cancelTracker); void Release(); System.Drawing.Graphics LabelGraphicsContext { get; } } public interface ISmartLabelPoint : IPoint { IMultiPoint AlernativeLabelPoints(IDisplay display); } public interface IGraphicElementList : IEnumerable<IGraphicElement> { void Add(IGraphicElement element); void Remove(IGraphicElement element); void Clear(); void Insert(int i, IGraphicElement element); bool Contains(IGraphicElement element); int Count { get; } IGraphicElement this[int i] { get; } IGraphicElementList Clone(); IGraphicElementList Swap(); } public enum GrabberMode { Pointer, Vertex } public interface IGraphicsContainer { event EventHandler SelectionChanged; IGraphicElementList Elements { get; } IGraphicElementList SelectedElements { get; } GrabberMode EditMode { get; set; } } public interface IGraphicElement { void Draw(IDisplay display); } public interface HitPositions { object Cursor { get; } int HitID { get; } } public interface IGraphicsElementDesigning { //bool Selected { get; set; } IGraphicElement2 Ghost { get; } HitPositions HitTest(IDisplay display, IPoint point); void Design(IDisplay display, HitPositions hit, double dx, double dy); bool TrySelect(IDisplay display, IEnvelope envelope); bool TrySelect(IDisplay display, IPoint point); bool RemoveVertex(IDisplay display, int index); bool AddVertex(IDisplay display, IPoint point); } public interface IGraphicElement2 : IGraphicElement, IGraphicsElementScaling, IGraphicsElementRotation, IIGraphicsElementTranslation, IGraphicsElementDesigning { string Name { get; } System.Drawing.Image Icon { get; } ISymbol Symbol { get; set; } void DrawGrabbers(IDisplay display); IGeometry Geometry { get; } } public interface IGraphicsElementScaling { void Scale(double scaleX, double scaleY); void ScaleX(double scale); void ScaleY(double scale); } public interface IGraphicsElementRotation { double Rotation { get; set; } } public interface IIGraphicsElementTranslation { void Translation(double x, double y); } public interface IRenderer { List<ISymbol> Symbols { get; } bool Combine(IRenderer renderer); } /// <summary> /// Porvide access to members and properties that control the functionality of renderers. /// </summary> public interface IFeatureRenderer : IRenderer, IPersistable, IClone, IClone2 { /// <summary> /// Draws features from the specified Featurecursor on the given display. /// </summary> /// <param name="disp"></param> /// <param name="fCursor"></param> /// <param name="drawPhase"></param> /// <param name="cancelTracker"></param> //void Draw(IDisplay disp,IFeatureCursor fCursor,DrawPhase drawPhase,ICancelTracker cancelTracker); void Draw(IDisplay disp, IFeature feature); void FinishDrawing(IDisplay disp, ICancelTracker cancelTracker); /// <summary> /// Prepares the query filter for the rendering process. /// </summary> /// <remarks> /// </remarks> /// This member is called by the framework befor querying the features. /// <param name="layer"></param> /// <param name="filter">The filter for querying the features</param> void PrepareQueryFilter(IFeatureLayer layer, IQueryFilter filter); /// <summary> /// Indicates if the specified feature class can be rendered on the given display. /// </summary> /// <param name="layer"></param> /// <param name="map"></param> /// <returns></returns> bool CanRender(IFeatureLayer layer, IMap map); bool HasEffect(IFeatureLayer layer, IMap map); bool UseReferenceScale { get; set; } /// <summary> /// The name of the renderer. /// </summary> string Name { get; } /// <summary> /// The category for the renderer. /// </summary> string Category { get; } } public interface IFeatureRenderer2 : IFeatureRenderer { ISymbol Symbol { get; set; } } public enum LabelRenderMode { RenderWithFeature, UseRenderPriority } public interface ILabelRenderer : IRenderer, IPersistable, IClone, IClone2 { void PrepareQueryFilter(IDisplay display, IFeatureLayer layer, IQueryFilter filter); bool CanRender(IFeatureLayer layer, IMap map); string Name { get; } LabelRenderMode RenderMode { get; } int RenderPriority { get; } void Draw(IDisplay disp, IFeature feature); } }
/* * 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 OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using System; using System.Collections.Specialized; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Reflection; using System.Web; namespace OpenSim.Capabilities.Handlers { public class GetTextureHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_assetService; public const string DefaultFormat = "x-j2c"; // TODO: Change this to a config option private string m_RedirectURL = null; public GetTextureHandler(string path, IAssetService assService, string name, string description, string redirectURL) : base("GET", path, name, description) { m_assetService = assService; m_RedirectURL = redirectURL; if (m_RedirectURL != null && !m_RedirectURL.EndsWith("/")) m_RedirectURL += "/"; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Try to parse the texture ID from the request URL NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query); string textureStr = query.GetOne("texture_id"); string format = query.GetOne("format"); //m_log.DebugFormat("[GETTEXTURE]: called {0}", textureStr); if (m_assetService == null) { m_log.Error("[GETTEXTURE]: Cannot fetch texture " + textureStr + " without an asset service"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; } UUID textureID; if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID)) { // m_log.DebugFormat("[GETTEXTURE]: Received request for texture id {0}", textureID); string[] formats; if (!string.IsNullOrEmpty(format)) { formats = new string[1] { format.ToLower() }; } else { formats = WebUtil.GetPreferredImageTypes(httpRequest.Headers.Get("Accept")); if (formats.Length == 0) formats = new string[1] { DefaultFormat }; // default } // OK, we have an array with preferred formats, possibly with only one entry httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; foreach (string f in formats) { if (FetchTexture(httpRequest, httpResponse, textureID, f)) break; } } else { m_log.Warn("[GETTEXTURE]: Failed to parse a texture_id from GetTexture request: " + httpRequest.Url); } // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} sending back response {1}, data length {2}", // textureID, httpResponse.StatusCode, httpResponse.ContentLength); return null; } /// <summary> /// /// </summary> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <param name="textureID"></param> /// <param name="format"></param> /// <returns>False for "caller try another codec"; true otherwise</returns> private bool FetchTexture(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse, UUID textureID, string format) { // m_log.DebugFormat("[GETTEXTURE]: {0} with requested format {1}", textureID, format); AssetBase texture; string fullID = textureID.ToString(); if (format != DefaultFormat) fullID = fullID + "-" + format; if (!String.IsNullOrEmpty(m_RedirectURL)) { // Only try to fetch locally cached textures. Misses are redirected texture = m_assetService.GetCached(fullID); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } WriteTextureData(httpRequest, httpResponse, texture, format); } else { string textureUrl = m_RedirectURL + "?texture_id="+ textureID.ToString(); m_log.Debug("[GETTEXTURE]: Redirecting texture request to " + textureUrl); httpResponse.StatusCode = (int)OSHttpStatusCode.RedirectMovedPermanently; httpResponse.RedirectLocation = textureUrl; return true; } } else // no redirect { // try the cache texture = m_assetService.GetCached(fullID); if (texture == null) { // m_log.DebugFormat("[GETTEXTURE]: texture was not in the cache"); // Fetch locally or remotely. Misses return a 404 texture = m_assetService.Get(textureID.ToString()); if (texture != null) { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } if (format == DefaultFormat) { WriteTextureData(httpRequest, httpResponse, texture, format); return true; } else { AssetBase newTexture = new AssetBase(texture.ID + "-" + format, texture.Name, (sbyte)AssetType.Texture, texture.Metadata.CreatorID); newTexture.Data = ConvertTextureData(texture, format); if (newTexture.Data.Length == 0) return false; // !!! Caller try another codec, please! newTexture.Flags = AssetFlags.Collectable; newTexture.Temporary = true; newTexture.Local = true; m_assetService.Store(newTexture); WriteTextureData(httpRequest, httpResponse, newTexture, format); return true; } } } else // it was on the cache { if (texture.Type != (sbyte)AssetType.Texture) { httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } // m_log.DebugFormat("[GETTEXTURE]: texture was in the cache"); WriteTextureData(httpRequest, httpResponse, texture, format); return true; } } // not found // m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; } private void WriteTextureData(IOSHttpRequest request, IOSHttpResponse response, AssetBase texture, string format) { string range = request.Headers.GetOne("Range"); if (!String.IsNullOrEmpty(range)) // JP2's only { // Range request int start, end; if (TryParseRange(range, out start, out end)) { // Before clamping start make sure we can satisfy it in order to avoid // sending back the last byte instead of an error status if (start >= texture.Data.Length) { // m_log.DebugFormat( // "[GETTEXTURE]: Client requested range for texture {0} starting at {1} but texture has end of {2}", // texture.ID, start, texture.Data.Length); // Stricly speaking, as per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, we should be sending back // Requested Range Not Satisfiable (416) here. However, it appears that at least recent implementations // of the Linden Lab viewer (3.2.1 and 3.3.4 and probably earlier), a viewer that has previously // received a very small texture may attempt to fetch bytes from the server past the // range of data that it received originally. Whether this happens appears to depend on whether // the viewer's estimation of how large a request it needs to make for certain discard levels // (http://wiki.secondlife.com/wiki/Image_System#Discard_Level_and_Mip_Mapping), chiefly discard // level 2. If this estimate is greater than the total texture size, returning a RequestedRangeNotSatisfiable // here will cause the viewer to treat the texture as bad and never display the full resolution // However, if we return PartialContent (or OK) instead, the viewer will display that resolution. // response.StatusCode = (int)System.Net.HttpStatusCode.RequestedRangeNotSatisfiable; // response.AddHeader("Content-Range", String.Format("bytes */{0}", texture.Data.Length)); // response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.ContentLength = texture.Data.Length; response.ContentType = texture.Metadata.ContentType; response.Body.Write(texture.Data, 0, texture.Data.Length); } else { // Handle the case where no second range value was given. This is equivalent to requesting // the rest of the entity. if (end == -1) end = int.MaxValue; end = Utils.Clamp(end, 0, texture.Data.Length - 1); start = Utils.Clamp(start, 0, end); int len = end - start + 1; if (0 == start && len == texture.Data.Length) { response.StatusCode = (int)System.Net.HttpStatusCode.OK; } else { response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.AddHeader("Content-Range", String.Format("bytes {0}-{1}/{2}", start, end, texture.Data.Length)); } response.ContentLength = len; response.ContentType = texture.Metadata.ContentType; response.Body.Write(texture.Data, start, len); } } else { m_log.Warn("[GETTEXTURE]: Malformed Range header: " + range); response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest; } } else // JP2's or other formats { // Full content request response.StatusCode = (int)System.Net.HttpStatusCode.OK; response.ContentLength = texture.Data.Length; if (format == DefaultFormat) response.ContentType = texture.Metadata.ContentType; else response.ContentType = "image/" + format; response.Body.Write(texture.Data, 0, texture.Data.Length); } // if (response.StatusCode < 200 || response.StatusCode > 299) // m_log.WarnFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); // else // m_log.DebugFormat( // "[GETTEXTURE]: For texture {0} requested range {1} responded {2} with content length {3} (actual {4})", // texture.FullID, range, response.StatusCode, response.ContentLength, texture.Data.Length); } /// <summary> /// Parse a range header. /// </summary> /// <remarks> /// As per http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html, /// this obeys range headers with two values (e.g. 533-4165) and no second value (e.g. 533-). /// Where there is no value, -1 is returned. /// FIXME: Need to cover the case where only a second value is specified (e.g. -4165), probably by returning -1 /// for start.</remarks> /// <returns></returns> /// <param name='header'></param> /// <param name='start'>Start of the range. Undefined if this was not a number.</param> /// <param name='end'>End of the range. Will be -1 if no end specified. Undefined if there was a raw string but this was not a number.</param> private bool TryParseRange(string header, out int start, out int end) { start = end = 0; if (header.StartsWith("bytes=")) { string[] rangeValues = header.Substring(6).Split('-'); if (rangeValues.Length == 2) { if (!Int32.TryParse(rangeValues[0], out start)) return false; string rawEnd = rangeValues[1]; if (rawEnd == "") { end = -1; return true; } else if (Int32.TryParse(rawEnd, out end)) { return true; } } } start = end = 0; return false; } private byte[] ConvertTextureData(AssetBase texture, string format) { m_log.DebugFormat("[GETTEXTURE]: Converting texture {0} to {1}", texture.ID, format); byte[] data = new byte[0]; MemoryStream imgstream = new MemoryStream(); Bitmap mTexture = new Bitmap(1, 1); ManagedImage managedImage; Image image = (Image)mTexture; try { // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular data imgstream = new MemoryStream(); // Decode image to System.Drawing.Image if (OpenJPEG.DecodeToImage(texture.Data, out managedImage, out image)) { // Save to bitmap mTexture = new Bitmap(image); EncoderParameters myEncoderParameters = new EncoderParameters(); myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L); // Save bitmap to stream ImageCodecInfo codec = GetEncoderInfo("image/" + format); if (codec != null) { mTexture.Save(imgstream, codec, myEncoderParameters); // Write the stream to a byte array for output data = imgstream.ToArray(); } else m_log.WarnFormat("[GETTEXTURE]: No such codec {0}", format); } } catch (Exception e) { m_log.WarnFormat("[GETTEXTURE]: Unable to convert texture {0} to {1}: {2}", texture.ID, format, e.Message); } finally { // Reclaim memory, these are unmanaged resources // If we encountered an exception, one or more of these will be null if (mTexture != null) mTexture.Dispose(); if (image != null) image.Dispose(); if (imgstream != null) { imgstream.Close(); imgstream.Dispose(); } } return data; } // From msdn private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Diagnostics { using System.Text; using System.Threading; using System; using System.Security; using System.Security.Permissions; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. [Serializable] internal class StackFrameHelper { [NonSerialized] private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; // this field is here only for backwards compatibility of serialization format private MethodBase[] rgMethodBase; #pragma warning disable 414 // Field is not used from managed. // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of StackFrameHelper. private Object dynamicMethods; #pragma warning restore 414 [NonSerialized] private IntPtr[] rgMethodHandle; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; #if FEATURE_EXCEPTIONDISPATCHINFO [OptionalField] private bool[] rgiLastFrameFromForeignExceptionStackTrace; #endif // FEATURE_EXCEPTIONDISPATCHINFO private int iFrameCount; private bool fNeedFileInfo; public StackFrameHelper(bool fNeedFileLineColInfo, Thread target) { targetThread = target; rgMethodBase = null; rgMethodHandle = null; rgiOffset = null; rgiILOffset = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; dynamicMethods = null; #if FEATURE_EXCEPTIONDISPATCHINFO rgiLastFrameFromForeignExceptionStackTrace = null; #endif // FEATURE_EXCEPTIONDISPATCHINFO // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; fNeedFileInfo = fNeedFileLineColInfo; } [System.Security.SecuritySafeCritical] public virtual MethodBase GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! IntPtr mh = rgMethodHandle[i]; if (mh.IsNull()) return null; IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } public virtual int GetOffset(int i) { return rgiOffset[i];} public virtual int GetILOffset(int i) { return rgiILOffset[i];} public virtual String GetFilename(int i) { return rgFilename[i];} public virtual int GetLineNumber(int i) { return rgiLineNumber[i];} public virtual int GetColumnNumber(int i) { return rgiColumnNumber[i];} #if FEATURE_EXCEPTIONDISPATCHINFO public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i) { return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i]; } #endif // FEATURE_EXCEPTIONDISPATCHINFO public virtual int GetNumberOfFrames() { return iFrameCount;} public virtual void SetNumberOfFrames(int i) { iFrameCount = i;} // // serialization implementation // [OnSerializing] [SecuritySafeCritical] void OnSerializing(StreamingContext context) { // this is called in the process of serializing this object. // For compatibility with Everett we need to assign the rgMethodBase field as that is the field // that will be serialized rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length]; if (rgMethodHandle != null) { for (int i = 0; i < rgMethodHandle.Length; i++) { if (!rgMethodHandle[i].IsNull()) rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this)); } } } [OnSerialized] void OnSerialized(StreamingContext context) { // after we are done serializing null the rgMethodBase field rgMethodBase = null; } [OnDeserialized] [SecuritySafeCritical] void OnDeserialized(StreamingContext context) { // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length]; if (rgMethodBase != null) { for (int i = 0; i < rgMethodBase.Length; i++) { if (rgMethodBase[i] != null) rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value; } } rgMethodBase = null; } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. // In order to ensure trusted code can trust the data it gets from a // StackTrace, we use an InheritanceDemand to prevent partially-trusted // subclasses. #if !FEATURE_CORECLR [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] #endif [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StackTrace { private StackFrame[] frames; private int m_iNumOfFrames; public const int METHODS_TO_SKIP = 0; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public StackTrace() { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(bool fNeedFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(int skipFrames) { if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(int skipFrames, bool fNeedFileInfo) { if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location. public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException("e"); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location. // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException("e"); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, int skipFrames) { if (e == null) throw new ArgumentNullException("e"); if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException("e"); if (skipFrames < 0) throw new ArgumentOutOfRangeException("skipFrames", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace(StackFrame frame) { frames = new StackFrame[1]; frames[0] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } // Constructs a stack trace for the given thread // #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")] public StackTrace(Thread targetThread, bool needFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null); } [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, Exception e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase(i); if (mb != null) { Type t = mb.DeclaringType; if (t == null) break; String ns = t.Namespace; if (ns == null) break; if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e) { m_iMethodsToSkip += iSkip; StackFrameHelper StackF = new StackFrameHelper(fNeedFileInfo, targetThread); GetStackFramesInternal(StackF, 0, e); m_iNumOfFrames = StackF.GetNumberOfFrames(); if (m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if (m_iNumOfFrames != 0) { frames = new StackFrame[m_iNumOfFrames]; for (int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame(fDummy1, fDummy2); sfTemp.SetMethodBase(StackF.GetMethodBase(i)); sfTemp.SetOffset(StackF.GetOffset(i)); sfTemp.SetILOffset(StackF.GetILOffset(i)); #if FEATURE_EXCEPTIONDISPATCHINFO sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i)); #endif // FEATURE_EXCEPTIONDISPATCHINFO if (fNeedFileInfo) { sfTemp.SetFileName(StackF.GetFilename (i)); sfTemp.SetLineNumber(StackF.GetLineNumber(i)); sfTemp.SetColumnNumber(StackF.GetColumnNumber(i)); } frames[i] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if (e == null) m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames); m_iNumOfFrames -= m_iMethodsToSkip; if (m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames;} } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame(int index) { if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) return frames[index+m_iMethodsToSkip]; return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // [ComVisible(false)] public virtual StackFrame [] GetFrames() { if (frames == null || m_iNumOfFrames <= 0) return null; // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame [] array = new StackFrame[m_iNumOfFrames]; Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames); return array; } // Builds a readable representation of the stack trace // #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public override String ToString() { // Include a trailing newline for backwards compatibility return ToString(TraceFormat.TrailingNewLine); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal String ToString(TraceFormat traceFormat) { bool displayFilenames = true; // we'll try, but demand may fail String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if(traceFormat != TraceFormat.NoResourceLookup) { word_At = Environment.GetResourceString("Word_At"); inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber"); } bool fFirstFrame = true; StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame(iFrameIndex); MethodBase mb = sf.GetMethod(); if (mb != null) { // We want a newline at the end of every line except for the last if (fFirstFrame) fFirstFrame = false; else sb.Append(Environment.NewLine); sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); Type t = mb.DeclaringType; // if there is a type (non global method) print it if (t != null) { sb.Append(t.FullName.Replace('+', '.')); sb.Append("."); } sb.Append(mb.Name); // deal with the generic portion of the method if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append("["); int k=0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(","); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append("]"); } // arguments printing sb.Append("("); ParameterInfo[] pi = mb.GetParameters(); bool fFirstParam = true; for (int j = 0; j < pi.Length; j++) { if (fFirstParam == false) sb.Append(", "); else fFirstParam = false; String typeName = "<UnknownType>"; if (pi[j].ParameterType != null) typeName = pi[j].ParameterType.Name; sb.Append(typeName + " " + pi[j].Name); } sb.Append(")"); // source location printing if (displayFilenames && (sf.GetILOffset() != -1)) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. String fileName = null; // Getting the filename from a StackFrame is a privileged operation - we won't want // to disclose full path names to arbitrarily untrusted code. Rather than just omit // this we could probably trim to just the filename so it's still mostly usefull. try { fileName = sf.GetFileName(); } #if FEATURE_CAS_POLICY catch (NotSupportedException) { // Having a deprecated stack modifier on the callstack (such as Deny) will cause // a NotSupportedException to be thrown. Since we don't know if the app can // access the file names, we'll conservatively hide them. displayFilenames = false; } #endif // FEATURE_CAS_POLICY catch (SecurityException) { // If the demand for displaying filenames fails, then it won't // succeed later in the loop. Avoid repeated exceptions by not trying again. displayFilenames = false; } if (fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber()); } } #if FEATURE_EXCEPTIONDISPATCHINFO if (sf.GetIsLastFrameFromForeignExceptionStackTrace()) { sb.Append(Environment.NewLine); sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow")); } #endif // FEATURE_EXCEPTIONDISPATCHINFO } } if(traceFormat == TraceFormat.TrailingNewLine) sb.Append(Environment.NewLine); return sb.ToString(); } // This helper is called from within the EE to construct a string representation // of the current stack trace. #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private static String GetManagedStackTraceStringHelper(bool fNeedFileInfo) { // Note all the frames in System.Diagnostics will be skipped when capturing // a normal stack trace (not from an exception) so we don't need to explicitly // skip the GetManagedStackTraceStringHelper frame. StackTrace st = new StackTrace(0, fNeedFileInfo); return st.ToString(); } } }
// 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.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> [NonVersionable] public readonly ref partial struct Span<T> { /// <summary>A byref or a native ptr.</summary> internal readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> #if PROJECTN [Bound] #endif private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array) { if (array == null) { this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757) ThrowHelper.ThrowArrayTypeMismatchException(); #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { #if PROJECTN [BoundsChecking] get { return ref Unsafe.Add(ref _pointer.Value, index); } #else [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } #endif } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. /// It can be used for pinning and is required to support the use of span within a fixed statement. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref T GetPinnableReference() { // Ensure that the native code has just one forward branch that is predicted-not-taken. ref T ret = ref Unsafe.AsRef<T>(null); if (_length != 0) ret = ref _pointer.Value; return ref ret; } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { SpanHelpers.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint))); } else { SpanHelpers.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>()); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { if (Unsafe.SizeOf<T>() == 1) { uint length = (uint)_length; if (length == 0) return; T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length); } else { // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations nuint length = (uint)_length; if (length == 0) return; ref T r = ref _pointer.Value; // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 nuint elementSize = (uint)Unsafe.SizeOf<T>(); nuint i = 0; for (; i < (length & ~(nuint)7); i += 8) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value; } if (i < (length & ~(nuint)3)) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; i += 4; } for (; i < length; i++) { Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span<T> destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length // check, and one for the result of TryCopyTo. Since these checks are equivalent, // we can optimize by performing the check once ourselves then calling Memmove directly. if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { bool retVal = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); retVal = true; } return retVal; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// For <see cref="Span{Char}"/>, returns a new instance of string that represents the characters pointed to by the span. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { return new string(new ReadOnlySpan<char>(ref Unsafe.As<T, char>(ref _pointer.Value), _length)); } #if FEATURE_UTF8STRING else if (typeof(T) == typeof(Char8)) { // TODO_UTF8STRING: Call into optimized transcoding routine when it's available. return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref _pointer.Value), _length)); } #endif // FEATURE_UTF8STRING return string.Format("System.Span<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { #if BIT64 // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. // We don't use this same mechanism in a 32-bit process due to the overhead of 64-bit arithmetic. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length); return destination; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion #if !NETCF using System; using System.Collections; using log4net.Core; namespace log4net.Util { /// <summary> /// Delegate type used for LogicalThreadContextStack's callbacks. /// </summary> #if NET_2_0 || MONO_2_0 public delegate void TwoArgAction<T1, T2>(T1 t1, T2 t2); #else public delegate void TwoArgAction(string t1, LogicalThreadContextStack t2); #endif /// <summary> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </summary> /// <remarks> /// <para> /// Implementation of Stack for the <see cref="log4net.LogicalThreadContext"/> /// </para> /// </remarks> /// <author>Nicko Cadell</author> public sealed class LogicalThreadContextStack : IFixingRequired { #region Private Instance Fields /// <summary> /// The stack store. /// </summary> private Stack m_stack = new Stack(); /// <summary> /// The name of this <see cref="log4net.Util.LogicalThreadContextStack"/> within the /// <see cref="log4net.Util.LogicalThreadContextProperties"/>. /// </summary> private string m_propertyKey; /// <summary> /// The callback used to let the <see cref="log4net.Util.LogicalThreadContextStacks"/> register a /// new instance of a <see cref="log4net.Util.LogicalThreadContextStack"/>. /// </summary> #if NET_2_0 || MONO_2_0 private TwoArgAction<string, LogicalThreadContextStack> m_registerNew; #else private TwoArgAction m_registerNew; #endif #endregion Private Instance Fields #region Public Instance Constructors /// <summary> /// Internal constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="LogicalThreadContextStack" /> class. /// </para> /// </remarks> #if NET_2_0 || MONO_2_0 internal LogicalThreadContextStack(string propertyKey, TwoArgAction<string, LogicalThreadContextStack> registerNew) #else internal LogicalThreadContextStack(string propertyKey, TwoArgAction registerNew) #endif { m_propertyKey = propertyKey; m_registerNew = registerNew; } #endregion Public Instance Constructors #region Public Properties /// <summary> /// The number of messages in the stack /// </summary> /// <value> /// The current number of messages in the stack /// </value> /// <remarks> /// <para> /// The current number of messages in the stack. That is /// the number of times <see cref="Push"/> has been called /// minus the number of times <see cref="Pop"/> has been called. /// </para> /// </remarks> public int Count { get { return m_stack.Count; } } #endregion // Public Properties #region Public Methods /// <summary> /// Clears all the contextual information held in this stack. /// </summary> /// <remarks> /// <para> /// Clears all the contextual information held in this stack. /// Only call this if you think that this thread is being reused after /// a previous call execution which may not have completed correctly. /// You do not need to use this method if you always guarantee to call /// the <see cref="IDisposable.Dispose"/> method of the <see cref="IDisposable"/> /// returned from <see cref="Push"/> even in exceptional circumstances, /// for example by using the <c>using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message"))</c> /// syntax. /// </para> /// </remarks> public void Clear() { m_registerNew(m_propertyKey, new LogicalThreadContextStack(m_propertyKey, m_registerNew)); } /// <summary> /// Removes the top context from this stack. /// </summary> /// <returns>The message in the context that was removed from the top of this stack.</returns> /// <remarks> /// <para> /// Remove the top context from this stack, and return /// it to the caller. If this stack is empty then an /// empty string (not <see langword="null"/>) is returned. /// </para> /// </remarks> public string Pop() { // copy current stack Stack stack = new Stack(new Stack(m_stack)); string result = ""; if (stack.Count > 0) { result = ((StackFrame)(stack.Pop())).Message; } LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_propertyKey, m_registerNew); ltcs.m_stack = stack; m_registerNew(m_propertyKey, ltcs); return result; } /// <summary> /// Pushes a new context message into this stack. /// </summary> /// <param name="message">The new context message.</param> /// <returns> /// An <see cref="IDisposable"/> that can be used to clean up the context stack. /// </returns> /// <remarks> /// <para> /// Pushes a new context onto this stack. An <see cref="IDisposable"/> /// is returned that can be used to clean up this stack. This /// can be easily combined with the <c>using</c> keyword to scope the /// context. /// </para> /// </remarks> /// <example>Simple example of using the <c>Push</c> method with the <c>using</c> keyword. /// <code lang="C#"> /// using(log4net.LogicalThreadContext.Stacks["NDC"].Push("Stack_Message")) /// { /// log.Warn("This should have an ThreadContext Stack message"); /// } /// </code> /// </example> public IDisposable Push(string message) { // do modifications on a copy Stack stack = new Stack(new Stack(m_stack)); stack.Push(new StackFrame(message, (stack.Count > 0) ? (StackFrame)stack.Peek() : null)); LogicalThreadContextStack contextStack = new LogicalThreadContextStack(m_propertyKey, m_registerNew); contextStack.m_stack = stack; m_registerNew(m_propertyKey, contextStack); return new AutoPopStackFrame(contextStack, stack.Count - 1); } #endregion Public Methods #region Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>The current context information.</returns> internal string GetFullMessage() { Stack stack = m_stack; if (stack.Count > 0) { return ((StackFrame)(stack.Peek())).FullMessage; } return null; } /// <summary> /// Gets and sets the internal stack used by this <see cref="LogicalThreadContextStack"/> /// </summary> /// <value>The internal storage stack</value> /// <remarks> /// <para> /// This property is provided only to support backward compatability /// of the <see cref="NDC"/>. Tytpically the internal stack should not /// be modified. /// </para> /// </remarks> internal Stack InternalStack { get { return m_stack; } set { m_stack = value; } } #endregion Internal Methods /// <summary> /// Gets the current context information for this stack. /// </summary> /// <returns>Gets the current context information</returns> /// <remarks> /// <para> /// Gets the current context information for this stack. /// </para> /// </remarks> public override string ToString() { return GetFullMessage(); } /// <summary> /// Get a portable version of this object /// </summary> /// <returns>the portable instance of this object</returns> /// <remarks> /// <para> /// Get a cross thread portable version of this object /// </para> /// </remarks> object IFixingRequired.GetFixedObject() { return GetFullMessage(); } /// <summary> /// Inner class used to represent a single context frame in the stack. /// </summary> /// <remarks> /// <para> /// Inner class used to represent a single context frame in the stack. /// </para> /// </remarks> private sealed class StackFrame { #region Private Instance Fields private readonly string m_message; private readonly StackFrame m_parent; private string m_fullMessage = null; #endregion #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="message">The message for this context.</param> /// <param name="parent">The parent context in the chain.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="StackFrame" /> class /// with the specified message and parent context. /// </para> /// </remarks> internal StackFrame(string message, StackFrame parent) { m_message = message; m_parent = parent; if (parent == null) { m_fullMessage = message; } } #endregion Internal Instance Constructors #region Internal Instance Properties /// <summary> /// Get the message. /// </summary> /// <value>The message.</value> /// <remarks> /// <para> /// Get the message. /// </para> /// </remarks> internal string Message { get { return m_message; } } /// <summary> /// Gets the full text of the context down to the root level. /// </summary> /// <value> /// The full text of the context down to the root level. /// </value> /// <remarks> /// <para> /// Gets the full text of the context down to the root level. /// </para> /// </remarks> internal string FullMessage { get { if (m_fullMessage == null && m_parent != null) { m_fullMessage = string.Concat(m_parent.FullMessage, " ", m_message); } return m_fullMessage; } } #endregion Internal Instance Properties } /// <summary> /// Struct returned from the <see cref="LogicalThreadContextStack.Push"/> method. /// </summary> /// <remarks> /// <para> /// This struct implements the <see cref="IDisposable"/> and is designed to be used /// with the <see langword="using"/> pattern to remove the stack frame at the end of the scope. /// </para> /// </remarks> private struct AutoPopStackFrame : IDisposable { #region Private Instance Fields /// <summary> /// The depth to trim the stack to when this instance is disposed /// </summary> private int m_frameDepth; /// <summary> /// The outer LogicalThreadContextStack. /// </summary> private LogicalThreadContextStack m_logicalThreadContextStack; #endregion Private Instance Fields #region Internal Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="logicalThreadContextStack">The internal stack used by the ThreadContextStack.</param> /// <param name="frameDepth">The depth to return the stack to when this object is disposed.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="AutoPopStackFrame" /> class with /// the specified stack and return depth. /// </para> /// </remarks> internal AutoPopStackFrame(LogicalThreadContextStack logicalThreadContextStack, int frameDepth) { m_frameDepth = frameDepth; m_logicalThreadContextStack = logicalThreadContextStack; } #endregion Internal Instance Constructors #region Implementation of IDisposable /// <summary> /// Returns the stack to the correct depth. /// </summary> /// <remarks> /// <para> /// Returns the stack to the correct depth. /// </para> /// </remarks> public void Dispose() { if (m_frameDepth >= 0 && m_logicalThreadContextStack.m_stack != null) { Stack stack = new Stack(new Stack(m_logicalThreadContextStack.m_stack)); while (stack.Count > m_frameDepth) { stack.Pop(); } LogicalThreadContextStack ltcs = new LogicalThreadContextStack(m_logicalThreadContextStack.m_propertyKey, m_logicalThreadContextStack.m_registerNew); ltcs.m_stack = stack; m_logicalThreadContextStack.m_registerNew(m_logicalThreadContextStack.m_propertyKey, ltcs); } } #endregion Implementation of IDisposable } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbTrans2QueryFileInformation Request /// </summary> public class SmbTrans2QueryFileInformationRequestPacket : SmbTransaction2RequestPacket { #region Fields private TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters trans2Parameters; private TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Data trans2Data; /// <summary> /// The size of SizeOfListInBytes field in trans2Data /// </summary> private const ushort sizeOfListInBytesLength = 4; #endregion #region Properties /// <summary> /// get or set the Trans2_Parameters:TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters /// </summary> public TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters Trans2Parameters { get { return this.trans2Parameters; } set { this.trans2Parameters = value; } } /// <summary> /// get or set the Trans2_Parameters:TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters /// </summary> public TRANS2_QUERY_PATH_INFORMATION_Request_Trans2_Data Trans2Data { get { return this.trans2Data; } set { this.trans2Data = value; } } /// <summary> /// get the FID of Trans2_Parameters /// </summary> internal override ushort FID { get { return trans2Parameters.FID; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbTrans2QueryFileInformationRequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbTrans2QueryFileInformationRequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbTrans2QueryFileInformationRequestPacket(SmbTrans2QueryFileInformationRequestPacket packet) : base(packet) { this.InitDefaultValue(); this.trans2Parameters.FID = packet.trans2Parameters.FID; this.trans2Parameters.InformationLevel = packet.trans2Parameters.InformationLevel; this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes = packet.trans2Data.GetExtendedAttributeList.SizeOfListInBytes; if (packet.trans2Data.GetExtendedAttributeList.GEAList != null && packet.trans2Data.GetExtendedAttributeList.GEAList.Length > 0) { this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[packet.trans2Data.GetExtendedAttributeList.GEAList.Length]; Array.Copy( packet.trans2Data.GetExtendedAttributeList.GEAList, this.trans2Data.GetExtendedAttributeList.GEAList, packet.trans2Data.GetExtendedAttributeList.GEAList.Length); } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbTrans2QueryFileInformationRequestPacket(this); } /// <summary> /// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters /// </summary> protected override void EncodeTrans2Parameters() { this.smbData.Trans2_Parameters = CifsMessageUtils.ToBytes<TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters>( this.trans2Parameters); } /// <summary> /// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data /// </summary> protected override void EncodeTrans2Data() { if (this.trans2Parameters.InformationLevel == QueryInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST) { this.smbData.Trans2_Data = new byte[sizeOfListInBytesLength + CifsMessageUtils.GetSmbQueryEAListSize( this.trans2Data.GetExtendedAttributeList.GEAList)]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<uint>(this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes); if (this.trans2Data.GetExtendedAttributeList.GEAList != null) { foreach (SMB_GEA smbQueryEa in this.trans2Data.GetExtendedAttributeList.GEAList) { channel.Write<byte>(smbQueryEa.AttributeNameLengthInBytes); if (smbQueryEa.AttributeName != null) { channel.WriteBytes(smbQueryEa.AttributeName); } } } channel.EndWriteGroup(); } } } else { this.smbData.Trans2_Data = new byte[0]; } } /// <summary> /// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters. /// </summary> protected override void DecodeTrans2Parameters() { if (this.smbData.Trans2_Parameters != null) { this.trans2Parameters = CifsMessageUtils.ToStuct< TRANS2_QUERY_FILE_INFORMATION_Request_Trans2_Parameters>( this.smbData.Trans2_Parameters); } } /// <summary> /// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data. /// </summary> protected override void DecodeTrans2Data() { if (this.smbData.Trans2_Data != null && this.smbData.Trans2_Data.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes = channel.Read<uint>(); uint sizeOfListInBytes = this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes - sizeOfListInBytesLength; List<SMB_GEA> eaList = new List<SMB_GEA>(); while (sizeOfListInBytes > 0) { SMB_GEA smbQueryEa = channel.Read<SMB_GEA>(); eaList.Add(smbQueryEa); sizeOfListInBytes -= (uint)(EA.SMB_QUERY_EA_FIXED_SIZE + smbQueryEa.AttributeName.Length); } this.trans2Data.GetExtendedAttributeList.GEAList = eaList.ToArray(); } } } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Avalonia.Data; using Avalonia.Logging; using Avalonia.Utilities; namespace Avalonia { /// <summary> /// Maintains a list of prioritised bindings together with a current value. /// </summary> /// <remarks> /// Bindings, in the form of <see cref="IObservable{Object}"/>s are added to the object using /// the <see cref="Add"/> method. With the observable is passed a priority, where lower values /// represent higher priorites. The current <see cref="Value"/> is selected from the highest /// priority binding that doesn't return <see cref="AvaloniaProperty.UnsetValue"/>. Where there /// are multiple bindings registered with the same priority, the most recently added binding /// has a higher priority. Each time the value changes, the /// <see cref="IPriorityValueOwner.Changed(PriorityValue, object, object)"/> method on the /// owner object is fired with the old and new values. /// </remarks> internal class PriorityValue { private readonly IPriorityValueOwner _owner; private readonly Type _valueType; private readonly Dictionary<int, PriorityLevel> _levels = new Dictionary<int, PriorityLevel>(); private object _value; private readonly Func<object, object> _validate; /// <summary> /// Initializes a new instance of the <see cref="PriorityValue"/> class. /// </summary> /// <param name="owner">The owner of the object.</param> /// <param name="property">The property that the value represents.</param> /// <param name="valueType">The value type.</param> /// <param name="validate">An optional validation function.</param> public PriorityValue( IPriorityValueOwner owner, AvaloniaProperty property, Type valueType, Func<object, object> validate = null) { _owner = owner; Property = property; _valueType = valueType; _value = AvaloniaProperty.UnsetValue; ValuePriority = int.MaxValue; _validate = validate; } /// <summary> /// Gets the property that the value represents. /// </summary> public AvaloniaProperty Property { get; } /// <summary> /// Gets the current value. /// </summary> public object Value => _value; /// <summary> /// Gets the priority of the binding that is currently active. /// </summary> public int ValuePriority { get; private set; } /// <summary> /// Adds a new binding. /// </summary> /// <param name="binding">The binding.</param> /// <param name="priority">The binding priority.</param> /// <param name="validation">Validation settings for the binding.</param> /// <returns> /// A disposable that will remove the binding. /// </returns> public IDisposable Add(IObservable<object> binding, int priority) { return GetLevel(priority).Add(binding); } /// <summary> /// Sets the value for a specified priority. /// </summary> /// <param name="value">The value.</param> /// <param name="priority">The priority</param> public void SetValue(object value, int priority) { GetLevel(priority).DirectValue = value; } /// <summary> /// Gets the currently active bindings on this object. /// </summary> /// <returns>An enumerable collection of bindings.</returns> public IEnumerable<PriorityBindingEntry> GetBindings() { foreach (var level in _levels) { foreach (var binding in level.Value.Bindings) { yield return binding; } } } /// <summary> /// Returns diagnostic string that can help the user debug the bindings in effect on /// this object. /// </summary> /// <returns>A diagnostic string.</returns> public string GetDiagnostic() { var b = new StringBuilder(); var first = true; foreach (var level in _levels) { if (!first) { b.AppendLine(); } b.Append(ValuePriority == level.Key ? "*" : string.Empty); b.Append("Priority "); b.Append(level.Key); b.Append(": "); b.AppendLine(level.Value.Value?.ToString() ?? "(null)"); b.AppendLine("--------"); b.Append("Direct: "); b.AppendLine(level.Value.DirectValue?.ToString() ?? "(null)"); foreach (var binding in level.Value.Bindings) { b.Append(level.Value.ActiveBindingIndex == binding.Index ? "*" : string.Empty); b.Append(binding.Description ?? binding.Observable.GetType().Name); b.Append(": "); b.AppendLine(binding.Value?.ToString() ?? "(null)"); } first = false; } return b.ToString(); } /// <summary> /// Called when the value for a priority level changes. /// </summary> /// <param name="level">The priority level of the changed entry.</param> public void LevelValueChanged(PriorityLevel level) { if (level.Priority <= ValuePriority) { if (level.Value != AvaloniaProperty.UnsetValue) { UpdateValue(level.Value, level.Priority); } else { foreach (var i in _levels.Values.OrderBy(x => x.Priority)) { if (i.Value != AvaloniaProperty.UnsetValue) { UpdateValue(i.Value, i.Priority); return; } } UpdateValue(AvaloniaProperty.UnsetValue, int.MaxValue); } } } /// <summary> /// Called whenever a priority level validation state changes. /// </summary> /// <param name="priorityLevel">The priority level of the changed entry.</param> /// <param name="validationStatus">The validation status.</param> public void LevelValidation(PriorityLevel priorityLevel, IValidationStatus validationStatus) { _owner.DataValidationChanged(this, validationStatus); } /// <summary> /// Called when a priority level encounters an error. /// </summary> /// <param name="level">The priority level of the changed entry.</param> /// <param name="error">The binding error.</param> public void LevelError(PriorityLevel level, BindingError error) { Logger.Log( LogEventLevel.Error, LogArea.Binding, _owner, "Error binding to {Target}.{Property}: {Message}", _owner, Property, error.Exception.Message); } /// <summary> /// Causes a revalidation of the value. /// </summary> public void Revalidate() { if (_validate != null) { PriorityLevel level; if (_levels.TryGetValue(ValuePriority, out level)) { UpdateValue(level.Value, level.Priority); } } } /// <summary> /// Gets the <see cref="PriorityLevel"/> with the specified priority, creating it if it /// doesn't already exist. /// </summary> /// <param name="priority">The priority.</param> /// <returns>The priority level.</returns> private PriorityLevel GetLevel(int priority) { PriorityLevel result; if (!_levels.TryGetValue(priority, out result)) { result = new PriorityLevel(this, priority); _levels.Add(priority, result); } return result; } /// <summary> /// Updates the current <see cref="Value"/> and notifies all subscibers. /// </summary> /// <param name="value">The value to set.</param> /// <param name="priority">The priority level that the value came from.</param> private void UpdateValue(object value, int priority) { object castValue; if (TypeUtilities.TryCast(_valueType, value, out castValue)) { var old = _value; if (_validate != null && castValue != AvaloniaProperty.UnsetValue) { castValue = _validate(castValue); } ValuePriority = priority; _value = castValue; _owner?.Changed(this, old, _value); } else { Logger.Error( LogArea.Binding, _owner, "Binding produced invalid value for {$Property} ({$PropertyType}): {$Value} ({$ValueType})", Property.Name, _valueType, value, value.GetType()); } } } }
using System.Diagnostics.CodeAnalysis; using System.Reflection; using Newtonsoft.Json; namespace Facility.Core; /// <summary> /// A service result success or error. /// </summary> [JsonConverter(typeof(ServiceResultJsonConverter))] [System.Text.Json.Serialization.JsonConverter(typeof(ServiceResultSystemTextJsonConverter))] public class ServiceResult { /// <summary> /// Creates a successful result. /// </summary> public static ServiceResult Success() => new(null); /// <summary> /// Creates a successful result. /// </summary> public static ServiceResult<T> Success<T>(T value) => new(value); /// <summary> /// Creates a failed result. /// </summary> public static ServiceResultFailure Failure(ServiceErrorDto error) => new(error ?? throw new ArgumentNullException(nameof(error))); /// <summary> /// True if the result has a value. /// </summary> public bool IsSuccess => Error == null; /// <summary> /// True if the result has an error. /// </summary> public bool IsFailure => Error != null; /// <summary> /// The error. /// </summary> public ServiceErrorDto? Error { get; } /// <summary> /// Throws a ServiceException if the result is an error. /// </summary> public void Verify() { if (Error != null) throw new ServiceException(Error); } /// <summary> /// Casts to a ServiceResult with a value. /// </summary> /// <remarks>A failed ServiceResult can be cast to a ServiceResult of any type. /// A successful ServiceResult can only be cast to a ServiceResult of another type /// if its value can be successfully cast through object.</remarks> public ServiceResult<T> Cast<T>() { if (IsFailure) return Failure(Error!); else return Success((T) InternalValue!); } /// <summary> /// The service result as a failure; null if it is a success. /// </summary> public ServiceResultFailure? AsFailure() => this as ServiceResultFailure ?? (IsFailure ? Failure(Error!) : null); /// <summary> /// The service result as a failure; throws if it is a success. /// </summary> public ServiceResultFailure ToFailure() => AsFailure() ?? throw new InvalidOperationException("Result is not a failure."); /// <summary> /// Check service results for equivalence. /// </summary> public bool IsEquivalentTo(ServiceResult? other) { if (other == null) return false; if (IsFailure) return other.IsFailure && ServiceDataUtility.AreEquivalentDtos(Error, other.Error); var valueType = InternalValueType; if (valueType == null) return other.InternalValueType == null; return IsInternalValueEquivalent(other); } /// <summary> /// Validates the server result value. /// </summary> public bool Validate(out string? errorMessage) { if (IsFailure) { errorMessage = null; return true; } return ValidateInternalValue(out errorMessage); } /// <summary> /// Render result as a string. /// </summary> public override string ToString() => IsSuccess ? "<Success>" : $"<Failure={Error}>"; /// <summary> /// Used by Json.NET to convert <see cref="ServiceResult" />. /// </summary> [SuppressMessage("Design", "CA1034:Nested types should not be visible", Justification = "Legacy.")] public sealed class ServiceResultJsonConverter : JsonConverter { /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> public override bool CanConvert(Type objectType) => objectType.GetTypeInfo().IsAssignableFrom(typeof(ServiceResult).GetTypeInfo()); /// <summary> /// Reads the JSON representation of the object. /// </summary> public override object? ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return null; MatchTokenOrThrow(reader, JsonToken.StartObject); ReadOrThrow(reader); var valueType = objectType.IsConstructedGenericType ? objectType.GenericTypeArguments[0] : null; object? value = null; ServiceErrorDto? error = null; while (reader.TokenType == JsonToken.PropertyName) { var propertyName = (string) reader.Value; ReadOrThrow(reader); if (string.Equals(propertyName, c_valuePropertyName, StringComparison.OrdinalIgnoreCase)) { if (valueType == null) throw new JsonSerializationException("ServiceResult does not support 'value'; use ServiceResult<T>."); value = serializer.Deserialize(reader, valueType); } else if (string.Equals(propertyName, c_errorPropertyName, StringComparison.OrdinalIgnoreCase)) { error = serializer.Deserialize<ServiceErrorDto>(reader); } ReadOrThrow(reader); } MatchTokenOrThrow(reader, JsonToken.EndObject); if (value != null && error != null) throw new JsonSerializationException("ServiceResult must not have both 'value' and 'error'."); if (valueType == null) { return error != null ? Failure(error) : Success(); } else if (error != null) { return (ServiceResult) s_genericCastMethod.MakeGenericMethod(valueType).Invoke(Failure(error), Array.Empty<object>())!; } else { if (value == null && valueType.GetTypeInfo().IsValueType) value = Activator.CreateInstance(valueType); return (ServiceResult) s_genericSuccessMethod.MakeGenericMethod(valueType).Invoke(null, new[] { value })!; } } /// <summary> /// Writes the JSON representation of the object. /// </summary> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var serviceResult = (ServiceResult) value; var valueType = serviceResult.InternalValueType; writer.WriteStartObject(); if (serviceResult.IsFailure) { writer.WritePropertyName(c_errorPropertyName); serializer.Serialize(writer, serviceResult.Error); } else if (valueType != null) { writer.WritePropertyName(c_valuePropertyName); serializer.Serialize(writer, serviceResult.InternalValue); } writer.WriteEndObject(); } private static void ReadOrThrow(JsonReader reader) { if (!reader.Read()) throw new JsonSerializationException("ServiceResult JSON ended unexpectedly."); } private static void MatchTokenOrThrow(JsonReader reader, JsonToken tokenType) { if (reader.TokenType != tokenType) throw new JsonSerializationException($"ServiceResult expected {tokenType} but found {reader.TokenType}."); } private const string c_valuePropertyName = "value"; private const string c_errorPropertyName = "error"; private static readonly MethodInfo s_genericSuccessMethod = typeof(ServiceResult).GetRuntimeMethods().First(x => x.Name == "Success" && x.IsStatic && x.IsGenericMethodDefinition); private static readonly MethodInfo s_genericCastMethod = typeof(ServiceResult).GetRuntimeMethods().First(x => x.Name == "Cast" && !x.IsStatic && x.IsGenericMethodDefinition); } internal ServiceResult(ServiceErrorDto? error) { Error = error; } internal virtual Type? InternalValueType => null; internal virtual object? InternalValue => throw new InvalidCastException("A successful result without a value cannot be cast."); internal virtual bool IsInternalValueEquivalent(ServiceResult result) => false; internal virtual bool ValidateInternalValue(out string? errorMessage) { errorMessage = null; return true; } } /// <summary> /// A service result value or error. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Same name.")] [System.Text.Json.Serialization.JsonConverter(typeof(ServiceResultSystemTextJsonConverter))] public sealed class ServiceResult<T> : ServiceResult { /// <summary> /// Implicitly create a failed result from an error. /// </summary> [SuppressMessage("Usage", "CA2225:Operator overloads have named alternates", Justification = "Used to create results from failures.")] public static implicit operator ServiceResult<T>(ServiceResultFailure failure) => new(failure.Error); /// <summary> /// The value. (Throws a ServiceException on failure.) /// </summary> public T Value { get { Verify(); return m_value!; } } /// <summary> /// The value. (Returns null on failure.) /// </summary> [SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "By design.")] public T? GetValueOrDefault() => m_value; /// <summary> /// Maps a ServiceResult from one type to another. /// </summary> /// <remarks>If the result is a success, the function is called on the input value to produce /// a successful service result matching the type of the output value. If the result is a failure, /// the function is not called, and a failed service result using the output type is returned.</remarks> public ServiceResult<TOutput> Map<TOutput>(Func<T, TOutput> func) => IsFailure ? new ServiceResult<TOutput>(Error) : new ServiceResult<TOutput>(func(m_value!)); /// <summary> /// Maps a ServiceResult from one type to another. /// </summary> /// <remarks>If the result is a success, the function is called on the input value to produce /// a service result matching the type of the output value. If the result is a failure, /// the function is not called, and a failed service result using the output type is returned.</remarks> public ServiceResult<TOutput> Map<TOutput>(Func<T, ServiceResult<TOutput>> func) => IsFailure ? new ServiceResult<TOutput>(Error) : func(m_value!); /// <summary> /// Check service results for equivalence. /// </summary> public bool IsEquivalentTo(ServiceResult<T>? other) => base.IsEquivalentTo(other); /// <summary> /// Render result as a string. /// </summary> public override string ToString() => IsSuccess ? $"<Success={m_value}>" : base.ToString(); internal ServiceResult(T value) : base(null) { m_value = value; } internal override Type InternalValueType => typeof(T); internal override object? InternalValue => m_value; internal override bool IsInternalValueEquivalent(ServiceResult other) { var otherOfT = other as ServiceResult<T>; if (otherOfT == null) return false; return ServiceDataUtility.AreEquivalentFieldValues(m_value, otherOfT.m_value); } internal override bool ValidateInternalValue(out string? errorMessage) => ServiceDataUtility.ValidateFieldValue(m_value, out errorMessage); private ServiceResult(ServiceErrorDto? error) : base(error) { } private readonly T? m_value; } /// <summary> /// A failed service result. /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Same name.")] [System.Text.Json.Serialization.JsonConverter(typeof(ServiceResultSystemTextJsonConverter))] public sealed class ServiceResultFailure : ServiceResult { internal ServiceResultFailure(ServiceErrorDto error) : base(error) { } /// <summary> /// Check service results for equivalence. /// </summary> public bool IsEquivalentTo(ServiceResultFailure? other) => base.IsEquivalentTo(other); }
//----------------------------------------------------------------------- // <copyright file="ADMGUIController.cs" company="Google"> // // Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Threading; using Tango; using UnityEngine; using UnityEngine.UI; /// <summary> /// Class for all the UI interaction in the AreaDescriptionManagement sample. /// </summary> public class ADMGUIController : MonoBehaviour, ITangoLifecycle, ITangoEvent { /// <summary> /// Parent of the Area Description management screen. /// </summary> public GameObject m_managementRoot; /// <summary> /// Parent of the Area Description quality screen. /// </summary> public GameObject m_qualityRoot; /// <summary> /// UI parent of the list of Area Descriptions on the device. /// </summary> public RectTransform m_listParent; /// <summary> /// UI prefab for each element in the list of Area Descriptions on the device. /// </summary> public AreaDescriptionListElement m_listElement; /// <summary> /// UI to enable when m_ListParent has no children. /// </summary> public RectTransform m_listEmptyText; /// <summary> /// UI parent of the selected Area Description's details. /// </summary> public RectTransform m_detailsParent; /// <summary> /// Read-only UI for the selected Area Description's date. /// </summary> public Text m_detailsDate; /// <summary> /// Editable UI for the selected Area Description's human readable name. /// </summary> public InputField m_detailsEditableName; /// <summary> /// Editable UI for the selected Area Description's X position. /// </summary> public InputField m_detailsEditablePosX; /// <summary> /// Editable UI for the selected Area Description's Y position. /// </summary> public InputField m_detailsEditablePosY; /// <summary> /// Editable UI for the selected Area Description's Z position. /// </summary> public InputField m_detailsEditablePosZ; /// <summary> /// Editable UI for the selected Area Description's qX rotation. /// </summary> public InputField m_detailsEditableRotQX; /// <summary> /// Editable UI for the selected Area Description's qY rotation. /// </summary> public InputField m_detailsEditableRotQY; /// <summary> /// Editable UI for the selected Area Description's qZ rotation. /// </summary> public InputField m_detailsEditableRotQZ; /// <summary> /// Editable UI for the selected Area Description's qW rotation. /// </summary> public InputField m_detailsEditableRotQW; /// <summary> /// The reference of the TangoDeltaPoseController object. /// /// TangoDeltaPoseController listens to pose updates and applies the correct pose to itself and its built-in camera. /// </summary> public TangoDeltaPoseController m_deltaPoseController; /// <summary> /// Saving progress UI parent. /// </summary> public RectTransform m_savingTextParent; /// <summary> /// Saving progress UI text. /// </summary> public Text m_savingText; /// <summary> /// TangoApplication for this scene. /// </summary> private TangoApplication m_tangoApplication; /// <summary> /// Currently selected Area Description. /// </summary> private AreaDescription m_selectedAreaDescription; /// <summary> /// Currently selected Area Description's metadata. /// </summary> private AreaDescription.Metadata m_selectedMetadata; /// <summary> /// The background thread saving occurs on. /// </summary> private Thread m_saveThread; /// <summary> /// Update is called once per frame. /// </summary> public void Update() { if (m_saveThread != null && m_saveThread.ThreadState != ThreadState.Running) { // After saving an Area Description, we reload the scene to restart the game. Application.LoadLevel(Application.loadedLevel); } // Pressing the back button should popup the management window if you are not in the management screen, // otherwise it can quit. if (Input.GetKey(KeyCode.Escape)) { if (m_managementRoot.activeSelf) { Application.Quit(); } else { Application.LoadLevel(Application.loadedLevel); } } } /// <summary> /// Use this for initialization. /// </summary> public void Start() { m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); if (AndroidHelper.IsTangoCorePresent()) { m_tangoApplication.RequestPermissions(); } } else { Debug.Log("No Tango Manager found in scene."); } } /// <summary> /// Applicaiton onPause / onResume callback. /// </summary> /// <param name="pauseStatus"><c>true</c> if the application about to pause, otherwise <c>false</c>.</param> public void OnApplicationPause(bool pauseStatus) { if (pauseStatus && !m_managementRoot.activeSelf) { // When application is backgrounded, we reload the level because the Tango Service is disconected. All // learned area and placed marker should be discarded as they are not saved. Application.LoadLevel(Application.loadedLevel); } } /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { if (permissionsGranted) { RefreshAreaDescriptionList(); } } /// <summary> /// This is called when succesfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { } /// <summary> /// This is called when disconnected from the Tango service. /// </summary> public void OnTangoServiceDisconnected() { } /// <summary> /// This is called each time a Tango event happens. /// </summary> /// <param name="tangoEvent">Tango event.</param> public void OnTangoEventAvailableEventHandler(Tango.TangoEvent tangoEvent) { // We will not have the saving progress when the learning mode is off. if (!m_tangoApplication.m_areaDescriptionLearningMode) { return; } if (tangoEvent.type == TangoEnums.TangoEventType.TANGO_EVENT_AREA_LEARNING && tangoEvent.event_key == "AreaDescriptionSaveProgress") { m_savingText.text = "Saving... " + Mathf.RoundToInt(float.Parse(tangoEvent.event_value) * 100) + "%"; } } /// <summary> /// Refresh the UI list of Area Descriptions. /// </summary> public void RefreshAreaDescriptionList() { AreaDescription[] areaDescriptions = AreaDescription.GetList(); _SelectAreaDescription(null); // Always remove all old children. foreach (Transform child in m_listParent) { Destroy(child.gameObject); } if (areaDescriptions != null) { // Add new children ToggleGroup toggleGroup = GetComponent<ToggleGroup>(); foreach (AreaDescription areaDescription in areaDescriptions) { AreaDescriptionListElement button = GameObject.Instantiate(m_listElement) as AreaDescriptionListElement; button.m_areaDescriptionName.text = areaDescription.GetMetadata().m_name; button.m_areaDescriptionUUID.text = areaDescription.m_uuid; button.m_toggle.group = toggleGroup; // Ensure the lambda gets a copy of the reference to areaDescription in its current state. // (See https://resnikb.wordpress.com/2009/06/17/c-lambda-and-foreach-variable/) AreaDescription lambdaParam = areaDescription; button.m_toggle.onValueChanged.AddListener((value) => _OnAreaDescriptionToggleChanged(lambdaParam, value)); button.transform.SetParent(m_listParent, false); } m_listEmptyText.gameObject.SetActive(false); } else { m_listEmptyText.gameObject.SetActive(true); } } /// <summary> /// Start quality mode, creating a brand new Area Description. /// </summary> public void NewAreaDescription() { m_tangoApplication.Startup(null); // Disable the management UI, we are now in the world. m_managementRoot.SetActive(false); m_qualityRoot.SetActive(true); } /// <summary> /// Start quality mode, extending an existing Area Description. /// </summary> public void ExtendSelectedAreaDescription() { if (m_selectedAreaDescription == null) { AndroidHelper.ShowAndroidToastMessage("You must have a selected Area Description to extend"); return; } m_tangoApplication.Startup(m_selectedAreaDescription); // Disable the management UI, we are now in the world. m_managementRoot.SetActive(false); m_qualityRoot.SetActive(true); } /// <summary> /// Import an Area Description. /// </summary> public void ImportAreaDescription() { StartCoroutine(_DoImportAreaDescription()); } /// <summary> /// Export an Area Description. /// </summary> public void ExportSelectedAreaDescription() { if (m_selectedAreaDescription != null) { StartCoroutine(_DoExportAreaDescription(m_selectedAreaDescription)); } } /// <summary> /// Delete the selected Area Description. /// </summary> public void DeleteSelectedAreaDescription() { if (m_selectedAreaDescription != null) { m_selectedAreaDescription.Delete(); RefreshAreaDescriptionList(); } } /// <summary> /// Save changes made to the selected Area Description's metaata. /// </summary> public void SaveSelectedAreaDescriptionMetadata() { if (m_selectedAreaDescription != null && m_selectedMetadata != null) { m_selectedMetadata.m_name = m_detailsEditableName.text; double.TryParse(m_detailsEditablePosX.text, out m_selectedMetadata.m_transformationPosition[0]); double.TryParse(m_detailsEditablePosY.text, out m_selectedMetadata.m_transformationPosition[1]); double.TryParse(m_detailsEditablePosZ.text, out m_selectedMetadata.m_transformationPosition[2]); double.TryParse(m_detailsEditableRotQX.text, out m_selectedMetadata.m_transformationRotation[0]); double.TryParse(m_detailsEditableRotQY.text, out m_selectedMetadata.m_transformationRotation[1]); double.TryParse(m_detailsEditableRotQZ.text, out m_selectedMetadata.m_transformationRotation[2]); double.TryParse(m_detailsEditableRotQW.text, out m_selectedMetadata.m_transformationRotation[3]); m_selectedAreaDescription.SaveMetadata(m_selectedMetadata); RefreshAreaDescriptionList(); } } /// <summary> /// When in quality mode, save the current Area Description and switch back to management mode. /// </summary> public void SaveCurrentAreaDescription() { StartCoroutine(_DoSaveCurrentAreaDescription()); } /// <summary> /// Actually do the Area Description import. /// /// This runs over multiple frames, so a Unity coroutine is used. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoImportAreaDescription() { if (TouchScreenKeyboard.visible) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("/sdcard/", TouchScreenKeyboardType.Default, false); while (!kb.done && !kb.wasCanceled) { yield return null; } if (kb.done) { AreaDescription.ImportFromFile(kb.text); } } /// <summary> /// Actually do the Area description export. /// /// This runs over multiple frames, so a Unity coroutine is used. /// </summary> /// <returns>Coroutine IEnumerator.</returns> /// <param name="areaDescription">Area Description to export.</param> private IEnumerator _DoExportAreaDescription(AreaDescription areaDescription) { if (TouchScreenKeyboard.visible) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("/sdcard/", TouchScreenKeyboardType.Default, false); while (!kb.done && !kb.wasCanceled) { yield return null; } if (kb.done) { areaDescription.ExportToFile(kb.text); } } /// <summary> /// Called every time an Area Description toggle changes state. /// </summary> /// <param name="areaDescription">Area Description the toggle is for.</param> /// <param name="value">The new state of the toggle.</param> private void _OnAreaDescriptionToggleChanged(AreaDescription areaDescription, bool value) { if (value) { _SelectAreaDescription(areaDescription); } else { _SelectAreaDescription(null); } } /// <summary> /// Select a specific Area Description to show details. /// </summary> /// <param name="areaDescription">Area Description to show details for, or <c>null</c> if details should be hidden.</param> private void _SelectAreaDescription(AreaDescription areaDescription) { m_selectedAreaDescription = areaDescription; if (areaDescription != null) { m_selectedMetadata = areaDescription.GetMetadata(); m_detailsParent.gameObject.SetActive(true); m_detailsDate.text = m_selectedMetadata.m_dateTime.ToLongDateString() + ", " + m_selectedMetadata.m_dateTime.ToLongTimeString(); m_detailsEditableName.text = m_selectedMetadata.m_name; m_detailsEditablePosX.text = m_selectedMetadata.m_transformationPosition[0].ToString(); m_detailsEditablePosY.text = m_selectedMetadata.m_transformationPosition[1].ToString(); m_detailsEditablePosZ.text = m_selectedMetadata.m_transformationPosition[2].ToString(); m_detailsEditableRotQX.text = m_selectedMetadata.m_transformationRotation[0].ToString(); m_detailsEditableRotQY.text = m_selectedMetadata.m_transformationRotation[1].ToString(); m_detailsEditableRotQZ.text = m_selectedMetadata.m_transformationRotation[2].ToString(); m_detailsEditableRotQW.text = m_selectedMetadata.m_transformationRotation[3].ToString(); } else { m_selectedMetadata = null; m_detailsParent.gameObject.SetActive(false); } } /// <summary> /// Actually do the Area Description save. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoSaveCurrentAreaDescription() { if (TouchScreenKeyboard.visible || m_saveThread != null) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("Unnamed"); while (!kb.done && !kb.wasCanceled) { yield return null; } // Save the text in a background thread. m_savingTextParent.gameObject.SetActive(true); m_saveThread = new Thread(delegate() { // Save the name put in with the Area Description. AreaDescription areaDescription = AreaDescription.SaveCurrent(); AreaDescription.Metadata metadata = areaDescription.GetMetadata(); metadata.m_name = kb.text; areaDescription.SaveMetadata(metadata); }); m_saveThread.Start(); } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.GeoDatabaseDistributed; namespace RasterSyncExtension { /// <summary> /// An example of a workspace extension that extends the synchronization process. This /// implementation synchronizes a specific raster catalog in addition to the out-of-the-box /// synchronization process. /// </summary> [Guid("97CD2883-37CB-4f76-BD0F-945279C783DC")] [ClassInterface(ClassInterfaceType.None)] [ProgId("RasterSyncExtension.RasterSyncWorkspaceExtension")] [ComVisible(true)] public class RasterSyncWorkspaceExtension : IWorkspaceExtensionControl, IWorkspaceExtension2, IWorkspaceReplicaSyncEvents { #region Private Variables /// <summary> /// Provides a weak reference to the extension's workspace. /// </summary> private IWorkspaceHelper workspaceHelper = null; /// <summary> /// The name of the raster catalog to synchronize. /// </summary> private const String rasterCatalogName = "ras_cat"; /// <summary> /// The name of the replica that requires raster synchronization. /// </summary> private const String rasterReplicaName = "myreplicaras"; /// <summary> /// The name of the integer field in the raster catalogs that stores generation numbers. /// </summary> private const String genFieldName = "gen"; #endregion #region IWorkspaceExtensionControl Members /// <summary> /// Initializes the workspace extension. /// </summary> /// <param name="workspaceHelper">Provides a weak reference to the workspace.</param> public void Init(IWorkspaceHelper workspaceHelper) { this.workspaceHelper = workspaceHelper; } /// <summary> /// Called to shutdown the extension. /// </summary> public void Shutdown() { workspaceHelper = null; } #endregion #region IWorkspaceExtension2 Members /// <summary> /// The name of the extension. /// </summary> public string Name { get { return "RasterSyncWorkspaceExtension"; } } /// <summary> /// The extension's GUID. /// </summary> public UID GUID { get { UID uid = new UIDClass(); uid.Value = "{97CD2883-37CB-4f76-BD0F-945279C783DC}"; return uid; } } /// <summary> /// An enumerator of private dataset names used by the extension. /// Not used in this implementation. /// </summary> /// <param name="datasetType">The dataset type.</param> /// <returns>An enumerator of strings.</returns> public IEnumBSTR get_PrivateDatasetNames(esriDatasetType datasetType) { return null; } /// <summary> /// An enumerator of data dictionary names used by the extension. /// Not used in this implementation. /// </summary> public IEnumBSTR DataDictionaryTableNames { get { return null; } } /// <summary> /// Indicates whether the extension owns a dataset type. /// </summary> /// <param name="datasetType">The type of dataset to check.</param> /// <returns>False; this extension owns no dataset types.</returns> public Boolean OwnsDatasetType(esriDatasetType datasetType) { return false; } /// <summary> /// Returns a reference to the extension's workspace. /// </summary> public IWorkspace Workspace { get { return workspaceHelper.Workspace; } } #endregion #region IWorkspaceReplicaSyncEvents Members /// <summary> /// Occurs in the replica geodatabase after data changes have been exported /// from that replica geodatabase to a delta database. /// Not used in this implementation. /// </summary> public void AfterExportingDataChanges(IReplica sourceReplica, object dataChangesSource, object deltaFile) { // Not used in this implementation. } /// <summary> /// Occurs in the master geodatabase after data changes in either a replica /// geodatabase or delta database are transferred to the master geodatabase. /// </summary> /// <param name="targetReplica">The target replica.</param> /// <param name="dataChangesSource">A collection of changes made to the master geodatabase.</param> /// <param name="oidMappingTable">Not used in this implementation.</param> /// <param name="changesTable">Not used in this implemented.</param> public void AfterSynchronizingDataChanges(IReplica targetReplica, object dataChangesSource, ITable oidMappingTable, ITable changesTable) { // Make sure that the correct replica is being synchronized. String replicaName = targetReplica.Name; String unqualifiedReplicaName = replicaName.Substring(replicaName.LastIndexOf('.') + 1); if (!unqualifiedReplicaName.Equals(rasterReplicaName)) { return; } // Get the rasters to pull if connected synchronization is occurring. IDataChanges3 dataChanges3 = dataChangesSource as IDataChanges3; if (dataChanges3 != null) { // Get the source's replicas. IName sourceWorkspaceName = (IName)dataChanges3.ParentWorkspaceName; IWorkspace sourceWorkspace = (IWorkspace)sourceWorkspaceName.Open(); IWorkspaceReplicas sourceWorkspaceReplicas = (IWorkspaceReplicas)sourceWorkspace; // Get the replica generation numbers. int genBegin = 0; int genEnd = 0; int targetGen = 0; dataChanges3.GenerationNumbers(out genBegin, out genEnd, out targetGen); IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = String.Format("{0} > {1} or {0} is NULL", genFieldName, genBegin); // Open a cursor to get the rasters to copy form the source. IRasterWorkspaceEx sourceRasterWorkspaceEx = (IRasterWorkspaceEx)sourceWorkspace; IRasterCatalog sourceRasterCatalog = sourceRasterWorkspaceEx.OpenRasterCatalog(rasterCatalogName); IFeatureClass sourceFeatureClass = (IFeatureClass)sourceRasterCatalog; int sourceGenFieldIndex = sourceFeatureClass.FindField(genFieldName); IFeatureCursor sourceCursor = sourceFeatureClass.Search(queryFilter, true); // Open the target raster catalog. IRasterWorkspaceEx targetRasterWorkspaceEx = (IRasterWorkspaceEx)workspaceHelper.Workspace; IRasterCatalog targetRasterCatalog = targetRasterWorkspaceEx.OpenRasterCatalog(rasterCatalogName); IFeatureClass targetFeatureClass = (IFeatureClass)targetRasterCatalog; int targetGenFieldIndex = targetFeatureClass.FindField(genFieldName); IFeatureCursor targetCursor = targetFeatureClass.Insert(true); // Copy the rasters from the source to the target. IFeature sourceFeature = null; while ((sourceFeature = sourceCursor.NextFeature()) != null) { // Copy the raster and set the target gen to -1 (received). IFeatureBuffer featureBuffer = targetFeatureClass.CreateFeatureBuffer(); featureBuffer.set_Value(targetRasterCatalog.RasterFieldIndex, sourceFeature.get_Value(sourceRasterCatalog.RasterFieldIndex)); featureBuffer.set_Value(targetGenFieldIndex, -1); targetCursor.InsertFeature(featureBuffer); // Set the source row value to the current generation. if (sourceFeature.get_Value(sourceGenFieldIndex) == DBNull.Value) { sourceFeature.set_Value(sourceGenFieldIndex, genEnd); } sourceFeature.Store(); } Marshal.FinalReleaseComObject(sourceCursor); Marshal.FinalReleaseComObject(targetCursor); } } /// <summary> /// Occurs in the replica geodatabase before data changes are exported from that replica geodatabase to a delta database. /// Not used in this implementation. /// </summary> public void BeforeExportingDataChanges(IReplica sourceReplica, object dataChangesSource, object deltaFile) { // Not used in this implementation. } /// <summary> /// Occurs in the master geodatabase before data changes in either a replica geodatabase or delta /// database are transferred to the master geodatabase. /// Not used in this implementation. /// </summary> public void BeforeSynchronizingDataChanges(IReplica targetReplica, object dataChangesSource) { // Not used in this implementation. } #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.Rfc2251.RfcLdapMessage.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.IO; using Novell.Directory.LDAP.VQ.Asn1; namespace Novell.Directory.LDAP.VQ.Rfc2251 { /// <summary> Represents an Ldap Message. /// /// <pre> /// LdapMessage ::= SEQUENCE { /// messageID MessageID, /// protocolOp CHOICE { /// bindRequest BindRequest, /// bindResponse BindResponse, /// unbindRequest UnbindRequest, /// searchRequest SearchRequest, /// searchResEntry SearchResultEntry, /// searchResDone SearchResultDone, /// searchResRef SearchResultReference, /// modifyRequest ModifyRequest, /// modifyResponse ModifyResponse, /// addRequest AddRequest, /// addResponse AddResponse, /// delRequest DelRequest, /// delResponse DelResponse, /// modDNRequest ModifyDNRequest, /// modDNResponse ModifyDNResponse, /// compareRequest CompareRequest, /// compareResponse CompareResponse, /// abandonRequest AbandonRequest, /// extendedReq ExtendedRequest, /// extendedResp ExtendedResponse }, /// controls [0] Controls OPTIONAL } /// </pre> /// /// /// Note: The creation of a MessageID should be hidden within the creation of /// an RfcLdapMessage. The MessageID needs to be in sequence, and has an /// upper and lower limit. There is never a case when a user should be /// able to specify the MessageID for an RfcLdapMessage. The MessageID() /// constructor should be package protected. (So the MessageID value /// isn't arbitrarily run up.) /// </summary> public class RfcLdapMessage : Asn1Sequence { /// <summary> Returns this RfcLdapMessage's messageID as an int.</summary> virtual public int MessageID { get { return ((Asn1Integer)get_Renamed(0)).intValue(); } } /// <summary> Returns this RfcLdapMessage's message type</summary> virtual public int Type { get { return get_Renamed(1).getIdentifier().Tag; } } /// <summary> Returns the response associated with this RfcLdapMessage. /// Can be one of RfcLdapResult, RfcBindResponse, RfcExtendedResponse /// all which extend RfcResponse. It can also be /// RfcSearchResultEntry, or RfcSearchResultReference /// </summary> virtual public Asn1Object Response { get { return get_Renamed(1); } } /// <summary> Returns the optional Controls for this RfcLdapMessage.</summary> virtual public RfcControls Controls { get { if (size() > 2) return (RfcControls)get_Renamed(2); return null; } } /// <summary> Returns the dn of the request, may be null</summary> virtual public string RequestDN { get { return ((RfcRequest)op).getRequestDN(); } } /// <summary> returns the original request in this message /// /// </summary> /// <returns> the original msg request for this response /// </returns> /// <summary> sets the original request in this message /// /// </summary> /// <param name="msg">the original request for this response /// </param> virtual public LdapMessage RequestingMessage { get { return requestMessage; } set { requestMessage = value; } } private Asn1Object op; private RfcControls controls; private LdapMessage requestMessage = null; /// <summary> Create an RfcLdapMessage by copying the content array /// /// </summary> /// <param name="origContent">the array list to copy /// </param> /* package */ internal RfcLdapMessage(Asn1Object[] origContent, RfcRequest origRequest, string dn, string filter, bool reference) : base(origContent, origContent.Length) { set_Renamed(0, new RfcMessageID()); // MessageID has static counter RfcRequest req = (RfcRequest)origContent[1]; RfcRequest newreq = req.dupRequest(dn, filter, reference); op = (Asn1Object)newreq; set_Renamed(1, (Asn1Object)newreq); } /// <summary> Create an RfcLdapMessage using the specified Ldap Request.</summary> public RfcLdapMessage(RfcRequest op) : this(op, null) { } /// <summary> Create an RfcLdapMessage request from input parameters.</summary> public RfcLdapMessage(RfcRequest op, RfcControls controls) : base(3) { this.op = (Asn1Object)op; this.controls = controls; add(new RfcMessageID()); // MessageID has static counter add((Asn1Object)op); if (controls != null) { add(controls); } } /// <summary> Create an RfcLdapMessage using the specified Ldap Response.</summary> public RfcLdapMessage(Asn1Sequence op) : this(op, null) { } /// <summary> Create an RfcLdapMessage response from input parameters.</summary> public RfcLdapMessage(Asn1Sequence op, RfcControls controls) : base(3) { this.op = op; this.controls = controls; add(new RfcMessageID()); // MessageID has static counter add(op); if (controls != null) { add(controls); } } /// <summary> Will decode an RfcLdapMessage directly from an InputStream.</summary> [CLSCompliant(false)] public RfcLdapMessage(Asn1Decoder dec, Stream in_Renamed, int len) : base(dec, in_Renamed, len) { sbyte[] content; MemoryStream bais; // Decode implicitly tagged protocol operation from an Asn1Tagged type // to its appropriate application type. Asn1Tagged protocolOp = (Asn1Tagged)get_Renamed(1); Asn1Identifier protocolOpId = protocolOp.getIdentifier(); content = ((Asn1OctetString)protocolOp.taggedValue()).byteValue(); bais = new MemoryStream(SupportClass.ToByteArray(content)); switch (protocolOpId.Tag) { case LdapMessage.SEARCH_RESPONSE: set_Renamed(1, new RfcSearchResultEntry(dec, bais, content.Length)); break; case LdapMessage.SEARCH_RESULT: set_Renamed(1, new RfcSearchResultDone(dec, bais, content.Length)); break; case LdapMessage.SEARCH_RESULT_REFERENCE: set_Renamed(1, new RfcSearchResultReference(dec, bais, content.Length)); break; case LdapMessage.ADD_RESPONSE: set_Renamed(1, new RfcAddResponse(dec, bais, content.Length)); break; case LdapMessage.BIND_RESPONSE: set_Renamed(1, new RfcBindResponse(dec, bais, content.Length)); break; case LdapMessage.COMPARE_RESPONSE: set_Renamed(1, new RfcCompareResponse(dec, bais, content.Length)); break; case LdapMessage.DEL_RESPONSE: set_Renamed(1, new RfcDelResponse(dec, bais, content.Length)); break; case LdapMessage.EXTENDED_RESPONSE: set_Renamed(1, new RfcExtendedResponse(dec, bais, content.Length)); break; case LdapMessage.INTERMEDIATE_RESPONSE: set_Renamed(1, new RfcIntermediateResponse(dec, bais, content.Length)); break; case LdapMessage.MODIFY_RESPONSE: set_Renamed(1, new RfcModifyResponse(dec, bais, content.Length)); break; case LdapMessage.MODIFY_RDN_RESPONSE: set_Renamed(1, new RfcModifyDNResponse(dec, bais, content.Length)); break; default: throw new Exception("RfcLdapMessage: Invalid tag: " + protocolOpId.Tag); } // decode optional implicitly tagged controls from Asn1Tagged type to // to RFC 2251 types. if (size() > 2) { Asn1Tagged controls = (Asn1Tagged)get_Renamed(2); // Asn1Identifier controlsId = protocolOp.getIdentifier(); // we could check to make sure we have controls here.... content = ((Asn1OctetString)controls.taggedValue()).byteValue(); bais = new MemoryStream(SupportClass.ToByteArray(content)); set_Renamed(2, new RfcControls(dec, bais, content.Length)); } } //************************************************************************* // Accessors //************************************************************************* /// <summary> Returns the request associated with this RfcLdapMessage. /// Throws a class cast exception if the RfcLdapMessage is not a request. /// </summary> public RfcRequest getRequest() { return (RfcRequest)get_Renamed(1); } public virtual bool isRequest() { return get_Renamed(1) is RfcRequest; } /// <summary> Duplicate this message, replacing base dn, filter, and scope if supplied /// /// </summary> /// <param name="dn">the base dn /// /// </param> /// <param name="filter">the filter /// /// </param> /// <param name="reference">true if a search reference /// /// </param> /// <returns> the object representing the new message /// </returns> public object dupMessage(string dn, string filter, bool reference) { if ((op == null)) { throw new LdapException("DUP_ERROR", LdapException.LOCAL_ERROR, (string)null); } RfcLdapMessage newMsg = new RfcLdapMessage(toArray(), (RfcRequest)get_Renamed(1), dn, filter, reference); return newMsg; } } }
namespace MicroMapper.UnitTests { using System; using System.Collections; using System.Collections.Generic; using Should; using Xunit; namespace Regression { public class TestDomainItem : ITestDomainItem { public Guid ItemId { get; set; } } public interface ITestDomainItem { Guid ItemId { get; } } public class TestDtoItem { public Guid Id { get; set; } } public class Mapper_fails_to_map_custom_mappings_when_mapping_collections_for_an_interface { public Mapper_fails_to_map_custom_mappings_when_mapping_collections_for_an_interface() { Setup(); } public void Setup() { Mapper.Reset(); } [Fact] public void Should_map_the_id_property() { var domainItems = new List<ITestDomainItem> { new TestDomainItem {ItemId = Guid.NewGuid()}, new TestDomainItem {ItemId = Guid.NewGuid()} }; Mapper.CreateMap<ITestDomainItem, TestDtoItem>() .ForMember(d => d.Id, s => s.MapFrom(x => x.ItemId)); Mapper.AssertConfigurationIsValid(); var dtos = Mapper.Map<IEnumerable<ITestDomainItem>, TestDtoItem[]>(domainItems); domainItems[0].ItemId.ShouldEqual(dtos[0].Id); } } public class Chris_bennages_nullable_datetime_issue : AutoMapperSpecBase { private Destination _result; public class Source { public DateTime? SomeDate { get; set; } } public class Destination { public MyCustomDate SomeDate { get; set; } } public class MyCustomDate { public int Day { get; set; } public int Month { get; set; } public int Year { get; set; } public MyCustomDate(int day, int month, int year) { Day = day; Month = month; Year = year; } } protected override void Establish_context() { Mapper.CreateMap<Source, Destination>(); Mapper.CreateMap<DateTime?, MyCustomDate>() .ConvertUsing( src => src.HasValue ? new MyCustomDate(src.Value.Day, src.Value.Month, src.Value.Year) : null); } protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {SomeDate = new DateTime(2005, 12, 1)}); } [Fact] public void Should_map_a_date_with_a_value() { _result.SomeDate.Day.ShouldEqual(1); } [Fact] public void Should_map_null_to_null() { var destination = Mapper.Map<Source, Destination>(new Source()); destination.SomeDate.ShouldBeNull(); } } public class When_mappings_are_created_on_the_fly : NonValidatingSpecBase { public class Order { public string Name { get; set; } public Product Product { get; set; } } public class Product { public string ProductName { get; set; } } [Fact(Skip = "I don't like this scenario, don't create mappings on the fly")] public void Should_not_use_AssignableMapper_when_mappings_are_specified_on_the_fly() { Mapper.CreateMap<Order, Order>(); var sourceOrder = new Order() { Name = "order", Product = new Product() {ProductName = "product"} }; var destinationOrder = new Order(); destinationOrder = Mapper.Map(sourceOrder, destinationOrder); // Defining this mapping on the fly, but since the previous call to Mapper.Map() // had to deal with mapping Product to Product, it created an AssignableMapper // which will get used in place of this one. I would expect that if I call // Mapper.CreateMap(), that should replace any cached value in // MappingEngine._objectMapperCache. Mapper.CreateMap<Product, Product>(); var sourceProduct = new Product() {ProductName = "name"}; var destinationProduct = new Product(); destinationProduct = Mapper.Map(sourceProduct, destinationProduct); sourceProduct.ProductName.ShouldEqual(destinationProduct.ProductName); sourceProduct.ShouldNotEqual(destinationProduct); } } public class TestEnumerable : AutoMapperSpecBase { protected override void Establish_context() { Mapper.Initialize(cfg => cfg.CreateMap<Person, PersonModel>()); } [Fact] public void MapsEnumerableTypes() { Person[] personArr = new[] {new Person() {Name = "Name"}}; People people = new People(personArr); var pmc = Mapper.Map<People, List<PersonModel>>(people); pmc.ShouldNotBeNull(); (pmc.Count == 1).ShouldBeTrue(); } public class People : IEnumerable { private readonly Person[] people; public People(Person[] people) { this.people = people; } public IEnumerator GetEnumerator() { foreach (var person in people) { yield return person; } } } public class Person { public string Name { get; set; } } public class PersonModel { public string Name { get; set; } } } } }
namespace Palaso.UI.WindowsForms.WritingSystems { partial class WritingSystemSetupView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this._treeView = new Palaso.UI.WindowsForms.WritingSystems.WSTree.WritingSystemTreeView(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this._languageName = new Palaso.UI.WindowsForms.Widgets.BetterLabel(); this._rfc4646 = new Palaso.UI.WindowsForms.Widgets.BetterLabel(); this._propertiesTabControl = new Palaso.UI.WindowsForms.WritingSystems.WSPropertiesTabControl(); this._buttonBar = new Palaso.UI.WindowsForms.WritingSystems.WSAddDuplicateMoreButtonBar(); this.localizationHelper1 = new Palaso.UI.WindowsForms.i18n.LocalizationHelper(this.components); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.localizationHelper1)).BeginInit(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer1.IsSplitterFixed = true; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.splitContainer2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this._buttonBar); this.splitContainer1.Size = new System.Drawing.Size(841, 461); this.splitContainer1.SplitterDistance = 422; this.splitContainer1.TabIndex = 2; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this._treeView); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.tableLayoutPanel1); this.splitContainer2.Panel2.Controls.Add(this._propertiesTabControl); this.splitContainer2.Size = new System.Drawing.Size(841, 422); this.splitContainer2.SplitterDistance = 222; this.splitContainer2.SplitterWidth = 10; this.splitContainer2.TabIndex = 0; // // _treeView // this._treeView.BackColor = System.Drawing.Color.White; this._treeView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._treeView.Dock = System.Windows.Forms.DockStyle.Fill; this._treeView.Location = new System.Drawing.Point(0, 0); this._treeView.Name = "_treeView"; this._treeView.Padding = new System.Windows.Forms.Padding(10, 10, 0, 0); this._treeView.Size = new System.Drawing.Size(222, 422); this._treeView.TabIndex = 1; // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 66.66666F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel1.Controls.Add(this._languageName, 0, 0); this.tableLayoutPanel1.Controls.Add(this._rfc4646, 1, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(603, 27); this.tableLayoutPanel1.TabIndex = 3; // // _languageName // this._languageName.Dock = System.Windows.Forms.DockStyle.Fill; this._languageName.BorderStyle = System.Windows.Forms.BorderStyle.None; this._languageName.Font = new System.Drawing.Font("Segoe UI", 9F); this._languageName.Location = new System.Drawing.Point(3, 3); this._languageName.Multiline = true; this._languageName.Name = "_languageName"; this._languageName.ReadOnly = true; this._languageName.Size = new System.Drawing.Size(395, 21); this._languageName.TabIndex = 1; this._languageName.TabStop = false; this._languageName.Text = "Language Name"; // // _rfc4646 // this._rfc4646.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._rfc4646.BorderStyle = System.Windows.Forms.BorderStyle.None; this._rfc4646.Font = new System.Drawing.Font("Segoe UI", 9F); this._rfc4646.Location = new System.Drawing.Point(404, 3); this._rfc4646.Multiline = true; this._rfc4646.Name = "_rfc4646"; this._rfc4646.ReadOnly = true; this._rfc4646.Size = new System.Drawing.Size(196, 21); this._rfc4646.TabIndex = 2; this._rfc4646.TabStop = false; this._rfc4646.Text = "foo-CN-variant1-a-extend1-x-wadefile"; this._rfc4646.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // _propertiesTabControl // this._propertiesTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._propertiesTabControl.Location = new System.Drawing.Point(0, 30); this._propertiesTabControl.Name = "_propertiesTabControl"; this._propertiesTabControl.Size = new System.Drawing.Size(609, 392); this._propertiesTabControl.TabIndex = 0; this._propertiesTabControl.Load += new System.EventHandler(this._propertiesTabControl_Load); // // _buttonBar // this._buttonBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._buttonBar.Location = new System.Drawing.Point(0, 4); this._buttonBar.Name = "_buttonBar"; this._buttonBar.Size = new System.Drawing.Size(841, 31); this._buttonBar.TabIndex = 0; // // localizationHelper1 // this.localizationHelper1.Parent = this; // // WritingSystemSetupView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer1); this.Name = "WritingSystemSetupView"; this.Size = new System.Drawing.Size(841, 461); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.localizationHelper1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private WSAddDuplicateMoreButtonBar _buttonBar; private System.Windows.Forms.SplitContainer splitContainer2; private WSPropertiesTabControl _propertiesTabControl; private Palaso.UI.WindowsForms.WritingSystems.WSTree.WritingSystemTreeView _treeView; private Palaso.UI.WindowsForms.Widgets.BetterLabel _rfc4646; private Palaso.UI.WindowsForms.Widgets.BetterLabel _languageName; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private i18n.LocalizationHelper localizationHelper1; } }
using System; using System.Runtime.CompilerServices; using QUnit; #pragma warning disable 184, 458, 1720 namespace CoreLib.TestScript.Reflection { [TestFixture] public class TypeSystemLanguageSupportTests { public class C1 {} [IncludeGenericArguments] public class C2<T> {} public interface I1 {} [IncludeGenericArguments] public interface I2<T1> {} public interface I3 : I1 {} public interface I4 {} [IncludeGenericArguments] public interface I5<T1> : I2<T1> {} [IncludeGenericArguments] public interface I6<out T> {} [IncludeGenericArguments] public interface I7<in T> {} [IncludeGenericArguments] public interface I8<out T1, in T2> : I6<T1>, I7<T2> {} [IncludeGenericArguments] public interface I9<T1, out T2> {} [IncludeGenericArguments] public interface I10<out T1, in T2> : I8<T1,T2> {} public class D1 : C1, I1 { } [IncludeGenericArguments] public class D2<T> : C2<T>, I2<T>, I1 { } public class D3 : C2<int>, I2<string> { } public class D4 : I3, I4 { } public class X1 : I1 { } public class X2 : X1 { } [IncludeGenericArguments] public class Y1<T> : I6<T> {} public class Y1X1 : Y1<X1> {} public class Y1X2 : Y1<X2> {} [IncludeGenericArguments] public class Y2<T> : I7<T> {} public class Y2X1 : Y2<X1> {} public class Y2X2 : Y2<X2> {} [IncludeGenericArguments] public class Y3<T1, T2> : I8<T1, T2> {} public class Y3X1X1 : Y3<X1, X1> {} public class Y3X1X2 : Y3<X1, X2> {} public class Y3X2X1 : Y3<X2, X1> {} public class Y3X2X2 : Y3<X2, X2> {} [IncludeGenericArguments] public class Y4<T1, T2> : I9<T1, T2> {} public class Y5<T1, T2> : I6<I8<T1, T2>> {} public class Y6<T1, T2> : I7<I8<T1, T2>> {} public enum E1 {} public enum E2 {} [Serializable] public class BS { public int X; public BS(int x) { X = x; } } [Serializable(TypeCheckCode = "{$System.Script}.isValue({this}.y)")] public class DS : BS { public DS() : base(0) {} } [Imported(TypeCheckCode = "{$System.Script}.isValue({this}.y)")] public class CI { } [IncludeGenericArguments] private static bool CanConvert<T>(object arg) { try { #pragma warning disable 219 // The variable `x' is assigned but its value is never used var x = (T)arg; #pragma warning restore 219 return true; } catch { return false; } } [Test] public void TypeIsWorksForReferenceTypes() { Assert.IsFalse((object)new object() is C1, "#1"); Assert.IsTrue ((object)new C1() is object, "#2"); Assert.IsFalse((object)new object() is I1, "#3"); Assert.IsFalse((object)new C1() is D1, "#4"); Assert.IsTrue ((object)new D1() is C1, "#5"); Assert.IsTrue ((object)new D1() is I1, "#6"); Assert.IsTrue ((object)new D2<int>() is C2<int>, "#7"); Assert.IsFalse((object)new D2<int>() is C2<string>, "#8"); Assert.IsTrue ((object)new D2<int>() is I2<int>, "#9"); Assert.IsFalse((object)new D2<int>() is I2<string>, "#10"); Assert.IsTrue ((object)new D2<int>() is I1, "#11"); Assert.IsFalse((object)new D3() is C2<string>, "#12"); Assert.IsTrue ((object)new D3() is C2<int>, "#13"); Assert.IsFalse((object)new D3() is I2<int>, "#14"); Assert.IsTrue ((object)new D3() is I2<string>, "#15"); Assert.IsTrue ((object)new D4() is I1, "#16"); Assert.IsTrue ((object)new D4() is I3, "#17"); Assert.IsTrue ((object)new D4() is I4, "#18"); Assert.IsTrue ((object)new X2() is I1, "#19"); Assert.IsTrue ((object)new E2() is E1, "#20"); Assert.IsTrue ((object)new E1() is int, "#21"); Assert.IsTrue ((object)new E1() is object, "#22"); Assert.IsFalse((object)new Y1<X1>() is I7<X1>, "#23"); Assert.IsTrue ((object)new Y1<X1>() is I6<X1>, "#24"); Assert.IsTrue ((object)new Y1X1() is I6<X1>, "#25"); Assert.IsFalse((object)new Y1<X1>() is I6<X2>, "#26"); Assert.IsFalse((object)new Y1X1() is I6<X2>, "#27"); Assert.IsTrue ((object)new Y1<X2>() is I6<X1>, "#28"); Assert.IsTrue ((object)new Y1X2() is I6<X1>, "#29"); Assert.IsTrue ((object)new Y1<X2>() is I6<X2>, "#30"); Assert.IsTrue ((object)new Y1X2() is I6<X2>, "#31"); Assert.IsFalse((object)new Y2<X1>() is I6<X1>, "#32"); Assert.IsTrue ((object)new Y2<X1>() is I7<X1>, "#33"); Assert.IsTrue ((object)new Y2X1() is I7<X1>, "#34"); Assert.IsTrue ((object)new Y2<X1>() is I7<X2>, "#35"); Assert.IsTrue ((object)new Y2X1() is I7<X2>, "#36"); Assert.IsFalse((object)new Y2<X2>() is I7<X1>, "#37"); Assert.IsFalse((object)new Y2X2() is I7<X1>, "#38"); Assert.IsTrue ((object)new Y2<X2>() is I7<X2>, "#39"); Assert.IsTrue ((object)new Y2X2() is I7<X2>, "#40"); Assert.IsFalse((object)new Y3<X1, X1>() is I1, "#41"); Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X1>, "#42"); Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X1>, "#43"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X1, X1>, "#44"); Assert.IsFalse((object)new Y3X1X2() is I8<X1, X1>, "#45"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X1>, "#46"); Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X1>, "#47"); Assert.IsFalse((object)new Y3<X2, X2>() is I8<X1, X1>, "#48"); Assert.IsFalse((object)new Y3X2X2() is I8<X1, X1>, "#49"); Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X2>, "#50"); Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X2>, "#51"); Assert.IsTrue ((object)new Y3<X1, X2>() is I8<X1, X2>, "#52"); Assert.IsTrue ((object)new Y3X1X2() is I8<X1, X2>, "#53"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X2>, "#54"); Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X2>, "#55"); Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X1, X2>, "#56"); Assert.IsTrue ((object)new Y3X2X2() is I8<X1, X2>, "#57"); Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X1>, "#58"); Assert.IsFalse((object)new Y3X1X1() is I8<X2, X1>, "#59"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X1>, "#60"); Assert.IsFalse((object)new Y3X1X2() is I8<X2, X1>, "#61"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X1>, "#62"); Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X1>, "#63"); Assert.IsFalse((object)new Y3<X2, X2>() is I8<X2, X1>, "#64"); Assert.IsFalse((object)new Y3X2X2() is I8<X2, X1>, "#65"); Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X2>, "#66"); Assert.IsFalse((object)new Y3X1X1() is I8<X2, X2>, "#67"); Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X2>, "#68"); Assert.IsFalse((object)new Y3X1X2() is I8<X2, X2>, "#69"); Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X2>, "#70"); Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X2>, "#71"); Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X2, X2>, "#72"); Assert.IsTrue ((object)new Y3X2X2() is I8<X2, X2>, "#73"); Assert.IsTrue ((object)new Y4<string, X1>() is I9<string, X1>, "#74"); Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X1>, "#75"); Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X1>, "#76"); Assert.IsTrue ((object)new Y4<object, X1>() is I9<object, X1>, "#77"); Assert.IsFalse((object)new Y4<string, X1>() is I9<string, X2>, "#78"); Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X2>, "#79"); Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X2>, "#80"); Assert.IsFalse((object)new Y4<object, X1>() is I9<object, X2>, "#81"); Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X1>, "#82"); Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X1>, "#83"); Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X1>, "#84"); Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X1>, "#85"); Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X2>, "#86"); Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X2>, "#87"); Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X2>, "#88"); Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X2>, "#89"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I6<X1>>, "#90"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X1>>, "#91"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I6<X2>>, "#92"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X2>>, "#93"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X1>>, "#94"); Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X2>>, "#95"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X1>>, "#96"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X2>>, "#97"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X1>>, "#98"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X2>>, "#99"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X1>>, "#100"); Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X2>>, "#101"); Assert.IsTrue((object)new Y5<X2, X2>() is I6<I6<X1>>, "#102"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I7<X1>>, "#103"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I6<X2>>, "#104"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I7<X2>>, "#105"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X1, X1>>, "#106"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X1, X2>>, "#107"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X2, X1>>, "#108"); Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X2, X2>>, "#109"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X1>>, "#110"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X2>>, "#111"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X1>>, "#112"); Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X2>>, "#113"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X1>>, "#114"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X1>>, "#115"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X2>>, "#116"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X2>>, "#117"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X1, X1>>, "#118"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X1, X2>>, "#119"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X2, X1>>, "#120"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X2, X2>>, "#121"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X1, X1>>, "#122"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X1, X2>>, "#123"); Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X2, X1>>, "#124"); Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X2, X2>>, "#125"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X1>>, "#126"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X1>>, "#127"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X2>>, "#128"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X2>>, "#129"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X1>>, "#130"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X2>>, "#131"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X1>>, "#132"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X2>>, "#133"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X1>>, "#134"); Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X2>>, "#135"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X1>>, "#136"); Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X2>>, "#137"); Assert.IsFalse((object)null is object, "#138"); } [Test] public void TypeAsWorksForReferenceTypes() { Assert.IsFalse(((object)new object() as C1) != null, "#1"); Assert.IsTrue (((object)new C1() as object) != null, "#2"); Assert.IsFalse(((object)new object() as I1) != null, "#3"); Assert.IsFalse(((object)new C1() as D1) != null, "#4"); Assert.IsTrue (((object)new D1() as C1) != null, "#5"); Assert.IsTrue (((object)new D1() as I1) != null, "#6"); Assert.IsTrue (((object)new D2<int>() as C2<int>) != null, "#7"); Assert.IsFalse(((object)new D2<int>() as C2<string>) != null, "#8"); Assert.IsTrue (((object)new D2<int>() as I2<int>) != null, "#9"); Assert.IsFalse(((object)new D2<int>() as I2<string>) != null, "#10"); Assert.IsTrue (((object)new D2<int>() as I1) != null, "#11"); Assert.IsFalse(((object)new D3() as C2<string>) != null, "#12"); Assert.IsTrue (((object)new D3() as C2<int>) != null, "#13"); Assert.IsFalse(((object)new D3() as I2<int>) != null, "#14"); Assert.IsTrue (((object)new D3() as I2<string>) != null, "#15"); Assert.IsTrue (((object)new D4() as I1) != null, "#16"); Assert.IsTrue (((object)new D4() as I3) != null, "#17"); Assert.IsTrue (((object)new D4() as I4) != null, "#18"); Assert.IsTrue (((object)new X2() as I1) != null, "#19"); Assert.IsTrue (((object)new E2() as E1?) != null, "#20"); Assert.IsTrue (((object)new E1() as int?) != null, "#21"); Assert.IsTrue (((object)new E1() as object) != null, "#22"); Assert.IsFalse(((object)new Y1<X1>() as I7<X1>) != null, "#23"); Assert.IsTrue (((object)new Y1<X1>() as I6<X1>) != null, "#24"); Assert.IsTrue (((object)new Y1X1() as I6<X1>) != null, "#25"); Assert.IsFalse(((object)new Y1<X1>() as I6<X2>) != null, "#26"); Assert.IsFalse(((object)new Y1X1() as I6<X2>) != null, "#27"); Assert.IsTrue (((object)new Y1<X2>() as I6<X1>) != null, "#28"); Assert.IsTrue (((object)new Y1X2() as I6<X1>) != null, "#29"); Assert.IsTrue (((object)new Y1<X2>() as I6<X2>) != null, "#30"); Assert.IsTrue (((object)new Y1X2() as I6<X2>) != null, "#31"); Assert.IsFalse(((object)new Y2<X1>() as I6<X1>) != null, "#32"); Assert.IsTrue (((object)new Y2<X1>() as I7<X1>) != null, "#33"); Assert.IsTrue (((object)new Y2X1() as I7<X1>) != null, "#34"); Assert.IsTrue (((object)new Y2<X1>() as I7<X2>) != null, "#35"); Assert.IsTrue (((object)new Y2X1() as I7<X2>) != null, "#36"); Assert.IsFalse(((object)new Y2<X2>() as I7<X1>) != null, "#37"); Assert.IsFalse(((object)new Y2X2() as I7<X1>) != null, "#38"); Assert.IsTrue (((object)new Y2<X2>() as I7<X2>) != null, "#39"); Assert.IsTrue (((object)new Y2X2() as I7<X2>) != null, "#40"); Assert.IsFalse(((object)new Y3<X1, X1>() as I1) != null, "#41"); Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X1>) != null, "#42"); Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X1>) != null, "#43"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X1, X1>) != null, "#44"); Assert.IsFalse(((object)new Y3X1X2() as I8<X1, X1>) != null, "#45"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X1>) != null, "#46"); Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X1>) != null, "#47"); Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X1, X1>) != null, "#48"); Assert.IsFalse(((object)new Y3X2X2() as I8<X1, X1>) != null, "#49"); Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X2>) != null, "#50"); Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X2>) != null, "#51"); Assert.IsTrue (((object)new Y3<X1, X2>() as I8<X1, X2>) != null, "#52"); Assert.IsTrue (((object)new Y3X1X2() as I8<X1, X2>) != null, "#53"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X2>) != null, "#54"); Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X2>) != null, "#55"); Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X1, X2>) != null, "#56"); Assert.IsTrue (((object)new Y3X2X2() as I8<X1, X2>) != null, "#57"); Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X1>) != null, "#58"); Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X1>) != null, "#59"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X1>) != null, "#60"); Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X1>) != null, "#61"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X1>) != null, "#62"); Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X1>) != null, "#63"); Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X2, X1>) != null, "#64"); Assert.IsFalse(((object)new Y3X2X2() as I8<X2, X1>) != null, "#65"); Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X2>) != null, "#66"); Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X2>) != null, "#67"); Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X2>) != null, "#68"); Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X2>) != null, "#69"); Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X2>) != null, "#70"); Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X2>) != null, "#71"); Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X2, X2>) != null, "#72"); Assert.IsTrue (((object)new Y3X2X2() as I8<X2, X2>) != null, "#73"); Assert.IsTrue (((object)new Y4<string, X1>() as I9<string, X1>) != null, "#74"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X1>) != null, "#75"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X1>) != null, "#76"); Assert.IsTrue (((object)new Y4<object, X1>() as I9<object, X1>) != null, "#77"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<string, X2>) != null, "#78"); Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X2>) != null, "#79"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X2>) != null, "#80"); Assert.IsFalse(((object)new Y4<object, X1>() as I9<object, X2>) != null, "#81"); Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X1>) != null, "#82"); Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X1>) != null, "#83"); Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X1>) != null, "#84"); Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X1>) != null, "#85"); Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X2>) != null, "#86"); Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X2>) != null, "#87"); Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X2>) != null, "#88"); Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X2>) != null, "#89"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I6<X1>>) != null, "#90"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X1>>) != null, "#91"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I6<X2>>) != null, "#92"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X2>>) != null, "#93"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X1>>) != null, "#94"); Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X2>>) != null, "#95"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X1>>) != null, "#96"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X2>>) != null, "#97"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X1>>) != null, "#98"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X2>>) != null, "#99"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X1>>) != null, "#100"); Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X2>>) != null, "#101"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X1>>) != null, "#102"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I7<X1>>) != null, "#103"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X2>>) != null, "#104"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I7<X2>>) != null, "#105"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X1, X1>>) != null, "#106"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X1, X2>>) != null, "#107"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X2, X1>>) != null, "#108"); Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X2, X2>>) != null, "#109"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X1>>) != null, "#110"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X2>>) != null, "#111"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X1>>) != null, "#112"); Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X2>>) != null, "#113"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X1>>) != null, "#114"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X1>>) != null, "#115"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X2>>) != null, "#116"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X2>>) != null, "#117"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X1, X1>>) != null, "#118"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X1, X2>>) != null, "#119"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X2, X1>>) != null, "#120"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X2, X2>>) != null, "#121"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X1, X1>>) != null, "#122"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X1, X2>>) != null, "#123"); Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X2, X1>>) != null, "#124"); Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X2, X2>>) != null, "#125"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X1>>) != null, "#126"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X1>>) != null, "#127"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X2>>) != null, "#128"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X2>>) != null, "#129"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X1>>) != null, "#130"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X2>>) != null, "#131"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X1>>) != null, "#132"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X2>>) != null, "#133"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X1>>) != null, "#134"); Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X2>>) != null, "#135"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X1>>) != null, "#136"); Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X2>>) != null, "#137"); Assert.IsFalse(((object)null as object) != null, "#138"); } [Test] public void CastWorksForReferenceTypes() { Assert.IsFalse(CanConvert<C1>(new object()), "#1"); Assert.IsTrue (CanConvert<object>(new C1()), "#2"); Assert.IsFalse(CanConvert<I1>(new object()), "#3"); Assert.IsFalse(CanConvert<D1>(new C1()), "#4"); Assert.IsTrue (CanConvert<C1>(new D1()), "#5"); Assert.IsTrue (CanConvert<I1>(new D1()), "#6"); Assert.IsTrue (CanConvert<C2<int>>(new D2<int>()), "#7"); Assert.IsFalse(CanConvert<C2<string>>(new D2<int>()), "#8"); Assert.IsTrue (CanConvert<I2<int>>(new D2<int>()), "#9"); Assert.IsFalse(CanConvert<I2<string>>(new D2<int>()), "#10"); Assert.IsTrue (CanConvert<I1>(new D2<int>()), "#11"); Assert.IsFalse(CanConvert<C2<string>>(new D3()), "#12"); Assert.IsTrue (CanConvert<C2<int>>(new D3()), "#13"); Assert.IsFalse(CanConvert<I2<int>>(new D3()), "#14"); Assert.IsTrue (CanConvert<I2<string>>(new D3()), "#15"); Assert.IsTrue (CanConvert<I1>(new D4()), "#16"); Assert.IsTrue (CanConvert<I3>(new D4()), "#17"); Assert.IsTrue (CanConvert<I4>(new D4()), "#18"); Assert.IsTrue (CanConvert<I1>(new X2()), "#19"); Assert.IsTrue (CanConvert<E1>(new E2()), "#20"); Assert.IsTrue (CanConvert<int>(new E1()), "#21"); Assert.IsTrue (CanConvert<object>(new E1()), "#22"); Assert.IsFalse(CanConvert<I7<X1>>(new Y1<X1>()), "#23"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X1>()), "#24"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1X1()), "#25"); Assert.IsFalse(CanConvert<I6<X2>>(new Y1<X1>()), "#26"); Assert.IsFalse(CanConvert<I6<X2>>(new Y1X1()), "#27"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X2>()), "#28"); Assert.IsTrue (CanConvert<I6<X1>>(new Y1X2()), "#29"); Assert.IsTrue (CanConvert<I6<X2>>(new Y1<X2>()), "#30"); Assert.IsTrue (CanConvert<I6<X2>>(new Y1X2()), "#31"); Assert.IsFalse(CanConvert<I6<X1>>(new Y2<X1>()), "#32"); Assert.IsTrue (CanConvert<I7<X1>>(new Y2<X1>()), "#33"); Assert.IsTrue (CanConvert<I7<X1>>(new Y2X1()), "#34"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X1>()), "#35"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2X1()), "#36"); Assert.IsFalse(CanConvert<I7<X1>>(new Y2<X2>()), "#37"); Assert.IsFalse(CanConvert<I7<X1>>(new Y2X2()), "#38"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X2>()), "#39"); Assert.IsTrue (CanConvert<I7<X2>>(new Y2X2()), "#40"); Assert.IsFalse(CanConvert<I1>(new Y3<X1, X1>()), "#41"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X1, X1>()), "#42"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X1X1()), "#43"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X1, X2>()), "#44"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X1X2()), "#45"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X2, X1>()), "#46"); Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X2X1()), "#47"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X2, X2>()), "#48"); Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X2X2()), "#49"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X1>()), "#50"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X1()), "#51"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X2>()), "#52"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X2()), "#53"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X1>()), "#54"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X1()), "#55"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X2>()), "#56"); Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X2()), "#57"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X1>()), "#58"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X1()), "#59"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X2>()), "#60"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X2()), "#61"); Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3<X2, X1>()), "#62"); Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3X2X1()), "#63"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X2, X2>()), "#64"); Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X2X2()), "#65"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X1>()), "#66"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X1()), "#67"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X2>()), "#68"); Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X2()), "#69"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X1>()), "#70"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X1()), "#71"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X2>()), "#72"); Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X2()), "#73"); Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X1>()), "#74"); Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X1>()), "#75"); Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X1>()), "#76"); Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X1>()), "#77"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<string, X1>()), "#78"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X1>()), "#79"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X1>()), "#80"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<object, X1>()), "#81"); Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X2>()), "#82"); Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X2>()), "#83"); Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X2>()), "#84"); Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X2>()), "#85"); Assert.IsTrue (CanConvert<I9<string, X2>>(new Y4<string, X2>()), "#86"); Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X2>()), "#87"); Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X2>()), "#88"); Assert.IsTrue (CanConvert<I9<object, X2>>(new Y4<object, X2>()), "#89"); Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X1, X1>()), "#90"); Assert.IsTrue (CanConvert<I6<I7<X1>>>(new Y5<X1, X1>()), "#91"); Assert.IsFalse(CanConvert<I6<I6<X2>>>(new Y5<X1, X1>()), "#92"); Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X1, X1>()), "#93"); Assert.IsTrue (CanConvert<I6<I8<X1, X1>>>(new Y5<X1, X1>()), "#94"); Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X1, X1>()), "#95"); Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X1, X1>()), "#96"); Assert.IsFalse(CanConvert<I6<I8<X2, X2>>>(new Y5<X1, X1>()), "#97"); Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X1, X1>()), "#98"); Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X1, X1>()), "#99"); Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X1, X1>()), "#100"); Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X1, X1>()), "#101"); Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X2, X2>()), "#102"); Assert.IsFalse(CanConvert<I6<I7<X1>>>(new Y5<X2, X2>()), "#103"); Assert.IsTrue (CanConvert<I6<I6<X2>>>(new Y5<X2, X2>()), "#104"); Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X2, X2>()), "#105"); Assert.IsFalse(CanConvert<I6<I8<X1, X1>>>(new Y5<X2, X2>()), "#106"); Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X2, X2>()), "#107"); Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X2, X2>()), "#108"); Assert.IsTrue (CanConvert<I6<I8<X2, X2>>>(new Y5<X2, X2>()), "#109"); Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X2, X2>()), "#110"); Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X2, X2>()), "#111"); Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X2, X2>()), "#112"); Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X2, X2>()), "#113"); Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X1, X1>()), "#114"); Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X1, X1>()), "#115"); Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X1, X1>()), "#116"); Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X1, X1>()), "#117"); Assert.IsTrue (CanConvert<I7<I8<X1, X1>>>(new Y6<X1, X1>()), "#118"); Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X1, X1>()), "#119"); Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X1, X1>()), "#120"); Assert.IsFalse(CanConvert<I7<I8<X2, X2>>>(new Y6<X1, X1>()), "#121"); Assert.IsTrue (CanConvert<I7<I10<X1, X1>>>(new Y6<X1, X1>()), "#122"); Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X1, X1>()), "#123"); Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X1, X1>()), "#124"); Assert.IsFalse(CanConvert<I7<I10<X2, X2>>>(new Y6<X1, X1>()), "#125"); Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X2, X2>()), "#126"); Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X2, X2>()), "#127"); Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X2, X2>()), "#128"); Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X2, X2>()), "#129"); Assert.IsFalse(CanConvert<I7<I8<X1, X1>>>(new Y6<X2, X2>()), "#130"); Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X2, X2>()), "#131"); Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X2, X2>()), "#132"); Assert.IsTrue (CanConvert<I7<I8<X2, X2>>>(new Y6<X2, X2>()), "#133"); Assert.IsFalse(CanConvert<I7<I10<X1, X1>>>(new Y6<X2, X2>()), "#134"); Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X2, X2>()), "#135"); Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X2, X2>()), "#136"); Assert.IsTrue (CanConvert<I7<I10<X2, X2>>>(new Y6<X2, X2>()), "#137"); Assert.IsFalse((object)null is object, "#138"); } [Test] public void GetTypeWorksOnObjects() { Action a = () => {}; Assert.AreEqual(new C1().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C1"); Assert.AreEqual(new C2<int>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[[ss.Int32, mscorlib]]"); Assert.AreEqual(new C2<string>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[[String]]"); Assert.AreEqual((1).GetType().FullName, "Number"); Assert.AreEqual("X".GetType().FullName, "String"); Assert.AreEqual(a.GetType().FullName, "Function"); Assert.AreEqual(new object().GetType().FullName, "Object"); Assert.AreEqual(new[] { 1, 2 }.GetType().FullName, "Array"); } [Test] public void GetTypeOnNullInstanceThrowsException() { Assert.Throws(() => ((object)null).GetType()); } #pragma warning disable 219 [Test] public void CastOperatorsWorkForSerializableTypesWithCustomTypeCheckCode() { object o1 = new { x = 1 }; object o2 = new { x = 1, y = 2 }; Assert.IsFalse(o1 is DS, "o1 should not be of type"); Assert.IsTrue (o2 is DS, "o2 should be of type"); Assert.AreStrictEqual(o1 as DS, null, "Try cast o1 to type should be null"); Assert.IsTrue((o2 as DS) == o2, "Try cast o2 to type should return o2"); Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw"); Assert.IsTrue((DS)o2 == o2, "Cast o2 to type should return o2"); } [Test] public void CastOperatorsWorkForImportedTypesWithCustomTypeCheckCode() { object o1 = new { x = 1 }; object o2 = new { x = 1, y = 2 }; Assert.IsFalse(o1 is CI, "o1 should not be of type"); Assert.IsTrue (o2 is CI, "o2 should be of type"); Assert.AreStrictEqual(o1 as CI, null, "Try cast o1 to type should be null"); Assert.IsTrue((o2 as CI) == o2, "Try cast o2 to type should return o2"); Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw"); Assert.IsTrue((CI)o2 == o2, "Cast o2 to type should return o2"); } #pragma warning restore 219 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.IO; using System.Net.Test.Common; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; using System.Net.Sockets; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class HttpClientHandlerTest { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public readonly static object[][] EchoServers = HttpTestServers.EchoServers; public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers; public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers; public readonly static object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, }; public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers; public readonly static object[][] RedirectStatusCodes = { new object[] { 300 }, new object[] { 301 }, new object[] { 302 }, new object[] { 303 }, new object[] { 307 } }; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public readonly static IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "CUSTOM1"); private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); Assert.NotNull(handler.Properties); } } [Fact] public void MaxRequestContentBufferSize_Get_ReturnsZero() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException() { using (var handler = new HttpClientHandler()) { Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Fact] public void Properties_Get_CountIsZero() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; Assert.Same(dict, handler.Properties); Assert.Equal(0, dict.Count); } [Fact] public void Properties_AddItemToDictionary_ItemPresent() { var handler = new HttpClientHandler(); IDictionary<String, object> dict = handler.Properties; var item = new Object(); dict.Add("item", item); object value; Assert.True(dict.TryGetValue("item", out value)); Assert.Equal(item, value); } [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory] [MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))] public async Task GetAsync_IPBasedUri_Success(IPAddress address) { using (var client = new HttpClient()) { var options = new LoopbackServer.Options { Address = address }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData() { foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() }) { if (addr != null) { yield return new object[] { addr }; } } } [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (var client = new HttpClient()) { HttpResponseMessage response; for (int i = 0; i < 3; i++) { response = await client.GetAsync(HttpTestServers.RemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response.Dispose(); } } } [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { HttpResponseMessage response = null; using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); } Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { using (var client = new HttpClient()) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(statusCode, (int)response.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode) { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:statusCode, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.SecureRemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:true, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:targetUri, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [Theory] [InlineData(6)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHopsNPlus1_Throw(int hops) { var handler = new HttpClientHandler(); handler.MaxAutomaticRedirections = hops; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:(hops + 1)))); } } [Fact] public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:302, userName:Username, password:Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Theory, MemberData(nameof(RedirectStatusCodes))] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); Uri redirectUri = HttpTestServers.RedirectUriForCreds( secure:false, statusCode:statusCode, userName:Username, password:Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie")); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, statusCode:302, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM") } }; [Theory] [MemberData(nameof(CookieNameValues))] public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); await LoopbackServer.CreateServerAsync(async (server, url) => { using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponse = client.GetAsync(url); await LoopbackServer.ReadRequestAndSendResponseAsync(server, $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + $"Set-Cookie: {cookie1.Key}={cookie1.Value}; Path=/\r\n" + $"Set-Cookie: {cookie2.Key}={cookie2.Value}; Path=/\r\n" + $"Set-Cookie: {cookie3.Key}={cookie3.Value}; Path=/\r\n" + "\r\n"); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(url); Assert.Equal(3, cookies.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } }); } [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(reader.ReadLine())) ; await writer.WriteAsync( "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 16000\r\n" + "\r\n" + "less than 16000 bytes"); using (HttpResponseMessage response = await getResponse) { var buffer = new byte[8000]; using (Stream clientStream = await response.Content.ReadAsStreamAsync()) { int bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length); _output.WriteLine($"Bytes read from stream: {bytesRead}"); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } }); } }); } [Fact] public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses() { await LoopbackServer.CreateServerAsync(async (socket1, url1) => { await LoopbackServer.CreateServerAsync(async (socket2, url2) => { await LoopbackServer.CreateServerAsync(async (socket3, url3) => { var unblockServers = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously); // First server connects but doesn't send any response yet Task server1 = LoopbackServer.AcceptSocketAsync(socket1, async (s, stream, reader, writer) => { await unblockServers.Task; }); // Second server connects and sends some but not all headers Task server2 = LoopbackServer.AcceptSocketAsync(socket2, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\n"); await unblockServers.Task; }); // Third server connects and sends all headers and some but not all of the body Task server3 = LoopbackServer.AcceptSocketAsync(socket3, async (s, stream, reader, writer) => { while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ; await writer.WriteAsync($"HTTP/1.1 200 OK\r\nDate: {DateTimeOffset.UtcNow:R}\r\nContent-Length: 20\r\n\r\n"); await writer.WriteAsync("1234567890"); await unblockServers.Task; await writer.WriteAsync("1234567890"); s.Shutdown(SocketShutdown.Send); }); // Make three requests Task<HttpResponseMessage> get1, get2; HttpResponseMessage response3; using (var client = new HttpClient()) { get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead); get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead); response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead); } // Requests 1 and 2 should be canceled as we haven't finished receiving their headers await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get2); // Request 3 should still be active, and we should be able to receive all of the data. unblockServers.SetResult(true); using (response3) { Assert.Equal("12345678901234567890", await response3.Content.ReadAsStringAsync()); } try { await Task.WhenAll(server1, server2, server3); } catch { } // Ignore errors: we expect this may fail, as the clients may hang up on the servers }); }); }); } #region Post Methods Tests [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData) { using (var client = new HttpClient()) { content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private sealed class StreamContentWithSyncAsyncCopy : StreamContent { private readonly Stream _stream; private readonly bool _syncCopy; public StreamContentWithSyncAsyncCopy(Stream stream, bool syncCopy) : base(stream) { _stream = stream; _syncCopy = syncCopy; } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { if (_syncCopy) { try { _stream.CopyTo(stream, 128); // arbitrary size likely to require multiple read/writes return Task.CompletedTask; } catch (Exception exc) { return Task.FromException(exc); } } return base.SerializeToStreamAsync(stream, context); } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) // target server foreach (bool syncCopy in new[] { true, false }) // force the content copy to happen via Read/Write or ReadAsync/WriteAsync { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(memStream, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncKnownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: (buffer, offset, count, token) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return Task.FromResult(bytesToCopy); }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(syncUnknownLengthStream, syncCopy: syncCopy), data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }); yield return new object[] { server, new StreamContentWithSyncAsyncCopy(asyncStream, syncCopy: syncCopy), data }; } } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri( secure, 302, secure ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [Fact] public async Task PostAsync_Post_ChannelBindingHasExpectedValue() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new ChannelBindingAwareContent(expectedContent); using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); Assert.Contains($"\"Content-Length\": \"{request.Content.Headers.ContentLength.Value}\"", responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } #endregion #region Version tests [Fact] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0)); Assert.Equal(new Version(1, 0), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request() { Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 1)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Fact] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request() { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different (0,0), to test the "unknown" version. Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0,0)); Assert.Equal(new Version(1, 1), receivedRequestVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. var request = new HttpRequestMessage(HttpMethod.Get, server); request.Version = new Version(2, 0); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True( response.Version == new Version(2, 0) || response.Version == new Version(1, 1), "Response version " + response.Version); } } private async Task<Version> SendRequestAndGetRequestVersionAsync(Version requestVersion) { Version receivedRequestVersion = null; await LoopbackServer.CreateServerAsync(async (server, url) => { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Version = requestVersion; using (var client = new HttpClient()) { Task<HttpResponseMessage> getResponse = client.SendAsync(request); await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { string statusLine = reader.ReadLine(); while (!string.IsNullOrEmpty(reader.ReadLine())) ; if (statusLine.Contains("/1.0")) { receivedRequestVersion = new Version(1, 0); } else if (statusLine.Contains("/1.1")) { receivedRequestVersion = new Version(1, 1); } else { Assert.True(false, "Invalid HTTP request version"); } await writer.WriteAsync( $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"); s.Shutdown(SocketShutdown.Send); }); using (HttpResponseMessage response = await getResponse) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); return receivedRequestVersion; } #endregion #region SSL Version tests [Theory] [InlineData("SSLv2", HttpTestServers.SSLv2RemoteServer)] [InlineData("SSLv3", HttpTestServers.SSLv3RemoteServer)] public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url) { using (HttpClient client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [Theory] [InlineData("TLSv1.0", HttpTestServers.TLSv10RemoteServer)] [InlineData("TLSv1.1", HttpTestServers.TLSv11RemoteServer)] [InlineData("TLSv1.2", HttpTestServers.TLSv12RemoteServer)] public async Task GetAsync_SupportedSSLVersion_Succeeds(string name, string url) { using (HttpClient client = new HttpClient()) using (await client.GetAsync(url)) { } } #endregion #region Proxy tests [Theory] [MemberData(nameof(CredentialsForProxy))] public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } } [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [Fact] public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new PlatformNotSupportedWebProxy() }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache }; yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion } }
// <copyright file="ZipfTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Discrete { /// <summary> /// Zipf law tests. /// </summary> [TestFixture, Category("Distributions")] public class ZipfTests { /// <summary> /// Can create zipf. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> [TestCase(0.1, 1)] [TestCase(1, 20)] [TestCase(1, 50)] public void CanCreateZipf(double s, int n) { var d = new Zipf(s, n); Assert.AreEqual(s, d.S); Assert.AreEqual(n, d.N); } /// <summary> /// Zipf create fails with bad parameters. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> [TestCase(0.0, -10)] [TestCase(0.0, 0)] public void ZipfCreateFailsWithBadParameters(double s, int n) { Assert.That(() => new Zipf(s, n), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var d = new Zipf(1.0, 5); Assert.AreEqual("Zipf(S = 1, N = 5)", d.ToString()); } /// <summary> /// Validate entropy. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> /// <param name="e">Expected value.</param> [TestCase(0.1, 1, 0.0)] [TestCase(0.1, 20, 2.9924075515295949)] [TestCase(0.1, 50, 3.9078245132371388)] [TestCase(1.0, 1, 0.0)] [TestCase(1.0, 20, 2.5279968533953743)] [TestCase(1.0, 50, 3.1971263138845916)] public void ValidateEntropy(double s, int n, double e) { var d = new Zipf(s, n); AssertHelpers.AlmostEqualRelative(e, d.Entropy, 15); } /// <summary> /// Validate skewness. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> [TestCase(5.0, 1)] [TestCase(10.0, 20)] [TestCase(10.0, 50)] public void ValidateSkewness(double s, int n) { var d = new Zipf(s, n); if (s > 4) { Assert.AreEqual(((SpecialFunctions.GeneralHarmonic(n, s - 3) * Math.Pow(SpecialFunctions.GeneralHarmonic(n, s), 2)) - (SpecialFunctions.GeneralHarmonic(n, s - 1) * ((3 * SpecialFunctions.GeneralHarmonic(n, s - 2) * SpecialFunctions.GeneralHarmonic(n, s)) - Math.Pow(SpecialFunctions.GeneralHarmonic(n, s - 1), 2)))) / Math.Pow((SpecialFunctions.GeneralHarmonic(n, s - 2) * SpecialFunctions.GeneralHarmonic(n, s)) - Math.Pow(SpecialFunctions.GeneralHarmonic(n, s - 1), 2), 1.5), d.Skewness); } } /// <summary> /// Validate mode. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> [TestCase(0.1, 1)] [TestCase(1, 20)] [TestCase(1, 50)] public void ValidateMode(double s, int n) { var d = new Zipf(s, n); Assert.AreEqual(1, d.Mode); } /// <summary> /// Validate median throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateMedianThrowsNotSupportedException() { var d = new Zipf(1.0, 5); Assert.Throws<NotSupportedException>(() => { var m = d.Median; }); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var d = new Zipf(1.0, 5); Assert.AreEqual(1, d.Minimum); } /// <summary> /// Validate maximum. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> [TestCase(0.1, 1)] [TestCase(1, 20)] [TestCase(1, 50)] public void ValidateMaximum(double s, int n) { var d = new Zipf(s, n); Assert.AreEqual(n, d.Maximum); } /// <summary> /// Validate probability. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> /// <param name="x">Input X value.</param> [TestCase(0.1, 1, 1)] [TestCase(1, 20, 15)] [TestCase(1, 50, 20)] public void ValidateProbability(double s, int n, int x) { var d = new Zipf(s, n); Assert.AreEqual((1.0 / Math.Pow(x, s)) / SpecialFunctions.GeneralHarmonic(n, s), d.Probability(x)); } /// <summary> /// Validate probability log. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> /// <param name="x">Input X value.</param> [TestCase(0.1, 1, 1)] [TestCase(1, 20, 15)] [TestCase(1, 50, 20)] public void ValidateProbabilityLn(double s, int n, int x) { var d = new Zipf(s, n); Assert.AreEqual(Math.Log(d.Probability(x)), d.ProbabilityLn(x)); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var d = new Zipf(0.7, 5); var s = d.Sample(); Assert.LessOrEqual(s, 5); Assert.GreaterOrEqual(s, 0); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var d = new Zipf(0.7, 5); var ied = d.Samples(); var e = ied.Take(1000).ToArray(); foreach (var i in e) { Assert.LessOrEqual(i, 5); Assert.GreaterOrEqual(i, 0); } } /// <summary> /// Validate cumulative distribution. /// </summary> /// <param name="s">S parameter.</param> /// <param name="n">N parameter.</param> /// <param name="x">Input X value.</param> [TestCase(0.1, 1, 2)] [TestCase(1, 20, 15)] [TestCase(1, 50, 20)] public void ValidateCumulativeDistribution(double s, int n, int x) { var d = new Zipf(s, n); var cdf = SpecialFunctions.GeneralHarmonic(x, s) / SpecialFunctions.GeneralHarmonic(n, s); AssertHelpers.AlmostEqualRelative(cdf, d.CumulativeDistribution(x), 14); } } }
// <copyright file="GPGSUtil.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // Keep this even on unsupported configurations. namespace GooglePlayGames.Editor { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; /// <summary> /// Utility class to perform various tasks in the editor. /// </summary> public static class GPGSUtil { /// <summary>Property key for project settings.</summary> public const string SERVICEIDKEY = "App.NearbdServiceId"; /// <summary>Property key for project settings.</summary> public const string APPIDKEY = "proj.AppId"; /// <summary>Property key for project settings.</summary> public const string CLASSDIRECTORYKEY = "proj.classDir"; /// <summary>Property key for project settings.</summary> public const string CLASSNAMEKEY = "proj.ConstantsClassName"; /// <summary>Property key for project settings.</summary> public const string WEBCLIENTIDKEY = "and.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSCLIENTIDKEY = "ios.ClientId"; /// <summary>Property key for project settings.</summary> public const string IOSBUNDLEIDKEY = "ios.BundleId"; /// <summary>Property key for project settings.</summary> public const string ANDROIDRESOURCEKEY = "and.ResourceData"; /// <summary>Property key for project settings.</summary> public const string ANDROIDSETUPDONEKEY = "android.SetupDone"; /// <summary>Property key for project settings.</summary> public const string ANDROIDBUNDLEIDKEY = "and.BundleId"; /// <summary>Property key for project settings.</summary> public const string IOSRESOURCEKEY = "ios.ResourceData"; /// <summary>Property key for project settings.</summary> public const string IOSSETUPDONEKEY = "ios.SetupDone"; /// <summary>Property key for plugin version.</summary> public const string PLUGINVERSIONKEY = "proj.pluginVersion"; /// <summary>Property key for nearby settings done.</summary> public const string NEARBYSETUPDONEKEY = "android.NearbySetupDone"; /// <summary>Property key for project settings.</summary> public const string LASTUPGRADEKEY = "lastUpgrade"; /// <summary>Constant for token replacement</summary> private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__"; /// <summary>Constant for token replacement</summary> private const string APPIDPLACEHOLDER = "__APP_ID__"; /// <summary>Constant for token replacement</summary> private const string CLASSNAMEPLACEHOLDER = "__Class__"; /// <summary>Constant for token replacement</summary> private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__"; /// <summary>Constant for token replacement</summary> private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__"; /// <summary>Constant for token replacement</summary> private const string PLUGINVERSIONPLACEHOLDER = "__PLUGIN_VERSION__"; /// <summary>Constant for require google plus token replacement</summary> private const string REQUIREGOOGLEPLUSPLACEHOLDER = "__REQUIRE_GOOGLE_PLUS__"; /// <summary>Property key for project settings.</summary> private const string TOKENPERMISSIONKEY = "proj.tokenPermissions"; /// <summary>Constant for token replacement</summary> private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__"; /// <summary>Constant for token replacement</summary> private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__"; /// <summary>Constant for token replacement</summary> private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__"; /// <summary> /// The game info file path. This is a generated file. /// </summary> private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs"; /// <summary> /// The manifest path. /// </summary> /// <remarks>The Games SDK requires additional metadata in the AndroidManifest.xml /// file. </remarks> private const string ManifestPath = "Assets/GooglePlayGames/Plugins/Android/GooglePlayGamesManifest.plugin/AndroidManifest.xml"; /// <summary> /// The map of replacements for filling in code templates. The /// key is the string that appears in the template as a placeholder, /// the value is the key into the GPGSProjectSettings. /// </summary> private static Dictionary<string, string> replacements = new Dictionary<string, string>() { { SERVICEIDPLACEHOLDER, SERVICEIDKEY }, { APPIDPLACEHOLDER, APPIDKEY }, { CLASSNAMEPLACEHOLDER, CLASSNAMEKEY }, { WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY }, { IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY }, { IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY }, { PLUGINVERSIONPLACEHOLDER, PLUGINVERSIONKEY} }; /// <summary> /// Replaces / in file path to be the os specific separator. /// </summary> /// <returns>The path.</returns> /// <param name="path">Path with correct separators.</param> public static string SlashesToPlatformSeparator(string path) { return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); } /// <summary> /// Reads the file. /// </summary> /// <returns>The file contents. The slashes are corrected.</returns> /// <param name="filePath">File path.</param> public static string ReadFile(string filePath) { filePath = SlashesToPlatformSeparator(filePath); if (!File.Exists(filePath)) { Alert("Plugin error: file not found: " + filePath); return null; } StreamReader sr = new StreamReader(filePath); string body = sr.ReadToEnd(); sr.Close(); return body; } /// <summary> /// Reads the editor template. /// </summary> /// <returns>The editor template contents.</returns> /// <param name="name">Name of the template in the editor directory.</param> public static string ReadEditorTemplate(string name) { return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt")); } /// <summary> /// Writes the file. /// </summary> /// <param name="file">File path - the slashes will be corrected.</param> /// <param name="body">Body of the file to write.</param> public static void WriteFile(string file, string body) { file = SlashesToPlatformSeparator(file); using (var wr = new StreamWriter(file, false)) { wr.Write(body); } } /// <summary> /// Validates the string to be a valid nearby service id. /// </summary> /// <returns><c>true</c>, if like valid service identifier was looksed, <c>false</c> otherwise.</returns> /// <param name="s">string to test.</param> public static bool LooksLikeValidServiceId(string s) { if (s.Length < 3) { return false; } foreach (char c in s) { if (!char.IsLetterOrDigit(c) && c != '.') { return false; } } return true; } /// <summary> /// Looks the like valid app identifier. /// </summary> /// <returns><c>true</c>, if valid app identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidAppId(string s) { if (s.Length < 5) { return false; } foreach (char c in s) { if (c < '0' || c > '9') { return false; } } return true; } /// <summary> /// Looks the like valid client identifier. /// </summary> /// <returns><c>true</c>, if valid client identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidClientId(string s) { return s.EndsWith(".googleusercontent.com"); } /// <summary> /// Looks the like a valid bundle identifier. /// </summary> /// <returns><c>true</c>, if valid bundle identifier, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidBundleId(string s) { return s.Length > 3; } /// <summary> /// Looks like a valid package. /// </summary> /// <returns><c>true</c>, if valid package name, <c>false</c> otherwise.</returns> /// <param name="s">the string to test.</param> public static bool LooksLikeValidPackageName(string s) { if (string.IsNullOrEmpty(s)) { throw new Exception("cannot be empty"); } string[] parts = s.Split(new char[] { '.' }); foreach (string p in parts) { char[] bytes = p.ToCharArray(); for (int i = 0; i < bytes.Length; i++) { if (i == 0 && !char.IsLetter(bytes[i])) { throw new Exception("each part must start with a letter"); } else if (char.IsWhiteSpace(bytes[i])) { throw new Exception("cannot contain spaces"); } else if (!char.IsLetterOrDigit(bytes[i]) && bytes[i] != '_') { throw new Exception("must be alphanumeric or _"); } } } return parts.Length >= 1; } /// <summary> /// Determines if is setup done. /// </summary> /// <returns><c>true</c> if is setup done; otherwise, <c>false</c>.</returns> public static bool IsSetupDone() { bool doneSetup = true; #if UNITY_ANDROID doneSetup = GPGSProjectSettings.Instance.GetBool(ANDROIDSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(APPIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with AppId. " + "Run Window > Google Play Games > Setup > Android Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > Android Setup..."); return false; } #elif (UNITY_IPHONE && !NO_GPGS) doneSetup = GPGSProjectSettings.Instance.GetBool(IOSSETUPDONEKEY, false); // check gameinfo if (File.Exists(GameInfoPath)) { string contents = ReadFile(GameInfoPath); if (contents.Contains(IOSCLIENTIDPLACEHOLDER)) { Debug.Log("GameInfo not initialized with Client Id. " + "Run Window > Google Play Games > Setup > iOS Setup..."); return false; } } else { Debug.Log("GameInfo.cs does not exist. Run Window > Google Play Games > Setup > iOS Setup..."); return false; } #endif return doneSetup; } /// <summary> /// Makes legal identifier from string. /// Returns a legal C# identifier from the given string. The transformations are: /// - spaces => underscore _ /// - punctuation => empty string /// - leading numbers are prefixed with underscore. /// </summary> /// <returns>the id</returns> /// <param name="key">Key to convert to an identifier.</param> public static string MakeIdentifier(string key) { string s; string retval = string.Empty; if (string.IsNullOrEmpty(key)) { return "_"; } s = key.Trim().Replace(' ', '_'); foreach (char c in s) { if (char.IsLetterOrDigit(c) || c == '_') { retval += c; } } return retval; } /// <summary> /// Displays an error dialog. /// </summary> /// <param name="s">the message</param> public static void Alert(string s) { Alert(GPGSStrings.Error, s); } /// <summary> /// Displays a dialog with the given title and message. /// </summary> /// <param name="title">the title.</param> /// <param name="message">the message.</param> public static void Alert(string title, string message) { EditorUtility.DisplayDialog(title, message, GPGSStrings.Ok); } /// <summary> /// Gets the android sdk path. /// </summary> /// <returns>The android sdk path.</returns> public static string GetAndroidSdkPath() { string sdkPath = EditorPrefs.GetString("AndroidSdkRoot"); if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\"))) { sdkPath = sdkPath.Substring(0, sdkPath.Length - 1); } return sdkPath; } /// <summary> /// Determines if the android sdk exists. /// </summary> /// <returns><c>true</c> if android sdk exists; otherwise, <c>false</c>.</returns> public static bool HasAndroidSdk() { string sdkPath = GetAndroidSdkPath(); return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath); } /// <summary> /// Gets the unity major version. /// </summary> /// <returns>The unity major version.</returns> public static int GetUnityMajorVersion() { #if UNITY_5 string majorVersion = Application.unityVersion.Split('.')[0]; int ver; if (!int.TryParse(majorVersion, out ver)) { ver = 0; } return ver; #elif UNITY_4_6 return 4; #else return 0; #endif } /// <summary> /// Checks for the android manifest file exsistance. /// </summary> /// <returns><c>true</c>, if the file exists <c>false</c> otherwise.</returns> public static bool AndroidManifestExists() { string destFilename = GPGSUtil.SlashesToPlatformSeparator(ManifestPath); return File.Exists(destFilename); } /// <summary> /// Generates the android manifest. /// </summary> public static void GenerateAndroidManifest() { string destFilename = GPGSUtil.SlashesToPlatformSeparator(ManifestPath); // Generate AndroidManifest.xml string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest"); Dictionary<string, string> overrideValues = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value, overrideValues); manifestBody = manifestBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(destFilename, manifestBody); GPGSUtil.UpdateGameInfo(); } /// <summary> /// Writes the resource identifiers file. This file contains the /// resource ids copied (downloaded?) from the play game app console. /// </summary> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="resourceKeys">Resource keys.</param> public static void WriteResourceIds(string classDirectory, string className, Hashtable resourceKeys) { string constantsValues = string.Empty; string[] parts = className.Split('.'); string dirName = classDirectory; if (string.IsNullOrEmpty(dirName)) { dirName = "Assets"; } string nameSpace = string.Empty; for (int i = 0; i < parts.Length - 1; i++) { dirName += "/" + parts[i]; if (nameSpace != string.Empty) { nameSpace += "."; } nameSpace += parts[i]; } EnsureDirExists(dirName); foreach (DictionaryEntry ent in resourceKeys) { string key = MakeIdentifier((string)ent.Key); constantsValues += " public const string " + key + " = \"" + ent.Value + "\"; // <GPGSID>\n"; } string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants"); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACESTARTPLACEHOLDER, "namespace " + nameSpace + "\n{"); } else { fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, string.Empty); } fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]); fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues); if (nameSpace != string.Empty) { fileBody = fileBody.Replace( NAMESPACEENDPLACEHOLDER, "}"); } else { fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, string.Empty); } WriteFile(Path.Combine(dirName, parts[parts.Length - 1] + ".cs"), fileBody); } /// <summary> /// Updates the game info file. This is a generated file containing the /// app and client ids. /// </summary> public static void UpdateGameInfo() { string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo"); foreach (KeyValuePair<string, string> ent in replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value); fileBody = fileBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(GameInfoPath, fileBody); } /// <summary> /// Ensures the dir exists. /// </summary> /// <param name="dir">Directory to check.</param> public static void EnsureDirExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } /// <summary> /// Deletes the dir if exists. /// </summary> /// <param name="dir">Directory to delete.</param> public static void DeleteDirIfExists(string dir) { dir = SlashesToPlatformSeparator(dir); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } } /// <summary> /// Gets the Google Play Services library version. This is only /// needed for Unity versions less than 5. /// </summary> /// <returns>The GPS version.</returns> /// <param name="libProjPath">Lib proj path.</param> private static int GetGPSVersion(string libProjPath) { string versionFile = libProjPath + "/res/values/version.xml"; XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile)); bool inResource = false; int version = -1; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "integer") { if ("google_play_services_version".Equals( reader.GetAttribute("name"))) { reader.Read(); Debug.Log("Read version string: " + reader.Value); version = Convert.ToInt32(reader.Value); } } } reader.Close(); return version; } } }
using NetApp.Tests.Helpers; using Microsoft.Azure.Management.NetApp.Models; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Xunit; using System; using System.Collections.Generic; using System.Threading; namespace NetApp.Tests.ResourceTests { public class VolumeTests : TestBase { public static ExportPolicyRule exportPolicyRule = new ExportPolicyRule() { RuleIndex = 1, UnixReadOnly = false, UnixReadWrite = true, Cifs = false, Nfsv3 = true, Nfsv41 = false, AllowedClients = "1.2.3.0/24" }; public static IList<ExportPolicyRule> exportPolicyRuleList = new List<ExportPolicyRule>() { exportPolicyRule }; public static VolumePropertiesExportPolicy exportPolicy = new VolumePropertiesExportPolicy() { Rules = exportPolicyRuleList }; public static VolumePatchPropertiesExportPolicy exportPatchPolicy = new VolumePatchPropertiesExportPolicy() { Rules = exportPolicyRuleList }; [Fact] public void CreateDeleteVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create a volume, get all and check var resource = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), resource.ExportPolicy.ToString()); Assert.Null(resource.Tags); // check DP properties exist but unassigned because // dataprotection volume was not created Assert.Null(resource.VolumeType); Assert.Null(resource.DataProtection); var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Single(volumesBefore); // delete the volume and check again netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Empty(volumesAfter); // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CreateVolumeWithProperties() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create a volume with tags and export policy var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value2"); var protocolTypes = new List<string>() { "NFSv3" }; var resource = ResourceUtils.CreateVolume(netAppMgmtClient, protocolTypes: protocolTypes, tags: dict, exportPolicy: exportPolicy); Assert.Equal(exportPolicy.ToString(), resource.ExportPolicy.ToString()); Assert.Equal(protocolTypes, resource.ProtocolTypes); Assert.True(resource.Tags.ContainsKey("Tag2")); Assert.Equal("Value2", resource.Tags["Tag2"]); var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Single(volumesBefore); // delete the volume and check again netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Empty(volumesAfter); // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void ListVolumes() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create two volumes under same pool ResourceUtils.CreateVolume(netAppMgmtClient); ResourceUtils.CreateVolume(netAppMgmtClient, ResourceUtils.volumeName2, volumeOnly: true); // get the account list and check var volumes = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Equal(volumes.ElementAt(0).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1); Assert.Equal(volumes.ElementAt(1).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName2); Assert.Equal(2, volumes.Count()); // clean up - delete the two volumes, the pool and the account ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeleteVolume(netAppMgmtClient, ResourceUtils.volumeName2); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByName() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume ResourceUtils.CreateVolume(netAppMgmtClient); // retrieve it var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal(volume.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1); // clean up - delete the volume, pool and account ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByNameNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create volume ResourceUtils.CreatePool(netAppMgmtClient); // try and get a volume in the pool - none have been created yet try { var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("was not found", ex.Message); } // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByNamePoolNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); ResourceUtils.CreateAccount(netAppMgmtClient); // try and create a volume before the pool exist try { var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("not found", ex.Message); } // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CreateVolumePoolNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); ResourceUtils.CreateAccount(netAppMgmtClient); // try and create a volume before the pool exist try { ResourceUtils.CreateVolume(netAppMgmtClient, volumeOnly: true); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("not found", ex.Message); } // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void DeletePoolWithVolumePresent() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account and pool ResourceUtils.CreateVolume(netAppMgmtClient); var poolsBefore = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Single(poolsBefore); // try and delete the pool try { netAppMgmtClient.Pools.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("Can not delete resource before nested resources are deleted", ex.Message); } // clean up ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CheckAvailability() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // check account resource name - should be available var response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, ResourceUtils.accountName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccounts, ResourceUtils.resourceGroup); Assert.True(response.IsAvailable); // now check file path availability response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.True(response.IsAvailable); // create the volume var volume = ResourceUtils.CreateVolume(netAppMgmtClient); // check volume resource name - should be unavailable after its creation var resourceName = ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1; response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, resourceName, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.False(response.IsAvailable); // now check file path availability again response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.False(response.IsAvailable); // clean up ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void UpdateVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume var oldVolume = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal("Premium", oldVolume.ServiceLevel); Assert.Equal(100 * ResourceUtils.gibibyte, oldVolume.UsageThreshold); // The returned volume contains some items which cnanot be part of the payload, such as baremetaltenant, therefore create a new object selectively from the old one var volume = new Volume { Location = oldVolume.Location, ServiceLevel = oldVolume.ServiceLevel, CreationToken = oldVolume.CreationToken, SubnetId = oldVolume.SubnetId, }; // update volume.UsageThreshold = 2 * oldVolume.UsageThreshold; var updatedVolume = netAppMgmtClient.Volumes.CreateOrUpdate(volume, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected Assert.Equal(100 * ResourceUtils.gibibyte * 2, updatedVolume.UsageThreshold); // cleanup ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void PatchVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume var volume = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal("Premium", volume.ServiceLevel); Assert.Equal(100 * ResourceUtils.gibibyte, volume.UsageThreshold); Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), volume.ExportPolicy.ToString()); Assert.Null(volume.Tags); // create a volume with tags and export policy var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value2"); // Now try and modify it var volumePatch = new VolumePatch() { UsageThreshold = 2 * volume.UsageThreshold, Tags = dict, ExportPolicy = exportPatchPolicy }; // patch var updatedVolume = netAppMgmtClient.Volumes.Update(volumePatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected Assert.Equal(200 * ResourceUtils.gibibyte, updatedVolume.UsageThreshold); Assert.Equal(exportPolicy.ToString(), updatedVolume.ExportPolicy.ToString()); Assert.True(updatedVolume.Tags.ContainsKey("Tag2")); Assert.Equal("Value2", updatedVolume.Tags["Tag2"]); // cleanup ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } private void WaitForReplicationStatus(AzureNetAppFilesManagementClient netAppMgmtClient, string targetState) { ReplicationStatus replicationStatus; int attempts = 0; do { replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); Thread.Sleep(1); } while (replicationStatus.MirrorState != targetState); //sometimes they dont sync up right away if (!replicationStatus.Healthy.Value) { do { replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); attempts++; Thread.Sleep(100); } while (replicationStatus.Healthy.Value || attempts == 5); } Assert.True(replicationStatus.Healthy); } private void WaitForSucceeded(AzureNetAppFilesManagementClient netAppMgmtClient) { Volume sourceVolume; Volume dpVolume; do { sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); Thread.Sleep(1); } while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded")); } [Fact] public void CreateDpVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the source volume var sourceVolume = ResourceUtils.CreateVolume(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup, vnet: ResourceUtils.repVnet); sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); // create the data protection volume from the source var dpVolume = ResourceUtils.CreateDpVolume(netAppMgmtClient, sourceVolume); Assert.Equal(ResourceUtils.remoteVolumeName1, dpVolume.Name.Substring(dpVolume.Name.LastIndexOf('/') + 1)); Assert.NotNull(dpVolume.DataProtection); var authorizeRequest = new AuthorizeRequest { RemoteVolumeResourceId = dpVolume.Id }; if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } netAppMgmtClient.Volumes.AuthorizeReplication(ResourceUtils.repResourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1, authorizeRequest); WaitForSucceeded(netAppMgmtClient); WaitForReplicationStatus(netAppMgmtClient, "Mirrored"); netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); WaitForReplicationStatus(netAppMgmtClient, "Broken"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // sync to the test WaitForSucceeded(netAppMgmtClient); // resync netAppMgmtClient.Volumes.ResyncReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); WaitForReplicationStatus(netAppMgmtClient, "Mirrored"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // break again netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); WaitForReplicationStatus(netAppMgmtClient, "Broken"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // delete the data protection object // - initiate delete replication on destination, this then releases on source, both resulting in object deletion netAppMgmtClient.Volumes.DeleteReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); var replicationFound = true; // because it was previously present while (replicationFound) { try { var replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); } catch { // an exception means the replication was not found // i.e. it has been deleted // ok without checking it could have been for another reason // but then the delete below will fail replicationFound = false; } Thread.Sleep(1); } // seems the volumes are not always in a terminal state here so check again // and ensure the replication objects are removed do { sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); Thread.Sleep(1); } while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded") || (sourceVolume.DataProtection.Replication != null) || (dpVolume.DataProtection.Replication != null)); // now proceed with the delete of the volumes netAppMgmtClient.Volumes.Delete(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.remoteVolumeName1); netAppMgmtClient.Volumes.Delete(ResourceUtils.repResourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); // cleanup pool and account ResourceUtils.DeletePool(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup); ResourceUtils.DeletePool(netAppMgmtClient, ResourceUtils.remotePoolName1, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup); ResourceUtils.DeleteAccount(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup); } } private static string GetSessionsDirectoryPath() { string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.VolumeTests).GetTypeInfo().Assembly.Location; return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords"); } } }
// // Mono.Google.Picasa.PicasaAlbum.cs: // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // Stephane Delcroix (stephane@delcroix.org) // // (C) Copyright 2006 Novell, Inc. (http://www.novell.com) // (C) Copyright 2007 S. Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Text; using System.Xml; namespace Mono.Google.Picasa { public class PicasaAlbum { GoogleConnection conn; string user; string title; string description; string id; string link; string authkey = null; AlbumAccess access = AlbumAccess.Public; int num_photos = -1; int num_photos_remaining = -1; long bytes_used = -1; private PicasaAlbum (GoogleConnection conn) { if (conn == null) throw new ArgumentNullException ("conn"); this.conn = conn; } public PicasaAlbum (GoogleConnection conn, string aid) : this (conn) { if (conn.User == null) throw new ArgumentException ("Need authentication before being used.", "conn"); if (aid == null || aid == String.Empty) throw new ArgumentNullException ("aid"); this.user = conn.User; this.id = aid; string received = conn.DownloadString (GDataApi.GetAlbumEntryById (conn.User, aid)); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr); ParseAlbum (entry, nsmgr); } public PicasaAlbum (GoogleConnection conn, string user, string aid, string authkey) : this (conn) { if (user == null || user == String.Empty) throw new ArgumentNullException ("user"); if (aid == null || aid == String.Empty) throw new ArgumentNullException ("aid"); this.user = user; this.id = aid; this.authkey = authkey; string download_link = GDataApi.GetAlbumEntryById (user, id); if (authkey != null && authkey != "") download_link += "&authkey=" + authkey; string received = conn.DownloadString (download_link); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr); ParseAlbum (entry, nsmgr); } internal PicasaAlbum (GoogleConnection conn, string user, XmlNode nodeitem, XmlNamespaceManager nsmgr) : this (conn) { this.user = user ?? conn.User; ParseAlbum (nodeitem, nsmgr); } private void ParseAlbum (XmlNode nodeitem, XmlNamespaceManager nsmgr) { title = nodeitem.SelectSingleNode ("atom:title", nsmgr).InnerText; description = nodeitem.SelectSingleNode ("media:group/media:description", nsmgr).InnerText; XmlNode node = nodeitem.SelectSingleNode ("gphoto:id", nsmgr); if (node != null) id = node.InnerText; foreach (XmlNode xlink in nodeitem.SelectNodes ("atom:link", nsmgr)) { if (xlink.Attributes.GetNamedItem ("rel").Value == "alternate") { link = xlink.Attributes.GetNamedItem ("href").Value; break; } } node = nodeitem.SelectSingleNode ("gphoto:access", nsmgr); if (node != null) { string acc = node.InnerText; access = (acc == "public") ? AlbumAccess.Public : AlbumAccess.Private; } node = nodeitem.SelectSingleNode ("gphoto:numphotos", nsmgr); if (node != null) num_photos = (int) UInt32.Parse (node.InnerText); node = nodeitem.SelectSingleNode ("gphoto:numphotosremaining", nsmgr); if (node != null) num_photos_remaining = (int) UInt32.Parse (node.InnerText); node = nodeitem.SelectSingleNode ("gphoto:bytesused", nsmgr); if (node != null) bytes_used = (long) UInt64.Parse (node.InnerText); } public PicasaPictureCollection GetPictures () { string download_link = GDataApi.GetAlbumFeedById (user, id); if (authkey != null && authkey != "") download_link += "&authkey=" + authkey; string received = conn.DownloadString (download_link); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode feed = doc.SelectSingleNode ("atom:feed", nsmgr); PicasaPictureCollection coll = new PicasaPictureCollection (); foreach (XmlNode item in feed.SelectNodes ("atom:entry", nsmgr)) { coll.Add (new PicasaPicture (conn, this, item, nsmgr)); } coll.SetReadOnly (); return coll; } /* from http://code.google.com/apis/picasaweb/gdata.html#Add_Photo <entry xmlns='http://www.w3.org/2005/Atom'> <title>darcy-beach.jpg</title> <summary>Darcy on the beach</summary> <category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/photos/2007#photo"/> </entry> */ static string GetXmlForUpload (string title, string description) { XmlUtil xml = new XmlUtil (); xml.WriteElementString ("title", title); xml.WriteElementString ("summary", description); xml.WriteElementStringWithAttributes ("category", null, "scheme", "http://schemas.google.com/g/2005#kind", "term", "http://schemas.google.com/photos/2007#photo"); return xml.GetDocumentString (); } public PicasaPicture UploadPicture (string title, Stream input) { return UploadPicture (title, null, input); } public PicasaPicture UploadPicture (string title, string description, Stream input) { return UploadPicture (title, description, "image/jpeg", input); } public PicasaPicture UploadPicture (string title, string description, string mime_type, Stream input) { if (title == null) throw new ArgumentNullException ("title"); if (input == null) throw new ArgumentNullException ("input"); if (!input.CanRead) throw new ArgumentException ("Cannot read from stream", "input"); string url = GDataApi.GetURLForUpload (conn.User, id); if (url == null) throw new UnauthorizedAccessException ("You are not authorized to upload to this album."); MultipartRequest request = new MultipartRequest (conn, url); FileStream fs = null; try { if (UploadProgress != null) { // We do 'manual' buffering request.Request.AllowWriteStreamBuffering = false; fs = new FileStream (Path.GetTempFileName (), FileMode.OpenOrCreate, FileAccess.Read | FileAccess.Write, FileShare.None); request.OutputStream = fs; } request.BeginPart (true); request.AddHeader ("Content-Type: application/atom+xml; \r\n", true); string upload = GetXmlForUpload (title, description); request.WriteContent (upload); request.EndPart (false); request.BeginPart (); request.AddHeader ("Content-Type: " + mime_type + "\r\n", true); byte [] data = new byte [8192]; int nread; while ((nread = input.Read (data, 0, data.Length)) > 0) { request.WritePartialContent (data, 0, nread); } request.EndPartialContent (); request.EndPart (true); // It won't call Close() on the MemoryStream if (UploadProgress != null) { int req_length = (int) fs.Length; request.Request.ContentLength = req_length; fs.Position = 0; DoUploadProgress (title, 0, req_length); using (Stream req_stream = request.Request.GetRequestStream ()) { while ((nread = fs.Read (data, 0, data.Length)) > 0) { req_stream.Write (data, 0, nread); // The progress uses the actual request size, not file size. DoUploadProgress (title, fs.Position, req_length); } DoUploadProgress (title, fs.Position, req_length); } } } finally { if (fs != null) { string name = fs.Name; fs.Close (); File.Delete (name); } } string received = request.GetResponseAsString (); XmlDocument doc = new XmlDocument (); doc.LoadXml (received); XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable); XmlUtil.AddDefaultNamespaces (nsmgr); XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr); return new PicasaPicture (conn, this, entry, nsmgr); } public PicasaPicture UploadPicture (string filename) { return UploadPicture (filename, ""); } public PicasaPicture UploadPicture (string filename, string description) { return UploadPicture (filename, Path.GetFileName (filename), description); } public PicasaPicture UploadPicture (string filename, string title, string description) { if (filename == null) throw new ArgumentNullException ("filename"); if (title == null) throw new ArgumentNullException ("title"); using (Stream stream = File.OpenRead (filename)) { return UploadPicture (title, description, stream); } } public string Title { get { return title; } } public string Description { get { return description; } } public string Link { get { return link; } } public string UniqueID { get { return id; } } public AlbumAccess Access { get { return access; } } public int PicturesCount { get { return num_photos; } } public int PicturesRemaining { get { return num_photos_remaining; } } public string User { get { return user; } } public long BytesUsed { get { return bytes_used; } } internal GoogleConnection Connection { get { return conn; } } void DoUploadProgress (string title, long sent, long total) { if (UploadProgress != null) { UploadProgress (this, new UploadProgressEventArgs (title, sent, total)); } } public event UploadProgressEventHandler UploadProgress; } }
// 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.Reflection; using System.Diagnostics; using System.Collections.Concurrent; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.MethodInfos; using Internal.Reflection.Core.Execution; // // It is common practice for app code to compare Type objects using reference equality with the expectation that reference equality // is equivalent to semantic equality. To support this, all RuntimeTypeObject objects are interned using weak references. // // This assumption is baked into the codebase in these places: // // - RuntimeTypeInfo.Equals(object) implements itself as Object.ReferenceEquals(this, obj) // // - RuntimeTypeInfo.GetHashCode() is implemented in a flavor-specific manner (We can't use Object.GetHashCode() // because we don't want the hash value to change if a type is collected and resurrected later.) // // This assumption is actualized as follows: // // - RuntimeTypeInfo classes hide their constructor. The only way to instantiate a RuntimeTypeInfo // is through its public static factory method which ensures the interning and are collected in this one // file for easy auditing and to help ensure that they all operate in a consistent manner. // // - The TypeUnifier extension class provides a more friendly interface to the rest of the codebase. // namespace System.Reflection.Runtime.General { internal static partial class TypeUnifier { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType) { return elementType.GetArrayType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank) { return elementType.GetMultiDimArrayType(rank, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType) { return targetType.GetByRefType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType) { return targetType.GetPointerType(default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { return genericTypeDefinition.GetConstructedGenericType(genericTypeArguments, default(RuntimeTypeHandle)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetTypeForRuntimeTypeHandle(this RuntimeTypeHandle typeHandle) { Type type = Type.GetTypeFromHandle(typeHandle); return type.CastToRuntimeTypeInfo(); } //====================================================================================================== // This next group services the Type.GetTypeFromHandle() path. Since we already have a RuntimeTypeHandle // in that case, we pass it in as an extra argument as an optimization (otherwise, the unifier will // waste cycles looking up the handle again from the mapping tables.) //====================================================================================================== [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetArrayType(this RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: false, rank: 1, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetMultiDimArrayType(this RuntimeTypeInfo elementType, int rank, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeArrayTypeInfo.GetArrayTypeInfo(elementType, multiDim: true, rank: rank, precomputedTypeHandle: precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetPointerType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimePointerTypeInfo.GetPointerTypeInfo(targetType, precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetByRefType(this RuntimeTypeInfo targetType, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeByRefTypeInfo.GetByRefTypeInfo(targetType, precomputedTypeHandle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static RuntimeTypeInfo GetConstructedGenericType(this RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { return RuntimeConstructedGenericTypeInfo.GetRuntimeConstructedGenericTypeInfo(genericTypeDefinition, genericTypeArguments, precomputedTypeHandle); } } } namespace System.Reflection.Runtime.TypeInfos { //----------------------------------------------------------------------------------------------------------- // TypeInfos for type definitions (i.e. "Foo" and "Foo<>" but not "Foo<int>") that aren't opted into metadata. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeNoMetadataNamedTypeInfo { internal static RuntimeNoMetadataNamedTypeInfo GetRuntimeNoMetadataNamedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeNoMetadataNamedTypeInfo type; if (isGenericTypeDefinition) type = GenericNoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = NoMetadataNamedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class NoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly NoMetadataNamedTypeTable Table = new NoMetadataNamedTypeTable(); } private sealed class GenericNoMetadataNamedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeNoMetadataNamedTypeInfo> { protected sealed override RuntimeNoMetadataNamedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeNoMetadataNamedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericNoMetadataNamedTypeTable Table = new GenericNoMetadataNamedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos that represent type definitions (i.e. Foo or Foo<>) or constructed generic types (Foo<int>) // that can never be reflection-enabled due to the framework Reflection block. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeBlockedTypeInfo { internal static RuntimeBlockedTypeInfo GetRuntimeBlockedTypeInfo(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { RuntimeBlockedTypeInfo type; if (isGenericTypeDefinition) type = GenericBlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); else type = BlockedTypeTable.Table.GetOrAdd(new RuntimeTypeHandleKey(typeHandle)); type.EstablishDebugName(); return type; } private sealed class BlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: false); } public static readonly BlockedTypeTable Table = new BlockedTypeTable(); } private sealed class GenericBlockedTypeTable : ConcurrentUnifierW<RuntimeTypeHandleKey, RuntimeBlockedTypeInfo> { protected sealed override RuntimeBlockedTypeInfo Factory(RuntimeTypeHandleKey key) { return new RuntimeBlockedTypeInfo(key.TypeHandle, isGenericTypeDefinition: true); } public static readonly GenericBlockedTypeTable Table = new GenericBlockedTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Sz and multi-dim Array types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeArrayTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeArrayTypeInfo GetArrayTypeInfo(RuntimeTypeInfo elementType, bool multiDim, int rank, RuntimeTypeHandle precomputedTypeHandle) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType, multiDim, rank) : precomputedTypeHandle; UnificationKey key = new UnificationKey(elementType, typeHandle); RuntimeArrayTypeInfo type; if (!multiDim) type = ArrayTypeTable.Table.GetOrAdd(key); else type = TypeTableForMultiDimArrayTypeTables.Table.GetOrAdd(rank).GetOrAdd(key); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!multiDim) { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetArrayTypeForElementType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); } else { if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetMultiDimArrayTypeForElementType(elementTypeHandle, rank, out typeHandle)) return default(RuntimeTypeHandle); } return typeHandle; } private sealed class ArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: false, rank: 1); return new RuntimeArrayTypeInfo(key, multiDim: false, rank: 1); } public static readonly ArrayTypeTable Table = new ArrayTypeTable(); } private sealed class MultiDimArrayTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeArrayTypeInfo> { public MultiDimArrayTypeTable(int rank) { _rank = rank; } protected sealed override RuntimeArrayTypeInfo Factory(UnificationKey key) { ValidateElementType(key.ElementType, key.TypeHandle, multiDim: true, rank: _rank); return new RuntimeArrayTypeInfo(key, multiDim: true, rank: _rank); } private readonly int _rank; } // // For the hopefully rare case of multidim arrays, we have a dictionary of dictionaries. // private sealed class TypeTableForMultiDimArrayTypeTables : ConcurrentUnifier<int, MultiDimArrayTypeTable> { protected sealed override MultiDimArrayTypeTable Factory(int rank) { Debug.Assert(rank > 0); return new MultiDimArrayTypeTable(rank); } public static readonly TypeTableForMultiDimArrayTypeTables Table = new TypeTableForMultiDimArrayTypeTables(); } private static void ValidateElementType(RuntimeTypeInfo elementType, RuntimeTypeHandle typeHandle, bool multiDim, int rank) { Debug.Assert(multiDim || rank == 1); if (elementType.IsByRef || elementType.IsByRefLike) throw new TypeLoadException(SR.Format(SR.ArgumentException_InvalidArrayElementType, elementType)); // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (typeHandle.IsNull() && !elementType.ContainsGenericParameters && !(elementType is RuntimeCLSIDTypeInfo)) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingArrayTypeException(elementType, multiDim, rank); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for ByRef types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeByRefTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimeByRefTypeInfo GetByRefTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle; RuntimeByRefTypeInfo type = ByRefTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType) { RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetByRefTypeForTargetType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class ByRefTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeByRefTypeInfo> { protected sealed override RuntimeByRefTypeInfo Factory(UnificationKey key) { if (key.ElementType.IsByRef) throw new TypeLoadException(SR.Format(SR.CannotCreateByRefOfByRef, key.ElementType)); return new RuntimeByRefTypeInfo(key); } public static readonly ByRefTypeTable Table = new ByRefTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Pointer types. //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimePointerTypeInfo : RuntimeHasElementTypeInfo { internal static RuntimePointerTypeInfo GetPointerTypeInfo(RuntimeTypeInfo elementType, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(elementType) : precomputedTypeHandle; RuntimePointerTypeInfo type = PointerTypeTable.Table.GetOrAdd(new UnificationKey(elementType, typeHandle)); type.EstablishDebugName(); return type; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo elementType) { RuntimeTypeHandle elementTypeHandle = elementType.InternalTypeHandleIfAvailable; if (elementTypeHandle.IsNull()) return default(RuntimeTypeHandle); RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetPointerTypeForTargetType(elementTypeHandle, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class PointerTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimePointerTypeInfo> { protected sealed override RuntimePointerTypeInfo Factory(UnificationKey key) { if (key.ElementType.IsByRef) throw new TypeLoadException(SR.Format(SR.CannotCreatePointerOfByRef, key.ElementType)); return new RuntimePointerTypeInfo(key); } public static readonly PointerTypeTable Table = new PointerTypeTable(); } } //----------------------------------------------------------------------------------------------------------- // TypeInfos for Constructed generic types ("Foo<int>") //----------------------------------------------------------------------------------------------------------- internal sealed partial class RuntimeConstructedGenericTypeInfo : RuntimeTypeInfo, IKeyedItem<RuntimeConstructedGenericTypeInfo.UnificationKey> { internal static RuntimeConstructedGenericTypeInfo GetRuntimeConstructedGenericTypeInfo(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments, RuntimeTypeHandle precomputedTypeHandle) { RuntimeTypeHandle typeHandle = precomputedTypeHandle.IsNull() ? GetRuntimeTypeHandleIfAny(genericTypeDefinition, genericTypeArguments) : precomputedTypeHandle; UnificationKey key = new UnificationKey(genericTypeDefinition, genericTypeArguments, typeHandle); RuntimeConstructedGenericTypeInfo typeInfo = ConstructedGenericTypeTable.Table.GetOrAdd(key); typeInfo.EstablishDebugName(); return typeInfo; } private static RuntimeTypeHandle GetRuntimeTypeHandleIfAny(RuntimeTypeInfo genericTypeDefinition, RuntimeTypeInfo[] genericTypeArguments) { RuntimeTypeHandle genericTypeDefinitionHandle = genericTypeDefinition.InternalTypeHandleIfAvailable; if (genericTypeDefinitionHandle.IsNull()) return default(RuntimeTypeHandle); if (ReflectionCoreExecution.ExecutionEnvironment.IsReflectionBlocked(genericTypeDefinitionHandle)) return default(RuntimeTypeHandle); int count = genericTypeArguments.Length; RuntimeTypeHandle[] genericTypeArgumentHandles = new RuntimeTypeHandle[count]; for (int i = 0; i < count; i++) { RuntimeTypeHandle genericTypeArgumentHandle = genericTypeArguments[i].InternalTypeHandleIfAvailable; if (genericTypeArgumentHandle.IsNull()) return default(RuntimeTypeHandle); genericTypeArgumentHandles[i] = genericTypeArgumentHandle; } RuntimeTypeHandle typeHandle; if (!ReflectionCoreExecution.ExecutionEnvironment.TryGetConstructedGenericTypeForComponents(genericTypeDefinitionHandle, genericTypeArgumentHandles, out typeHandle)) return default(RuntimeTypeHandle); return typeHandle; } private sealed class ConstructedGenericTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeConstructedGenericTypeInfo> { protected sealed override RuntimeConstructedGenericTypeInfo Factory(UnificationKey key) { bool atLeastOneOpenType = false; foreach (RuntimeTypeInfo genericTypeArgument in key.GenericTypeArguments) { if (genericTypeArgument.IsByRef || genericTypeArgument.IsGenericTypeDefinition) throw new ArgumentException(SR.Format(SR.ArgumentException_InvalidTypeArgument, genericTypeArgument)); if (genericTypeArgument.ContainsGenericParameters) atLeastOneOpenType = true; } // We only permit creating parameterized types if the pay-for-play policy specifically allows them *or* if the result // type would be an open type. if (key.TypeHandle.IsNull() && !atLeastOneOpenType) throw ReflectionCoreExecution.ExecutionDomain.CreateMissingConstructedGenericTypeException(key.GenericTypeDefinition, key.GenericTypeArguments.CloneTypeArray()); return new RuntimeConstructedGenericTypeInfo(key); } public static readonly ConstructedGenericTypeTable Table = new ConstructedGenericTypeTable(); } } internal sealed partial class RuntimeCLSIDTypeInfo { public static RuntimeCLSIDTypeInfo GetRuntimeCLSIDTypeInfo(Guid clsid, string server) { UnificationKey key = new UnificationKey(clsid, server); return ClsIdTypeTable.Table.GetOrAdd(key); } private sealed class ClsIdTypeTable : ConcurrentUnifierWKeyed<UnificationKey, RuntimeCLSIDTypeInfo> { protected sealed override RuntimeCLSIDTypeInfo Factory(UnificationKey key) { return new RuntimeCLSIDTypeInfo(key.ClsId, key.Server); } public static readonly ClsIdTypeTable Table = new ClsIdTypeTable(); } } }
namespace AutoMapper { using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Linq; using System.Reflection; using Configuration; using Mappers; using QueryableExtensions; using QueryableExtensions.Impl; using IMemberConfiguration = Configuration.Conventions.IMemberConfiguration; public class MapperConfiguration : IConfigurationProvider, IMapperConfiguration { private readonly IEnumerable<IObjectMapper> _mappers; private readonly List<Action<TypeMap, IMappingExpression>> _allTypeMapActions = new List<Action<TypeMap, IMappingExpression>>(); private readonly Profile _defaultProfile; private readonly TypeMapRegistry _typeMapRegistry = new TypeMapRegistry(); private readonly ConcurrentDictionary<TypePair, TypeMap> _typeMapPlanCache = new ConcurrentDictionary<TypePair, TypeMap>(); private readonly IList<Profile> _profiles = new List<Profile>(); private readonly ConfigurationValidator _validator; private Func<Type, object> _serviceCtor = ObjectCreator.CreateObject; private readonly Func<TypePair, TypeMap> _getTypeMap; public MapperConfiguration(Action<IMapperConfiguration> configure) : this(configure, MapperRegistry.Mappers) { } public MapperConfiguration(Action<IMapperConfiguration> configure, IEnumerable<IObjectMapper> mappers) { _mappers = mappers; var profileExpression = new NamedProfile(ProfileName); _profiles.Add(profileExpression); _defaultProfile = profileExpression; _validator = new ConfigurationValidator(this); configure(this); Seal(); ExpressionBuilder = new ExpressionBuilder(this); _getTypeMap = GetTypeMap; } public string ProfileName => ""; #region IConfiguration Members void IConfiguration.CreateProfile(string profileName, Action<Profile> config) { var profile = new NamedProfile(profileName); config(profile); ((IConfiguration)this).AddProfile(profile); } private class NamedProfile : Profile { public NamedProfile(string profileName) : base(profileName) { } } void IConfiguration.AddProfile(Profile profile) { profile.Initialize(); _profiles.Add(profile); } void IConfiguration.AddProfile<TProfile>() => ((IConfiguration)this).AddProfile(new TProfile()); void IConfiguration.AddProfile(Type profileType) => ((IConfiguration)this).AddProfile((Profile)Activator.CreateInstance(profileType)); void IConfiguration.ConstructServicesUsing(Func<Type, object> constructor) => _serviceCtor = constructor; Func<PropertyInfo, bool> IProfileExpression.ShouldMapProperty { get { return _defaultProfile.ShouldMapProperty; } set { _defaultProfile.ShouldMapProperty = value; } } Func<FieldInfo, bool> IProfileExpression.ShouldMapField { get { return _defaultProfile.ShouldMapField; } set { _defaultProfile.ShouldMapField = value; } } bool IConfiguration.CreateMissingTypeMaps { get { return _defaultProfile.CreateMissingTypeMaps; } set { _defaultProfile.CreateMissingTypeMaps = value; } } void IProfileExpression.IncludeSourceExtensionMethods(Type type) { _defaultProfile.IncludeSourceExtensionMethods(type); } INamingConvention IProfileExpression.SourceMemberNamingConvention { get { return _defaultProfile.SourceMemberNamingConvention; } set { _defaultProfile.SourceMemberNamingConvention = value; } } INamingConvention IProfileExpression.DestinationMemberNamingConvention { get { return _defaultProfile.DestinationMemberNamingConvention; } set { _defaultProfile.DestinationMemberNamingConvention = value; } } bool IProfileExpression.AllowNullDestinationValues { get { return AllowNullDestinationValues; } set { AllowNullDestinationValues = value; } } bool IProfileExpression.AllowNullCollections { get { return AllowNullCollections; } set { AllowNullCollections = value; } } void IProfileExpression.ForAllMaps(Action<TypeMap, IMappingExpression> configuration) => _allTypeMapActions.Add(configuration); IMemberConfiguration IProfileExpression.AddMemberConfiguration() => _defaultProfile.AddMemberConfiguration(); IConditionalObjectMapper IProfileExpression.AddConditionalObjectMapper() => _defaultProfile.AddConditionalObjectMapper(); void IProfileExpression.DisableConstructorMapping() => _defaultProfile.DisableConstructorMapping(); IMappingExpression<TSource, TDestination> IProfileExpression.CreateMap<TSource, TDestination>() => _defaultProfile.CreateMap<TSource, TDestination>(); IMappingExpression<TSource, TDestination> IProfileExpression.CreateMap<TSource, TDestination>(MemberList memberList) => _defaultProfile.CreateMap<TSource, TDestination>(memberList); IMappingExpression IProfileExpression.CreateMap(Type sourceType, Type destinationType) => _defaultProfile.CreateMap(sourceType, destinationType, MemberList.Destination); IMappingExpression IProfileExpression.CreateMap(Type sourceType, Type destinationType, MemberList memberList) => _defaultProfile.CreateMap(sourceType, destinationType, memberList); void IProfileExpression.ClearPrefixes() => _defaultProfile.ClearPrefixes(); void IProfileExpression.RecognizeAlias(string original, string alias) => _defaultProfile.RecognizeAlias(original, alias); void IProfileExpression.ReplaceMemberName(string original, string newValue) => _defaultProfile.ReplaceMemberName(original, newValue); void IProfileExpression.RecognizePrefixes(params string[] prefixes) => _defaultProfile.RecognizePrefixes(prefixes); void IProfileExpression.RecognizePostfixes(params string[] postfixes) => _defaultProfile.RecognizePostfixes(postfixes); void IProfileExpression.RecognizeDestinationPrefixes(params string[] prefixes) => _defaultProfile.RecognizeDestinationPrefixes(prefixes); void IProfileExpression.RecognizeDestinationPostfixes(params string[] postfixes) => _defaultProfile.RecognizeDestinationPostfixes(postfixes); void IProfileExpression.AddGlobalIgnore(string startingwith) => _defaultProfile.AddGlobalIgnore(startingwith); #endregion #region IConfigurationProvider members public IExpressionBuilder ExpressionBuilder { get; } public Func<Type, object> ServiceCtor => _serviceCtor; public bool AllowNullDestinationValues { get { return _defaultProfile.AllowNullDestinationValues; } private set { _defaultProfile.AllowNullDestinationValues = value; } } public bool AllowNullCollections { get { return _defaultProfile.AllowNullCollections; } private set { _defaultProfile.AllowNullCollections = value; } } public TypeMap[] GetAllTypeMaps() => _typeMapRegistry.TypeMaps.ToArray(); public TypeMap FindTypeMapFor(Type sourceType, Type destinationType) => FindTypeMapFor(new TypePair(sourceType, destinationType)); public TypeMap FindTypeMapFor<TSource, TDestination>() => FindTypeMapFor(new TypePair(typeof(TSource), typeof(TDestination))); public TypeMap FindTypeMapFor(TypePair typePair) => _typeMapRegistry.GetTypeMap(typePair); public TypeMap ResolveTypeMap(Type sourceType, Type destinationType) { var typePair = new TypePair(sourceType, destinationType); return ResolveTypeMap(typePair); } public TypeMap ResolveTypeMap(TypePair typePair) { var typeMap = _typeMapPlanCache.GetOrAdd(typePair, _getTypeMap); return typeMap; } private TypeMap GetTypeMap(TypePair pair) { foreach(var tp in pair.GetRelatedTypePairs()) { var typeMap = _typeMapPlanCache.GetOrDefault(tp) ?? FindTypeMapFor(tp) ?? (!CoveredByObjectMap(pair) ? FindConventionTypeMapFor(tp) : null) ?? FindClosedGenericTypeMapFor(tp); if(typeMap != null) { return typeMap; } } return null; } public TypeMap ResolveTypeMap(object source, object destination, Type sourceType, Type destinationType) { return ResolveTypeMap(source?.GetType() ?? sourceType, destination?.GetType() ?? destinationType) ?? ResolveTypeMap(sourceType, destinationType); } public TypeMap ResolveTypeMap(Type sourceRuntimeType, Type sourceDeclaredType, Type destinationType) { return ResolveTypeMap(sourceRuntimeType, destinationType) ?? (sourceDeclaredType != sourceRuntimeType ? ResolveTypeMap(sourceDeclaredType, destinationType) : null); } public void AssertConfigurationIsValid(TypeMap typeMap) { _validator.AssertConfigurationIsValid(Enumerable.Repeat(typeMap, 1)); } public void AssertConfigurationIsValid(string profileName) { _validator.AssertConfigurationIsValid(_typeMapRegistry.TypeMaps.Where(typeMap => typeMap.Profile.ProfileName == profileName)); } public void AssertConfigurationIsValid<TProfile>() where TProfile : Profile, new() { AssertConfigurationIsValid(new TProfile().ProfileName); } public void AssertConfigurationIsValid() { _validator.AssertConfigurationIsValid(_typeMapRegistry.TypeMaps.Where(tm => !tm.SourceType.IsGenericTypeDefinition() && !tm.DestinationType.IsGenericTypeDefinition())); } public IMapper CreateMapper() => new Mapper(this); public IMapper CreateMapper(Func<Type, object> serviceCtor) => new Mapper(this, serviceCtor); public IEnumerable<IObjectMapper> GetMappers() => _mappers; #endregion private void Seal() { var derivedMaps = new List<Tuple<TypePair, TypeMap>>(); var redirectedTypes = new List<Tuple<TypePair, TypePair>>(); foreach (var profile in _profiles.Cast<IProfileConfiguration>()) { profile.Register(_typeMapRegistry); } foreach (var action in _allTypeMapActions) { foreach (var typeMap in _typeMapRegistry.TypeMaps) { var expression = new MappingExpression(typeMap.Types, typeMap.ConfiguredMemberList); action(typeMap, expression); expression.Configure(typeMap.Profile, typeMap); } } foreach (var profile in _profiles.Cast<IProfileConfiguration>()) { profile.Configure(_typeMapRegistry); } foreach (var typeMap in _typeMapRegistry.TypeMaps) { _typeMapPlanCache[typeMap.Types] = typeMap; if (typeMap.DestinationTypeOverride != null) { redirectedTypes.Add(Tuple.Create(typeMap.Types, new TypePair(typeMap.SourceType, typeMap.DestinationTypeOverride))); } if (typeMap.SourceType.IsNullableType()) { var nonNullableTypes = new TypePair(Nullable.GetUnderlyingType(typeMap.SourceType), typeMap.DestinationType); redirectedTypes.Add(Tuple.Create(nonNullableTypes, typeMap.Types)); } derivedMaps.AddRange(GetDerivedTypeMaps(typeMap).Select(derivedMap => Tuple.Create(new TypePair(derivedMap.SourceType, typeMap.DestinationType), derivedMap))); } foreach (var redirectedType in redirectedTypes) { var derivedMap = FindTypeMapFor(redirectedType.Item2); if (derivedMap != null) { _typeMapPlanCache[redirectedType.Item1] = derivedMap; } } foreach (var derivedMap in derivedMaps.Where(derivedMap => !_typeMapPlanCache.ContainsKey(derivedMap.Item1))) { _typeMapPlanCache[derivedMap.Item1] = derivedMap.Item2; } foreach (var typeMap in _typeMapRegistry.TypeMaps) { typeMap.Seal(_typeMapRegistry); } } private IEnumerable<TypeMap> GetDerivedTypeMaps(TypeMap typeMap) { foreach (var derivedTypes in typeMap.IncludedDerivedTypes) { var derivedMap = FindTypeMapFor(derivedTypes); if (derivedMap == null) { throw QueryMapperHelper.MissingMapException(derivedTypes.SourceType, derivedTypes.DestinationType); } yield return derivedMap; foreach (var derivedTypeMap in GetDerivedTypeMaps(derivedMap)) { yield return derivedTypeMap; } } } private bool CoveredByObjectMap(TypePair typePair) { return GetMappers().FirstOrDefault(m => m.IsMatch(typePair)) != null; } private TypeMap FindConventionTypeMapFor(TypePair typePair) { var typeMap = _profiles .Cast<IProfileConfiguration>() .Select(p => p.ConfigureConventionTypeMap(_typeMapRegistry, typePair)) .FirstOrDefault(t => t != null); typeMap?.Seal(_typeMapRegistry); return typeMap; } private TypeMap FindClosedGenericTypeMapFor(TypePair typePair) { if (typePair.GetOpenGenericTypePair() == null) return null; var typeMap = _profiles .Cast<IProfileConfiguration>() .Select(p => p.ConfigureClosedGenericTypeMap(_typeMapRegistry, typePair)) .FirstOrDefault(t => t != null); typeMap?.Seal(_typeMapRegistry); return typeMap; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.PointOfService; using Windows.Graphics.Display; using Windows.Media.Capture; using Windows.System.Display; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario5_DisplayingBarcodePreview : Page, INotifyPropertyChanged { public bool IsScannerClaimed { get; set; } = false; public bool IsPreviewing { get; set; } = false; public bool ScannerSupportsPreview { get; set; } = false; public bool SoftwareTriggerStarted { get; set; } = false; MainPage rootPage = MainPage.Current; ObservableCollection<BarcodeScannerInfo> barcodeScanners = new ObservableCollection<BarcodeScannerInfo>(); BarcodeScanner selectedScanner = null; ClaimedBarcodeScanner claimedScanner = null; DeviceWatcher watcher; static readonly Guid rotationGuid = new Guid("C380465D-2271-428C-9B83-ECEA3B4A85C1"); DisplayRequest displayRequest = new DisplayRequest(); MediaCapture mediaCapture; bool isSelectionChanging = false; string pendingSelectionDeviceId = null; bool isStopPending = false; public event PropertyChangedEventHandler PropertyChanged; public Scenario5_DisplayingBarcodePreview() { this.InitializeComponent(); ScannerListSource.Source = barcodeScanners; watcher = DeviceInformation.CreateWatcher(BarcodeScanner.GetDeviceSelector()); watcher.Added += Watcher_Added; watcher.Removed += Watcher_Removed; watcher.Updated += Watcher_Updated; watcher.Start(); DataContext = this; } private async void Watcher_Added(DeviceWatcher sender, DeviceInformation args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { barcodeScanners.Add(new BarcodeScannerInfo(args.Name, args.Id)); // Select the first scanner by default. if (barcodeScanners.Count == 1) { ScannerListBox.SelectedIndex = 0; } }); } private void Watcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args) { // We don't do anything here, but this event needs to be handled to enable realtime updates. // See https://aka.ms/devicewatcher_added. } private void Watcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args) { // We don't do anything here, but this event needs to be handled to enable realtime updates. //See https://aka.ms/devicewatcher_added. } protected async override void OnNavigatedFrom(NavigationEventArgs e) { watcher.Stop(); if (isSelectionChanging) { // If selection is changing, then let it know to stop media capture // when it's done. isStopPending = true; } else { // If selection is not changing, then it's safe to stop immediately. await CloseScannerResourcesAsync(); } } /// <summary> /// Starts previewing the selected scanner's video feed and prevents the display from going to sleep. /// </summary> private async Task StartMediaCaptureAsync(string videoDeviceId) { mediaCapture = new MediaCapture(); // Register for a notification when something goes wrong mediaCapture.Failed += MediaCapture_Failed; var settings = new MediaCaptureInitializationSettings { VideoDeviceId = videoDeviceId, StreamingCaptureMode = StreamingCaptureMode.Video, }; // Initialize MediaCapture bool captureInitialized = false; try { await mediaCapture.InitializeAsync(settings); captureInitialized = true; } catch (UnauthorizedAccessException) { rootPage.NotifyUser("The app was denied access to the camera", NotifyType.ErrorMessage); } catch (Exception e) { rootPage.NotifyUser("Failed to initialize the camera: " + e.Message, NotifyType.ErrorMessage); } if (captureInitialized) { // Prevent the device from sleeping while the preview is running. displayRequest.RequestActive(); PreviewControl.Source = mediaCapture; await mediaCapture.StartPreviewAsync(); await SetPreviewRotationAsync(DisplayInformation.GetForCurrentView().CurrentOrientation); IsPreviewing = true; RaisePropertyChanged(nameof(IsPreviewing)); } else { mediaCapture.Dispose(); mediaCapture = null; } } /// <summary> /// Close the scanners and stop the preview. /// </summary> private async Task CloseScannerResourcesAsync() { claimedScanner?.Dispose(); claimedScanner = null; selectedScanner?.Dispose(); selectedScanner = null; SoftwareTriggerStarted = false; RaisePropertyChanged(nameof(SoftwareTriggerStarted)); if (IsPreviewing) { if (mediaCapture != null) { await mediaCapture.StopPreviewAsync(); mediaCapture.Dispose(); mediaCapture = null; } // Allow the display to go to sleep. displayRequest.RequestRelease(); IsPreviewing = false; RaisePropertyChanged(nameof(IsPreviewing)); } } /// <summary> /// Set preview rotation and mirroring state to adjust for the orientation of the camera, and for embedded cameras, the rotation of the device. /// </summary> /// <param name="message"></param> /// <param name="type"></param> private async Task SetPreviewRotationAsync(DisplayOrientations displayOrientation) { bool isExternalCamera; bool isPreviewMirrored; // Figure out where the camera is located to account for mirroring and later adjust rotation accordingly. DeviceInformation cameraInformation = await DeviceInformation.CreateFromIdAsync(selectedScanner.VideoDeviceId); if ((cameraInformation.EnclosureLocation == null) || (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Unknown)) { isExternalCamera = true; isPreviewMirrored = false; } else { isExternalCamera = false; isPreviewMirrored = (cameraInformation.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front); } PreviewControl.FlowDirection = isPreviewMirrored ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; if (!isExternalCamera) { // Calculate which way and how far to rotate the preview. int rotationDegrees = 0; switch (displayOrientation) { case DisplayOrientations.Portrait: rotationDegrees = 90; break; case DisplayOrientations.LandscapeFlipped: rotationDegrees = 180; break; case DisplayOrientations.PortraitFlipped: rotationDegrees = 270; break; case DisplayOrientations.Landscape: default: rotationDegrees = 0; break; } // The rotation direction needs to be inverted if the preview is being mirrored. if (isPreviewMirrored) { rotationDegrees = (360 - rotationDegrees) % 360; } // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames. var streamProperties = mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview); streamProperties.Properties[rotationGuid] = rotationDegrees; await mediaCapture.SetEncodingPropertiesAsync(MediaStreamType.VideoPreview, streamProperties, null); } } /// <summary> /// Media capture failed, potentially due to the camera being unplugged. /// </summary> /// <param name="sender"></param> /// <param name="errorEventArgs"></param> private void MediaCapture_Failed(MediaCapture sender, MediaCaptureFailedEventArgs errorEventArgs) { rootPage.NotifyUser("Media capture failed. Make sure the camera is still connected.", NotifyType.ErrorMessage); } /// <summary> /// Event Handler for Show Preview Button Click. /// Displays the preview window for the selected barcode scanner. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void ShowPreviewButton_Click(object sender, RoutedEventArgs e) { await claimedScanner?.ShowVideoPreviewAsync(); } /// <summary> /// Event Handler for Hide Preview Button Click. /// Hides the preview window for the selected barcode scanner. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HidePreviewButton_Click(object sender, RoutedEventArgs e) { claimedScanner?.HideVideoPreview(); } /// <summary> /// Event Handler for Start Software Trigger Button Click. /// Starts scanning. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void StartSoftwareTriggerButton_Click(object sender, RoutedEventArgs e) { if (claimedScanner != null) { await claimedScanner.StartSoftwareTriggerAsync(); SoftwareTriggerStarted = true; RaisePropertyChanged(nameof(SoftwareTriggerStarted)); } } /// <summary> /// Event Handler for Stop Software Trigger Button Click. /// Stops scanning. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void StopSoftwareTriggerButton_Click(object sender, RoutedEventArgs e) { if (claimedScanner != null) { await claimedScanner.StopSoftwareTriggerAsync(); SoftwareTriggerStarted = false; RaisePropertyChanged(nameof(SoftwareTriggerStarted)); } } /// <summary> /// Event Handler for Flip Preview Button Click. /// Stops scanning. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FlipPreview_Click(object sender, RoutedEventArgs e) { if (PreviewControl.FlowDirection == FlowDirection.LeftToRight) { PreviewControl.FlowDirection = FlowDirection.RightToLeft; } else { PreviewControl.FlowDirection = FlowDirection.LeftToRight; } } /// <summary> /// Event handler for scanner listbox selection changed /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void ScannerSelection_Changed(object sender, SelectionChangedEventArgs args) { var selectedScannerInfo = (BarcodeScannerInfo)args.AddedItems[0]; var deviceId = selectedScannerInfo.DeviceId; if (isSelectionChanging) { pendingSelectionDeviceId = deviceId; return; } do { await SelectScannerAsync(deviceId); // Stop takes precedence over updating the selection. if (isStopPending) { await CloseScannerResourcesAsync(); break; } deviceId = pendingSelectionDeviceId; pendingSelectionDeviceId = null; } while (!String.IsNullOrEmpty(deviceId)); } /// <summary> /// Select the scanner specified by its device ID. /// </summary> /// <param name="scannerDeviceId"></param> private async Task SelectScannerAsync(string scannerDeviceId) { isSelectionChanging = true; await CloseScannerResourcesAsync(); selectedScanner = await BarcodeScanner.FromIdAsync(scannerDeviceId); if (selectedScanner != null) { claimedScanner = await selectedScanner.ClaimScannerAsync(); if (claimedScanner != null) { await claimedScanner.EnableAsync(); ScannerSupportsPreview = !String.IsNullOrEmpty(selectedScanner.VideoDeviceId); RaisePropertyChanged(nameof(ScannerSupportsPreview)); claimedScanner.DataReceived += ClaimedScanner_DataReceived; if (ScannerSupportsPreview) { await StartMediaCaptureAsync(selectedScanner.VideoDeviceId); } } else { rootPage.NotifyUser("Failed to claim the selected barcode scanner", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Failed to create a barcode scanner object", NotifyType.ErrorMessage); } IsScannerClaimed = claimedScanner != null; RaisePropertyChanged(nameof(IsScannerClaimed)); isSelectionChanging = false; } /// <summary> /// Scan data was received from the selected scanner. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private async void ClaimedScanner_DataReceived(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ScenarioOutputScanDataLabel.Text = DataHelpers.GetDataLabelString(args.Report.ScanDataLabel, args.Report.ScanDataType); ScenarioOutputScanData.Text = DataHelpers.GetDataString(args.Report.ScanData); ScenarioOutputScanDataType.Text = BarcodeSymbologies.GetName(args.Report.ScanDataType); }); } /// <summary> /// Update listeners that a property was changed so that data bindings can be updated. /// </summary> /// <param name="propertyName"></param> public void RaisePropertyChanged(string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
// Copyright 2019 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; namespace PreRel_UndoRedo { /// <summary> /// Dockpane that illustrates how to manage an OperationManager and add undo/redo operations to it. /// </summary> /// <remarks> /// The dockpane contains buttons that /// - adds a simple zoom in operation to the undo stack /// - adds a simple zoom out operation to the undo stack /// - adds a composite operation to the undo stack /// - undoes an operation from the undo stack /// - redoes an operation from the redo stack /// - removes an operation from the undo stack /// - clears all operations of a specific category from the undo and redo stacks /// </remarks> internal class SampleDockPaneViewModel : DockPane { internal static string _dockPaneID = "PreRel_UndoRedo_SampleDockPane"; /// <summary> /// Operation manager for the dockpane /// </summary> private OperationManager _operationManager = new OperationManager(); public override OperationManager OperationManager { get { return _operationManager; } } /// <summary> /// constructor for the dockpane viewmodel. /// </summary> protected SampleDockPaneViewModel() { _fixedZoomInCmd = new RelayCommand(() => FixedZoomIn(), () => true); _fixedZoomOutCmd = new RelayCommand(() => FixedZoomOut(), () => true); _compositeZoomInCmd = new RelayCommand(() => CompositeZoomIn(), () => true); _undoCmd = new RelayCommand(() => Undo(), () => CanUndo); _redoCmd = new RelayCommand(() => Redo(), () => CanRedo); _removeOperationCmd = new RelayCommand(() => RemoveOperation(), () => CanUndo); _clearOperationsCommand = new RelayCommand(() => ClearOperations(), () => CanUndo || CanRedo); } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID); if (pane == null) return; pane.Activate(); } /// <summary> /// Text shown near the top of the DockPane. /// </summary> private string _heading = "My DockPane"; public string Heading { get { return _heading; } set { SetProperty(ref _heading, value, () => Heading); } } #region Zoom Commands /// <summary> /// Composite zoom in command, binds to a button in the view /// </summary> private RelayCommand _compositeZoomInCmd; public ICommand CompositeZoomInCommand { get { return _compositeZoomInCmd; } } /// <summary> /// Fixed zoom in command, binds to a button in the view /// </summary> private RelayCommand _fixedZoomInCmd; public ICommand FixedZoomInCommand { get { return _fixedZoomInCmd; } } /// <summary> /// fixed zoom out command, binds to a button in the view /// </summary> private RelayCommand _fixedZoomOutCmd; public ICommand FixedZoomOutCommand { get { return _fixedZoomOutCmd; } } /// <summary> /// Action for the composite zoom in button. Performs a 3x zoom in. /// </summary> /// <returns>A Task that represents the CompositeZoomIn method</returns> private Task CompositeZoomIn() { // composite operations need to be created on the worker thread return QueuedTask.Run(() => { this.OperationManager.CreateCompositeOperation(() => { for (int idx = 0; idx < 3; idx++) { MyZoomOperation op = new MyZoomOperation(true); this.OperationManager.Do(op); } }, "Zoom In 3x"); }); } /// <summary> /// Action for the fixed zoom in button /// </summary> /// <returns>A Task that represents the FixedZoomIn method</returns> private async Task FixedZoomIn() { MyZoomOperation op = new MyZoomOperation(true); await this.OperationManager.DoAsync(op); } private async Task FixedZoomOut() { MyZoomOperation op = new MyZoomOperation(false); await this.OperationManager.DoAsync(op); } #endregion #region Undo/Redo Commands /// <summary> /// Determines if the undo button can be enabled. It should be enabled if operations exist on the undo stack of the OperationManager. /// </summary> /// <returns>returns True if operations exist</returns> internal bool CanUndo { get { if (OperationManager != null) return OperationManager.CanUndo; return false; } } /// <summary> /// Determines if the redo button can be enabled. It should be enabled if operations exist on the redo stack of the OperationManager /// </summary> private bool CanRedo { get { if (OperationManager != null) return OperationManager.CanRedo; return false; } } /// <summary> /// The Undo command; binds to a button on the view /// </summary> private RelayCommand _undoCmd; public ICommand UndoCommand { get { return _undoCmd; } } /// <summary> /// The Redo command; binds to a button on the view /// </summary> private RelayCommand _redoCmd; public ICommand RedoCommand { get { return _redoCmd; } } /// <summary> /// Action for the undo button; performs the undo action on the OperationManager /// </summary> /// <returns>A Task that represents the Undo method</returns> private async Task Undo() { if (OperationManager != null) { if (OperationManager.CanUndo) await OperationManager.UndoAsync(); } } /// <summary> /// Action for the redo button; performs the redo action on the OperationManager /// </summary> /// <returns>A Task that represents the Redo method</returns> private async Task Redo() { if (OperationManager != null) { if (OperationManager.CanRedo) await OperationManager.RedoAsync(); } } /// <summary> /// The RemoveOperation command; binds to a button on the view /// </summary> private RelayCommand _removeOperationCmd; public ICommand RemoveOperationCommand { get { return _removeOperationCmd; } } /// <summary> /// The Clear Operations command; binds to a button on the view /// </summary> private RelayCommand _clearOperationsCommand; public ICommand ClearOperationsCommand { get { return _clearOperationsCommand; } } /// <summary> /// Action for the RemoveOperation button; pops the most recent operation from the undo stack (without undoing it) /// </summary> private void RemoveOperation() { if (OperationManager != null) { // find all the operations of my category List<Operation> ops = OperationManager.FindUndoOperations(o => o.Category == PreRel_UndoRedo.Category); // remove the most recent (this is the one at the top of the list) if ((ops != null) && (ops.Count > 0)) OperationManager.RemoveUndoOperation(ops[0]); } } /// <summary> /// Action for the ClearOperations button; clears the undo and redo stacks of a specific category of operations /// </summary> private void ClearOperations() { if (OperationManager != null) { OperationManager.ClearUndoCategory(PreRel_UndoRedo.Category); OperationManager.ClearRedoCategory(PreRel_UndoRedo.Category); } } #endregion } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class SampleDockPane_ShowButton : Button { protected override void OnClick() { SampleDockPaneViewModel.Show(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using SortedDictionaryTests.SortedDictionary_SortedDictionary_RemoveTest; using SortedDictionary_SortedDictionaryUtils; namespace SortedDictionaryTests { public class SortedDictionary_RemoveTests { [Fact] public static void SortedDictionary_RemoveIntTest() { Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } //Ref<val>,Val<Ref> IntDriver.BasicRemove(intArr1, stringArr1); IntDriver.RemoveNegative(intArr1, stringArr1, intArr2); IntDriver.RemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.RemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.RemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.RemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.RemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.RemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryBasicRemove(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveNegative(intArr1, stringArr1, intArr2); IntDriver.NonGenericIDictionaryRemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 98, 6); } [Fact] public static void SortedDictionary_RemoveStringTest() { Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Val<Ref>,Ref<Val> StringDriver.BasicRemove(stringArr1, intArr1); StringDriver.RemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.RemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.RemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.RemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.RemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.RemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.RemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryBasicRemove(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.NonGenericIDictionaryRemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 98, 6); } [Fact] public static void SortedDictionary_RemoveTest_Negative() { Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(); Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } IntDriver.NonGenericIDictionaryRemoveValidations(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveValidations(new RefX1<int>[] { }, new ValX1<string>[] { }); StringDriver.NonGenericIDictionaryRemoveValidations(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveValidations(new ValX1<string>[] { }, new RefX1<int>[] { }); } } namespace SortedDictionary_SortedDictionary_RemoveTest { /// Helper class public class Driver<K, V> where K : IComparableValue { public void BasicRemove(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_1! Expected count to be equal to keys.Length" for (int i = 0; i < keys.Length; i++) { Assert.True(tbl.Remove(keys[i])); //"Err_2! Expected Remove() to return true" } Assert.Equal(tbl.Count, 0); //"Err_3! Count was expected to be zero" } public void RemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_4! Expected count to be equal to keys.Length" for (int i = 0; i < missingkeys.Length; i++) { Assert.False(tbl.Remove(missingkeys[i])); //"Err_5! Expected Remove() to return false" } Assert.Equal(tbl.Count, keys.Length); //"Err_6! Expected count to be equal to keys.Length" } public void RemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_7! Expected count to be equal to keys.Length" Assert.True(tbl.Remove(keys[index])); //"Err_8! Expected Remove() to return true" for (int i = 0; i < repeat; i++) { Assert.False(tbl.Remove(keys[index])); //"Err_9! Expected Remove() to return false" } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_10! Expected count to be equal to keys.Length-1" } public void AddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_11! Expected count to be equal to keys.Length" Assert.True(tbl.Remove(keys[index])); //"Err_12! Expected Remove() to return true" for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); Assert.True(tbl.Remove(keys[index])); //"Err_13! Expected Remove() to return true" } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_14! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryBasicRemove(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_16! Expected count to be equal to keys.Length" for (int i = 0; i < keys.Length; i++) { _idic.Remove(keys[i]); Assert.False(_idic.Contains(keys[i])); //"Err_17! Expected " + keys[i] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, 0); //"Err_18! Count was expected to be zero" } public void NonGenericIDictionaryRemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_19! Expected count to be equal to keys.Length" for (int i = 0; i < missingkeys.Length; i++) { _idic.Remove(missingkeys[i]); Assert.False(_idic.Contains(missingkeys[i])); //"Err_20! Expected " + missingkeys[i] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length); //"Err_21! Expected count to be equal to keys.Length" } public void NonGenericIDictionaryRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_22! Expected count to be equal to keys.Length" _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_23! Expected " + keys[index] + " to not still exist, but Contains returned true." for (int i = 0; i < repeat; i++) { _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_24! Expected " + keys[index] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_25! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryAddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } Assert.Equal(tbl.Count, keys.Length); //"Err_26! Expected count to be equal to keys.Length" _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_27! Expected " + keys[index] + " to not still exist, but Contains returned true." for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); _idic.Remove(keys[index]); Assert.False(_idic.Contains(keys[index])); //"Err_28! Expected " + keys[index] + " to not still exist, but Contains returned true." } Assert.Equal(tbl.Count, keys.Length - 1); //"Err_30! Expected count to be equal to keys.Length-1" } public void NonGenericIDictionaryRemoveValidations(K[] keys, V[] values) { SortedDictionary<K, V> tbl = new SortedDictionary<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } //try null key Assert.Throws<ArgumentNullException>(() => _idic.Remove(null)); //"Err_31! wrong exception thrown when trying to remove null." } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; namespace System.CommandLine { internal static class HelpTextGenerator { public static string Generate(ArgumentSyntax argumentSyntax, int maxWidth) { var forCommandList = argumentSyntax.ActiveCommand == null && argumentSyntax.Commands.Any(); var page = forCommandList ? GetCommandListHelp(argumentSyntax) : GetCommandHelp(argumentSyntax, argumentSyntax.ActiveCommand); var sb = new StringBuilder(); sb.WriteHelpPage(page, maxWidth); return sb.ToString(); } private struct HelpPage { public string ApplicationName; public IEnumerable<string> SyntaxElements; public IReadOnlyList<HelpRow> Rows; } private struct HelpRow { public string Header; public string Text; } private static void WriteHelpPage(this StringBuilder sb, HelpPage page, int maxWidth) { sb.WriteUsage(page.ApplicationName, page.SyntaxElements, maxWidth); if (!page.Rows.Any()) return; sb.AppendLine(); sb.WriteRows(page.Rows, maxWidth); sb.AppendLine(); } private static void WriteUsage(this StringBuilder sb, string applicationName, IEnumerable<string> syntaxElements, int maxWidth) { var usageHeader = string.Format(Strings.HelpUsageOfApplicationFmt, applicationName); sb.Append(usageHeader); if (syntaxElements.Any()) sb.Append(@" "); var syntaxIndent = usageHeader.Length + 1; var syntaxMaxWidth = maxWidth - syntaxIndent; sb.WriteWordWrapped(syntaxElements, syntaxIndent, syntaxMaxWidth); } private static void WriteRows(this StringBuilder sb, IReadOnlyList<HelpRow> rows, int maxWidth) { const int indent = 4; var maxColumnWidth = rows.Select(r => r.Header.Length).Max(); var helpStartColumn = maxColumnWidth + 2 * indent; var maxHelpWidth = maxWidth - helpStartColumn; if (maxHelpWidth < 0) maxHelpWidth = maxWidth; foreach (var row in rows) { var headerStart = sb.Length; sb.Append(' ', indent); sb.Append(row.Header); var headerLength = sb.Length - headerStart; var requiredSpaces = helpStartColumn - headerLength; sb.Append(' ', requiredSpaces); var words = SplitWords(row.Text); sb.WriteWordWrapped(words, helpStartColumn, maxHelpWidth); } } private static void WriteWordWrapped(this StringBuilder sb, IEnumerable<string> words, int indent, int maxidth) { var helpLines = WordWrapLines(words, maxidth); var isFirstHelpLine = true; foreach (var helpLine in helpLines) { if (isFirstHelpLine) isFirstHelpLine = false; else sb.Append(' ', indent); sb.AppendLine(helpLine); } if (isFirstHelpLine) sb.AppendLine(); } private static HelpPage GetCommandListHelp(ArgumentSyntax argumentSyntax) { return new HelpPage { ApplicationName = argumentSyntax.ApplicationName, SyntaxElements = GetGlobalSyntax(), Rows = GetCommandRows(argumentSyntax).ToArray() }; } private static HelpPage GetCommandHelp(ArgumentSyntax argumentSyntax, ArgumentCommand command) { return new HelpPage { ApplicationName = argumentSyntax.ApplicationName, SyntaxElements = GetCommandSyntax(argumentSyntax, command), Rows = GetArgumentRows(argumentSyntax, command).ToArray() }; } private static IEnumerable<string> GetGlobalSyntax() { yield return @"<command>"; yield return @"[<args>]"; } private static IEnumerable<string> GetCommandSyntax(ArgumentSyntax argumentSyntax, ArgumentCommand command) { if (command != null) yield return command.Name; foreach (var option in argumentSyntax.GetOptions(command).Where(o => !o.IsHidden)) yield return GetOptionSyntax(option); if (argumentSyntax.GetParameters(command).All(p => p.IsHidden)) yield break; if (argumentSyntax.GetOptions(command).Any(o => !o.IsHidden)) yield return @"[--]"; foreach (var parameter in argumentSyntax.GetParameters(command).Where(o => !o.IsHidden)) yield return GetParameterSyntax(parameter); } private static string GetOptionSyntax(Argument option) { var sb = new StringBuilder(); sb.Append(@"["); sb.Append(option.GetDisplayName()); if (!option.IsFlag) sb.Append(@" <arg>"); if (option.IsList) sb.Append(@"..."); sb.Append(@"]"); return sb.ToString(); } private static string GetParameterSyntax(Argument parameter) { var sb = new StringBuilder(); sb.Append(parameter.GetDisplayName()); if (parameter.IsList) sb.Append(@"..."); return sb.ToString(); } private static IEnumerable<HelpRow> GetCommandRows(ArgumentSyntax argumentSyntax) { return argumentSyntax.Commands .Where(c => !c.IsHidden) .Select(c => new HelpRow { Header = c.Name, Text = c.Help }); } private static IEnumerable<HelpRow> GetArgumentRows(ArgumentSyntax argumentSyntax, ArgumentCommand command) { return argumentSyntax.GetArguments(command) .Where(a => !a.IsHidden) .Select(a => new HelpRow { Header = GetArgumentRowHeader(a), Text = a.Help }); } private static string GetArgumentRowHeader(Argument argument) { var sb = new StringBuilder(); foreach (var displayName in argument.GetDisplayNames()) { if (sb.Length > 0) sb.Append(@", "); sb.Append(displayName); } if (argument.IsOption && !argument.IsFlag) sb.Append(@" <arg>"); if (argument.IsList) sb.Append(@"..."); return sb.ToString(); } private static IEnumerable<string> WordWrapLines(IEnumerable<string> tokens, int maxWidth) { var sb = new StringBuilder(); foreach (var token in tokens) { var newLength = sb.Length == 0 ? token.Length : sb.Length + 1 + token.Length; if (newLength > maxWidth) { if (sb.Length == 0) { yield return token; continue; } yield return sb.ToString(); sb.Clear(); } if (sb.Length > 0) sb.Append(@" "); sb.Append(token); } if (sb.Length > 0) yield return sb.ToString(); } private static IEnumerable<string> SplitWords(string text) { return string.IsNullOrEmpty(text) ? Enumerable.Empty<string>() : text.Split(' '); } } }
// 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.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void Add_Vector64_Int16() { var test = new SimpleBinaryOpTest__Add_Vector64_Int16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__Add_Vector64_Int16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int16> _fld1; public Vector64<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__Add_Vector64_Int16 testClass) { var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__Add_Vector64_Int16 testClass) { fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector64<Int16> _clsVar1; private static Vector64<Int16> _clsVar2; private Vector64<Int16> _fld1; private Vector64<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__Add_Vector64_Int16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); } public SimpleBinaryOpTest__Add_Vector64_Int16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.Add( Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Add), new Type[] { typeof(Vector64<Int16>), typeof(Vector64<Int16>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int16>* pClsVar1 = &_clsVar1) fixed (Vector64<Int16>* pClsVar2 = &_clsVar2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(pClsVar1)), AdvSimd.LoadVector64((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Int16>>(_dataTable.inArray2Ptr); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Int16*)(_dataTable.inArray2Ptr)); var result = AdvSimd.Add(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__Add_Vector64_Int16(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__Add_Vector64_Int16(); fixed (Vector64<Int16>* pFld1 = &test._fld1) fixed (Vector64<Int16>* pFld2 = &test._fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int16>* pFld1 = &_fld1) fixed (Vector64<Int16>* pFld2 = &_fld2) { var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(pFld1)), AdvSimd.LoadVector64((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Add( AdvSimd.LoadVector64((Int16*)(&test._fld1)), AdvSimd.LoadVector64((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int16> op1, Vector64<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] + right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] + right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Add)}<Int16>(Vector64<Int16>, Vector64<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.UI; using Microsoft.AppCenter.Unity.Crashes; public class SettingsCanvasController : Singleton<SettingsCanvasController> { protected SettingsCanvasController() { } // guarantee this will be always a singleton only - can't use the constructor! public Button openSettingsButton; public Button closeSettingsButton; public Transform menuOverlayPanel; public bool showOpenCloseButton = true; public string UBVersion = "v1.10.10"; public Text displayVersion; public Text activeTitleId; public enum SettingButtonTypes { none = 0, returnToCharacterSelect, leaveBattle, logout, accountSettings, setTitleId, communityPortal, redeemCoupon, triggerCrash } public List<SettingsButtonDetails> settingsButtons = new List<SettingsButtonDetails>(); public List<SceneToSettingsMapping> settingsByScene = new List<SceneToSettingsMapping>(); void OnLevelLoad(Scene scene, LoadSceneMode mode) { UpdateSettingsMenuButtons(); } public override void Awake() { base.Awake(); UpdateSettingsMenuButtons(); } // Use this for initialization void Start() { //CloseSettingsMenu(); this.displayVersion.text = this.UBVersion; SettingsButtonDisplay(showOpenCloseButton); } void OnEnable() { SceneManager.sceneLoaded += OnLevelLoad; } void OnDisable() { SceneManager.sceneLoaded -= OnLevelLoad; } public void OpenCommunityPortal() { if (string.IsNullOrEmpty(PF_GameData.CommunityWebsite)) { PF_Bridge.RaiseCallbackError("No URL was found for the Community Portal. Check TitleData.", PlayFabAPIMethods.Generic, MessageDisplayStyle.error); return; } Application.OpenURL(PF_GameData.CommunityWebsite); } void UpdateSettingsMenuButtons() { var levelName = SceneManager.GetActiveScene().name; var activeSettings = this.settingsByScene.Find((zz) => { return zz.sceneName.Contains(levelName); }); if (activeSettings != null) { foreach (var button in settingsButtons) { var sceneObject = activeSettings.buttons.Find((zz) => { return button.buttonType == zz; }); //Debug.Log(sceneObject.ToString()); if (sceneObject != SettingButtonTypes.none) { button.prefab.gameObject.SetActive(true); } else { button.prefab.gameObject.SetActive(false); } } } else { Debug.LogWarning("Something went wrong, check the scene names mappings"); } } public void OpenSettingsMenu() { // THIS BREAKS IF THE GO IS DISABLED!!! //Tween.Tween(this.menuOverlayPanel.gameObject, .001f, Quaternion.Euler(0,0,0) , Quaternion.Euler(0,0,15f), TweenMain.Style.PingPong, TweenMain.Method.EaseIn, null); //new Vector3(Screen.width/2, Screen.height/2, 0) menuOverlayPanel.gameObject.SetActive(true); TweenPos.Tween(this.menuOverlayPanel.gameObject, .001f, this.menuOverlayPanel.transform.position, new Vector3(0, Screen.height, 0), TweenMain.Style.Once, TweenMain.Method.Linear, null, Space.World); TweenScale.Tween(this.menuOverlayPanel.gameObject, .001f, new Vector3(1, 1, 1), new Vector3(0, 0, 0), TweenMain.Style.Once, TweenMain.Method.EaseIn, null); TweenPos.Tween(this.menuOverlayPanel.gameObject, .5f, new Vector3(0, 0, 0), new Vector3(Screen.width / 2, Screen.height / 2, 0), TweenMain.Style.Once, TweenMain.Method.EaseIn, null, Space.World); TweenScale.Tween(this.menuOverlayPanel.gameObject, .5f, new Vector3(0, 0, 0), new Vector3(1, 1, 1), TweenMain.Style.Once, TweenMain.Method.EaseIn, null); this.activeTitleId.text = PlayFab.PlayFabSettings.TitleId; ToggleOpenCloseButtons(); } // NEED TO MAKE THIS A COROUTINE public void CloseSettingsMenu() { TweenPos.Tween(this.menuOverlayPanel.gameObject, .5f, new Vector3(Screen.width / 2, Screen.height / 2, 0), new Vector3(0, 0, 0), TweenMain.Style.Once, TweenMain.Method.EaseIn, null, Space.World); TweenScale.Tween(this.menuOverlayPanel.gameObject, .5f, new Vector3(1, 1, 1), new Vector3(0, 0, 0), TweenMain.Style.Once, TweenMain.Method.EaseIn, null); StartCoroutine(PF_GamePlay.Wait(.75f, () => { menuOverlayPanel.gameObject.SetActive(false); ToggleOpenCloseButtons(); })); } public void ToggleOpenCloseButtons() { if (this.showOpenCloseButton) { if (this.openSettingsButton.gameObject.activeSelf) { this.openSettingsButton.gameObject.SetActive(false); this.closeSettingsButton.gameObject.SetActive(true); } else { this.openSettingsButton.gameObject.SetActive(true); this.closeSettingsButton.gameObject.SetActive(false); } } } void SettingsButtonDisplay(bool mode) { if (this.showOpenCloseButton && mode) { this.openSettingsButton.gameObject.SetActive(true); this.closeSettingsButton.gameObject.SetActive(false); } else if (this.showOpenCloseButton) { this.openSettingsButton.gameObject.SetActive(true); this.closeSettingsButton.gameObject.SetActive(false); } } public void ReturnToCharacterSelect() { PF_PlayerData.activeCharacter = null; SceneController.Instance.ReturnToCharacterSelect(); CloseSettingsMenu(); } public void LeaveBattle() { Action<bool> processResponse = (bool response) => { if (response) { Dictionary<string, object> eventData = new Dictionary<string, object>() { { "Current_Quest", PF_GamePlay.ActiveQuest.levelName }, { "Character_ID", PF_PlayerData.activeCharacter.characterDetails.CharacterId } }; PF_Bridge.LogCustomEvent(PF_Bridge.CustomEventTypes.Client_BattleAborted, eventData); CloseSettingsMenu(); SceneController.Instance.RequestSceneChange(SceneController.GameScenes.Profile, .333f); } }; DialogCanvasController.RequestConfirmationPrompt(GlobalStrings.QUIT_LEVEL_PROMPT, GlobalStrings.QUIT_LEVEL_MSG, processResponse); } public void ShowAccountSettings() { DialogCanvasController.RequestAccountSettings(); } public void RedeemCoupon() { UnityAction<string> afterPrompt = (string response) => { if (!string.IsNullOrEmpty(response)) { PF_GamePlay.RedeemCoupon(response); } }; DialogCanvasController.RequestTextInputPrompt("Redeem a Coupon Code", "Enter a valid code to redeem rewards.", (string response) => { afterPrompt(response); }, "XXX-XXXX-XXX"); } public void ForceCrash() { Crashes.GenerateTestCrash(); // Application.ForceCrash(2); // Crashes.GenerateTestCrash(); } public void SetTitleId() { UnityAction<string> afterPrompt = (string response) => { if (!string.IsNullOrEmpty(response)) { this.activeTitleId.text = response; PlayFab.PlayFabSettings.TitleId = response; PlayerPrefs.SetString("TitleId", response); } }; DialogCanvasController.RequestTextInputPrompt("Set Title Id", "This will update which PlayFab title this client connects to.", (string response) => { afterPrompt(response); }, PlayFab.PlayFabSettings.TitleId); } public void Logout() { Action<bool> processResponse = (bool response) => { if (response) { PF_PlayerData.activeCharacter = null; CloseSettingsMenu(); PF_Authentication.Logout(); } }; DialogCanvasController.RequestConfirmationPrompt(GlobalStrings.LOGOUT_PROMPT, GlobalStrings.LOGOUT_MSG, processResponse); } } [Serializable] public class SceneToSettingsMapping { public string sceneName; public SceneController.GameScenes scene; public bool showOpenCloseButtons = true; public List<SettingsCanvasController.SettingButtonTypes> buttons = new List<SettingsCanvasController.SettingButtonTypes>(); } [Serializable] public class SettingsButtonDetails { public string buttonName; public SettingsCanvasController.SettingButtonTypes buttonType; public Transform prefab; }
using Core.Common.Reflect; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; using System; using System.Reflection; using Newtonsoft.Json; using System.Collections.Generic; using System.Linq.Expressions; using System.Linq; using Core.Common.Collections; namespace Core.Common.Tests { public class MethodCall { private Delegate @delegate; public MethodCall() { } public object Target { get; set; } public MethodInfo Method { get; set; } public static MethodCall FromExpression(Expression<Action> expression) { var target = expression.GetTarget(); var instance = expression.GetMethodInfo(); return new MethodCall(); } } public static class Helpers { } public static class Bind { } [TestClass] public class MethodCallTests { [TestMethod] public void MethodCallCreate() { var uut = MethodCall.FromExpression(() => InstanceTwoArgsReturnString(new Bind<string>("asda"), "constant",new Bind<string>("output"))); } private void InstanceTwoArgsReturnString(string bind1, string v, string bind2) { throw new NotImplementedException(); } public string InstanceTwoArgsReturnTwoStrings(string lhs, string rhs, out string res1) { res1 = "output"; return lhs + rhs; } } public class Bind<T> { public Bind(string contract) { } public static implicit operator T(Bind<T> output) { return default(T); } } class MyTaskContext { int value = 0; } [TestClass] public class PersistentTaskTests { private string instanceField = null; private static string staticField = null; [TestMethod] [TestCategory("Persistent")] public void ShouldPerfomNullOpStatic() { staticField = null; var uut = new PersistentTaskRunner(); var result = uut.Run(() => DoNothing()); Assert.AreEqual("hello", staticField); } public static void DoNothing() { staticField = "hello"; } [TestMethod] public void ShouldRunLambdaTask() { staticField = null; var uut = new PersistentTaskRunner(); var result = uut.Run(() => Lala()); Assert.AreEqual("1", staticField); Assert.AreEqual(null, result); } private static void Lala() { staticField = "1"; } [TestMethod] public void ShouldReturnResult() { staticField = null; instanceField = "hiho"; var uut = new PersistentTaskRunner(); var result = uut.Run(() => ReturnSomthing()); Assert.AreEqual("hiho", result); } string ReturnSomthing() { return instanceField; } [TestMethod] void ShouldUseParameters() { var uut = new PersistentTaskRunner(); var result = uut.Run(() => StaticTwoArgsReturnAny(Arg.Create<string>("somthing"), "hello")); } private static string StaticTwoArgsReturnAny(string lhs, string rhs) { return lhs + rhs; } } public static class Helpers1 { public static string QualifiedParameterName(this ParameterInfo info) { return info.Member.DeclaringType.FullName + "." + info.Member.Name + "(" + info.Name + ")"; } } public class Arg { public static Arg<T> Create<T>(string name) { return new Arg<T>(name); } } public class Arg<T> { public string Name { get; set; } public Arg(string inputName) { Name = inputName; } public static implicit operator T(Arg<T> arg) { return default(T); } } public class PersistentTaskRunner { private Dictionary<string, object> inputvalues = new Dictionary<string, object>(); public bool HasParameter(string key) { lock (inputvalues) { return inputvalues.ContainsKey(key); } } public void Provide(string key, object value) { lock (inputvalues) { inputvalues[key] = value; } } public void Provide(Expression<Action> call, string parameter, object value) { var param = call.GetMethodInfo().GetParameters().FirstOrDefault(p => p.Name == parameter); var paramName = param.QualifiedParameterName(); Provide(paramName, value); } private object[] GetParameters(MethodInfo method) { lock (inputvalues) { var parameters = method.GetParameters().Select(p => p.QualifiedParameterName()).ToArray(); if (parameters.Any(p => !inputvalues.ContainsKey(p))) { return null; } var values = parameters.Select(p => inputvalues[p]).ToArray(); foreach (var p in parameters) { inputvalues.Remove(p); } return values; } } private void SetParameters(MethodInfo method, object[] parameters) { lock (inputvalues) { var parameterInfos = method.GetParameters(); for (int i = 0; i < parameterInfos.Length; i++) { var parameterInfo = parameterInfos[i]; if (parameterInfo.IsOut) { var parameterName = parameterInfo.QualifiedParameterName(); inputvalues[parameterName] = parameters[i]; } } } } public object Run(Expression<Action> start) { var method = start.GetMethodInfo(); var instance = start.GetTarget(); var del = instance.GetMethodCallDelegate(start); var parameters = Import(method); var result = del.DynamicInvoke(parameters); Export(method, result, parameters); return result; } private void Export(MethodInfo method, object result, object parameters) { } private object Import(MethodInfo method) { throw new NotImplementedException(); } } public class RegisterPersistentTask { private void InvokeDelegate(Delegate del1) { } private Delegate GetStartMetod() { var @delegate = this.GetMethodCallDelegate(() => Start()); return @delegate; } public Delegate Start() { return this.InformUser("Please enter a username and a password!", () => OnUserNameAndPasswordEntered(null, null)); } public void Provide(string name, object value) { } public void Test() { } public Delegate OnUserNameAndPasswordEntered(string userName, string password) { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System.Linq.Expressions; using System; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Microsoft.Scripting.Utils; using System.Collections.Generic; namespace Microsoft.Scripting.Generation { // TODO: This should be a static class // TODO: simplify initialization logic & state public sealed class Snippets { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Snippets Shared = new Snippets(); private Snippets() { } #if FEATURE_LCG private int _methodNameIndex; #endif #if FEATURE_REFEMIT private AssemblyGen _assembly; private AssemblyGen _debugAssembly; // TODO: options should be internal private string _snippetsDirectory; private bool _saveSnippets; /// <summary> /// Directory where snippet assembly will be saved if SaveSnippets is set. /// </summary> public string SnippetsDirectory { get { return _snippetsDirectory; } } /// <summary> /// Save snippets to an assembly (see also SnippetsDirectory, SnippetsFileName). /// </summary> public bool SaveSnippets { get { return _saveSnippets; } } private AssemblyGen GetAssembly(bool emitSymbols) { return (emitSymbols) ? GetOrCreateAssembly(emitSymbols, ref _debugAssembly) : GetOrCreateAssembly(emitSymbols, ref _assembly); } private AssemblyGen GetOrCreateAssembly(bool emitSymbols, ref AssemblyGen assembly) { if (assembly == null) { string suffix = (emitSymbols) ? ".debug" : ""; suffix += ".scripting"; Interlocked.CompareExchange(ref assembly, CreateNewAssembly(suffix, emitSymbols), null); } return assembly; } private AssemblyGen CreateNewAssembly(string nameSuffix, bool emitSymbols) { string dir = null; #if FEATURE_ASSEMBLYBUILDER_SAVE if (_saveSnippets) { dir = _snippetsDirectory ?? Directory.GetCurrentDirectory(); } #endif string name = "Snippets" + nameSuffix; return new AssemblyGen(new AssemblyName(name), dir, ".dll", emitSymbols); } #if OBSOLETE internal string GetMethodILDumpFile(MethodBase method) { string fullName = ((method.DeclaringType != null) ? method.DeclaringType.Name + "." : "") + method.Name; if (fullName.Length > 100) { fullName = fullName.Substring(0, 100); } string filename = String.Format("{0}_{1}.il", IOUtils.ToValidFileName(fullName), Interlocked.Increment(ref _methodNameIndex)); string dir = _snippetsDirectory ?? Path.Combine(Path.GetTempPath(), "__DLRIL"); Directory.CreateDirectory(dir); return Path.Combine(dir, filename); } #endif public static void SetSaveAssemblies(bool enable, string directory) { Shared.ConfigureSaveAssemblies(enable, directory); } private void ConfigureSaveAssemblies(bool enable, string directory) { _saveSnippets = enable; _snippetsDirectory = directory; } public static void SaveAndVerifyAssemblies() { if (!Shared.SaveSnippets) { return; } // Invoke the core AssemblyGen.SaveAssembliesToDisk via reflection to get the locations of assemlies // to be verified. Verify them using PEVerify.exe. // Do this before verifying outer ring assemblies because they will depend on // the core ones. // The order needs to be // 1) Save inner ring assemblies. // 2) Save outer ring assemblies. This has to happen before verifying inner ring assemblies because // inner ring assemblies have dependency on outer ring assemlies via generated IL. // 3) Verify inner ring assemblies. // 4) Verify outer ring assemblies. Assembly core = typeof(Expression).Assembly; Type assemblyGen = core.GetType(typeof(Expression).Namespace + ".Compiler.AssemblyGen"); //The type may not exist. string[] coreAssemblyLocations = null; if (assemblyGen != null) { MethodInfo saveAssemblies = assemblyGen.GetMethod("SaveAssembliesToDisk", BindingFlags.NonPublic | BindingFlags.Static); //The method may not exist. if (saveAssemblies != null) { coreAssemblyLocations = (string[])saveAssemblies.Invoke(null, null); } } string[] outerAssemblyLocations = Shared.SaveAssemblies(); if (coreAssemblyLocations != null) { foreach (var file in coreAssemblyLocations) { AssemblyGen.PeVerifyAssemblyFile(file); } } //verify outer ring assemblies foreach (var file in outerAssemblyLocations) { AssemblyGen.PeVerifyAssemblyFile(file); } } // Return the assembly locations that need to be verified private string[] SaveAssemblies() { if (!SaveSnippets) { return EmptyArray<string>.Instance; } List<string> assemlyLocations = new List<string>(); // first save all assemblies to disk: if (_assembly != null) { string assemblyLocation = _assembly.SaveAssembly(); if (assemblyLocation != null) { assemlyLocations.Add(assemblyLocation); } _assembly = null; } if (_debugAssembly != null) { string debugAssemblyLocation = _debugAssembly.SaveAssembly(); if (debugAssemblyLocation != null) { assemlyLocations.Add(debugAssemblyLocation); } _debugAssembly = null; } return assemlyLocations.ToArray(); } public TypeBuilder DefinePublicType(string name, Type parent) { return GetAssembly(false).DefinePublicType(name, parent, false); } public TypeGen DefineType(string name, Type parent, bool preserveName, bool emitDebugSymbols) { AssemblyGen ag = GetAssembly(emitDebugSymbols); TypeBuilder tb = ag.DefinePublicType(name, parent, preserveName); return new TypeGen(ag, tb); } public TypeBuilder DefineDelegateType(string name) { AssemblyGen assembly = GetAssembly(false); return assembly.DefineType( name, typeof(MulticastDelegate), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, false ); } private static readonly Type[] _DelegateCtorSignature = new Type[] { typeof(object), typeof(IntPtr) }; public Type DefineDelegate(string name, Type returnType, params Type[] argTypes) { TypeBuilder tb = DefineDelegateType(name); tb.DefineConstructor( MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, _DelegateCtorSignature).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); tb.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, returnType, argTypes).SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed); return tb.CreateTypeInfo(); } public bool IsSnippetsAssembly(Assembly asm) { return (_assembly != null && asm == _assembly.AssemblyBuilder) || (_debugAssembly != null && asm == _debugAssembly.AssemblyBuilder); } #endif #if FEATURE_LCG public DynamicILGen CreateDynamicMethod(string methodName, Type returnType, Type[] parameterTypes, bool isDebuggable) { ContractUtils.RequiresNotEmpty(methodName, nameof(methodName)); ContractUtils.RequiresNotNull(returnType, nameof(returnType)); ContractUtils.RequiresNotNullItems(parameterTypes, nameof(parameterTypes)); #if FEATURE_REFEMIT if (Snippets.Shared.SaveSnippets) { AssemblyGen assembly = GetAssembly(isDebuggable); TypeBuilder tb = assembly.DefinePublicType(methodName, typeof(object), false); MethodBuilder mb = tb.DefineMethod(methodName, CompilerHelpers.PublicStatic, returnType, parameterTypes); return new DynamicILGenType(tb, mb, mb.GetILGenerator()); } #endif DynamicMethod dm = ReflectionUtils.RawCreateDynamicMethod(methodName, returnType, parameterTypes); return new DynamicILGenMethod(dm, dm.GetILGenerator()); } internal DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes) { string uniqueName = name + "##" + Interlocked.Increment(ref _methodNameIndex); return ReflectionUtils.RawCreateDynamicMethod(uniqueName, returnType, parameterTypes); } #endif } }
using System; using System.Collections.Generic; using System.IO; using MongoDB; namespace MongoDB.GridFS { /// <summary> /// Provides instance methods for the creation, copying, deletion, moving, and opening of files, /// and aids in the creation of GridFileStream objects. The api is very similar to the FileInfo class in /// System.IO. /// /// </summary> public class GridFileInfo { private const int DEFAULT_CHUNKSIZE = 256 * 1024; private const string DEFAULT_CONTENT_TYPE = "text/plain"; private GridFile gridFile; private IMongoDatabase db; private string bucket; #region "filedata properties" private Document filedata = new Document(); /// <summary> /// Gets or sets the id. /// </summary> /// <value>The id.</value> public Object Id{ get { return filedata["_id"]; } set { filedata["_id"] = value; } } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value>The name of the file.</value> public string FileName { get { return (String)filedata["filename"]; } set { filedata["filename"] = value; } } /// <summary> /// Gets or sets the type of the content. /// </summary> /// <value>The type of the content.</value> public string ContentType{ get { return (String)filedata["contentType"]; } set { filedata["contentType"] = value; } } /// <summary> /// Writing to the length property will not affect the actual data of the file. Open a GridFileStream /// and call SetLength instead. /// </summary> public long Length{ get { return Convert.ToInt32(filedata["length"]); } set { filedata["length"] = value; } } /// <summary> /// Gets or sets the aliases. /// </summary> /// <value>The aliases.</value> public IList<String> Aliases{ get { if(filedata.ContainsKey("aliases") == false || filedata["aliases"] == null){ return null; } if(filedata["aliases"] is IList<String>){ return (List<String>)filedata["aliases"]; } return new List<String>(); } set { filedata["aliases"] = value; } } /// <summary> /// Gets or sets the size of the chunk. /// </summary> /// <value>The size of the chunk.</value> public int ChunkSize{ get { return Convert.ToInt32(filedata["chunkSize"]); } set { filedata["chunkSize"] = value; } } /// <summary> /// Gets the metadata. /// </summary> /// <value>The metadata.</value> public Object Metadata{ get { return (Document)filedata["metadata"]; } } /// <summary> /// Gets or sets the upload date. /// </summary> /// <value>The upload date.</value> public DateTime? UploadDate{ get { return Convert.ToDateTime(filedata["uploadDate"]); } set { filedata["uploadDate"] = value; } } /// <summary> /// Gets or sets the MD5. /// </summary> /// <value>The MD5.</value> public string Md5{ get { return (String)filedata["md5"]; } set { filedata["md5"] = value; } } #endregion /// <summary> /// Initializes a new instance of the <see cref="GridFileInfo"/> class. /// </summary> /// <param name="db">The db.</param> /// <param name="bucket">The bucket.</param> /// <param name="filename">The filename.</param> public GridFileInfo(IMongoDatabase db, string bucket, string filename){ this.db = db; this.bucket = bucket; this.gridFile = new GridFile(db,bucket); SetFileDataDefaults(filename); if(gridFile.Exists(filename)) this.LoadFileData(); } /// <summary> /// Initializes a new instance of the <see cref="GridFileInfo"/> class. /// </summary> /// <param name="db">The db.</param> /// <param name="filename">The filename.</param> public GridFileInfo(MongoDatabase db, string filename){ this.db = db; this.bucket = "fs"; this.gridFile = new GridFile(db); SetFileDataDefaults(filename); if(gridFile.Exists(filename)) this.LoadFileData(); } private void SetFileDataDefaults(string filename){ this.FileName = filename; this.ChunkSize = DEFAULT_CHUNKSIZE; this.ContentType = DEFAULT_CONTENT_TYPE; this.UploadDate = DateTime.UtcNow; this.Length = 0; } #region Create /// <summary> /// Creates the file named FileName and returns the GridFileStream /// </summary> /// <returns></returns> /// <exception cref="IOException">If the file already exists</exception> public GridFileStream Create(){ return Create(FileMode.CreateNew); } /// <summary> /// Creates the specified mode. /// </summary> /// <param name="mode">The mode.</param> /// <returns></returns> public GridFileStream Create(FileMode mode){ return Create(mode,FileAccess.ReadWrite); } /// <summary> /// Creates the specified mode. /// </summary> /// <param name="mode">The mode.</param> /// <param name="access">The access.</param> /// <returns></returns> public GridFileStream Create(FileMode mode, FileAccess access){ switch (mode) { case FileMode.CreateNew: if(gridFile.Exists(this.FileName)){ throw new IOException("File already exists"); } this.gridFile.Files.Insert(filedata); return new GridFileStream(this, this.gridFile.Files, this.gridFile.Chunks, access); case FileMode.Create: if(gridFile.Exists(this.FileName)){ return this.Open(FileMode.Truncate,access); }else{ return this.Create(FileMode.CreateNew,access); } default: throw new ArgumentException("Invalid FileMode", "mode"); } } #endregion #region Open /// <summary> /// Creates a read-only GridFileStream to an existing file. /// </summary> /// <returns></returns> public GridFileStream OpenRead(){ return this.Open(FileMode.Open, FileAccess.Read); } /// <summary> /// Creates a write-only GridFileStream to an existing file. /// </summary> /// <returns></returns> public GridFileStream OpenWrite(){ return this.Open(FileMode.Open, FileAccess.Write); } /// <summary> /// Opens the specified mode. /// </summary> /// <param name="mode">The mode.</param> /// <param name="access">The access.</param> /// <returns></returns> public GridFileStream Open(FileMode mode, FileAccess access){ switch (mode) { case FileMode.Create: if(gridFile.Exists(this.FileName) == true){ return this.Open(FileMode.Truncate, access); } return this.Create(FileMode.CreateNew, access); case FileMode.CreateNew: return this.Create(mode, access); case FileMode.Open: LoadFileData(); return new GridFileStream(this,this.gridFile.Files, this.gridFile.Chunks, access); case FileMode.OpenOrCreate: if(gridFile.Exists(this.FileName) == false) return this.Create(mode, access); LoadFileData(); return new GridFileStream(this, this.gridFile.Files, this.gridFile.Chunks, access); case FileMode.Truncate: this.Truncate(); return new GridFileStream(this,this.gridFile.Files, this.gridFile.Chunks, access); case FileMode.Append: LoadFileData(); GridFileStream gfs = new GridFileStream(this,this.gridFile.Files, this.gridFile.Chunks, access); gfs.Seek(0,SeekOrigin.End); return gfs; } throw new NotImplementedException("Mode not implemented."); } #endregion /// <summary> /// Permanently removes a file from the database. /// </summary> public void Delete(){ if(this.Id != null){ this.gridFile.Delete(this.Id); }else{ this.gridFile.Delete(this.FileName); } } /// <summary> /// Renames a file. /// </summary> public void MoveTo(String newFileName){ this.gridFile.Move(this.FileName, newFileName); this.FileName = newFileName; } /// <summary> /// Gets a value indicating whether the file exists. /// </summary> public Boolean Exists{ get{ return this.gridFile.Exists(this.FileName); } } /// <summary> /// Deletes all data in a file and sets the length to 0. /// </summary> public void Truncate(){ if(filedata.ContainsKey("_id") == false) return; this.gridFile.Chunks.Remove(new Document().Add("files_id", filedata["_id"])); this.Length = 0; this.gridFile.Files.Save(filedata); } /// <summary> /// Calcs the M d5. /// </summary> /// <returns></returns> public string CalcMD5(){ Document doc = this.db.SendCommand(new Document().Add("filemd5", this.Id).Add("root", this.bucket)); return (String)doc["md5"]; } /// <summary> /// Updates the aliases, contentType, metadata and uploadDate in the database. /// </summary> /// <remarks> To rename a file use the MoveTo method. /// </remarks> public void UpdateInfo(){ Document info = new Document(){{"uploadDate", this.UploadDate}, {"aliases", this.Aliases}, {"metadata", this.Metadata}, {"contentType", this.ContentType}}; this.gridFile.Files.Update(new Document(){{"$set",info}}, new Document(){{"_id", this.Id}}); } /// <summary> /// Reloads the file information from the database. /// </summary> /// <remarks>The data in the database will not reflect any changes done through an open stream until it is closed. /// </remarks> public void Refresh(){ LoadFileData(); } private void LoadFileData(){ Document doc = this.gridFile.Files.FindOne(new Document().Add("filename", this.FileName)); if(doc != null){ filedata = doc; }else{ throw new DirectoryNotFoundException(this.gridFile.Name + Path.VolumeSeparatorChar + this.FileName); } } /// <summary> /// Toes the document. /// </summary> /// <returns></returns> public Document ToDocument(){ return this.filedata; } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString(){ return filedata.ToString(); } } }
// // Ciff.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Larry Ewing <lewing@src.gnome.org> // // Copyright (C) 2005-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2005-2007 Larry Ewing // // 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 FSpot.Utils; using Hyena; using TagLib.Image; namespace FSpot.Imaging.Ciff { internal enum Tag { JpgFromRaw = 0x2007, } public enum EntryType : ushort { Byte = 0x0000, Ascii = 0x0800, Short = 0x1000, Int = 0x1800, Struct = 0x2000, Directory1 = 0x2800, Directory2 = 0x2800, } public enum Mask { Type = 0x3800, } /* See http://www.sno.phy.queensu.ca/~phil/exiftool/canon_raw.html */ internal struct Entry { internal Tag Tag; internal uint Size; internal uint Offset; public Entry (byte [] data, int pos, bool little) { Tag = (Tag) BitConverter.ToUInt16 (data, pos, little); Size = BitConverter.ToUInt32 (data, pos + 2, little); Offset = BitConverter.ToUInt32 (data, pos + 6, little); } } class ImageDirectory { System.Collections.ArrayList entry_list; uint Count; bool little; uint start; long DirPosition; System.IO.Stream stream; public ImageDirectory (System.IO.Stream stream, uint start, long end, bool little) { this.start = start; this.little = little; this.stream = stream; entry_list = new System.Collections.ArrayList (); stream.Position = end - 4; byte [] buf = new byte [10]; stream.Read (buf, 0, 4); uint directory_pos = BitConverter.ToUInt32 (buf, 0, little); DirPosition = start + directory_pos; stream.Position = DirPosition; stream.Read (buf, 0, 2); Count = BitConverter.ToUInt16 (buf, 0, little); for (int i = 0; i < Count; i++) { stream.Read (buf, 0, 10); Log.DebugFormat ("reading {0} {1}", i, stream.Position); Entry entry = new Entry (buf, 0, little); entry_list.Add (entry); } } public ImageDirectory ReadDirectory (Tag tag) { foreach (Entry e in entry_list) { if (e.Tag == tag) { uint subdir_start = this.start + e.Offset; ImageDirectory subdir = new ImageDirectory (stream, subdir_start, subdir_start + e.Size, little); return subdir; } } return null; } public byte [] ReadEntry (int pos) { Entry e = (Entry) entry_list [pos]; stream.Position = this.start + e.Offset; byte [] data = new byte [e.Size]; stream.Read (data, 0, data.Length); return data; } public byte [] ReadEntry (Tag tag) { int pos = 0; foreach (Entry e in entry_list) { if (e.Tag == tag) return ReadEntry (pos); pos++; } return null; } } public class CiffFile : BaseImageFile { ImageDirectory root; bool little; System.IO.Stream stream; ImageDirectory Root { get { if (root == null) { stream = base.PixbufStream (); root = Load (stream); } return root; } } public CiffFile (SafeUri uri) : base (uri) { } private ImageDirectory Load (System.IO.Stream stream) { byte [] header = new byte [26]; // the spec reserves the first 26 bytes as the header block stream.Read (header, 0, header.Length); uint start; little = (header [0] == 'I' && header [1] == 'I'); start = BitConverter.ToUInt32 (header, 2, little); // HEAP is the type CCDR is the subtype if (System.Text.Encoding.ASCII.GetString (header, 6, 8) != "HEAPCCDR") throw new ImageFormatException ("Invalid Ciff Header Block"); long end = stream.Length; return new ImageDirectory (stream, start, end, little); } public override System.IO.Stream PixbufStream () { byte [] data = GetEmbeddedJpeg (); if (data != null) return new System.IO.MemoryStream (data); else return DCRawFile.RawPixbufStream (Uri); } private byte [] GetEmbeddedJpeg () { return Root.ReadEntry (Tag.JpgFromRaw); } protected override void Close () { if (stream != null) { stream.Close (); stream = null; } } } }
/* * [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 NonSerialized = System.NonSerializedAttribute; using Regex = System.Text.RegularExpressions.Regex; using Serializable = System.SerializableAttribute; [Serializable] public class CommonToken : IToken { int type; int line; int charPositionInLine = -1; // set to invalid position int channel = TokenChannels.Default; [NonSerialized] ICharStream input; /** <summary> * We need to be able to change the text once in a while. If * this is non-null, then getText should return this. Note that * start/stop are not affected by changing this. * </summary> */ string text; /** <summary>What token number is this from 0..n-1 tokens; &lt; 0 implies invalid index</summary> */ int index = -1; /** <summary>The char position into the input buffer where this token starts</summary> */ int start; /** <summary>The char position into the input buffer where this token stops</summary> */ int stop; public CommonToken() { } public CommonToken(int type) { this.type = type; } public CommonToken(ICharStream input, int type, int channel, int start, int stop) { this.input = input; this.type = type; this.channel = channel; this.start = start; this.stop = stop; } public CommonToken(int type, string text) { this.type = type; this.channel = TokenChannels.Default; this.text = text; } public CommonToken(IToken oldToken) { text = oldToken.Text; type = oldToken.Type; line = oldToken.Line; index = oldToken.TokenIndex; charPositionInLine = oldToken.CharPositionInLine; channel = oldToken.Channel; input = oldToken.InputStream; if (oldToken is CommonToken) { start = ((CommonToken)oldToken).start; stop = ((CommonToken)oldToken).stop; } } #region IToken Members public string Text { get { if (text != null) return text; if (input == null) return null; if (start < input.Count && stop < input.Count) text = input.Substring(start, stop - start + 1); else text = "<EOF>"; return text; } set { /** Override the text for this token. getText() will return this text * rather than pulling from the buffer. Note that this does not mean * that start/stop indexes are not valid. It means that that input * was converted to a new string in the token object. */ text = value; } } public int Type { get { return type; } set { type = value; } } public int Line { get { return line; } set { line = value; } } public int CharPositionInLine { get { return charPositionInLine; } set { charPositionInLine = value; } } public int Channel { get { return channel; } set { channel = value; } } public int StartIndex { get { return start; } set { start = value; } } public int StopIndex { get { return stop; } set { stop = value; } } public int TokenIndex { get { return index; } set { index = value; } } public ICharStream InputStream { get { return input; } set { input = value; } } #endregion public override string ToString() { string channelStr = ""; if (channel > 0) { channelStr = ",channel=" + channel; } string txt = Text; if (txt != null) { txt = Regex.Replace(txt, "\n", "\\\\n"); txt = Regex.Replace(txt, "\r", "\\\\r"); txt = Regex.Replace(txt, "\t", "\\\\t"); } else { txt = "<no text>"; } return "[@" + TokenIndex + "," + start + ":" + stop + "='" + txt + "',<" + type + ">" + channelStr + "," + line + ":" + CharPositionInLine + "]"; } [System.Runtime.Serialization.OnSerializing] internal void OnSerializing(System.Runtime.Serialization.StreamingContext context) { if (text == null) text = Text; } } }
namespace InControl.NativeProfile { // @cond nodoc [AutoDiscover] public class XboxOneWindows10AENativeProfile : NativeInputDeviceProfile { public XboxOneWindows10AENativeProfile() { Name = "Xbox One Controller"; Meta = "Xbox One Controller on Windows"; // Link = "http://www.amazon.com/Microsoft-Xbox-Controller-Cable-Windows/dp/B00O65I2VY"; IncludePlatforms = new[] { "Windows" }; ExcludePlatforms = new[] { "Windows 7", "Windows 8" }; MinSystemBuildNumber = 14393; Matchers = new[] { new NativeInputDeviceMatcher { VendorID = 0x45e, ProductID = 0x2ff, }, new NativeInputDeviceMatcher { VendorID = 0x45e, ProductID = 0x2d1, }, new NativeInputDeviceMatcher { VendorID = 0x45e, ProductID = 0x2e0, }, }; ButtonMappings = new[] { new InputControlMapping { Handle = "A", Target = InputControlType.Action1, Source = Button( 0 ), }, new InputControlMapping { Handle = "B", Target = InputControlType.Action2, Source = Button( 1 ), }, new InputControlMapping { Handle = "X", Target = InputControlType.Action3, Source = Button( 2 ), }, new InputControlMapping { Handle = "Y", Target = InputControlType.Action4, Source = Button( 3 ), }, new InputControlMapping { Handle = "Left Bumper", Target = InputControlType.LeftBumper, Source = Button( 4 ), }, new InputControlMapping { Handle = "Right Bumper", Target = InputControlType.RightBumper, Source = Button( 5 ), }, new InputControlMapping { Handle = "View", Target = InputControlType.View, Source = Button( 6 ), }, new InputControlMapping { Handle = "Menu", Target = InputControlType.Menu, Source = Button( 7 ), }, new InputControlMapping { Handle = "Left Stick Button", Target = InputControlType.LeftStickButton, Source = Button( 8 ), }, new InputControlMapping { Handle = "Right Stick Button", Target = InputControlType.RightStickButton, Source = Button( 9 ), }, new InputControlMapping { Handle = "Guide", Target = InputControlType.System, Source = Button( 10 ), }, }; AnalogMappings = new[] { new InputControlMapping { Handle = "Left Stick Up", Target = InputControlType.LeftStickUp, Source = Analog( 0 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Left Stick Down", Target = InputControlType.LeftStickDown, Source = Analog( 0 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Left Stick Left", Target = InputControlType.LeftStickLeft, Source = Analog( 1 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Left Stick Right", Target = InputControlType.LeftStickRight, Source = Analog( 1 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Right Stick Up", Target = InputControlType.RightStickUp, Source = Analog( 2 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Right Stick Down", Target = InputControlType.RightStickDown, Source = Analog( 2 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Right Stick Left", Target = InputControlType.RightStickLeft, Source = Analog( 3 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Right Stick Right", Target = InputControlType.RightStickRight, Source = Analog( 3 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Left Trigger", Target = InputControlType.LeftTrigger, Source = Analog( 4 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "Right Trigger", Target = InputControlType.RightTrigger, Source = Analog( 4 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = Analog( 5 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = Analog( 5 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = Analog( 6 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = Analog( 6 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, }; } } // @endcond }
// // Copyright (c) 2010-2014 Frank A. Krueger // // 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.Drawing; // TODO do we need this? using System.Collections.Generic; #if MONOMAC using MonoMac.CoreGraphics; using MonoMac.AppKit; #else using MonoTouch.CoreGraphics; using MonoTouch.UIKit; #endif using MonoTouch.CoreText; using MonoTouch.Foundation; namespace CrossGraphics.CoreGraphics { public class CoreGraphicsGraphics : IGraphics { CGContext _c; //bool _highQuality = false; static CoreGraphicsGraphics () { //foreach (var f in UIFont.FamilyNames) { // Console.WriteLine (f); // var fs = UIFont.FontNamesForFamilyName (f); // foreach (var ff in fs) { // Console.WriteLine (" " + ff); // } //} _textMatrix = CGAffineTransform.MakeScale (1, -1); // TODO what is this for? } private float _overall_height; private Stack<float> _prev_overall_height; public CoreGraphicsGraphics (CGContext c, bool highQuality, float overall_height) { if (c == null) throw new ArgumentNullException ("c"); _overall_height = (float) overall_height; _c = c; //_highQuality = highQuality; if (highQuality) { c.SetLineCap (CGLineCap.Round); } else { c.SetLineCap (CGLineCap.Butt); } SetColor (Colors.Black); } public void SetColor (Color c) { var cgcol = c.GetCGColor (); #if MONOMAC _c.SetFillColorWithColor (cgcol); _c.SetStrokeColorWithColor (cgcol); #else _c.SetFillColor (cgcol); _c.SetStrokeColor (cgcol); #endif } public void FillRoundedRect (float x, float y, float width, float height, float radius) { _c.AddRoundedRect (new RectangleF (x, y, width, height), radius); _c.FillPath (); } public void DrawRoundedRect (float x, float y, float width, float height, float radius, float w) { _c.SetLineWidth (w); _c.AddRoundedRect (new RectangleF (x, y, width, height), radius); _c.StrokePath (); } public void FillRect (float x, float y, float width, float height) { _c.FillRect (new RectangleF (x, y, width, height)); } public void FillOval (float x, float y, float width, float height) { _c.FillEllipseInRect (new RectangleF (x, y, width, height)); } public void DrawOval (float x, float y, float width, float height, float w) { _c.SetLineWidth (w); _c.StrokeEllipseInRect (new RectangleF (x, y, width, height)); } public void DrawRect (float x, float y, float width, float height, float w) { _c.SetLineWidth (w); _c.StrokeRect (new RectangleF (x, y, width, height)); } public void DrawArc (float cx, float cy, float radius, float startAngle, float endAngle, float w) { _c.SetLineWidth (w); _c.AddArc (cx, cy, radius, -startAngle, -endAngle, true); _c.StrokePath (); } public void FillArc (float cx, float cy, float radius, float startAngle, float endAngle) { _c.AddArc (cx, cy, radius, -startAngle, -endAngle, true); _c.FillPath (); } const int _linePointsCount = 1024; PointF[] _linePoints = new PointF[_linePointsCount]; bool _linesBegun = false; int _numLinePoints = 0; float _lineWidth = 1; bool _lineRounded = false; public void BeginLines (bool rounded) { _linesBegun = true; _lineRounded = rounded; _numLinePoints = 0; } public void DrawLine (float sx, float sy, float ex, float ey, float w) { #if not #if DEBUG if (float.IsNaN (sx) || float.IsNaN (sy) || float.IsNaN (ex) || float.IsNaN (ey) || float.IsNaN (w)) { System.Diagnostics.Debug.WriteLine ("NaN in CoreGraphicsGraphics.DrawLine"); } #endif #endif if (_linesBegun) { _lineWidth = w; if (_numLinePoints < _linePointsCount) { if (_numLinePoints == 0) { _linePoints[_numLinePoints].X = sx; _linePoints[_numLinePoints].Y = sy; _numLinePoints++; } _linePoints[_numLinePoints].X = ex; _linePoints[_numLinePoints].Y = ey; _numLinePoints++; } } else { _c.MoveTo (sx, sy); _c.AddLineToPoint (ex, ey); _c.SetLineWidth (w); _c.StrokePath (); } } public void EndLines () { if (!_linesBegun) return; _c.SaveState (); _c.SetLineJoin (_lineRounded ? CGLineJoin.Round : CGLineJoin.Miter); _c.SetLineWidth (_lineWidth); for (var i = 0; i < _numLinePoints; i++) { var p = _linePoints[i]; if (i == 0) { _c.MoveTo (p.X, p.Y); } else { _c.AddLineToPoint (p.X, p.Y); } } _c.StrokePath (); _c.RestoreState (); _linesBegun = false; } static CGAffineTransform _textMatrix; Font _lastFont = null; UIFont _font_ui = null; CTFont _font_ct = null; CTStringAttributes _ct_attr = null; public void SetFont (Font f) { if (f != _lastFont) { _lastFont = f; // We have a Xamarin.Forms.Font object. We need a CTFont. X.F.Font has // ToUIFont() but not a Core Text version of same. So we make a UIFont first. //_font_ui = _lastFont.ToUIFont (); // TODO temporary hack _font_ui = UIFont.SystemFontOfSize (_lastFont.Size); _font_ct = new CTFont (_font_ui.Name, _font_ui.PointSize); // With Core Text, it is important that we use a CTStringAttributes() with the // NSAttributedString constructor. // TODO maybe we should have the text color be separate, have it be an arg on SetFont? _ct_attr = new CTStringAttributes { Font = _font_ct, ForegroundColorFromContext = true, //ForegroundColor = _clr_cg, // ParagraphStyle = new CTParagraphStyle(new CTParagraphStyleSettings() { Alignment = CTTextAlignment.Center }) }; } } public void SetClippingRect (float x, float y, float width, float height) { _c.ClipToRect (new RectangleF (x, y, width, height)); } // TODO using Core Text here is going to be a huge problem because we have to // change the coordinate system for every call to DrawString rather than changing // it once for all the calls. Not even sure we have enough info (the height of // the coord system or UIView) to do the transform? // TODO if we know the text is one-line, we can skip the big transform and just use // the textmatrix thing. public void DrawString(string s, float box_x, float box_y, float box_width, float box_height, LineBreakMode lineBreak, TextAlignment horizontal_align, TextAlignment vertical_align ) { _c.SaveState(); // TODO _c.SetTextDrawingMode (CGTextDrawingMode.Fill); // Core Text uses a different coordinate system. _c.TranslateCTM (0, _overall_height); _c.ScaleCTM (1, -1); var attributedString = new NSAttributedString (s, _ct_attr); float text_width; float text_height; if ( (horizontal_align != TextAlignment.Start) || (vertical_align != TextAlignment.Start)) { // not all of the alignments need the bounding rect. don't // calculate it if not needed. var sizeAttr = attributedString.GetBoundingRect ( new SizeF ( (float)box_width, int.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null ); text_width = sizeAttr.Width; //text_height = sizeAttr.Height; //text_height = sizeAttr.Height + uif.Descender; // descender is negative text_height = _font_ui.CapHeight; } else { text_width = 0; text_height = 0; } //Console.WriteLine ("width: {0} height: {1}", text_width, text_height); float x; switch (horizontal_align) { case TextAlignment.End: x = (box_x + box_width) - text_width; break; case TextAlignment.Center: x = box_x + (box_width - text_width) / 2; break; case TextAlignment.Start: default: x = box_x; break; } float y; switch (vertical_align) { case TextAlignment.End: y = box_y + text_height; break; case TextAlignment.Center: y = (box_y + box_height) - (box_height - text_height) / 2; break; case TextAlignment.Start: default: y = (box_y + box_height); break; } _c.TextPosition = new PointF ((float) x, (float) (_overall_height - y)); // I think that by using CTLine() below, we are preventing multi-line text. :-( using (var textLine = new CTLine (attributedString)) { textLine.Draw (_c); } //gctx.StrokeRect (new RectangleF(x, height - y, text_width, text_height)); _c.RestoreState (); } public void DrawImage (IImage img, float x, float y) { if (img is UIKitImage) { var uiImg = ((UIKitImage)img).Image; uiImg.Draw (new PointF ((float) x, (float) y)); } } public void DrawImage (IImage img, float x, float y, float width, float height) { if (img is UIKitImage) { var uiImg = ((UIKitImage)img).Image; uiImg.Draw (new RectangleF ((float)x, (float)y, (float)width, (float)height)); } } public void SaveState () { _c.SaveState (); } public void Translate (float dx, float dy) { _c.TranslateCTM (dx, dy); } public void Scale (float sx, float sy) { _c.ScaleCTM (sx, sy); } public void RestoreState () { _c.RestoreState (); // TODO do anything to the font? } public void BeginOffscreen(float width, float height, IImage img) { // iOS apparently cannot re-use an image for offscreen draws if (img != null) { img.Destroy (); } UIGraphics.BeginImageContextWithOptions (new SizeF ((float)width, (float)height), false, 0); if (_prev_overall_height == null) { _prev_overall_height = new Stack<float> (); } _prev_overall_height.Push (_overall_height); _overall_height = (float)height; _c = UIGraphics.GetCurrentContext (); } public IImage EndOffscreen() { UIImage img = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); _overall_height = _prev_overall_height.Pop (); _c = UIGraphics.GetCurrentContext(); return new UIKitImage(img); } public void BeginEntity (object entity) { } } public static class ColorEx { class ColorTag { #if MONOMAC public NSColor NSColor; #else public UIColor UIColor; #endif public CGColor CGColor; } #if MONOMAC public static NSColor GetNSColor (this Color c) { var t = c.Tag as ColorTag; if (t == null) { t = new ColorTag (); c.Tag = t; } if (t.NSColor == null) { t.NSColor = NSColor.FromDeviceRgba (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f); } return t.NSColor; } #else public static UIColor GetUIColor (this Color c) { var t = c.Tag as ColorTag; if (t == null) { t = new ColorTag (); c.Tag = t; } if (t.UIColor == null) { t.UIColor = UIColor.FromRGBA (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f); } return t.UIColor; } #endif public static CGColor GetCGColor (this Color c) { var t = c.Tag as ColorTag; if (t == null) { t = new ColorTag (); c.Tag = t; } if (t.CGColor == null) { t.CGColor = new CGColor (c.Red / 255.0f, c.Green / 255.0f, c.Blue / 255.0f, c.Alpha / 255.0f); } return t.CGColor; } } public class UIKitImage : IImage { #if not public CGImage Image { get; private set; } public UIKitImage (CGImage image) { Image = image; } #endif public UIImage Image { get; private set; } public UIKitImage(UIImage img) { Image = img; } public void Destroy() { Image.Dispose (); Image = null; } } public static class CGContextEx { public static void AddRoundedRect (this CGContext c, RectangleF b, float r) { c.MoveTo (b.Left, b.Top + r); c.AddLineToPoint (b.Left, b.Bottom - r); c.AddArc (b.Left + r, b.Bottom - r, r, (float)(Math.PI), (float)(Math.PI / 2), true); c.AddLineToPoint (b.Right - r, b.Bottom); c.AddArc (b.Right - r, b.Bottom - r, r, (float)(-3 * Math.PI / 2), (float)(0), true); c.AddLineToPoint (b.Right, b.Top + r); c.AddArc (b.Right - r, b.Top + r, r, (float)(0), (float)(-Math.PI / 2), true); c.AddLineToPoint (b.Left + r, b.Top); c.AddArc (b.Left + r, b.Top + r, r, (float)(-Math.PI / 2), (float)(Math.PI), true); } public static void AddBottomRoundedRect (this CGContext c, RectangleF b, float r) { c.MoveTo (b.Left, b.Top + r); c.AddLineToPoint (b.Left, b.Bottom - r); c.AddArc (b.Left + r, b.Bottom - r, r, (float)(Math.PI), (float)(Math.PI / 2), true); c.AddLineToPoint (b.Right - r, b.Bottom); c.AddArc (b.Right - r, b.Bottom - r, r, (float)(-3 * Math.PI / 2), (float)(0), true); c.AddLineToPoint (b.Right, b.Top); c.AddLineToPoint (b.Left, b.Top); } } }
// 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.Globalization; /// <summary> /// GetMonthName(System.Int32) /// </summary> public class DateTimeFormatInfoGetMonthName { #region Private Fields private const int c_MIN_MONTH_VALUE = 1; private const int c_MAX_MONTH_VALUE = 13; #endregion #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; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call GetAbbreviatedDayName on default invariant DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = CultureInfo.InvariantCulture.DateTimeFormat; string[] expected = new string[] { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "", }; retVal = VerificationHelper(info, expected, "001.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call GetAbbreviatedDayName on en-us culture DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = new CultureInfo("en-us").DateTimeFormat; string[] expected = new string[] { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "", }; retVal = VerificationHelper(info, expected, "002.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call GetAbbreviatedDayName on fr-FR culture DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = new CultureInfo("fr-FR").DateTimeFormat; string[] expected = new string[] { "", "janvier", "f\u00e9vrier", "mars", "avril", "mai", "juin", "juillet", "ao\u00fbt", "septembre", "octobre", "novembre", "d\u00e9cembre", "", }; retVal = VerificationHelper(info, expected, "003.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call GetAbbreviatedDayName on DateTimeFormatInfo instance created from ctor"); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); string[] expected = new string[] { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "", }; retVal = VerificationHelper(info, expected, "004.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. "); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetMonthName(c_MIN_MONTH_VALUE - 1); TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetMonthName(c_MAX_MONTH_VALUE + 1); TestLibrary.TestFramework.LogError("101.3", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.4", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeFormatInfoGetMonthName test = new DateTimeFormatInfoGetMonthName(); TestLibrary.TestFramework.BeginTestCase("DateTimeFormatInfoGetMonthName"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerificationHelper(DateTimeFormatInfo info, string[] expected, string errorno) { bool retval = true; for (int i = c_MIN_MONTH_VALUE; i <= c_MAX_MONTH_VALUE; ++i) { string actual = info.GetMonthName(i); if (actual != expected[i]) { TestLibrary.TestFramework.LogError(errorno + "." + i, "GetAbbreviatedDayName returns wrong value"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] i = " + i + ", expected[i] = " + expected[i] + ", actual = " + actual); retval = false; } } return retval; } #endregion }