context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System.Collections.Generic; /// <summary> /// Revision Manifest data element /// </summary> public class RevisionManifestDataElementData : DataElementData { /// <summary> /// Initializes a new instance of the RevisionManifestDataElementData class. /// </summary> public RevisionManifestDataElementData() { this.RevisionManifest = new RevisionManifest(); this.RevisionManifestRootDeclareList = new List<RevisionManifestRootDeclare>(); this.RevisionManifestObjectGroupReferencesList = new List<RevisionManifestObjectGroupReferences>(); } /// <summary> /// Gets or sets a 16-bit stream object header that specifies a revision manifest. /// </summary> public RevisionManifest RevisionManifest { get; set; } /// <summary> /// Gets or sets a revision manifest root declare, each followed by root and object extended GUIDs. /// </summary> public List<RevisionManifestRootDeclare> RevisionManifestRootDeclareList { get; set; } /// <summary> /// Gets or sets a list of revision manifest object group references, each followed by object group extended GUIDs. /// </summary> public List<RevisionManifestObjectGroupReferences> RevisionManifestObjectGroupReferencesList { get; set; } /// <summary> /// Used to return the length of this element. /// </summary> /// <param name="byteArray">A Byte list</param> /// <param name="startIndex">Start position</param> /// <returns>The length of the element</returns> public override int DeserializeDataElementDataFromByteArray(byte[] byteArray, int startIndex) { int index = startIndex; this.RevisionManifest = StreamObject.GetCurrent<RevisionManifest>(byteArray, ref index); this.RevisionManifestRootDeclareList = new List<RevisionManifestRootDeclare>(); this.RevisionManifestObjectGroupReferencesList = new List<RevisionManifestObjectGroupReferences>(); StreamObjectHeaderStart header; int headerLength = 0; while ((headerLength = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0) { if (header.Type == StreamObjectTypeHeaderStart.RevisionManifestRootDeclare) { index += headerLength; this.RevisionManifestRootDeclareList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as RevisionManifestRootDeclare); } else if (header.Type == StreamObjectTypeHeaderStart.RevisionManifestObjectGroupReferences) { index += headerLength; this.RevisionManifestObjectGroupReferencesList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as RevisionManifestObjectGroupReferences); } else { throw new DataElementParseErrorException(index, "Failed to parse RevisionManifestDataElement, expect the inner object type RevisionManifestRootDeclare or RevisionManifestObjectGroupReferences, but actual type value is " + header.Type, null); } } return index - startIndex; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <returns>A Byte list</returns> public override List<byte> SerializeToByteList() { List<byte> byteList = new List<byte>(); byteList.AddRange(this.RevisionManifest.SerializeToByteList()); if (this.RevisionManifestRootDeclareList != null) { foreach (RevisionManifestRootDeclare revisionManifestRootDeclare in this.RevisionManifestRootDeclareList) { byteList.AddRange(revisionManifestRootDeclare.SerializeToByteList()); } } if (this.RevisionManifestObjectGroupReferencesList != null) { foreach (RevisionManifestObjectGroupReferences revisionManifestObjectGroupReferences in this.RevisionManifestObjectGroupReferencesList) { byteList.AddRange(revisionManifestObjectGroupReferences.SerializeToByteList()); } } return byteList; } } /// <summary> /// Specifies a revision manifest. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")] public class RevisionManifest : StreamObject { /// <summary> /// Initializes a new instance of the RevisionManifest class. /// </summary> public RevisionManifest() : base(StreamObjectTypeHeaderStart.RevisionManifest) { } /// <summary> /// Gets or sets an extended GUID that specifies the revision identifier represented by this data element. /// </summary> public ExGuid RevisionID { get; set; } /// <summary> /// Gets or sets an extended GUID that specifies the revision identifier of a base revision that could contain additional information for this revision. /// </summary> public ExGuid BaseRevisionID { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.RevisionID = BasicObject.Parse<ExGuid>(byteArray, ref index); this.BaseRevisionID = BasicObject.Parse<ExGuid>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "RevisionManifest", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The length of list</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.RevisionID.SerializeToByteList()); byteList.AddRange(this.BaseRevisionID.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// Specifies a revision manifest root declare, each followed by root and object extended GUIDs. /// </summary> public class RevisionManifestRootDeclare : StreamObject { /// <summary> /// Initializes a new instance of the RevisionManifestRootDeclare class. /// </summary> public RevisionManifestRootDeclare() : base(StreamObjectTypeHeaderStart.RevisionManifestRootDeclare) { } /// <summary> /// Gets or sets an extended GUID that specifies the root revision for each revision manifest root declare. /// </summary> public ExGuid RootExtendedGUID { get; set; } /// <summary> /// Gets or sets an extended GUID that specifies the object for each revision manifest root declare. /// </summary> public ExGuid ObjectExtendedGUID { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte list</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.RootExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); this.ObjectExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "RevisionManifestRootDeclare", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The length of list</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.RootExtendedGUID.SerializeToByteList()); byteList.AddRange(this.ObjectExtendedGUID.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// Specifies a revision manifest object group references, each followed by object group extended GUIDs. /// </summary> public class RevisionManifestObjectGroupReferences : StreamObject { /// <summary> /// Initializes a new instance of the RevisionManifestObjectGroupReferences class. /// </summary> public RevisionManifestObjectGroupReferences() : base(StreamObjectTypeHeaderStart.RevisionManifestObjectGroupReferences) { } /// <summary> /// Initializes a new instance of the RevisionManifestObjectGroupReferences class. /// </summary> /// <param name="objectGroupExtendedGUID">Extended GUID</param> public RevisionManifestObjectGroupReferences(ExGuid objectGroupExtendedGUID) : this() { this.ObjectGroupExtendedGUID = objectGroupExtendedGUID; } /// <summary> /// Gets or sets an extended GUID that specifies the object group for each Revision Manifest Object Group References. /// </summary> public ExGuid ObjectGroupExtendedGUID { get; set; } /// <summary> /// Used to de-serialize the element. /// </summary> /// <param name="byteArray">A Byte array</param> /// <param name="currentIndex">Start position</param> /// <param name="lengthOfItems">The length of the items</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.ObjectGroupExtendedGUID = BasicObject.Parse<ExGuid>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "RevisionManifestObjectGroupReferences", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// Used to convert the element into a byte List. /// </summary> /// <param name="byteList">A Byte list</param> /// <returns>The number of elements actually contained in the list.</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { List<byte> tmpList = this.ObjectGroupExtendedGUID.SerializeToByteList(); byteList.AddRange(tmpList); return tmpList.Count; } } }
using System; using System.Collections.Generic; using System.Linq; using ModestTree; using ModestTree.Util; #if !NOT_UNITY3D using UnityEngine.SceneManagement; using UnityEngine; #endif namespace Zenject.Internal { public static class ZenUtilInternal { #if UNITY_EDITOR static GameObject _disabledIndestructibleGameObject; #endif // Due to the way that Unity overrides the Equals operator, // normal null checks such as (x == null) do not always work as // expected // In those cases you can use this function which will also // work with non-unity objects public static bool IsNull(System.Object obj) { return obj == null || obj.Equals(null); } #if UNITY_EDITOR // This can be useful if you are running code outside unity // since in that case you have to make sure to avoid calling anything // inside Unity DLLs public static bool IsOutsideUnity() { return AppDomain.CurrentDomain.FriendlyName != "Unity Child Domain"; } #endif public static bool AreFunctionsEqual(Delegate left, Delegate right) { return left.Target == right.Target && left.Method() == right.Method(); } // Taken from here: // http://stackoverflow.com/questions/28937324/in-c-how-could-i-get-a-classs-inheritance-distance-to-base-class/28937542#28937542 public static int GetInheritanceDelta(Type derived, Type parent) { Assert.That(derived.DerivesFromOrEqual(parent)); if (parent.IsInterface()) { // Not sure if we can calculate this so just return 1 return 1; } if (derived == parent) { return 0; } int distance = 1; Type child = derived; while ((child = child.BaseType()) != parent) { distance++; } return distance; } #if !NOT_UNITY3D public static IEnumerable<SceneContext> GetAllSceneContexts() { foreach (var scene in UnityUtil.AllLoadedScenes) { var contexts = scene.GetRootGameObjects() .SelectMany(root => root.GetComponentsInChildren<SceneContext>()).ToList(); if (contexts.IsEmpty()) { continue; } Assert.That(contexts.Count == 1, "Found multiple scene contexts in scene '{0}'", scene.name); yield return contexts[0]; } } public static void AddStateMachineBehaviourAutoInjectersInScene(Scene scene) { foreach (var rootObj in GetRootGameObjects(scene)) { if (rootObj != null) { AddStateMachineBehaviourAutoInjectersUnderGameObject(rootObj); } } } // Call this before calling GetInjectableMonoBehavioursUnderGameObject to ensure that the StateMachineBehaviour's // also get injected properly // The StateMachineBehaviour's cannot be retrieved until after the Start() method so we // need to use ZenjectStateMachineBehaviourAutoInjecter to do the injection at that // time for us public static void AddStateMachineBehaviourAutoInjectersUnderGameObject(GameObject root) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("Searching Hierarchy")) #endif { var animators = root.GetComponentsInChildren<Animator>(true); foreach (var animator in animators) { if (animator.gameObject.GetComponent<ZenjectStateMachineBehaviourAutoInjecter>() == null) { animator.gameObject.AddComponent<ZenjectStateMachineBehaviourAutoInjecter>(); } } } } public static void GetInjectableMonoBehavioursInScene( Scene scene, List<MonoBehaviour> monoBehaviours) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("Searching Hierarchy")) #endif { foreach (var rootObj in GetRootGameObjects(scene)) { if (rootObj != null) { GetInjectableMonoBehavioursUnderGameObjectInternal(rootObj, monoBehaviours); } } } } // NOTE: This method will not return components that are within a GameObjectContext // It returns monobehaviours in a bottom-up order public static void GetInjectableMonoBehavioursUnderGameObject( GameObject gameObject, List<MonoBehaviour> injectableComponents) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("Searching Hierarchy")) #endif { GetInjectableMonoBehavioursUnderGameObjectInternal(gameObject, injectableComponents); } } static void GetInjectableMonoBehavioursUnderGameObjectInternal( GameObject gameObject, List<MonoBehaviour> injectableComponents) { if (gameObject == null) { return; } var monoBehaviours = gameObject.GetComponents<MonoBehaviour>(); for (int i = 0; i < monoBehaviours.Length; i++) { var monoBehaviour = monoBehaviours[i]; // Can be null for broken component references if (monoBehaviour != null && monoBehaviour.GetType().DerivesFromOrEqual<GameObjectContext>()) { // Need to make sure we don't inject on any MonoBehaviour's that are below a GameObjectContext // Since that is the responsibility of the GameObjectContext // BUT we do want to inject on the GameObjectContext itself injectableComponents.Add(monoBehaviour); return; } } // Recurse first so it adds components bottom up though it shouldn't really matter much // because it should always inject in the dependency order for (int i = 0; i < gameObject.transform.childCount; i++) { var child = gameObject.transform.GetChild(i); if (child != null) { GetInjectableMonoBehavioursUnderGameObjectInternal(child.gameObject, injectableComponents); } } for (int i = 0; i < monoBehaviours.Length; i++) { var monoBehaviour = monoBehaviours[i]; // Can be null for broken component references if (monoBehaviour != null && IsInjectableMonoBehaviourType(monoBehaviour.GetType())) { injectableComponents.Add(monoBehaviour); } } } public static bool IsInjectableMonoBehaviourType(Type type) { // Do not inject on installers since these are always injected before they are installed return type != null && !type.DerivesFrom<MonoInstaller>() && TypeAnalyzer.HasInfo(type); } public static IEnumerable<GameObject> GetRootGameObjects(Scene scene) { #if ZEN_INTERNAL_PROFILING using (ProfileTimers.CreateTimedBlock("Searching Hierarchy")) #endif { if (scene.isLoaded) { return scene.GetRootGameObjects() .Where(x => x.GetComponent<ProjectContext>() == null); } // Note: We can't use scene.GetRootObjects() here because that apparently fails with an exception // about the scene not being loaded yet when executed in Awake // We also can't use GameObject.FindObjectsOfType<Transform>() because that does not include inactive game objects // So we use Resources.FindObjectsOfTypeAll, even though that may include prefabs. However, our assumption here // is that prefabs do not have their "scene" property set correctly so this should work // // It's important here that we only inject into root objects that are part of our scene, to properly support // multi-scene editing features of Unity 5.x // // Also, even with older Unity versions, if there is an object that is marked with DontDestroyOnLoad, then it will // be injected multiple times when another scene is loaded // // We also make sure not to inject into the project root objects which are injected by ProjectContext. return Resources.FindObjectsOfTypeAll<GameObject>() .Where(x => x.transform.parent == null && x.GetComponent<ProjectContext>() == null && x.scene == scene); } } #if UNITY_EDITOR // Returns a Transform in the DontDestroyOnLoad scene (or, if we're not in play mode, within the current active scene) // whose GameObject is inactive, and whose hide flags are set to HideAndDontSave. We can instantiate prefabs in here // without any of their Awake() methods firing. public static Transform GetOrCreateInactivePrefabParent() { if(_disabledIndestructibleGameObject == null || (!Application.isPlaying && _disabledIndestructibleGameObject.scene != SceneManager.GetActiveScene())) { var go = new GameObject("ZenUtilInternal_PrefabParent"); go.hideFlags = HideFlags.HideAndDontSave; go.SetActive(false); if(Application.isPlaying) { UnityEngine.Object.DontDestroyOnLoad(go); } _disabledIndestructibleGameObject = go; } return _disabledIndestructibleGameObject.transform; } #endif #endif } }
#region Using Statements using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Cake.Core; using Cake.Core.Diagnostics; using Microsoft.Web.Administration; #endregion namespace Cake.IIS { public abstract class BaseSiteManager : BaseManager { #region Constructor (1) public BaseSiteManager(ICakeEnvironment environment, ICakeLog log) : base(environment, log) { } #endregion #region Functions (9) protected Site CreateSite(SiteSettings settings, out bool exists) { if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrWhiteSpace(settings.Name)) { throw new ArgumentException("Site name cannot be null!"); } if (string.IsNullOrWhiteSpace(settings.HostName)) { throw new ArgumentException("Host name cannot be null!"); } //Get Site Site site = _Server.Sites.FirstOrDefault(p => p.Name == settings.Name); if (site != null) { _Log.Information("Site '{0}' already exists.", settings.Name); if (settings.Overwrite) { _Log.Information("Site '{0}' will be overriden by request.", settings.Name); this.Delete(settings.Name); ApplicationPoolManager .Using(_Environment, _Log, _Server) .Delete(site.ApplicationDefaults.ApplicationPoolName); exists = false; } else { exists = true; return site; } } else { exists = false; } //Create Pool ApplicationPoolManager .Using(_Environment, _Log, _Server) .Create(settings.ApplicationPool); //Site Settings site = _Server.Sites.Add( settings.Name, settings.BindingProtocol.ToString().ToLower(), settings.BindingInformation, this.GetPhysicalDirectory(settings)); if (settings.CertificateHash != null) { site.Bindings[0].CertificateHash = settings.CertificateHash; } if (!String.IsNullOrEmpty(settings.CertificateStoreName)) { site.Bindings[0].CertificateStoreName = settings.CertificateStoreName; } site.ServerAutoStart = settings.ServerAutoStart; site.ApplicationDefaults.ApplicationPoolName = settings.ApplicationPool.Name; //Security this.SetAuthentication(settings); this.SetAuthorization(settings); return site; } protected void SetAuthentication(SiteSettings settings) { if (settings.Authentication != null) { //Get Type string server = ""; if (settings is WebsiteSettings) { server = "webServer"; } else { server = "ftpServer"; } //Authentication var config = _Server.GetApplicationHostConfiguration(); var authentication = config.GetSection("system." + server + "/security/authorization", settings.Name); // Anonymous Authentication var anonymousAuthentication = authentication.GetChildElement("anonymousAuthentication"); anonymousAuthentication.SetAttributeValue("enabled", settings.Authentication.EnableAnonymousAuthentication); _Log.Information("Anonymous Authentication enabled: {0}", settings.Authentication.EnableAnonymousAuthentication); // Basic Authentication var basicAuthentication = authentication.GetChildElement("basicAuthentication"); basicAuthentication.SetAttributeValue("enabled", settings.Authentication.EnableBasicAuthentication); basicAuthentication.SetAttributeValue("userName", settings.Authentication.Username); basicAuthentication.SetAttributeValue("password", settings.Authentication.Password); _Log.Information("Basic Authentication enabled: {0}", settings.Authentication.EnableBasicAuthentication); // Windows Authentication var windowsAuthentication = authentication.GetChildElement("windowsAuthentication"); windowsAuthentication.SetAttributeValue("enabled", settings.Authentication.EnableWindowsAuthentication); _Log.Information("Windows Authentication enabled: {0}", settings.Authentication.EnableWindowsAuthentication); } } protected void SetAuthorization(SiteSettings settings) { if (settings.Authorization != null) { //Get Type string server = ""; if (settings is WebsiteSettings) { server = "webServer"; } else { server = "ftpServer"; } //Authorization var config = _Server.GetApplicationHostConfiguration(); var authorization = config.GetSection("system." + server + "/security/authorization", settings.Name); var authCollection = authorization.GetCollection(); var addElement = authCollection.CreateElement("add"); addElement.SetAttributeValue("accessType", "Allow"); switch (settings.Authorization.AuthorizationType) { case AuthorizationType.AllUsers: addElement.SetAttributeValue("users", "*"); break; case AuthorizationType.SpecifiedUser: addElement.SetAttributeValue("users", string.Join(", ", settings.Authorization.Users)); break; case AuthorizationType.SpecifiedRoleOrUserGroup: addElement.SetAttributeValue("roles", string.Join(", ", settings.Authorization.Roles)); break; } //Permissions var permissions = new List<string>(); if (settings.Authorization.CanRead) { permissions.Add("Read"); } if (settings.Authorization.CanWrite) { permissions.Add("Write"); } addElement.SetAttributeValue("permissions", string.Join(", ", permissions)); authCollection.Clear(); authCollection.Add(addElement); _Log.Information("Windows Authentication enabled: {0}", settings.Authentication.EnableWindowsAuthentication); } } public bool Delete(string name) { var site = _Server.Sites.FirstOrDefault(p => p.Name == name); if (site == null) { _Log.Information("Site '{0}' not found.", name); return true; } else { _Server.Sites.Remove(site); _Server.CommitChanges(); _Log.Information("Site '{0}' deleted.", site.Name); return false; } } public bool Exists(string name) { if (_Server.Sites.SingleOrDefault(p => p.Name == name) != null) { _Log.Information("The site '{0}' exists.", name); return true; } else { _Log.Information("The site '{0}' does not exist.", name); return false; } } public bool Start(string name) { var site = _Server.Sites.FirstOrDefault(p => p.Name == name); if (site == null) { _Log.Information("Site '{0}' not found.", name); return false; } else { try { site.Start(); } catch (System.Runtime.InteropServices.COMException) { _Log.Information("Waiting for IIS to activate new config"); Thread.Sleep(1000); } _Log.Information("Site '{0}' started.", site.Name); return true; } } public bool Stop(string name) { var site = _Server.Sites.FirstOrDefault(p => p.Name == name); if (site == null) { _Log.Information("Site '{0}' not found.", name); return false; } else { try { site.Stop(); } catch (System.Runtime.InteropServices.COMException) { _Log.Information("Waiting for IIS to activate new config"); Thread.Sleep(1000); } _Log.Information("Site '{0}' stopped.", site.Name); return true; } } public bool AddBinding(BindingSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrWhiteSpace(settings.Name)) { throw new ArgumentException("Site name cannot be null!"); } //Get Site Site site = _Server.Sites.SingleOrDefault(p => p.Name == settings.Name); if (site != null) { if (site.Bindings.FirstOrDefault(b => (b.Protocol == settings.BindingProtocol.ToString()) && (b.BindingInformation == settings.BindingInformation)) != null) { throw new Exception("A binding with the same ip, port and host header already exists."); } //Add Binding Binding newBinding = site.Bindings.CreateElement(); newBinding.Protocol = settings.BindingProtocol.ToString(); newBinding.BindingInformation = settings.BindingInformation; if (settings.CertificateHash != null) { newBinding.CertificateHash = settings.CertificateHash; } if (!String.IsNullOrEmpty(settings.CertificateStoreName)) { newBinding.CertificateStoreName = settings.CertificateStoreName; } site.Bindings.Add(newBinding); _Server.CommitChanges(); _Log.Information("Binding added."); return true; } else { throw new Exception("Site: " + settings.Name + " does not exist."); } } public bool RemoveBinding(BindingSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrWhiteSpace(settings.Name)) { throw new ArgumentException("Site name cannot be null!"); } //Get Site Site site = _Server.Sites.SingleOrDefault(p => p.Name == settings.Name); if (site != null) { Binding binding = site.Bindings.FirstOrDefault(b => (b.Protocol == settings.BindingProtocol.ToString()) && (b.BindingInformation == settings.BindingInformation)); if (binding != null) { //Remove Binding site.Bindings.Remove(binding); _Server.CommitChanges(); _Log.Information("Binding removed."); return true; } else { _Log.Information("A binding with the same ip, port and host header does not exists."); return false; } } else { throw new Exception("Site: " + settings.Name + " does not exist."); } } public bool AddApplication(ApplicationSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrWhiteSpace(settings.SiteName)) { throw new ArgumentException("Site name cannot be null!"); } if (string.IsNullOrWhiteSpace(settings.ApplicationPath)) { throw new ArgumentException("Applicaiton path cannot be null!"); } //Get Pool ApplicationPool appPool = _Server.ApplicationPools.SingleOrDefault(p => p.Name == settings.ApplicationPool); if (appPool == null) { throw new Exception("Application Pool '" + settings.ApplicationPool + "' does not exist."); } //Get Site Site site = _Server.Sites.SingleOrDefault(p => p.Name == settings.SiteName); if (site != null) { //Get Application Application app = site.Applications.SingleOrDefault(p => p.Path == settings.ApplicationPath); if (app != null) { throw new Exception("Application '" + settings.ApplicationPath + "' already exists."); } else { app = site.Applications.CreateElement(); app.Path = settings.ApplicationPath; app.ApplicationPoolName = settings.ApplicationPool; //Get Directory VirtualDirectory vDir = app.VirtualDirectories.CreateElement(); vDir.Path = settings.VirtualDirectory; vDir.PhysicalPath = this.GetPhysicalDirectory(settings); if (!string.IsNullOrEmpty(settings.UserName)) { if (string.IsNullOrEmpty(settings.Password)) { throw new Exception("Invalid Virtual Directory User Account Password."); } else { vDir.UserName = settings.UserName; vDir.Password = settings.Password; } } app.VirtualDirectories.Add(vDir); } site.Applications.Add(app); _Server.CommitChanges(); return true; } else { throw new Exception("Site '" + settings.SiteName + "' does not exist."); } } public bool RemoveApplication(ApplicationSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrWhiteSpace(settings.SiteName)) { throw new ArgumentException("Site name cannot be null!"); } if (string.IsNullOrWhiteSpace(settings.ApplicationPath)) { throw new ArgumentException("Applicaiton path cannot be null!"); } //Get Pool ApplicationPool appPool = _Server.ApplicationPools.SingleOrDefault(p => p.Name == settings.ApplicationPool); if (appPool == null) { throw new Exception("Application Pool '" + settings.ApplicationPool + "' does not exist."); } //Get Site Site site = _Server.Sites.SingleOrDefault(p => p.Name == settings.SiteName); if (site != null) { //Get Application Application app = site.Applications.SingleOrDefault(p => p.Path == settings.ApplicationPath); if (app == null) { throw new Exception("Application '" + settings.ApplicationPath + "' does not exists."); } else { site.Applications.Remove(app); _Server.CommitChanges(); return true; } } else { throw new Exception("Site '" + settings.SiteName + "' does not exist."); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System; using System.Collections.Generic; using NPOI.SS.Util; using System.Collections; /// <summary> /// Indicate the position of the margin. One of left, right, top and bottom. /// </summary> public enum MarginType : short { /// <summary> /// referes to the left margin /// </summary> LeftMargin = 0, /// <summary> /// referes to the right margin /// </summary> RightMargin = 1, /// <summary> /// referes to the top margin /// </summary> TopMargin = 2, /// <summary> /// referes to the bottom margin /// </summary> BottomMargin = 3, HeaderMargin = 4, FooterMargin = 5 } /// <summary> /// Define the position of the pane. One of lower/right, upper/right, lower/left and upper/left. /// </summary> public enum PanePosition : byte { /// <summary> /// referes to the lower/right corner /// </summary> LowerRight = 0, /// <summary> /// referes to the upper/right corner /// </summary> UpperRight = 1, /// <summary> /// referes to the lower/left corner /// </summary> LowerLeft = 2, /// <summary> /// referes to the upper/left corner /// </summary> UpperLeft = 3, } /// <summary> /// High level representation of a Excel worksheet. /// </summary> /// <remarks> /// Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. /// The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can /// contain text, numbers, dates, and formulas. Cells can also be formatted. /// </remarks> public interface ISheet { /// <summary> /// Create a new row within the sheet and return the high level representation /// </summary> /// <param name="rownum">The row number.</param> /// <returns>high level Row object representing a row in the sheet</returns> /// <see>RemoveRow(Row)</see> IRow CreateRow(int rownum); /// <summary> /// Remove a row from this sheet. All cells Contained in the row are Removed as well /// </summary> /// <param name="row">a row to Remove.</param> void RemoveRow(IRow row); /// <summary> /// Returns the logical row (not physical) 0-based. If you ask for a row that is not /// defined you get a null. This is to say row 4 represents the fifth row on a sheet. /// </summary> /// <param name="rownum">row to get (0-based).</param> /// <returns>the rownumber or null if its not defined on the sheet</returns> IRow GetRow(int rownum); /// <summary> /// Returns the number of physically defined rows (NOT the number of rows in the sheet) /// </summary> /// <value>the number of physically defined rows in this sheet.</value> int PhysicalNumberOfRows { get; } /// <summary> /// Gets the first row on the sheet /// </summary> /// <value>the number of the first logical row on the sheet (0-based).</value> int FirstRowNum { get; } /// <summary> /// Gets the last row on the sheet /// </summary> /// <value>last row contained n this sheet (0-based)</value> int LastRowNum { get; } /// <summary> /// whether force formula recalculation. /// </summary> bool ForceFormulaRecalculation { get; set; } /// <summary> /// Get the visibility state for a given column /// </summary> /// <param name="columnIndex">the column to get (0-based)</param> /// <param name="hidden">the visiblity state of the column</param> void SetColumnHidden(int columnIndex, bool hidden); /// <summary> /// Get the hidden state for a given column /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>hidden - <c>false</c> if the column is visible</returns> bool IsColumnHidden(int columnIndex); /// <summary> /// Copy the source row to the target row. If the target row exists, the new copied row will be inserted before the existing one /// </summary> /// <param name="sourceIndex">source index</param> /// <param name="targetIndex">target index</param> /// <returns>the new copied row object</returns> IRow CopyRow(int sourceIndex, int targetIndex); /// <summary> /// Set the width (in units of 1/256th of a character width) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <param name="width">the width in units of 1/256th of a character width</param> /// <remarks> /// The maximum column width for an individual cell is 255 characters. /// This value represents the number of characters that can be displayed /// in a cell that is formatted with the standard font. /// </remarks> void SetColumnWidth(int columnIndex, int width); /// <summary> /// get the width (in units of 1/256th of a character width ) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>the width in units of 1/256th of a character width</returns> int GetColumnWidth(int columnIndex); /// <summary> /// Get the default column width for the sheet (if the columns do not define their own width) /// in characters /// </summary> /// <value>default column width measured in characters.</value> int DefaultColumnWidth { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// twips (1/20 of a point) /// </summary> /// <value>default row height measured in twips (1/20 of a point)</value> short DefaultRowHeight { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// points. /// </summary> /// <value>The default row height in points.</value> float DefaultRowHeightInPoints { get; set; } /// <summary> /// Returns the CellStyle that applies to the given /// (0 based) column, or null if no style has been /// set for that column /// </summary> /// <param name="column">The column.</param> ICellStyle GetColumnStyle(int column); /// <summary> /// Adds a merged region of cells (hence those cells form one) /// </summary> /// <param name="region">(rowfrom/colfrom-rowto/colto) to merge.</param> /// <returns>index of this region</returns> int AddMergedRegion(NPOI.SS.Util.CellRangeAddress region); /// <summary> /// Determine whether printed output for this sheet will be horizontally centered. /// </summary> bool HorizontallyCenter { get; set; } /// <summary> /// Determine whether printed output for this sheet will be vertically centered. /// </summary> bool VerticallyCenter { get; set; } /// <summary> /// Removes a merged region of cells (hence letting them free) /// </summary> /// <param name="index">index of the region to unmerge</param> void RemoveMergedRegion(int index); /// <summary> /// Returns the number of merged regions /// </summary> int NumMergedRegions { get; } /// <summary> /// Returns the merged region at the specified index /// </summary> /// <param name="index">The index.</param> NPOI.SS.Util.CellRangeAddress GetMergedRegion(int index); /// <summary> /// Gets the row enumerator. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> IEnumerator GetRowEnumerator(); /// <summary> /// Alias for GetRowEnumerator() to allow <c>foreach</c> loops. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> IEnumerator GetEnumerator(); /// <summary> /// Gets the flag indicating whether the window should show 0 (zero) in cells Containing zero value. /// When false, cells with zero value appear blank instead of showing the number zero. /// </summary> /// <value>whether all zero values on the worksheet are displayed.</value> bool DisplayZeros { get; set; } /// <summary> /// Gets or sets a value indicating whether the sheet displays Automatic Page Breaks. /// </summary> bool Autobreaks { get; set; } /// <summary> /// Get whether to display the guts or not, /// </summary> /// <value>default value is true</value> bool DisplayGuts { get; set; } /// <summary> /// Flag indicating whether the Fit to Page print option is enabled. /// </summary> bool FitToPage { get; set; } /// <summary> /// Flag indicating whether summary rows appear below detail in an outline, when applying an outline. /// /// /// When true a summary row is inserted below the detailed data being summarized and a /// new outline level is established on that row. /// /// /// When false a summary row is inserted above the detailed data being summarized and a new outline level /// is established on that row. /// /// </summary> /// <returns><c>true</c> if row summaries appear below detail in the outline</returns> bool RowSumsBelow { get; set; } /// <summary> /// Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. /// /// /// When true a summary column is inserted to the right of the detailed data being summarized /// and a new outline level is established on that column. /// /// /// When false a summary column is inserted to the left of the detailed data being /// summarized and a new outline level is established on that column. /// /// </summary> /// <returns><c>true</c> if col summaries appear right of the detail in the outline</returns> bool RowSumsRight { get; set; } /// <summary> /// Gets the flag indicating whether this sheet displays the lines /// between rows and columns to make editing and reading easier. /// </summary> /// <returns><c>true</c> if this sheet displays gridlines.</returns> bool IsPrintGridlines { get; set; } /// <summary> /// Gets the print Setup object. /// </summary> /// <returns>The user model for the print Setup object.</returns> IPrintSetup PrintSetup { get; } /// <summary> /// Gets the user model for the default document header. /// <p/> /// Note that XSSF offers more kinds of document headers than HSSF does /// /// </summary> /// <returns>the document header. Never <code>null</code></returns> IHeader Header { get; } /// <summary> /// Gets the user model for the default document footer. /// <p/> /// Note that XSSF offers more kinds of document footers than HSSF does. /// </summary> /// <returns>the document footer. Never <code>null</code></returns> IFooter Footer { get; } /// <summary> /// Gets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <returns>the size of the margin</returns> double GetMargin(MarginType margin); /// <summary> /// Sets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <param name="size">the size of the margin</param> void SetMargin(MarginType margin, double size); /// <summary> /// Answer whether protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool Protect { get; } /// <summary> /// Sets the protection enabled as well as the password /// </summary> /// <param name="password">to set for protection. Pass <code>null</code> to remove protection</param> void ProtectSheet(String password); /// <summary> /// Answer whether scenario protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool ScenarioProtect { get; } /// <summary> /// Gets or sets the tab color of the _sheet /// </summary> short TabColorIndex { get; set; } /// <summary> /// Returns the top-level drawing patriach, if there is one. /// This will hold any graphics or charts for the _sheet. /// WARNING - calling this will trigger a parsing of the /// associated escher records. Any that aren't supported /// (such as charts and complex drawing types) will almost /// certainly be lost or corrupted when written out. Only /// use this with simple drawings, otherwise call /// HSSFSheet#CreateDrawingPatriarch() and /// start from scratch! /// </summary> /// <value>The drawing patriarch.</value> IDrawing DrawingPatriarch { get; } /// <summary> /// Sets the zoom magnication for the sheet. The zoom is expressed as a /// fraction. For example to express a zoom of 75% use 3 for the numerator /// and 4 for the denominator. /// </summary> /// <param name="numerator">The numerator for the zoom magnification.</param> /// <param name="denominator">denominator for the zoom magnification.</param> void SetZoom(int numerator, int denominator); /// <summary> /// The top row in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row.</value> short TopRow { get; set; } /// <summary> /// The left col in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row</value> short LeftCol { get; set; } /// <summary> /// Sets desktop window pane display area, when the /// file is first opened in a viewer. /// </summary> /// <param name="toprow"> the top row to show in desktop window pane</param> /// <param name="leftcol"> the left column to show in desktop window pane</param> void ShowInPane(short toprow, short leftcol); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around. /// /// Calls shiftRows(startRow, endRow, n, false, false); /// /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> void ShiftRows(int startRow, int endRow, int n); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> /// <param name="copyRowHeight">whether to copy the row height during the shift</param> /// <param name="resetOriginalRowHeight">whether to set the original row's height to the default</param> void ShiftRows(int startRow, int endRow, int n, bool copyRowHeight, bool resetOriginalRowHeight); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split</param> /// <param name="rowSplit">Vertical position of split</param> /// <param name="leftmostColumn">Top row visible in bottom pane</param> /// <param name="topRow">Left column visible in right pane</param> void CreateFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split.</param> /// <param name="rowSplit">Vertical position of split.</param> void CreateFreezePane(int colSplit, int rowSplit); /// <summary> /// Creates a split pane. Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="xSplitPos">Horizonatal position of split (in 1/20th of a point)</param> /// <param name="ySplitPos">Vertical position of split (in 1/20th of a point)</param> /// <param name="leftmostColumn">Left column visible in right pane</param> /// <param name="topRow">Top row visible in bottom pane</param> /// <param name="activePane">Active pane. One of: PANE_LOWER_RIGHT, PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT</param> /// @see #PANE_LOWER_LEFT /// @see #PANE_LOWER_RIGHT /// @see #PANE_UPPER_LEFT /// @see #PANE_UPPER_RIGHT void CreateSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, PanePosition activePane); /// <summary> /// Returns the information regarding the currently configured pane (split or freeze) /// </summary> /// <value>if no pane configured returns <c>null</c> else return the pane information.</value> PaneInformation PaneInformation { get; } /// <summary> /// Returns if gridlines are displayed /// </summary> bool DisplayGridlines { get; set; } /// <summary> /// Returns if formulas are displayed /// </summary> bool DisplayFormulas { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool DisplayRowColHeadings { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool IsActive { get; set; } /// <summary> /// Determines if there is a page break at the indicated row /// </summary> /// <param name="row">The row.</param> bool IsRowBroken(int row); /// <summary> /// Removes the page break at the indicated row /// </summary> /// <param name="row">The row index.</param> void RemoveRowBreak(int row); /// <summary> /// Retrieves all the horizontal page breaks /// </summary> /// <value>all the horizontal page breaks, or null if there are no row page breaks</value> int[] RowBreaks { get; } /// <summary> /// Retrieves all the vertical page breaks /// </summary> /// <value>all the vertical page breaks, or null if there are no column page breaks.</value> int[] ColumnBreaks { get; } /// <summary> /// Sets the active cell. /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> void SetActiveCell(int row, int column); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="firstRow">The firstrow.</param> /// <param name="lastRow">The lastrow.</param> /// <param name="firstColumn">The firstcolumn.</param> /// <param name="lastColumn">The lastcolumn.</param> void SetActiveCellRange(int firstRow, int lastRow, int firstColumn, int lastColumn); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="cellranges">The cellranges.</param> /// <param name="activeRange">The index of the active range.</param> /// <param name="activeRow">The active row in the active range</param> /// <param name="activeColumn">The active column in the active range</param> void SetActiveCellRange(List<CellRangeAddress8Bit> cellranges, int activeRange, int activeRow, int activeColumn); /// <summary> /// Sets a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void SetColumnBreak(int column); /// <summary> /// Sets the row break. /// </summary> /// <param name="row">The row.</param> void SetRowBreak(int row); /// <summary> /// Determines if there is a page break at the indicated column /// </summary> /// <param name="column">The column index.</param> bool IsColumnBroken(int column); /// <summary> /// Removes a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void RemoveColumnBreak(int column); /// <summary> /// Expands or collapses a column group. /// </summary> /// <param name="columnNumber">One of the columns in the group.</param> /// <param name="collapsed">if set to <c>true</c>collapse group.<c>false</c>expand group.</param> void SetColumnGroupCollapsed(int columnNumber, bool collapsed); /// <summary> /// Create an outline for the provided column range. /// </summary> /// <param name="fromColumn">beginning of the column range.</param> /// <param name="toColumn">end of the column range.</param> void GroupColumn(int fromColumn, int toColumn); /// <summary> /// Ungroup a range of columns that were previously groupped /// </summary> /// <param name="fromColumn">start column (0-based).</param> /// <param name="toColumn">end column (0-based).</param> void UngroupColumn(int fromColumn, int toColumn); /// <summary> /// Tie a range of rows toGether so that they can be collapsed or expanded /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void GroupRow(int fromRow, int toRow); /// <summary> /// Ungroup a range of rows that were previously groupped /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void UngroupRow(int fromRow, int toRow); /// <summary> /// Set view state of a groupped range of rows /// </summary> /// <param name="row">start row of a groupped range of rows (0-based).</param> /// <param name="collapse">whether to expand/collapse the detail rows.</param> void SetRowGroupCollapsed(int row, bool collapse); /// <summary> /// Sets the default column style for a given column. POI will only apply this style to new cells Added to the sheet. /// </summary> /// <param name="column">the column index</param> /// <param name="style">the style to set</param> void SetDefaultColumnStyle(int column, ICellStyle style); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index.</param> /// <param name="useMergedCells">whether to use the contents of merged cells when /// calculating the width of the column. Default is to ignore merged cells.</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column, bool useMergedCells); /// <summary> /// Returns cell comment for the specified row and column /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> IComment GetCellComment(int row, int column); /// <summary> /// Creates the top-level drawing patriarch. /// </summary> IDrawing CreateDrawingPatriarch(); /// <summary> /// Gets the parent workbook. /// </summary> IWorkbook Workbook { get; } /// <summary> /// Gets the name of the sheet. /// </summary> String SheetName { get; } /// <summary> /// Gets or sets a value indicating whether this sheet is currently selected. /// </summary> bool IsSelected { get; set; } /// <summary> /// Sets whether sheet is selected. /// </summary> /// <param name="sel">Whether to select the sheet or deselect the sheet.</param> void SetActive(bool value); /// <summary> /// Sets array formula to specified region for result. /// </summary> /// <param name="formula">text representation of the formula</param> /// <param name="range">Region of array formula for result</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> SetArrayFormula(String formula, CellRangeAddress range); /// <summary> /// Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well /// </summary> /// <param name="cell">any cell within Array Formula range</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> RemoveArrayFormula(ICell cell); /// <summary> /// Checks if the provided region is part of the merged regions. /// </summary> /// <param name="mergedRegion">Region searched in the merged regions</param> /// <returns><c>true</c>, when the region is contained in at least one of the merged regions</returns> bool IsMergedRegion(CellRangeAddress mergedRegion); /// <summary> /// Create an instance of a DataValidationHelper. /// </summary> /// <returns>Instance of a DataValidationHelper</returns> IDataValidationHelper GetDataValidationHelper(); /// <summary> /// Creates a data validation object /// </summary> /// <param name="dataValidation">The data validation object settings</param> void AddValidationData(IDataValidation dataValidation); /// <summary> /// Enable filtering for a range of cells /// </summary> /// <param name="range">the range of cells to filter</param> IAutoFilter SetAutoFilter(CellRangeAddress range); /// <summary> /// The 'Conditional Formatting' facet for this <c>Sheet</c> /// </summary> /// <returns>conditional formatting rule for this sheet</returns> ISheetConditionalFormatting SheetConditionalFormatting { get; } /// <summary> /// Whether the text is displayed in right-to-left mode in the window /// </summary> bool IsRightToLeft { get; set; } /// <summary> /// Get or set the repeating rows used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating rows cover a range of contiguous rows, e.g.: /// <pre> /// Sheet1!$1:$1 /// Sheet2!$5:$8 /// </pre> /// The {@link CellRangeAddress} returned contains a column part which spans /// all columns, and a row part which specifies the contiguous range of /// repeating rows. /// <p/> /// If the Sheet does not have any repeating rows defined, null is returned. /// </summary> CellRangeAddress RepeatingRows { get; set; } /// <summary> /// Gets or set the repeating columns used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating columns cover a range of contiguous columns, e.g.: /// <pre> /// Sheet1!$A:$A /// Sheet2!$C:$F /// </pre> /// The {@link CellRangeAddress} returned contains a row part which spans all /// rows, and a column part which specifies the contiguous range of /// repeating columns. /// <p/> /// If the Sheet does not have any repeating columns defined, null is /// returned. /// </summary> CellRangeAddress RepeatingColumns { get; set; } /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name); /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <param name="copyStyle">whether to copy styles</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name, Boolean copyStyle); } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // InteropEventProvider.cs // // // Managed event source for FXCore. // This will produce an XML file, where each event is pretty-printed with all its arguments nicely parsed. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Security; using System.Diagnostics.Tracing; namespace System.Runtime.InteropServices { //#define ENABLE_WINRT /// <summary>Provides an event source for tracing Interop information.</summary> #if ENABLE_WINRT [EventSource(Guid = "C4AC552A-E1EB-4FA2-A651-B200EFD7AA91", Name = "System.Runtime.InteropServices.InteropEventProvider")] #endif // ENABLE_WINRT internal sealed class InteropEventProvider #if ENABLE_WINRT : EventSource #endif // ENABLE_WINRT { // Defines the singleton instance for the Interop Event ETW provider public static readonly InteropEventProvider Log = new InteropEventProvider(); #if ENABLE_WINRT internal new static bool IsEnabled() { // The InteropEventProvider class constructor should create an instance of InteropEventProvider and assign // it to the Log field so Log should never be null here. However the EventSource performs some P/Invoke // interop and creating a System.Type object which happens while running the EventSource ctor can perform // WinRT interop so it is possible that we end up calling IsEnabled before the InteropEventProvider class // constructor has completed so we must check that Log is not null. return Log != null && ((EventSource)Log).IsEnabled(); } #else internal static bool IsEnabled() { return false; } private static bool IsEnabled(EventLevel level, EventKeywords keywords) { return false; } private struct EventData { public IntPtr DataPointer { get; set; } public int Size { get; set; } } private unsafe void WriteEventCore(int eventId, int eventDataCount, EventData* data) { } #endif // ENABLE_WINRT // The InteropEventSource GUID is {C4AC552A-E1EB-4FA2-A651-B200EFD7AA91} private InteropEventProvider() { } /// <summary>Keyword definitions.</summary> public static class Keywords { /// <summary>Interop keyword enable or disable the whole interop log events.</summary> public const EventKeywords Interop = (EventKeywords)0x0001; // This is bit 0. } //----------------------------------------------------------------------------------- // // Interop Event IDs (must be unique) // #region RCWProvider #region TaskID /// <summary>A new RCW was created. Details at TaskRCWCreation.</summary> private const int TASKRCWCREATION_ID = 10; /// <summary>A RCW was finalized. Details at TaskRCWFinalization.</summary> private const int TASKRCWFINALIZATION_ID = 11; /// <summary>The RCW reference counter was incremented. Details at TaskRCWRefCountInc.</summary> private const int TASKRCWREFCOUNTINC_ID = 12; /// <summary>The RCW reference counter was decremented. Details at TaskRCWRefCountDec.</summary> private const int TASKRCWREFCOUNTDEC_ID = 13; /// <summary>The query interface failure. Details at TaskRCWQueryInterfaceFailure.</summary> private const int TASKRCWQUERYINTERFACEFAILURE_ID = 14; /// <summary>The query interface. Details at TaskRCWQueryInterface.</summary> private const int TASKRCWQUERYINTERFACE_ID = 15; #endregion TaskID #region TaskRCWCreation /// <summary> /// Fired when a new RCW was created. /// </summary> /// <scenarios> /// - Pair with RCW finalization to understand RCW lifetime and analyze leaks /// - Reference with other RCW events to understand basic properties of RCW (without using tool to inspect RCWs at runtime) /// - Understanding why weakly typed RCW are created or strongly-typed RCW are created /// </scenarios> /// <param name="comObject">Base address that unique identify the RCW.</param> /// <param name="typeRawValue">RCW type identification.</param> /// <param name="runtimeClassName">RCW runtime class name.</param> /// <param name="context">RCW context.</param> /// <param name="flags">RCW control flags.</param> [Event(TASKRCWCREATION_ID, Message = "New RCW created", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWCreation(long objectID, long typeRawValue, string runtimeClassName, long context, long flags) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[5]; int runtimeClassNameLength = (runtimeClassName.Length + 1) * 2; fixed (char* StringAux = runtimeClassName) { eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&typeRawValue)); eventPayload[2].Size = runtimeClassNameLength; eventPayload[2].DataPointer = ((IntPtr)(StringAux)); eventPayload[3].Size = sizeof(long); eventPayload[3].DataPointer = ((IntPtr)(&context)); eventPayload[4].Size = sizeof(long); eventPayload[4].DataPointer = ((IntPtr)(&flags)); WriteEventCore(TASKRCWCREATION_ID, 5, eventPayload); } } } } #endregion TaskRCWCreation #region TaskRCWRefCountInc /// <summary> /// Fired when a reference counter is incremented in RCW. /// </summary> /// <scenarios> /// - Diagnosing Marshal.ReleaseCOmObject/FInalReleaseComObject errors /// </scenarios> /// <param name="objectID">Base address that unique identify the RCW.</param> /// <param name="refCount">New reference counter value.</param> [Event(TASKRCWREFCOUNTINC_ID, Message = "RCW refCount incremented", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWRefCountInc(long objectID, int refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKRCWREFCOUNTINC_ID, 2, eventPayload); } } } #endregion TaskRCWRefCountInc #region TaskRCWRefCountDec /// <summary> /// Fired when a reference counter is decremented in RCW. /// </summary> /// <scenarios> /// - Diagnosing Marshal.ReleaseCOmObject/FInalReleaseComObject errors /// </scenarios> /// <param name="objectID">Base address that unique identify the RCW.</param> /// <param name="refCount">New reference counter value.</param> [Event(TASKRCWREFCOUNTDEC_ID, Message = "RCW refCount decremented", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWRefCountDec(long objectID, int refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKRCWREFCOUNTDEC_ID, 2, eventPayload); } } } #endregion TaskRCWRefCountDec #region TaskRCWFinalization /// <summary> /// Fired when a new RCW was finalized. /// </summary> /// <scenarios> /// - Pair with RCW finalization to understand RCW lifetime and analyze leaks /// - See if certain COM objects are finalized or not /// </scenarios> /// <param name="objectID">Base address that unique identify the RCW.</param> /// <param name="refCount">RCW reference counter.</param> [Event(TASKRCWFINALIZATION_ID, Message = "RCW Finalized", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWFinalization(long objectID, int refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKRCWFINALIZATION_ID, 2, eventPayload); } } } #endregion TaskRCWFinalization #region TaskRCWQueryInterfaceFailure /// <summary> /// Fired when a RCW Interface address is queried and failure. /// </summary> /// <scenarios> /// </scenarios> /// <param name="objectID">Base address that unique identify the RCW.</param> /// <param name="context">RCW context.</param> /// <param name="interfaceIId">Queried interface IID.</param> /// <param name="reason">Failure reason.</param> /// <remarks>Not used</remarks> [Event(TASKRCWQUERYINTERFACEFAILURE_ID, Message = "RCW Queried Interface Failure", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWQueryInterfaceFailure(long objectID, long context, Guid interfaceIId, int reason) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&context)); eventPayload[2].Size = sizeof(Guid); eventPayload[2].DataPointer = ((IntPtr)(&interfaceIId)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&reason)); WriteEventCore(TASKRCWQUERYINTERFACEFAILURE_ID, 4, eventPayload); } } } #endregion TaskRCWQueryInterfaceFailure #region TaskRCWQueryInterface /// <summary> /// Fired when a RCW Interface address is queried for the first time /// </summary> /// <scenarios> /// </scenarios> /// <param name="objectID">Base address that unique identify the RCW.</param> /// <param name="context">RCW context.</param> /// <param name="interfaceIId">Queried interface IID.</param> /// <param name="typeRawValue">Raw value of the type.</param> /// <remarks>Not used</remarks> [Event(TASKRCWQUERYINTERFACE_ID, Message = "RCW Queried Interface for the first time", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskRCWQueryInterface(long objectID, long context, Guid interfaceIId, long typeRawValue) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&context)); eventPayload[2].Size = sizeof(Guid); eventPayload[2].DataPointer = ((IntPtr)(&interfaceIId)); eventPayload[3].Size = sizeof(long); eventPayload[3].DataPointer = ((IntPtr)(&typeRawValue)); WriteEventCore(TASKRCWQUERYINTERFACE_ID, 4, eventPayload); } } } #endregion TaskRCWQueryInterface #endregion RCWProvider #region CCWProvider #region TaskID /// <summary>A new CCW was created. Details at TaskCCWCreation. Details at TaskCCWCreation.</summary> private const int TASKCCWCREATION_ID = 20; /// <summary>A CCW was finalized. Details at TaskCCWFinalization. Details at TaskCCWFinalization.</summary> private const int TASKCCWFINALIZATION_ID = 21; /// <summary>The CCW reference counter was incremented. Details at TaskCCWRefCountInc.</summary> private const int TASKCCWREFCOUNTINC_ID = 22; /// <summary>The CCW reference counter was decremented. Details at TaskCCWRefCountDec.</summary> private const int TASKCCWREFCOUNTDEC_ID = 23; /// <summary>The Runtime class name was queried. Details at TaskCCWQueryRuntimeClassName.</summary> private const int TASKCCWQUERYRUNTIMECLASSNAME_ID = 24; /// <summary>An interface was queried whit error. Details at TaskCCWQueryInterfaceFailure.</summary> private const int TASKCCWQUERYINTERFACEFAILURE_ID = 30; /// <summary>An interface was queried for the first time. Details at TaskCCWQueryInterface.</summary> private const int TASKCCWQUERYINTERFACE_ID = 31; /// <summary>Resolve was queried with error. Details at TaskCCWResolveFailure.</summary> private const int TASKCCWRESOLVEFAILURE_ID = 33; #endregion TaskID #region TaskCCWCreation /// <summary> /// Fired when a new CCW was created. /// </summary> /// <scenarios> /// - Understand lifetime of CCWs /// - Reference with other CCW events /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="targetObjectID">Base address that unique identify the target object in CCW.</param> /// <param name="typeRawValue">Raw value for the type of the target Object.</param> [Event(TASKCCWCREATION_ID, Message = "New CCW created", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWCreation(long objectID, long targetObjectID, long typeRawValue) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&targetObjectID)); eventPayload[2].Size = sizeof(long); eventPayload[2].DataPointer = ((IntPtr)(&typeRawValue)); WriteEventCore(TASKCCWCREATION_ID, 3, eventPayload); } } } #endregion TaskCCWCreation #region TaskCCWFinalization /// <summary> /// Fired when a new CCW was finalized. /// </summary> /// <scenarios> /// - Understand lifetime of CCWs and help track addref/release problems. /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="refCount">The reference counter value at the ending time.</param> [Event(TASKCCWFINALIZATION_ID, Message = "CCW Finalized", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWFinalization(long objectID, long refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKCCWFINALIZATION_ID, 2, eventPayload); } } } #endregion TaskCCWFinalization #region TaskCCWRefCountInc /// <summary> /// Fired when a reference counter is incremented in CCW. /// </summary> /// <scenarios> /// - Tracking addref/release problems /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="refCount">New reference counter value.</param> [Event(TASKCCWREFCOUNTINC_ID, Message = "CCW refCount incremented", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWRefCountInc(long objectID, long refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKCCWREFCOUNTINC_ID, 2, eventPayload); } } } #endregion TaskCCWRefCountInc #region TaskCCWRefCountDec /// <summary> /// Fired when a reference counter is decremented in CCW. /// </summary> /// <scenarios> /// - Tracking addref/release problems /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="refCount">New reference counter value.</param> [Event(TASKCCWREFCOUNTDEC_ID, Message = "CCW refCount decremented", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWRefCountDec(long objectID, long refCount) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&refCount)); WriteEventCore(TASKCCWREFCOUNTDEC_ID, 2, eventPayload); } } } #endregion TaskCCWRefCountDec #region TaskCCWQueryRuntimeClassName /// <summary> /// Fired when a runtime class name was queried. /// </summary> /// <scenarios> /// - Diagnosing bugs in JavaScript/.NET interaction, such as why JavaSCript refuse to call a function on a managed WinMD type /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="runtimeClassName">Required runtime class name.</param> [Event(TASKCCWQUERYRUNTIMECLASSNAME_ID, Message = "CCW runtime class name required", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWQueryRuntimeClassName(long objectID, string runtimeClassName) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; int runtimeClassNameLength = (runtimeClassName.Length + 1) * 2; fixed (char* StringAux = runtimeClassName) { eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = runtimeClassNameLength; eventPayload[1].DataPointer = ((IntPtr)(StringAux)); WriteEventCore(TASKCCWQUERYRUNTIMECLASSNAME_ID, 2, eventPayload); } } } } #endregion TaskCCWQueryRuntimeClassName #region TaskCCWQueryInterfaceFailure /// <summary> /// Fired when a CCW Interface address is queried and for any reason it was rejected. /// </summary> /// <scenarios> /// - Diagnosing interop bugs where Qis are rejected for no apparent reason and causing Jupiter to fail in strange ways. /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="interfaceIId">Guid of the queried interface.</param> [Event(TASKCCWQUERYINTERFACEFAILURE_ID, Message = "CCW queried interface failure", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWQueryInterfaceFailure(long objectID, Guid interfaceIId) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(Guid); eventPayload[1].DataPointer = ((IntPtr)(&interfaceIId)); WriteEventCore(TASKCCWQUERYINTERFACEFAILURE_ID, 2, eventPayload); } } } #endregion TaskCCWQueryInterfaceFailure #region TaskCCWQueryInterface /// <summary> /// Fired when a CCW Interface address is queried for the first time /// </summary> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="typeRawValue">Raw value of the type.</param> [Event(TASKCCWQUERYINTERFACE_ID, Message = "CCW first queried interface", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWQueryInterface(long objectID, long typeRawValue) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&typeRawValue)); WriteEventCore(TASKCCWQUERYINTERFACE_ID, 2, eventPayload); } } } #endregion TaskCCWQueryInterface #region TaskCCWResolveFailure /// <summary> /// Fired when a CCW interface resolve is queried and for any reason it was rejected. /// </summary> /// <scenarios> /// - Diagnosing interop bugs where Resolves are rejected for no apparent reason and causing to fail. /// </scenarios> /// <param name="objectID">Base address that unique identify the CCW.</param> /// <param name="interfaceAddress">Address of the interface that must be resolved</param> /// <param name="interfaceIId">Guid of the queried interface.</param> /// <param name="rejectedReason">Rejected reason.</param> [Event(TASKCCWRESOLVEFAILURE_ID, Message = "CCW resolve failure", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskCCWResolveFailure(long objectID, long interfaceAddress, Guid interfaceIId, int rejectedReason) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&objectID)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&interfaceAddress)); eventPayload[2].Size = sizeof(Guid); eventPayload[2].DataPointer = ((IntPtr)(&interfaceIId)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&rejectedReason)); WriteEventCore(TASKCCWRESOLVEFAILURE_ID, 4, eventPayload); } } } #endregion TaskCCWResolveFailure #endregion CCWProvider #region JupiterProvider #region TaskID /// <summary>Jupter Garbage Collector was invoked via Callback. Details at TaskJupiterGarbageCollect.</summary> private const int TASKJUPITERGARBAGECOLLECT_ID = 40; /// <summary>Jupiter disconnect RCWs in current apartment. Details at TaskJupiterDisconnectRCWsInCurrentApartment.</summary> private const int TASKJUPITERDISCONNECTERCWSINCURRENTAPARTMENT_ID = 41; /// <summary>Jupiter add memory pressure callback. Details at TaskJupiterAddMemoryPressure.</summary> private const int TASKJUPITERADDMEMORYPRESSURE_ID = 42; /// <summary>Jupiter renove memory pressure callback. Details at TaskJupiterRemoveMemoryPressure.</summary> private const int TASKJUPITERREMOVEMEMORYPRESSURE_ID = 43; /// <summary>Jupiter create managed reference callback. Details at TaskJupiterCreateManagedReference.</summary> private const int TASKJUPITERCREATEMANAGEDREFERENCE_ID = 44; #endregion TaskID #region TaskJupiterGarbageCollect /// <summary> /// Fired when Jupiter garbage collector callback is called. /// </summary> /// <scenarios> /// - Monitoring the frequency of GarbageCollect is being triggered by Jupiter /// </scenarios> [Event(TASKJUPITERGARBAGECOLLECT_ID, Message = "Garbage Collect", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskJupiterGarbageCollect() { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { WriteEventCore(TASKJUPITERGARBAGECOLLECT_ID, 0, null); } } } #endregion TaskJupiterGarbageCollect #region TaskJupiterDisconnectRCWsInCurrentApartment /// <summary> /// Fired when Jupiter disconnect RCWs in current apartment. /// </summary> /// <scenarios> /// - Monitoring the frequency of wait for pending finalizer callback is being triggered by Jupiter /// </scenarios> [Event(TASKJUPITERDISCONNECTERCWSINCURRENTAPARTMENT_ID, Message = "Jupiter disconnect RCWs in current apartment", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskJupiterDisconnectRCWsInCurrentApartment() { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { WriteEventCore(TASKJUPITERDISCONNECTERCWSINCURRENTAPARTMENT_ID, 0, null); } } } #endregion TaskJupiterDisconnectRCWsInCurrentApartment #region TaskJupiterAddMemoryPressure /// <summary> /// Fired when a Jupiter add memory pressure callback is called. /// </summary> /// <scenarios> /// - Monitoring memory pressure added by Jupiter /// </scenarios> /// <param name="memorySize">Number of bytes in the added memory.</param> [Event(TASKJUPITERADDMEMORYPRESSURE_ID, Message = "Jupiter add memory pressure", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskJupiterAddMemoryPressure(long memorySize) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&memorySize)); WriteEventCore(TASKJUPITERADDMEMORYPRESSURE_ID, 1, eventPayload); } } } #endregion TaskJupiterAddMemoryPressure #region TaskJupiterRemoveMemoryPressure /// <summary> /// Fired when a Jupiter Remove memory pressure callback is called. /// </summary> /// <scenarios> /// - Monitoring memory pressure Removeed by Jupiter /// </scenarios> /// <param name="memorySize">Number of bytes in the memory removed.</param> [Event(TASKJUPITERREMOVEMEMORYPRESSURE_ID, Message = "Jupiter Remove memory pressure", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskJupiterRemoveMemoryPressure(long memorySize) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&memorySize)); WriteEventCore(TASKJUPITERREMOVEMEMORYPRESSURE_ID, 1, eventPayload); } } } #endregion TaskJupiterRemoveMemoryPressure #region TaskJupiterCreateManagedReference /// <summary> /// Fired when a new managed reference is created in Jupiter. /// </summary> /// <scenarios> /// - Monitoring the frequency of managed 'proxies' being created/used. /// </scenarios> /// <param name="IUnknown">Base address that unique identify the Jupiter.</param> /// <param name="objectType">Jupiter type.</param> [Event(TASKJUPITERCREATEMANAGEDREFERENCE_ID, Message = "Jupiter create managed reference", Level = EventLevel.Verbose, Keywords = Keywords.Interop)] public void TaskJupiterCreateManagedReference(long IUnknown, long objectType) { if (IsEnabled(EventLevel.Verbose, Keywords.Interop)) { unsafe { EventData* eventPayload = stackalloc EventData[2]; eventPayload[0].Size = sizeof(long); eventPayload[0].DataPointer = ((IntPtr)(&IUnknown)); eventPayload[1].Size = sizeof(long); eventPayload[1].DataPointer = ((IntPtr)(&objectType)); WriteEventCore(TASKJUPITERCREATEMANAGEDREFERENCE_ID, 2, eventPayload); } } } #endregion TaskJupiterCreateManagedReference #endregion JupiterProvider } //Class InteropEventProvider }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Serialization; using DotSpatial.Symbology; using GeoAPI.Geometries; namespace DotSpatial.Controls { /// <summary> /// This is a specialized FeatureLayer that specifically handles point drawing. /// </summary> public class MapPointLayer : PointLayer, IMapPointLayer { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MapPointLayer"/> class. /// This creates a blank MapPointLayer with the DataSet set to an empty new featureset of the Point featuretype. /// </summary> public MapPointLayer() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="MapPointLayer"/> class. /// </summary> /// <param name="featureSet">The point feature set used as data source.</param> public MapPointLayer(IFeatureSet featureSet) : base(featureSet) { // this simply handles the default case where no status messages are requested Configure(); OnFinishedLoading(); } /// <summary> /// Initializes a new instance of the <see cref="MapPointLayer"/> class. /// Creates a new instance of the point layer where the container is specified /// </summary> /// <param name="featureSet">The point feature set used as data source.</param> /// <param name="container">An IContainer that the point layer should be created in.</param> public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container) : base(featureSet, container, null) { Configure(); OnFinishedLoading(); } /// <summary> /// Initializes a new instance of the <see cref="MapPointLayer"/> class. /// Creates a new instance of the point layer where the container is specified /// </summary> /// <param name="featureSet">The point feature set used as data source.</param> /// <param name="container">An IContainer that the point layer should be created in.</param> /// <param name="notFinished">Indicates whether the OnFinishedLoading event should be suppressed after loading finished.</param> public MapPointLayer(IFeatureSet featureSet, ICollection<ILayer> container, bool notFinished) : base(featureSet, container, null) { Configure(); if (!notFinished) OnFinishedLoading(); } #endregion #region Events /// <summary> /// Occurs when drawing content has changed on the buffer for this layer /// </summary> public event EventHandler<ClipArgs> BufferChanged; #endregion #region Properties /// <summary> /// Gets or sets the back buffer that will be drawn to as part of the initialization process. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image BackBuffer { get; set; } /// <summary> /// Gets or sets the current buffer. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Image Buffer { get; set; } /// <summary> /// Gets or sets the geographic region represented by the buffer /// Calling Initialize will set this automatically. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Envelope BufferEnvelope { get; set; } /// <summary> /// Gets or sets the rectangle in pixels to use as the back buffer. /// Calling Initialize will set this automatically. /// </summary> [ShallowCopy] [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle BufferRectangle { get; set; } /// <summary> /// Gets or sets the label layer that is associated with this point layer. /// </summary> [ShallowCopy] public new IMapLabelLayer LabelLayer { get { return base.LabelLayer as IMapLabelLayer; } set { base.LabelLayer = value; } } #endregion #region Methods /// <summary> /// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not /// does not generate a point layer, an exception will be thrown. /// </summary> /// <param name="fileName">A string fileName to create a point layer for.</param> /// <param name="progressHandler">Any valid implementation of IProgressHandler for receiving progress messages</param> /// <returns>A GeoPointLayer created from the specified fileName.</returns> public static new MapPointLayer OpenFile(string fileName, IProgressHandler progressHandler) { ILayer fl = LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler); return fl as MapPointLayer; } /// <summary> /// Attempts to create a new GeoPointLayer using the specified file. If the filetype is not /// does not generate a point layer, an exception will be thrown. /// </summary> /// <param name="fileName">A string fileName to create a point layer for.</param> /// <returns>A GeoPointLayer created from the specified fileName.</returns> public static new MapPointLayer OpenFile(string fileName) { IFeatureLayer fl = LayerManager.DefaultLayerManager.OpenVectorLayer(fileName); return fl as MapPointLayer; } /// <summary> /// Call StartDrawing before using this. /// </summary> /// <param name="rectangles">The rectangular region in pixels to clear.</param> /// <param name= "color">The color to use when clearing. Specifying transparent /// will replace content with transparent pixels.</param> public void Clear(List<Rectangle> rectangles, Color color) { if (BackBuffer == null) return; Graphics g = Graphics.FromImage(BackBuffer); foreach (Rectangle r in rectangles) { if (r.IsEmpty == false) { g.Clip = new Region(r); g.Clear(color); } } g.Dispose(); } /// <summary> /// This is testing the idea of using an input parameter type that is marked as out /// instead of a return type. /// </summary> /// <param name="result">The result of the creation</param> /// <returns>Boolean, true if a layer can be created</returns> public override bool CreateLayerFromSelectedFeatures(out IFeatureLayer result) { MapPointLayer temp; bool resultOk = CreateLayerFromSelectedFeatures(out temp); result = temp; return resultOk; } /// <summary> /// This is the strong typed version of the same process that is specific to geo point layers. /// </summary> /// <param name="result">The new GeoPointLayer to be created</param> /// <returns>Boolean, true if there were any values in the selection</returns> public virtual bool CreateLayerFromSelectedFeatures(out MapPointLayer result) { result = null; if (Selection == null || Selection.Count == 0) return false; FeatureSet fs = Selection.ToFeatureSet(); result = new MapPointLayer(fs); return true; } /// <summary> /// If EditMode is true, then this method is used for drawing. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="features">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawFeatures(MapArgs args, List<IFeature> features, List<Rectangle> clipRectangles, bool useChunks, bool selected) { if (!useChunks || features.Count < ChunkSize) { DrawFeatures(args, features, selected); return; } int count = features.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int groupSize = ChunkSize; if (chunk == numChunks - 1) groupSize = count - (chunk * ChunkSize); List<IFeature> subset = features.GetRange(chunk * ChunkSize, groupSize); DrawFeatures(args, subset, selected); if (numChunks <= 0 || chunk >= numChunks - 1) continue; FinishDrawing(); OnBufferChanged(clipRectangles); Application.DoEvents(); } } /// <summary> /// If EditMode is false, then this method is used for drawing. /// </summary> /// <param name="args">The GeoArgs that control how these features should be drawn.</param> /// <param name="indices">The features that should be drawn.</param> /// <param name="clipRectangles">If an entire chunk is drawn and an update is specified, this clarifies the changed rectangles.</param> /// <param name="useChunks">Boolean, if true, this will refresh the buffer in chunks.</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawFeatures(MapArgs args, List<int> indices, List<Rectangle> clipRectangles, bool useChunks, bool selected) { if (!useChunks) { DrawFeatures(args, indices, selected); return; } int count = indices.Count; int numChunks = (int)Math.Ceiling(count / (double)ChunkSize); for (int chunk = 0; chunk < numChunks; chunk++) { int numFeatures = ChunkSize; if (chunk == numChunks - 1) numFeatures = indices.Count - (chunk * ChunkSize); DrawFeatures(args, indices.GetRange(chunk * ChunkSize, numFeatures), selected); if (numChunks > 0 && chunk < numChunks - 1) { OnBufferChanged(clipRectangles); Application.DoEvents(); } } } /// <summary> /// This will draw any features that intersect this region. To specify the features /// directly, use OnDrawFeatures. This will not clear existing buffer content. /// For that call Initialize instead. /// </summary> /// <param name="args">A GeoArgs clarifying the transformation from geographic to image space</param> /// <param name="regions">The geographic regions to draw</param> /// <param name="selected">Indicates whether to draw the normal colored features or the selection colored features.</param> public virtual void DrawRegions(MapArgs args, List<Extent> regions, bool selected) { // First determine the number of features we are talking about based on region. List<Rectangle> clipRects = args.ProjToPixel(regions); if (EditMode) { List<IFeature> drawList = new List<IFeature>(); foreach (Extent region in regions) { if (region != null) { // Use union to prevent duplicates. No sense in drawing more than we have to. drawList = drawList.Union(DataSet.Select(region)).ToList(); } } DrawFeatures(args, drawList, clipRects, true, selected); } else { List<int> drawList = new List<int>(); double[] verts = DataSet.Vertex; if (DataSet.FeatureType == FeatureType.Point) { for (int shp = 0; shp < verts.Length / 2; shp++) { foreach (Extent extent in regions) { if (extent.Intersects(verts[shp * 2], verts[(shp * 2) + 1])) { drawList.Add(shp); } } } } else { List<ShapeRange> shapes = DataSet.ShapeIndices; for (int shp = 0; shp < shapes.Count; shp++) { foreach (Extent region in regions) { if (!shapes[shp].Extent.Intersects(region)) continue; drawList.Add(shp); break; } } } DrawFeatures(args, drawList, clipRects, true, selected); } } /// <summary> /// Indicates that the drawing process has been finalized and swaps the back buffer /// to the front buffer. /// </summary> public void FinishDrawing() { OnFinishDrawing(); if (Buffer != null && Buffer != BackBuffer) Buffer.Dispose(); Buffer = BackBuffer; } /// <summary> /// Copies any current content to the back buffer so that drawing should occur on the /// back buffer (instead of the fore-buffer). Calling draw methods without /// calling this may cause exceptions. /// </summary> /// <param name="preserve">Boolean, true if the front buffer content should be copied to the back buffer /// where drawing will be taking place.</param> public void StartDrawing(bool preserve) { Bitmap backBuffer = new Bitmap(BufferRectangle.Width, BufferRectangle.Height); if (Buffer?.Width == backBuffer.Width && Buffer.Height == backBuffer.Height && preserve) { Graphics g = Graphics.FromImage(backBuffer); g.DrawImageUnscaled(Buffer, 0, 0); } if (BackBuffer != null && BackBuffer != Buffer) BackBuffer.Dispose(); BackBuffer = backBuffer; OnStartDrawing(); } /// <summary> /// Fires the OnBufferChanged event /// </summary> /// <param name="clipRectangles">The Rectangle in pixels</param> protected virtual void OnBufferChanged(List<Rectangle> clipRectangles) { if (BufferChanged != null) { ClipArgs e = new ClipArgs(clipRectangles); BufferChanged(this, e); } } /// <summary> /// A default method to generate a label layer. /// </summary> protected override void OnCreateLabels() { LabelLayer = new MapLabelLayer(this); } /// <summary> /// Indiciates that whatever drawing is going to occur has finished and the contents /// are about to be flipped forward to the front buffer. /// </summary> protected virtual void OnFinishDrawing() { } /// <summary> /// Occurs when a new drawing is started, but after the BackBuffer has been established. /// </summary> protected virtual void OnStartDrawing() { } private void Configure() { ChunkSize = 50000; } // This draws the individual point features private void DrawFeatures(MapArgs e, IEnumerable<int> indices, bool selected) { if (selected && (!DrawnStatesNeeded || !DrawnStates.Any(_ => _.Selected))) return; // there are no selected features Graphics g = e.Device ?? Graphics.FromImage(BackBuffer); Matrix origTransform = g.Transform; FeatureType featureType = DataSet.FeatureType; double minX = e.MinX; double maxY = e.MaxY; double dx = e.Dx; double dy = e.Dy; // CGX if (dx < 2000000000 && dx > -2000000000 && dy < 2000000000 && dy > -2000000000) { if (!DrawnStatesNeeded) { if (Symbology == null || Symbology.Categories.Count == 0) return; FastDrawnState state = new FastDrawnState(false, Symbology.Categories[0]); IPointSymbolizer ps = (state.Category as IPointCategory)?.Symbolizer; if (ps == null) return; double[] vertices = DataSet.Vertex; foreach (int index in indices) { // CGX if (Visibility != null) { bool visi = Visibility[index].Visible; if (!visi) continue; } if (featureType == FeatureType.Point) { DrawPoint(vertices[index * 2], vertices[(index * 2) + 1], e, ps, g, origTransform); } else { // multi-point ShapeRange range = DataSet.ShapeIndices[index]; for (int i = range.StartIndex; i <= range.EndIndex(); i++) { DrawPoint(vertices[i * 2], vertices[(i * 2) + 1], e, ps, g, origTransform); } } } } else { FastDrawnState[] states = DrawnStates; var indexList = indices as IList<int> ?? indices.ToList(); if (indexList.Max() >= states.Length) { AssignFastDrawnStates(); states = DrawnStates; } double[] vertices = DataSet.Vertex; foreach (int index in indexList) { if (index >= states.Length) break; FastDrawnState state = states[index]; if (!state.Visible || state.Category == null) continue; if (selected && !state.Selected) continue; IPointCategory pc = state.Category as IPointCategory; if (pc == null) continue; IPointSymbolizer ps = selected ? pc.SelectionSymbolizer : pc.Symbolizer; if (ps == null) continue; if (featureType == FeatureType.Point) { DrawPoint(vertices[index * 2], vertices[(index * 2) + 1], e, ps, g, origTransform); } else { ShapeRange range = DataSet.ShapeIndices[index]; for (int i = range.StartIndex; i <= range.EndIndex(); i++) { DrawPoint(vertices[i * 2], vertices[(i * 2) + 1], e, ps, g, origTransform); } } } } } if (e.Device == null) g.Dispose(); else g.Transform = origTransform; } // This draws the individual point features private void DrawFeatures(MapArgs e, IEnumerable<IFeature> features, bool selected) { IDictionary<IFeature, IDrawnState> states = DrawingFilter.DrawnStates; if (states == null) return; if (selected && !states.Any(_ => _.Value.IsSelected)) return; Graphics g = e.Device ?? Graphics.FromImage(BackBuffer); Matrix origTransform = g.Transform; foreach (IFeature feature in features) { if (!states.ContainsKey(feature)) continue; IDrawnState ds = states[feature]; if (ds == null || !ds.IsVisible || ds.SchemeCategory == null) continue; if (selected && !ds.IsSelected) continue; IPointCategory pc = ds.SchemeCategory as IPointCategory; if (pc == null) continue; IPointSymbolizer ps = selected ? pc.SelectionSymbolizer : pc.Symbolizer; if (ps == null) continue; foreach (Coordinate c in feature.Geometry.Coordinates) { DrawPoint(c.X, c.Y, e, ps, g, origTransform); } } if (e.Device == null) g.Dispose(); else g.Transform = origTransform; } /// <summary> /// Draws a point at the given location. /// </summary> /// <param name="ptX">X-Coordinate of the point, that should be drawn.</param> /// <param name="ptY">Y-Coordinate of the point, that should be drawn.</param> /// <param name="e">MapArgs for calculating the scaleSize.</param> /// <param name="ps">PointSymbolizer with which the point gets drawn.</param> /// <param name="g">Graphics-Object that should be used by the PointSymbolizer.</param> /// <param name="origTransform">The original transformation that is used to position the point.</param> private void DrawPoint(double ptX, double ptY, MapArgs e, IPointSymbolizer ps, Graphics g, Matrix origTransform) { var pt = new Point { X = Convert.ToInt32((ptX - e.MinX) * e.Dx), Y = Convert.ToInt32((e.MaxY - ptY) * e.Dy) }; double scaleSize = ps.GetScale(e); // CGX if (MapFrame != null && (MapFrame as IMapFrame).ReferenceScale > 1.0 && (MapFrame as IMapFrame).CurrentScale > 0.0) { double dReferenceScale = (MapFrame as IMapFrame).ReferenceScale; double dCurrentScale = (MapFrame as IMapFrame).CurrentScale; scaleSize = dReferenceScale / dCurrentScale; } // Fin CGX Matrix shift = origTransform.Clone(); shift.Translate(pt.X, pt.Y); g.Transform = shift; ps.Draw(g, scaleSize); } #endregion #region CGX /// <summary> /// Constructor /// </summary> /// <param name="inFeatureSet"></param> public MapPointLayer(IFeatureSet inFeatureSet, FastDrawnState[] inVisibility) : base(inFeatureSet) { Configure(); OnFinishedLoading(); Visibility = inVisibility; } FastDrawnState[] _Visibility = null; [Serialize("FastDrawnState", ConstructorArgumentIndex = 1)] public FastDrawnState[] Visibility { get { return _Visibility; } set { _Visibility = value; } } public void StoreVisibility() { Visibility = DrawnStates; } public void SetVisibility() { DrawnStatesNeeded = true; if (_Visibility != null && DrawnStates != null && _Visibility.Length == DrawnStates.Length) { for (int i = 0; i < _Visibility.Length; i++) { DrawnStates[i].Visible = _Visibility[i].Visible; } } } #endregion } }
namespace Epi.Windows.Analysis.Dialogs { partial class WriteDialog { /// <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(WriteDialog)); this.cbxAllExcept = new System.Windows.Forms.CheckBox(); this.label1 = new System.Windows.Forms.Label(); this.lbxVariables = new System.Windows.Forms.ListBox(); this.gbxOutputMode = new System.Windows.Forms.GroupBox(); this.rdbReplace = new System.Windows.Forms.RadioButton(); this.rdbAppend = new System.Windows.Forms.RadioButton(); this.lblOutputFormat = new System.Windows.Forms.Label(); this.cmbOutputFormat = new System.Windows.Forms.ComboBox(); this.btnGetFile = new System.Windows.Forms.Button(); this.txtFileName = new System.Windows.Forms.TextBox(); this.lblFilename = new System.Windows.Forms.Label(); this.cmbDataTable = new System.Windows.Forms.ComboBox(); this.lblDataTable = new System.Windows.Forms.Label(); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.gbxOutputMode.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); // // cbxAllExcept // resources.ApplyResources(this.cbxAllExcept, "cbxAllExcept"); this.cbxAllExcept.Name = "cbxAllExcept"; // // label1 // this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // lbxVariables // resources.ApplyResources(this.lbxVariables, "lbxVariables"); this.lbxVariables.Name = "lbxVariables"; this.lbxVariables.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple; this.lbxVariables.TabStop = false; this.lbxVariables.SelectedValueChanged += new System.EventHandler(this.SomethingChanged); // // gbxOutputMode // resources.ApplyResources(this.gbxOutputMode, "gbxOutputMode"); this.gbxOutputMode.Controls.Add(this.rdbReplace); this.gbxOutputMode.Controls.Add(this.rdbAppend); this.gbxOutputMode.FlatStyle = System.Windows.Forms.FlatStyle.System; this.gbxOutputMode.Name = "gbxOutputMode"; this.gbxOutputMode.TabStop = false; // // rdbReplace // resources.ApplyResources(this.rdbReplace, "rdbReplace"); this.rdbReplace.Name = "rdbReplace"; // // rdbAppend // this.rdbAppend.Checked = true; resources.ApplyResources(this.rdbAppend, "rdbAppend"); this.rdbAppend.Name = "rdbAppend"; this.rdbAppend.TabStop = true; // // lblOutputFormat // resources.ApplyResources(this.lblOutputFormat, "lblOutputFormat"); this.lblOutputFormat.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblOutputFormat.Name = "lblOutputFormat"; // // cmbOutputFormat // resources.ApplyResources(this.cmbOutputFormat, "cmbOutputFormat"); this.cmbOutputFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cmbOutputFormat.Items.AddRange(new object[] { resources.GetString("cmbOutputFormat.Items"), resources.GetString("cmbOutputFormat.Items1"), resources.GetString("cmbOutputFormat.Items2"), resources.GetString("cmbOutputFormat.Items3")}); this.cmbOutputFormat.Name = "cmbOutputFormat"; this.cmbOutputFormat.SelectedIndexChanged += new System.EventHandler(this.FormatChanged); // // btnGetFile // resources.ApplyResources(this.btnGetFile, "btnGetFile"); this.btnGetFile.Name = "btnGetFile"; this.btnGetFile.Click += new System.EventHandler(this.btnGetFile_Click); // // txtFileName // resources.ApplyResources(this.txtFileName, "txtFileName"); this.txtFileName.Name = "txtFileName"; this.txtFileName.ReadOnly = true; this.txtFileName.TextChanged += new System.EventHandler(this.FileNameChanged); // // lblFilename // resources.ApplyResources(this.lblFilename, "lblFilename"); this.lblFilename.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblFilename.Name = "lblFilename"; // // cmbDataTable // resources.ApplyResources(this.cmbDataTable, "cmbDataTable"); this.cmbDataTable.Name = "cmbDataTable"; this.cmbDataTable.TextChanged += new System.EventHandler(this.SomethingChanged); // // lblDataTable // resources.ApplyResources(this.lblDataTable, "lblDataTable"); this.lblDataTable.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblDataTable.Name = "lblDataTable"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // WriteDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnClear); this.Controls.Add(this.cmbDataTable); this.Controls.Add(this.lblDataTable); this.Controls.Add(this.btnGetFile); this.Controls.Add(this.txtFileName); this.Controls.Add(this.lblFilename); this.Controls.Add(this.cmbOutputFormat); this.Controls.Add(this.lblOutputFormat); this.Controls.Add(this.gbxOutputMode); this.Controls.Add(this.lbxVariables); this.Controls.Add(this.label1); this.Controls.Add(this.cbxAllExcept); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "WriteDialog"; this.Load += new System.EventHandler(this.Write_Load); this.gbxOutputMode.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtFileName; private System.Windows.Forms.Label lblFilename; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.CheckBox cbxAllExcept; private System.Windows.Forms.GroupBox gbxOutputMode; private System.Windows.Forms.RadioButton rdbReplace; private System.Windows.Forms.RadioButton rdbAppend; private System.Windows.Forms.Label lblOutputFormat; private System.Windows.Forms.ComboBox cmbOutputFormat; private System.Windows.Forms.Button btnGetFile; private System.Windows.Forms.ComboBox cmbDataTable; private System.Windows.Forms.Label lblDataTable; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.ListBox lbxVariables; } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Math.Splines; using BitmapFont = FlatRedBall.Graphics.BitmapFont; using Cursor = FlatRedBall.Gui.Cursor; using GuiManager = FlatRedBall.Gui.GuiManager; using GlueTestProject.DataTypes; #if FRB_XNA || SILVERLIGHT using Keys = Microsoft.Xna.Framework.Input.Keys; using Vector3 = Microsoft.Xna.Framework.Vector3; using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D; using FlatRedBall.Screens; #elif FRB_MDX using Keys = Microsoft.DirectX.DirectInput.Key; #endif namespace GlueTestProject.Entities { public partial class PlatformerCharacterBase { #region Fields bool mIsOnGround = false; bool mHitHead = false; bool mHasDoubleJumped = false; double mTimeJumpPushed = double.NegativeInfinity; MovementValues mValuesJumpedWith; MovementValues mCurrentMovement; HorizontalDirection mDirectionFacing; MovementType mMovementType; double mLastCollisionTime = -1; #endregion #region Properties double CurrentTime { get { if (ScreenManager.CurrentScreen != null) { return ScreenManager.CurrentScreen.PauseAdjustedCurrentTime; } else { return TimeManager.CurrentTime; } } } MovementValues CurrentMovement { get { return mCurrentMovement; } } HorizontalDirection DirectionFacing { get { return mDirectionFacing; } } public FlatRedBall.Input.IPressableInput JumpInput { get; set; } public FlatRedBall.Input.I1DInput HorizontalInput { get; set; } protected virtual float HorizontalRatio { get { if(!InputEnabled) { return 0; } else { return HorizontalInput.Value; } } } public bool IsOnGround { get { return mIsOnGround; } } public MovementType CurrentMovementType { get { return mMovementType; } set { mMovementType = value; switch (mMovementType) { case MovementType.Ground: mCurrentMovement = GroundMovement; break; case MovementType.Air: mCurrentMovement = AirMovement; break; case MovementType.AfterDoubleJump: mCurrentMovement = AfterDoubleJump; break; } } } public bool InputEnabled { get; set; } #endregion private void CustomInitialize() { if (FlatRedBall.Input.InputManager.Xbox360GamePads [0].IsConnected) { this.JumpInput = FlatRedBall.Input.InputManager.Xbox360GamePads [0].GetButton (FlatRedBall.Input.Xbox360GamePad.Button.A); this.HorizontalInput = FlatRedBall.Input.InputManager.Xbox360GamePads[0].LeftStick.Horizontal; } else { this.JumpInput = FlatRedBall.Input.InputManager.Keyboard.GetKey (Keys.Space); this.HorizontalInput = FlatRedBall.Input.InputManager.Keyboard.Get1DInput(Keys.Left, Keys.Right); } InputEnabled = true; CurrentMovementType = MovementType.Ground; YAcceleration = this.CurrentMovement.Gravity; } private void CustomActivity() { InputActivity(); } private void InputActivity() { HorizontalMovementActivity(); JumpVelocity(); } private void JumpVelocity() { bool jumpPushed = JumpInput.WasJustPressed && InputEnabled; bool jumpDown = JumpInput.IsDown && InputEnabled; if (jumpPushed && CurrentMovement.JumpVelocity > 0 && (mIsOnGround || AfterDoubleJump == null || (AfterDoubleJump != null && mHasDoubleJumped == false)) ) { mTimeJumpPushed = CurrentTime; this.YVelocity = CurrentMovement.JumpVelocity; mValuesJumpedWith = CurrentMovement; if (CurrentMovementType == MovementType.Air) { mHasDoubleJumped = true ; } } double secondsSincePush = CurrentTime - mTimeJumpPushed; if (mValuesJumpedWith != null && secondsSincePush < mValuesJumpedWith.JumpApplyLength && (mValuesJumpedWith.JumpApplyByButtonHold == false || JumpInput.IsDown) ) { this.YVelocity = mValuesJumpedWith.JumpVelocity; } if (mValuesJumpedWith != null && mValuesJumpedWith.JumpApplyByButtonHold && (!JumpInput.IsDown || mHitHead) ) { mValuesJumpedWith = null; } this.YVelocity = Math.Max(-CurrentMovement.MaxFallSpeed, this.YVelocity); } private void HorizontalMovementActivity() { float horizontalRatio = HorizontalRatio; if(horizontalRatio > 0) { mDirectionFacing = HorizontalDirection.Right; } else if(horizontalRatio < 0) { mDirectionFacing = HorizontalDirection.Left; } if (this.CurrentMovement.AccelerationTimeX <= 0) { this.XVelocity = horizontalRatio * CurrentMovement.MaxSpeedX; } else { float acceleration = CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX; float sign = Math.Sign(horizontalRatio); float magnitude = Math.Abs(horizontalRatio); if(sign == 0) { sign = -Math.Sign(XVelocity); magnitude = 1; } if (XVelocity == 0 || sign == Math.Sign(XVelocity)) { this.XAcceleration = sign * magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX; } else { float accelerationValue = magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.DecelerationTimeX; if (Math.Abs(XVelocity) < accelerationValue * TimeManager.SecondDifference) { this.XAcceleration = 0; this.XVelocity = 0; } else { // slowing down this.XAcceleration = sign * accelerationValue; } } XVelocity = Math.Min(XVelocity, CurrentMovement.MaxSpeedX); XVelocity = Math.Max(XVelocity, -CurrentMovement.MaxSpeedX); } } private void CustomDestroy() { } private static void CustomLoadStaticContent(string contentManagerName) { } public void CollideAgainst(ShapeCollection shapeCollection) { CollideAgainst(shapeCollection, false); } public void CollideAgainst(ShapeCollection shapeCollection, bool isCloudCollision) { CollideAgainst(() => shapeCollection.CollideAgainstBounceWithoutSnag(this.Collision, 0), isCloudCollision); } public void CollideAgainst(Func<bool> collisionFunction, bool isCloudCollision) { Vector3 positionBeforeCollision = this.Position; Vector3 velocityBeforeCollision = this.Velocity; float lastY = this.Y; bool isFirstCollisionOfTheFrame = TimeManager.CurrentTime != mLastCollisionTime; if (isFirstCollisionOfTheFrame) { mLastCollisionTime = TimeManager.CurrentTime; mIsOnGround = false; mHitHead = false; } if(isCloudCollision == false || velocityBeforeCollision.Y < 0) { if (collisionFunction()) { // make sure that we've been moved up, and that we're falling bool shouldApplyCollision = true; if (isCloudCollision) { if (this.Y <= positionBeforeCollision.Y) { shouldApplyCollision = false; } } if (shouldApplyCollision) { if (this.Y > lastY) { mIsOnGround = true; } if (this.Y < lastY) { mHitHead = true; } } else { Position = positionBeforeCollision; Velocity = velocityBeforeCollision; } } } } public virtual void DetermineMovementValues() { if (mIsOnGround) { mHasDoubleJumped = false; if (CurrentMovementType == MovementType.Air || CurrentMovementType == MovementType.AfterDoubleJump) { CurrentMovementType = MovementType.Ground; } } else { if (CurrentMovementType == MovementType.Ground) { CurrentMovementType = MovementType.Air; } } if (CurrentMovementType == MovementType.Air && mHasDoubleJumped) { CurrentMovementType = MovementType.AfterDoubleJump; } } public virtual void SetAnimations(AnimationChainList animations) { if(this.MainSprite != null) { string chainToSet = GetChainToSet(); if(!string.IsNullOrEmpty(chainToSet)) { bool differs = MainSprite.CurrentChainName == null || MainSprite.CurrentChainName != chainToSet; if(differs) { this.MainSprite.SetAnimationChain(animations[chainToSet]); } } } } protected virtual string GetChainToSet() { string chainToSet = null; if (IsOnGround == false) { if (mDirectionFacing == HorizontalDirection.Right) { if (this.YVelocity > 0) { chainToSet = "JumpRight"; } else { chainToSet = "FallRight"; } } else { if (this.YVelocity > 0) { chainToSet = "JumpLeft"; } else { chainToSet = "FallLeft"; } } } else if (HorizontalRatio != 0) { if (mDirectionFacing == HorizontalDirection.Right) { chainToSet = "WalkRight"; } else { chainToSet = "WalkLeft"; } } else { if (mDirectionFacing == HorizontalDirection.Right) { chainToSet = "StandRight"; } else { chainToSet = "StandLeft"; } } return chainToSet; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Uheer.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Speech.V1 { /// <summary>Settings for <see cref="SpeechClient"/> instances.</summary> public sealed partial class SpeechSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="SpeechSettings"/>.</summary> /// <returns>A new instance of the default <see cref="SpeechSettings"/>.</returns> public static SpeechSettings GetDefault() => new SpeechSettings(); /// <summary>Constructs a new <see cref="SpeechSettings"/> object with default settings.</summary> public SpeechSettings() { } private SpeechSettings(SpeechSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); RecognizeSettings = existing.RecognizeSettings; LongRunningRecognizeSettings = existing.LongRunningRecognizeSettings; LongRunningRecognizeOperationsSettings = existing.LongRunningRecognizeOperationsSettings.Clone(); StreamingRecognizeSettings = existing.StreamingRecognizeSettings; StreamingRecognizeStreamingSettings = existing.StreamingRecognizeStreamingSettings; OnCopy(existing); } partial void OnCopy(SpeechSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>SpeechClient.Recognize</c> /// and <c>SpeechClient.RecognizeAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 5000 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings RecognizeSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(100), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SpeechClient.LongRunningRecognize</c> and <c>SpeechClient.LongRunningRecognizeAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 5000 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings LongRunningRecognizeSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000))); /// <summary> /// Long Running Operation settings for calls to <c>SpeechClient.LongRunningRecognize</c> and /// <c>SpeechClient.LongRunningRecognizeAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings LongRunningRecognizeOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>SpeechClient.StreamingRecognize</c> and <c>SpeechClient.StreamingRecognizeAsync</c>. /// </summary> /// <remarks>Timeout: 5000 seconds.</remarks> public gaxgrpc::CallSettings StreamingRecognizeSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(5000000))); /// <summary> /// <see cref="gaxgrpc::BidirectionalStreamingSettings"/> for calls to <c>SpeechClient.StreamingRecognize</c> /// and <c>SpeechClient.StreamingRecognizeAsync</c>. /// </summary> /// <remarks>The default local send queue size is 100.</remarks> public gaxgrpc::BidirectionalStreamingSettings StreamingRecognizeStreamingSettings { get; set; } = new gaxgrpc::BidirectionalStreamingSettings(100); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="SpeechSettings"/> object.</returns> public SpeechSettings Clone() => new SpeechSettings(this); } /// <summary> /// Builder class for <see cref="SpeechClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class SpeechClientBuilder : gaxgrpc::ClientBuilderBase<SpeechClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public SpeechSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public SpeechClientBuilder() { UseJwtAccessWithScopes = SpeechClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref SpeechClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<SpeechClient> task); /// <summary>Builds the resulting client.</summary> public override SpeechClient Build() { SpeechClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<SpeechClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<SpeechClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private SpeechClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return SpeechClient.Create(callInvoker, Settings); } private async stt::Task<SpeechClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return SpeechClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => SpeechClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => SpeechClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => SpeechClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>Speech client wrapper, for convenient use.</summary> /// <remarks> /// Service that implements Google Cloud Speech API. /// </remarks> public abstract partial class SpeechClient { /// <summary> /// The default endpoint for the Speech service, which is a host of "speech.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "speech.googleapis.com:443"; /// <summary>The default Speech scopes.</summary> /// <remarks> /// The default Speech scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="SpeechClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="SpeechClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="SpeechClient"/>.</returns> public static stt::Task<SpeechClient> CreateAsync(st::CancellationToken cancellationToken = default) => new SpeechClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="SpeechClient"/> using the default credentials, endpoint and settings. To /// specify custom credentials or other settings, use <see cref="SpeechClientBuilder"/>. /// </summary> /// <returns>The created <see cref="SpeechClient"/>.</returns> public static SpeechClient Create() => new SpeechClientBuilder().Build(); /// <summary> /// Creates a <see cref="SpeechClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="SpeechSettings"/>.</param> /// <returns>The created <see cref="SpeechClient"/>.</returns> internal static SpeechClient Create(grpccore::CallInvoker callInvoker, SpeechSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } Speech.SpeechClient grpcClient = new Speech.SpeechClient(callInvoker); return new SpeechClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC Speech client</summary> public virtual Speech.SpeechClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual RecognizeResponse Recognize(RecognizeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<RecognizeResponse> RecognizeAsync(RecognizeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<RecognizeResponse> RecognizeAsync(RecognizeRequest request, st::CancellationToken cancellationToken) => RecognizeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual RecognizeResponse Recognize(RecognitionConfig config, RecognitionAudio audio, gaxgrpc::CallSettings callSettings = null) => Recognize(new RecognizeRequest { Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<RecognizeResponse> RecognizeAsync(RecognitionConfig config, RecognitionAudio audio, gaxgrpc::CallSettings callSettings = null) => RecognizeAsync(new RecognizeRequest { Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<RecognizeResponse> RecognizeAsync(RecognitionConfig config, RecognitionAudio audio, st::CancellationToken cancellationToken) => RecognizeAsync(config, audio, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(LongRunningRecognizeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(LongRunningRecognizeRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(LongRunningRecognizeRequest request, st::CancellationToken cancellationToken) => LongRunningRecognizeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>LongRunningRecognize</c>.</summary> public virtual lro::OperationsClient LongRunningRecognizeOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>LongRunningRecognize</c> /// . /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> PollOnceLongRunningRecognize(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), LongRunningRecognizeOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>LongRunningRecognize</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> PollOnceLongRunningRecognizeAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), LongRunningRecognizeOperationsClient, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(RecognitionConfig config, RecognitionAudio audio, gaxgrpc::CallSettings callSettings = null) => LongRunningRecognize(new LongRunningRecognizeRequest { Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(RecognitionConfig config, RecognitionAudio audio, gaxgrpc::CallSettings callSettings = null) => LongRunningRecognizeAsync(new LongRunningRecognizeRequest { Config = gax::GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = gax::GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="config"> /// Required. Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// Required. The audio data to be recognized. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(RecognitionConfig config, RecognitionAudio audio, st::CancellationToken cancellationToken) => LongRunningRecognizeAsync(config, audio, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Bidirectional streaming methods for /// <see cref="StreamingRecognize(gaxgrpc::CallSettings,gaxgrpc::BidirectionalStreamingSettings)"/>. /// </summary> public abstract partial class StreamingRecognizeStream : gaxgrpc::BidirectionalStreamingBase<StreamingRecognizeRequest, StreamingRecognizeResponse> { } /// <summary> /// Performs bidirectional streaming speech recognition: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public virtual StreamingRecognizeStream StreamingRecognize(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) => throw new sys::NotImplementedException(); } /// <summary>Speech client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service that implements Google Cloud Speech API. /// </remarks> public sealed partial class SpeechClientImpl : SpeechClient { private readonly gaxgrpc::ApiCall<RecognizeRequest, RecognizeResponse> _callRecognize; private readonly gaxgrpc::ApiCall<LongRunningRecognizeRequest, lro::Operation> _callLongRunningRecognize; private readonly gaxgrpc::ApiBidirectionalStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> _callStreamingRecognize; /// <summary> /// Constructs a client wrapper for the Speech service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="SpeechSettings"/> used within this client.</param> public SpeechClientImpl(Speech.SpeechClient grpcClient, SpeechSettings settings) { GrpcClient = grpcClient; SpeechSettings effectiveSettings = settings ?? SpeechSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); LongRunningRecognizeOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.LongRunningRecognizeOperationsSettings); _callRecognize = clientHelper.BuildApiCall<RecognizeRequest, RecognizeResponse>(grpcClient.RecognizeAsync, grpcClient.Recognize, effectiveSettings.RecognizeSettings); Modify_ApiCall(ref _callRecognize); Modify_RecognizeApiCall(ref _callRecognize); _callLongRunningRecognize = clientHelper.BuildApiCall<LongRunningRecognizeRequest, lro::Operation>(grpcClient.LongRunningRecognizeAsync, grpcClient.LongRunningRecognize, effectiveSettings.LongRunningRecognizeSettings); Modify_ApiCall(ref _callLongRunningRecognize); Modify_LongRunningRecognizeApiCall(ref _callLongRunningRecognize); _callStreamingRecognize = clientHelper.BuildApiCall<StreamingRecognizeRequest, StreamingRecognizeResponse>(grpcClient.StreamingRecognize, effectiveSettings.StreamingRecognizeSettings, effectiveSettings.StreamingRecognizeStreamingSettings); Modify_ApiCall(ref _callStreamingRecognize); Modify_StreamingRecognizeApiCall(ref _callStreamingRecognize); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiBidirectionalStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_RecognizeApiCall(ref gaxgrpc::ApiCall<RecognizeRequest, RecognizeResponse> call); partial void Modify_LongRunningRecognizeApiCall(ref gaxgrpc::ApiCall<LongRunningRecognizeRequest, lro::Operation> call); partial void Modify_StreamingRecognizeApiCall(ref gaxgrpc::ApiBidirectionalStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call); partial void OnConstruction(Speech.SpeechClient grpcClient, SpeechSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC Speech client</summary> public override Speech.SpeechClient GrpcClient { get; } partial void Modify_RecognizeRequest(ref RecognizeRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_LongRunningRecognizeRequest(ref LongRunningRecognizeRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_StreamingRecognizeRequestCallSettings(ref gaxgrpc::CallSettings settings); partial void Modify_StreamingRecognizeRequestRequest(ref StreamingRecognizeRequest request); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override RecognizeResponse Recognize(RecognizeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RecognizeRequest(ref request, ref callSettings); return _callRecognize.Sync(request, callSettings); } /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<RecognizeResponse> RecognizeAsync(RecognizeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RecognizeRequest(ref request, ref callSettings); return _callRecognize.Async(request, callSettings); } /// <summary>The long-running operations client for <c>LongRunningRecognize</c>.</summary> public override lro::OperationsClient LongRunningRecognizeOperationsClient { get; } /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize(LongRunningRecognizeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LongRunningRecognizeRequest(ref request, ref callSettings); return new lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>(_callLongRunningRecognize.Sync(request, callSettings), LongRunningRecognizeOperationsClient); } /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// For more information on asynchronous speech recognition, see the /// [how-to](https://cloud.google.com/speech-to-text/docs/async-recognize). /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync(LongRunningRecognizeRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_LongRunningRecognizeRequest(ref request, ref callSettings); return new lro::Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>(await _callLongRunningRecognize.Async(request, callSettings).ConfigureAwait(false), LongRunningRecognizeOperationsClient); } internal sealed partial class StreamingRecognizeStreamImpl : StreamingRecognizeStream { /// <summary>Construct the bidirectional streaming method for <c>StreamingRecognize</c>.</summary> /// <param name="service">The service containing this streaming method.</param> /// <param name="call">The underlying gRPC duplex streaming call.</param> /// <param name="writeBuffer"> /// The <see cref="gaxgrpc::BufferedClientStreamWriter{StreamingRecognizeRequest}"/> instance associated /// with this streaming call. /// </param> public StreamingRecognizeStreamImpl(SpeechClientImpl service, grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call, gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer) { _service = service; GrpcCall = call; _writeBuffer = writeBuffer; } private SpeechClientImpl _service; private gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> _writeBuffer; public override grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> GrpcCall { get; } private StreamingRecognizeRequest ModifyRequest(StreamingRecognizeRequest request) { _service.Modify_StreamingRecognizeRequestRequest(ref request); return request; } public override stt::Task TryWriteAsync(StreamingRecognizeRequest message) => _writeBuffer.TryWriteAsync(ModifyRequest(message)); public override stt::Task WriteAsync(StreamingRecognizeRequest message) => _writeBuffer.WriteAsync(ModifyRequest(message)); public override stt::Task TryWriteAsync(StreamingRecognizeRequest message, grpccore::WriteOptions options) => _writeBuffer.TryWriteAsync(ModifyRequest(message), options); public override stt::Task WriteAsync(StreamingRecognizeRequest message, grpccore::WriteOptions options) => _writeBuffer.WriteAsync(ModifyRequest(message), options); public override stt::Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync(); public override stt::Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync(); } /// <summary> /// Performs bidirectional streaming speech recognition: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <param name="streamingSettings">If not null, applies streaming overrides to this RPC call.</param> /// <returns>The client-server stream.</returns> public override SpeechClient.StreamingRecognizeStream StreamingRecognize(gaxgrpc::CallSettings callSettings = null, gaxgrpc::BidirectionalStreamingSettings streamingSettings = null) { Modify_StreamingRecognizeRequestCallSettings(ref callSettings); gaxgrpc::BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callStreamingRecognize.StreamingSettings; grpccore::AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call = _callStreamingRecognize.Call(callSettings); gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer = new gaxgrpc::BufferedClientStreamWriter<StreamingRecognizeRequest>(call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity); return new StreamingRecognizeStreamImpl(this, call, writeBuffer); } } public static partial class Speech { public partial class SpeechClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
// 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.Completion.Providers; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Snippets; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion { internal abstract partial class AbstractCompletionService : ICompletionService { private static readonly Func<string, List<CompletionItem>> s_createList = _ => new List<CompletionItem>(); private const int MruSize = 10; private readonly List<string> _committedItems = new List<string>(MruSize); private readonly object _mruGate = new object(); internal void CompletionItemCommitted(CompletionItem item) { lock (_mruGate) { // We need to remove the item if it's already in the list. // If we're at capacity, we need to remove the LRU item. var removed = _committedItems.Remove(item.DisplayText); if (!removed && _committedItems.Count == MruSize) { _committedItems.RemoveAt(0); } _committedItems.Add(item.DisplayText); } } internal int GetMRUIndex(CompletionItem item) { lock (_mruGate) { // A lower value indicates more recently used. Since items are added // to the end of the list, our result just maps to the negation of the // index. // -1 => 1 == Not Found // 0 => 0 == least recently used // 9 => -9 == most recently used var index = _committedItems.IndexOf(item.DisplayText); return -index; } } public void ClearMRUCache() { lock (_mruGate) { _committedItems.Clear(); } } /// <summary> /// Apply any culture-specific quirks to the given text for the purposes of pattern matching. /// For example, in the Turkish locale, capital 'i's should be treated specially in Visual Basic. /// </summary> public virtual string GetCultureSpecificQuirks(string candidate) { return candidate; } public abstract IEnumerable<CompletionListProvider> GetDefaultCompletionProviders(); protected abstract string GetLanguageName(); private class ProviderList { public CompletionListProvider Provider; public CompletionList List; } public async Task<CompletionList> GetCompletionListAsync( Document document, int position, CompletionTriggerInfo triggerInfo, OptionSet options, IEnumerable<CompletionListProvider> providers, CancellationToken cancellationToken) { options = options ?? document.Project.Solution.Workspace.Options; providers = providers ?? GetDefaultCompletionProviders(); var completionProviderToIndex = GetCompletionProviderToIndex(providers); var completionRules = GetCompletionRules(); var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); IEnumerable<CompletionListProvider> triggeredProviders; switch (triggerInfo.TriggerReason) { case CompletionTriggerReason.TypeCharCommand: triggeredProviders = providers.Where(p => p.IsTriggerCharacter(text, position - 1, options)).ToList(); break; case CompletionTriggerReason.BackspaceOrDeleteCommand: triggeredProviders = this.TriggerOnBackspace(text, position, triggerInfo, options) ? providers : SpecializedCollections.EmptyEnumerable<CompletionListProvider>(); break; default: triggeredProviders = providers; break; } // Now, ask all the triggered providers if they can provide a group. var providersAndLists = new List<ProviderList>(); foreach (var provider in triggeredProviders) { var completionList = await GetCompletionListAsync(provider, document, position, triggerInfo, options, cancellationToken).ConfigureAwait(false); if (completionList != null) { providersAndLists.Add(new ProviderList { Provider = provider, List = completionList }); } } // See if there was a group provided that was exclusive and had items in it. If so, then // that's all we'll return. var firstExclusiveList = providersAndLists.FirstOrDefault( t => t.List.IsExclusive && t.List.Items.Any()); if (firstExclusiveList != null) { return MergeAndPruneCompletionLists(SpecializedCollections.SingletonEnumerable(firstExclusiveList.List), completionRules); } // If no exclusive providers provided anything, then go through the remaining // triggered list and see if any provide items. var nonExclusiveLists = providersAndLists.Where(t => !t.List.IsExclusive).ToList(); // If we still don't have any items, then we're definitely done. if (!nonExclusiveLists.Any(g => g.List.Items.Any())) { return null; } // If we do have items, then ask all the other (non exclusive providers) if they // want to augment the items. var usedProviders = nonExclusiveLists.Select(g => g.Provider); var nonUsedProviders = providers.Except(usedProviders); var nonUsedNonExclusiveProviders = new List<ProviderList>(); foreach (var provider in nonUsedProviders) { var completionList = await GetCompletionListAsync(provider, document, position, triggerInfo, options, cancellationToken).ConfigureAwait(false); if (completionList != null && !completionList.IsExclusive) { nonUsedNonExclusiveProviders.Add(new ProviderList { Provider = provider, List = completionList }); } } var allProvidersAndLists = nonExclusiveLists.Concat(nonUsedNonExclusiveProviders).ToList(); if (allProvidersAndLists.Count == 0) { return null; } // Providers are ordered, but we processed them in our own order. Ensure that the // groups are properly ordered based on the original providers. allProvidersAndLists.Sort((p1, p2) => completionProviderToIndex[p1.Provider] - completionProviderToIndex[p2.Provider]); return MergeAndPruneCompletionLists(allProvidersAndLists.Select(g => g.List), completionRules); } private static CompletionList MergeAndPruneCompletionLists(IEnumerable<CompletionList> completionLists, CompletionRules completionRules) { var displayNameToItemsMap = new Dictionary<string, List<CompletionItem>>(); CompletionItem builder = null; foreach (var completionList in completionLists) { Contract.Assert(completionList != null); foreach (var item in completionList.Items) { Contract.Assert(item != null); // New items that match an existing item will replace it. ReplaceExistingItem(item, displayNameToItemsMap, completionRules); } builder = builder ?? completionList.Builder; } if (displayNameToItemsMap.Count == 0) { return null; } // TODO(DustinCa): Revisit performance of this. var totalItems = displayNameToItemsMap.Values.Flatten().ToList(); totalItems.Sort(); // TODO(DustinCa): This is lossy -- we lose the IsExclusive field. Fix that. return new CompletionList(totalItems.ToImmutableArray(), builder); } private static void ReplaceExistingItem( CompletionItem item, Dictionary<string, List<CompletionItem>> displayNameToItemsMap, CompletionRules completionRules) { // See if we have an item with var sameNamedItems = displayNameToItemsMap.GetOrAdd(item.DisplayText, s_createList); for (int i = 0; i < sameNamedItems.Count; i++) { var existingItem = sameNamedItems[i]; Contract.Assert(item.DisplayText == existingItem.DisplayText); if (completionRules.ItemsMatch(item, existingItem)) { sameNamedItems[i] = Disambiguate(item, existingItem); return; } } sameNamedItems.Add(item); } private static CompletionItem Disambiguate(CompletionItem item, CompletionItem existingItem) { // We've constructed the export order of completion providers so // that snippets are exported after everything else. That way, // when we choose a single item per display text, snippet // glyphs appear by snippets. This breaks preselection of items // whose display text is also a snippet (workitem 852578), // the snippet item doesn't have its preselect bit set. // We'll special case this by not preferring later items // if they are snippets and the other candidate is preselected. if (existingItem.MatchPriority != MatchPriority.Default && item.CompletionProvider is ISnippetCompletionProvider) { return existingItem; } // If one is a keyword, and the other is some other item that inserts the same text as the keyword, // keep the keyword var keywordItem = existingItem as KeywordCompletionItem ?? item as KeywordCompletionItem; if (keywordItem != null) { return keywordItem; } return item; } private Dictionary<CompletionListProvider, int> GetCompletionProviderToIndex(IEnumerable<CompletionListProvider> completionProviders) { var result = new Dictionary<CompletionListProvider, int>(); int i = 0; foreach (var completionProvider in completionProviders) { result[completionProvider] = i; i++; } return result; } private static async Task<CompletionList> GetCompletionListAsync( CompletionListProvider provider, Document document, int position, CompletionTriggerInfo triggerInfo, OptionSet options, CancellationToken cancellationToken) { var context = new CompletionListContext(document, position, triggerInfo, options, cancellationToken); if (document.SupportsSyntaxTree) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!root.FullSpan.IntersectsWith(position)) { try { // Trying to track down source of https://github.com/dotnet/roslyn/issues/9325 var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); ReportException(position, root, sourceText); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } } else { await provider.ProduceCompletionListAsync(context).ConfigureAwait(false); } } else { await provider.ProduceCompletionListAsync(context).ConfigureAwait(false); } return new CompletionList(context.GetItems(), context.Builder, context.IsExclusive); } private static void ReportException(int position, SyntaxNode root, SourceText sourceText) { throw new InvalidOperationException( $"Position '{position}' is not contained in SyntaxTree Span '{root.FullSpan}' source text length '{sourceText.Length}'"); } public bool IsTriggerCharacter(SourceText text, int characterPosition, IEnumerable<CompletionListProvider> completionProviders, OptionSet options) { if (!options.GetOption(CompletionOptions.TriggerOnTyping, GetLanguageName())) { return false; } completionProviders = completionProviders ?? GetDefaultCompletionProviders(); return completionProviders.Any(p => p.IsTriggerCharacter(text, characterPosition, options)); } protected abstract bool TriggerOnBackspace(SourceText text, int position, CompletionTriggerInfo triggerInfo, OptionSet options); public abstract Task<TextSpan> GetDefaultTrackingSpanAsync(Document document, int position, CancellationToken cancellationToken); public virtual CompletionRules GetCompletionRules() { return new CompletionRules(this); } public virtual bool DismissIfEmpty { get { return false; } } public Task<string> GetSnippetExpansionNoteForCompletionItemAsync(CompletionItem completionItem, Workspace workspace) { var insertionText = GetCompletionRules().GetTextChange(completionItem, '\t').NewText; var snippetInfoService = workspace.Services.GetLanguageServices(GetLanguageName()).GetService<ISnippetInfoService>(); if (snippetInfoService != null && snippetInfoService.SnippetShortcutExists_NonBlocking(insertionText)) { return Task.FromResult(string.Format(FeaturesResources.Note_colon_Tab_twice_to_insert_the_0_snippet, insertionText)); } return SpecializedTasks.Default<string>(); } public virtual bool SupportSnippetCompletionListOnTab { get { return false; } } public virtual bool DismissIfLastFilterCharacterDeleted { get { return false; } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: __Error ** ** ** Purpose: Centralized error methods. Used for translating ** Win32 HRESULTs into meaningful error strings & exceptions. ** ** ===========================================================*/ using System; using System.Globalization; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using UnsafeNativeMethods = Microsoft.Win32.UnsafeNativeMethods; namespace System.IO { // Only static data; no need to serialize internal static class __Error { internal static void EndOfFile() { throw new EndOfStreamException(SR.GetString(SR.IO_EOF_ReadBeyondEOF)); } internal static void FileNotOpen() { throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_FileClosed)); } internal static void PipeNotOpen() { throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_PipeClosed)); } internal static void StreamIsClosed() { throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_StreamIsClosed)); } internal static void ReadNotSupported() { throw new NotSupportedException(SR.GetString(SR.NotSupported_UnreadableStream)); } internal static void SeekNotSupported() { throw new NotSupportedException(SR.GetString(SR.NotSupported_UnseekableStream)); } internal static void WrongAsyncResult() { throw new ArgumentException(SR.GetString(SR.Argument_WrongAsyncResult)); } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work throw new ArgumentException(SR.GetString(SR.InvalidOperation_EndReadCalledMultiple)); } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work throw new ArgumentException(SR.GetString(SR.InvalidOperation_EndWriteCalledMultiple)); } internal static void EndWaitForConnectionCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work throw new ArgumentException(SR.GetString(SR.InvalidOperation_EndWaitForConnectionCalledMultiple)); } /// <summary> /// Given a possible fully qualified path, ensure that we have path discovery permission /// to that path. If we do not, return just the file name. If we know it is a directory, /// then don't return the directory name. /// </summary> /// <param name="path"></param> /// <param name="isInvalidPath"></param> /// <returns></returns> [SecuritySafeCritical] internal static String GetDisplayablePath(String path, bool isInvalidPath) { if (String.IsNullOrEmpty(path)) { return path; } // Is it a fully qualified path? bool isFullyQualified = false; if (path.Length < 2) { return path; } if ((path[0] == Path.DirectorySeparatorChar) && (path[1] == Path.DirectorySeparatorChar)) { isFullyQualified = true; } else if (path[1] == Path.VolumeSeparatorChar) { isFullyQualified = true; } if (!isFullyQualified && !isInvalidPath) { return path; } bool safeToReturn = false; try { if (!isInvalidPath) { new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }).Demand(); safeToReturn = true; } } catch (SecurityException) { } catch (ArgumentException) { // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters // inside FileIOPermission.AddPathList } catch (NotSupportedException) { // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path // beyond string index position 1. } if (!safeToReturn) { if ((path[path.Length - 1]) == Path.DirectorySeparatorChar) { path = SR.GetString(SR.IO_IO_NoPermissionToDirectoryName); } else { path = Path.GetFileName(path); } } return path; } [System.Security.SecurityCritical] internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } // After calling GetLastWin32Error(), it clears the last error field, so you must save the // HResult and pass it to this method. This method will determine the appropriate // exception to throw dependent on your error, and depending on the error, insert a string // into the message gotten from the ResourceManager. [System.Security.SecurityCritical] internal static void WinIOError(int errorCode, String maybeFullPath) { // This doesn't have to be perfect, but is a perf optimization. bool isInvalidPath = errorCode == UnsafeNativeMethods.ERROR_INVALID_NAME || errorCode == UnsafeNativeMethods.ERROR_BAD_PATHNAME; String str = GetDisplayablePath(maybeFullPath, isInvalidPath); switch (errorCode) { case UnsafeNativeMethods.ERROR_FILE_NOT_FOUND: if (str.Length == 0) { throw new FileNotFoundException(SR.GetString(SR.IO_FileNotFound)); } else { throw new FileNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.IO_FileNotFound_FileName), str), str); } case UnsafeNativeMethods.ERROR_PATH_NOT_FOUND: if (str.Length == 0) { throw new DirectoryNotFoundException(SR.GetString(SR.IO_PathNotFound_NoPathName)); } else { throw new DirectoryNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.IO_PathNotFound_Path), str)); } case UnsafeNativeMethods.ERROR_ACCESS_DENIED: if (str.Length == 0) { throw new UnauthorizedAccessException(SR.GetString(SR.UnauthorizedAccess_IODenied_NoPathName)); } else { throw new UnauthorizedAccessException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.UnauthorizedAccess_IODenied_Path), str)); } case UnsafeNativeMethods.ERROR_ALREADY_EXISTS: if (str.Length == 0) { goto default; } throw new IOException(SR.GetString(SR.IO_IO_AlreadyExists_Name, str), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); case UnsafeNativeMethods.ERROR_FILENAME_EXCED_RANGE: throw new PathTooLongException(SR.GetString(SR.IO_PathTooLong)); case UnsafeNativeMethods.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.IO_DriveNotFound_Drive), str)); case UnsafeNativeMethods.ERROR_INVALID_PARAMETER: throw new IOException(UnsafeNativeMethods.GetMessage(errorCode), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); case UnsafeNativeMethods.ERROR_SHARING_VIOLATION: if (str.Length == 0) { throw new IOException(SR.GetString(SR.IO_IO_SharingViolation_NoFileName), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); } else { throw new IOException(SR.GetString(SR.IO_IO_SharingViolation_File, str), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); } case UnsafeNativeMethods.ERROR_FILE_EXISTS: if (str.Length == 0) { goto default; } throw new IOException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.IO_IO_FileExists_Name), str), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); case UnsafeNativeMethods.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(); default: throw new IOException(UnsafeNativeMethods.GetMessage(errorCode), UnsafeNativeMethods.MakeHRFromErrorCode(errorCode)); } } internal static void WriteNotSupported() { throw new NotSupportedException(SR.GetString(SR.NotSupported_UnwritableStream)); } } }
//********************************************************* // // 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.Generic; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Printing; using Windows.Graphics.Printing; using Windows.Graphics.Printing.OptionDetails; using Windows.Storage.Streams; using SDKTemplate; namespace PrintSample { [Flags] internal enum DisplayContent : int { /// <summary> /// Show only text /// </summary> Text = 1, /// <summary> /// Show only images /// </summary> Images = 2, /// <summary> /// Show a combination of images and text /// </summary> TextAndImages = 3 } class CustomOptionsPrintHelper : PrintHelper { /// <summary> /// A flag that determines if text & images are to be shown /// </summary> internal DisplayContent imageText = DisplayContent.TextAndImages; /// <summary> /// Helper getter for text showing /// </summary> private bool ShowText { get { return (imageText & DisplayContent.Text) == DisplayContent.Text; } } /// <summary> /// Helper getter for image showing /// </summary> private bool ShowImage { get { return (imageText & DisplayContent.Images) == DisplayContent.Images; } } private bool showHeader = true; Task<IRandomAccessStreamWithContentType> wideMarginsIconTask; Task<IRandomAccessStreamWithContentType> moderateMarginsIconTask; Task<IRandomAccessStreamWithContentType> narrowMarginsIconTask; public CustomOptionsPrintHelper(Page scenarioPage) : base(scenarioPage) { // Start these tasks early because we know we're going to need the // streams in PrintTaskRequested. RandomAccessStreamReference wideMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/wideMargins.svg")); wideMarginsIconTask = wideMarginsIconReference.OpenReadAsync().AsTask(); RandomAccessStreamReference moderateMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/moderateMargins.svg")); moderateMarginsIconTask = moderateMarginsIconReference.OpenReadAsync().AsTask(); RandomAccessStreamReference narrowMarginsIconReference = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/narrowMargins.svg")); narrowMarginsIconTask = narrowMarginsIconReference.OpenReadAsync().AsTask(); } /// <summary> /// This is the event handler for PrintManager.PrintTaskRequested. /// In order to ensure a good user experience, the system requires that the app handle the PrintTaskRequested event within the time specified by PrintTaskRequestedEventArgs.Request.Deadline. /// Therefore, we use this handler to only create the print task. /// The print settings customization can be done when the print document source is requested. /// </summary> /// <param name="sender">PrintManager</param> /// <param name="e">PrintTaskRequestedEventArgs</param> protected override void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e) { PrintTask printTask = null; printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", async sourceRequestedArgs => { var deferral = sourceRequestedArgs.GetDeferral(); PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options); IList<string> displayedOptions = printDetailedOptions.DisplayedOptions; // Choose the printer options to be shown. // The order in which the options are appended determines the order in which they appear in the UI displayedOptions.Clear(); displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Copies); displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Orientation); displayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.ColorMode); // Create a new list option PrintCustomItemListOptionDetails pageFormat = printDetailedOptions.CreateItemListOption("PageContent", "Pictures"); pageFormat.AddItem("PicturesText", "Pictures and text"); pageFormat.AddItem("PicturesOnly", "Pictures only"); pageFormat.AddItem("TextOnly", "Text only"); // Add the custom option to the option list displayedOptions.Add("PageContent"); // Create a new toggle option "Show header". PrintCustomToggleOptionDetails header = printDetailedOptions.CreateToggleOption("Header", "Show header"); // App tells the user some more information about what the feature means. header.Description = "Display a header on the first page"; // Set the default value header.TrySetValue(showHeader); // Add the custom option to the option list displayedOptions.Add("Header"); // Create a new list option PrintCustomItemListOptionDetails margins = printDetailedOptions.CreateItemListOption("Margins", "Margins"); margins.AddItem("WideMargins", "Wide", "Each margin is 20% of the paper size", await wideMarginsIconTask); margins.AddItem("ModerateMargins", "Moderate", "Each margin is 10% of the paper size", await moderateMarginsIconTask); margins.AddItem("NarrowMargins", "Narrow", "Each margin is 5% of the paper size", await narrowMarginsIconTask); // The default is ModerateMargins ApplicationContentMarginTop = 0.1; ApplicationContentMarginLeft = 0.1; margins.TrySetValue("ModerateMargins"); // App tells the user some more information about what the feature means. margins.Description = "The space between the content of your document and the edge of the paper"; // Add the custom option to the option list displayedOptions.Add("Margins"); printDetailedOptions.OptionChanged += printDetailedOptions_OptionChanged; // Print Task event handler is invoked when the print job is completed. printTask.Completed += (s, args) => { // Notify the user when the print operation fails. if (args.Completion == PrintTaskCompletion.Failed) { MainPage.Current.NotifyUser("Failed to print.", NotifyType.ErrorMessage); } }; sourceRequestedArgs.SetSource(printDocumentSource); deferral.Complete(); }); } /// <summary> /// This is the event handler for whenever the user makes changes to the options. /// In this case, the options of interest are PageContent, Margins and Header. /// </summary> /// <param name="sender">PrintTaskOptionDetails</param> /// <param name="args">PrintTaskOptionChangedEventArgs</param> async void printDetailedOptions_OptionChanged(PrintTaskOptionDetails sender, PrintTaskOptionChangedEventArgs args) { bool invalidatePreview = false; string optionId = args.OptionId as string; if (string.IsNullOrEmpty(optionId)) { return; } if (optionId == "PageContent") { invalidatePreview = true; } if (optionId == "Margins") { PrintCustomItemListOptionDetails marginsOption = (PrintCustomItemListOptionDetails)sender.Options["Margins"]; string marginsValue = marginsOption.Value.ToString(); switch (marginsValue) { case "WideMargins": ApplicationContentMarginTop = 0.2; ApplicationContentMarginLeft = 0.2; break; case "ModerateMargins": ApplicationContentMarginTop = 0.1; ApplicationContentMarginLeft = 0.1; break; case "NarrowMargins": ApplicationContentMarginTop = 0.05; ApplicationContentMarginLeft = 0.05; break; } if (marginsValue == "NarrowMargins") { marginsOption.WarningText = "Narrow margins may not be supported by some printers"; } else { marginsOption.WarningText = ""; } invalidatePreview = true; } if (optionId == "Header") { PrintCustomToggleOptionDetails headerOption = (PrintCustomToggleOptionDetails)sender.Options["Header"]; showHeader = (bool)headerOption.Value; invalidatePreview = true; } if (invalidatePreview) { await scenarioPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { printDocument.InvalidatePreview(); }); } } #region PrintPreview protected override RichTextBlockOverflow AddOnePrintPreviewPage(RichTextBlockOverflow lastRTBOAdded, PrintPageDescription printPageDescription) { // Check if we need to hide/show text & images for this scenario // Since all is rulled by the first page (page flow), here is where we must start if (lastRTBOAdded == null) { // Get a refference to page objects Grid pageContent = (Grid)firstPage.FindName("PrintableArea"); Image scenarioImage = (Image)firstPage.FindName("ScenarioImage"); RichTextBlock mainText = (RichTextBlock)firstPage.FindName("TextContent"); RichTextBlockOverflow firstLink = (RichTextBlockOverflow)firstPage.FindName("FirstLinkedContainer"); RichTextBlockOverflow continuationLink = (RichTextBlockOverflow)firstPage.FindName("ContinuationPageLinkedContainer"); // Hide(collapse) and move elements in different grid cells depending by the viewable content(only text, only pictures) scenarioImage.Visibility = ShowImage ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed; firstLink.SetValue(Grid.ColumnSpanProperty, ShowImage ? 1 : 2); scenarioImage.SetValue(Grid.RowProperty, ShowText ? 2 : 1); scenarioImage.SetValue(Grid.ColumnProperty, ShowText ? 1 : 0); pageContent.ColumnDefinitions[0].Width = new GridLength(ShowText ? 6 : 4, GridUnitType.Star); pageContent.ColumnDefinitions[1].Width = new GridLength(ShowText ? 4 : 6, GridUnitType.Star); // Break the text flow if the app is not printing text in order not to spawn pages with blank content mainText.Visibility = ShowText ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed; continuationLink.Visibility = ShowText ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed; // Hide header if appropriate StackPanel header = (StackPanel)firstPage.FindName("Header"); header.Visibility = showHeader ? Windows.UI.Xaml.Visibility.Visible : Windows.UI.Xaml.Visibility.Collapsed; } //Continue with the rest of the base printing layout processing (paper size, printable page size) return base.AddOnePrintPreviewPage(lastRTBOAdded, printPageDescription); } protected override void CreatePrintPreviewPages(object sender, PaginateEventArgs e) { // Get PageContent property PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTaskOptions); string pageContent = (printDetailedOptions.Options["PageContent"].Value as string).ToLowerInvariant(); // Set the text & image display flag imageText = (DisplayContent)((Convert.ToInt32(pageContent.Contains("pictures")) << 1) | Convert.ToInt32(pageContent.Contains("text"))); base.CreatePrintPreviewPages(sender, e); } #endregion } /// <summary> /// Scenario that demos how to add custom options (specific for the application) /// </summary> public sealed partial class Scenario3CustomOptions : Page { private CustomOptionsPrintHelper printHelper; public Scenario3CustomOptions() { this.InitializeComponent(); } /// <summary> /// This is the click handler for the 'Print' button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OnPrintButtonClick(object sender, RoutedEventArgs e) { await printHelper.ShowPrintUIAsync(); } protected override void OnNavigatedTo(NavigationEventArgs e) { if (PrintManager.IsSupported()) { // Tell the user how to print MainPage.Current.NotifyUser("Print contract registered with customization, use the Print button to print.", NotifyType.StatusMessage); } else { // Remove the print button InvokePrintingButton.Visibility = Visibility.Collapsed; // Inform user that Printing is not supported MainPage.Current.NotifyUser("Printing is not supported.", NotifyType.ErrorMessage); // Printing-related event handlers will never be called if printing // is not supported, but it's okay to register for them anyway. } // Initalize common helper class and register for printing printHelper = new CustomOptionsPrintHelper(this); printHelper.RegisterForPrinting(); // Initialize print content for this scenario printHelper.PreparePrintContent(new PageToPrint()); } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (printHelper != null) { printHelper.UnregisterForPrinting(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Attributes for debugger ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Diagnostics { // // This attribute is used by the IL2IL toolchain to mark generated code to control debugger stepping policy // [System.Runtime.CompilerServices.DependencyReductionRoot] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] public sealed class DebuggerStepThroughAttribute : Attribute { public DebuggerStepThroughAttribute() { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] public sealed class DebuggerGuidedStepThroughAttribute : Attribute { public DebuggerGuidedStepThroughAttribute() { } } // This attribute is not in Win8P because it is not portable and so we aren't including it, if it turns out to be important we can consider // adding it into the next version of System.Diagnostics.Debug contract assembly //[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] //public sealed class DebuggerStepperBoundaryAttribute : Attribute //{ // public DebuggerStepperBoundaryAttribute() { } //} [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] public sealed class DebuggerHiddenAttribute : Attribute { public DebuggerHiddenAttribute() { } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)] public sealed class DebuggerNonUserCodeAttribute : Attribute { public DebuggerNonUserCodeAttribute() { } } // Attribute class used by the compiler to mark modules. // If present, then debugging information for everything in the // assembly was generated by the compiler, and will be preserved // by the Runtime so that the debugger can provide full functionality // in the case of JIT attach. If not present, then the compiler may // or may not have included debugging information, and the Runtime // won't preserve the debugging info, which will make debugging after // a JIT attach difficult. [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false)] public sealed class DebuggableAttribute : Attribute { [Flags] public enum DebuggingModes { None = 0x0, Default = 0x1, DisableOptimizations = 0x100, IgnoreSymbolStoreSequencePoints = 0x2, EnableEditAndContinue = 0x4 } public DebuggableAttribute(bool isJITTrackingEnabled, bool isJITOptimizerDisabled) { DebuggingFlags = 0; if (isJITTrackingEnabled) { DebuggingFlags |= DebuggingModes.Default; } if (isJITOptimizerDisabled) { DebuggingFlags |= DebuggingModes.DisableOptimizations; } } public DebuggableAttribute(DebuggingModes modes) { DebuggingFlags = modes; } public bool IsJITTrackingEnabled => (DebuggingFlags & DebuggingModes.Default) != 0; public bool IsJITOptimizerDisabled => (DebuggingFlags & DebuggingModes.DisableOptimizations) != 0; public DebuggingModes DebuggingFlags { get; } } // DebuggerBrowsableState states are defined as follows: // Never never show this element // Expanded expansion of the class is done, so that all visible internal members are shown // Collapsed expansion of the class is not performed. Internal visible members are hidden // RootHidden The target element itself should not be shown, but should instead be // automatically expanded to have its members displayed. // Default value is collapsed // Please also change the code which validates DebuggerBrowsableState variable (in this file) // if you change this enum. public enum DebuggerBrowsableState { Never = 0, //Expanded is not supported in this release //Expanded = 1, Collapsed = 2, RootHidden = 3 } // the one currently supported with the csee.dat // (mcee.dat, autoexp.dat) file. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] public sealed class DebuggerBrowsableAttribute : Attribute { private DebuggerBrowsableState _state; public DebuggerBrowsableAttribute(DebuggerBrowsableState state) { if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden) throw new ArgumentOutOfRangeException(nameof(state)); Contract.EndContractBlock(); _state = state; } public DebuggerBrowsableState State { get { return _state; } } } // DebuggerTypeProxyAttribute [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DebuggerTypeProxyAttribute : Attribute { private string _typeName; private string _targetName; private Type _target; public DebuggerTypeProxyAttribute(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } Contract.EndContractBlock(); _typeName = type.AssemblyQualifiedName; } public DebuggerTypeProxyAttribute(string typeName) { _typeName = typeName; } public string ProxyTypeName { get { return _typeName; } } public Type Target { set { if (value == null) { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); _targetName = value.AssemblyQualifiedName; _target = value; } get { return _target; } } public string TargetTypeName { get { return _targetName; } set { _targetName = value; } } } // This attribute is used to control what is displayed for the given class or field // in the data windows in the debugger. The single argument to this attribute is // the string that will be displayed in the value column for instances of the type. // This string can include text between { and } which can be either a field, // property or method (as will be documented in mscorlib). In the C# case, // a general expression will be allowed which only has implicit access to the this pointer // for the current instance of the target type. The expression will be limited, // however: there is no access to aliases, locals, or pointers. // In addition, attributes on properties referenced in the expression are not processed. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DebuggerDisplayAttribute : Attribute { private string _name; private string _value; private string _type; private string _targetName; private Type _target; public DebuggerDisplayAttribute(string value) { if (value == null) { _value = ""; } else { _value = value; } _name = ""; _type = ""; } public string Value { get { return _value; } } public string Name { get { return _name; } set { _name = value; } } public string Type { get { return _type; } set { _type = value; } } public Type Target { set { if (value == null) { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); _targetName = value.AssemblyQualifiedName; _target = value; } get { return _target; } } public string TargetTypeName { get { return _targetName; } set { _targetName = value; } } } ///// <summary> ///// Signifies that the attributed type has a visualizer which is pointed ///// to by the parameter type name strings. ///// </summary> //[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)] //public sealed class DebuggerVisualizerAttribute: Attribute //{ // private string visualizerObjectSourceName; // private string visualizerName; // private string description; // private string targetName; // private Type target; // public DebuggerVisualizerAttribute(string visualizerTypeName) // { // this.visualizerName = visualizerTypeName; // } // public DebuggerVisualizerAttribute(string visualizerTypeName, string visualizerObjectSourceTypeName) // { // this.visualizerName = visualizerTypeName; // this.visualizerObjectSourceName = visualizerObjectSourceTypeName; // } // public DebuggerVisualizerAttribute(string visualizerTypeName, Type visualizerObjectSource) // { // if (visualizerObjectSource == null) { // throw new ArgumentNullException("visualizerObjectSource"); // } // Contract.EndContractBlock(); // this.visualizerName = visualizerTypeName; // this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName; // } // public DebuggerVisualizerAttribute(Type visualizer) // { // if (visualizer == null) { // throw new ArgumentNullException("visualizer"); // } // Contract.EndContractBlock(); // this.visualizerName = visualizer.AssemblyQualifiedName; // } // public DebuggerVisualizerAttribute(Type visualizer, Type visualizerObjectSource) // { // if (visualizer == null) { // throw new ArgumentNullException("visualizer"); // } // if (visualizerObjectSource == null) { // throw new ArgumentNullException("visualizerObjectSource"); // } // Contract.EndContractBlock(); // this.visualizerName = visualizer.AssemblyQualifiedName; // this.visualizerObjectSourceName = visualizerObjectSource.AssemblyQualifiedName; // } // public DebuggerVisualizerAttribute(Type visualizer, string visualizerObjectSourceTypeName) // { // if (visualizer == null) { // throw new ArgumentNullException("visualizer"); // } // Contract.EndContractBlock(); // this.visualizerName = visualizer.AssemblyQualifiedName; // this.visualizerObjectSourceName = visualizerObjectSourceTypeName; // } // public string VisualizerObjectSourceTypeName // { // get { return visualizerObjectSourceName; } // } // public string VisualizerTypeName // { // get { return visualizerName; } // } // public string Description // { // get { return description; } // set { description = value; } // } // public Type Target // { // set { // if( value == null) { // throw new ArgumentNullException("value"); // } // Contract.EndContractBlock(); // targetName = value.AssemblyQualifiedName; // target = value; // } // get { return target; } // } // public string TargetTypeName // { // set { targetName = value; } // get { return targetName; } // } //} }
using System; using System.Collections.Generic; using PaletteInsightAgent.Output; using System.Configuration; using Microsoft.Win32; using System.IO; using YamlDotNet.Serialization; using NLog; using PaletteInsightAgent.Helpers; using PaletteInsightAgent.Output.OutputDrivers; using System.Text.RegularExpressions; using System.Management; namespace PaletteInsightAgent { namespace Configuration { /// <summary> /// A class for loading the configuration and converting it to /// the legacy PaletteInsightAgentOptions class. /// </summary> public class Loader { internal const string LOGFOLDER_DEFAULTS_FILE = "Config/LogFolders.yml"; internal const string PROCESSES_DEFAULT_FILE = "Config/Processes.yml"; private const string REPOSITORY_TABLES_FILE = "Config/Repository.yml"; private const string TABLEAU_SERVER_APPLICATION_SERVICE_NAME = "tabsvc"; private const int TABLEAU_VERSION_2018_2 = 20182; private static readonly Logger Log = LogManager.GetCurrentClassLogger(); /// <summary> /// Do the conversion of config types /// </summary> /// <param name="conf"></param> /// <param name="outConfig">the PaletteInsightAgentOptions instance to update, since its a singleton, we cannot /// call its constructor, hence we cannot return it.</param> public static void LoadConfigTo(PaletteInsightConfiguration config, string tableauRoot, PaletteInsightAgentOptions options) { options.PollInterval = config.PollInterval; options.LogPollInterval = config.LogPollInterval; options.UploadInterval = config.UploadInterval; options.RepoTablesPollInterval = config.RepoTablesPollInterval; options.StreamingTablesPollInterval = config.StreamingTablesPollInterval; options.ThreadInfoPollInterval = config.ThreadInfoPollInterval; options.ProcessedFilestTTL = config.ProcessedFilesTTL; options.StorageLimit = config.StorageLimit; options.AllProcesses = config.AllProcesses; options.PreferPassiveRepository = config.PreferPassiveRepository; options.AuthToken = config.InsightAuthToken; if (config.Webservice != null) { // Do not add the username or password here, as they come from the license options.WebserviceConfig = new WebserviceConfiguration { Endpoint = config.Webservice.Endpoint, UseProxy = config.Webservice.UseProxy, ProxyAddress = config.Webservice.ProxyAddress, ProxyUsername = config.Webservice.ProxyUsername, ProxyPassword = config.Webservice.ProxyPassword }; } else { // make sure the webservice config is null, so we wont write // to the webservice if its not configured options.WebserviceConfig = null; } // Load thread monitoring configuration options.Processes = new Dictionary<string, ProcessData>(); foreach (var process in LoadProcessData()) { options.Processes.Add(process.Name, process); } options.RepositoryTables = LoadRepositoryTables(); // Add the log folders based on the Tableau Data path from the registry AddLogFoldersToOptions(config, options, tableauRoot); // setup the polling options options.UseCounterSamples = config.UseCounterSamples; options.UseLogPolling = config.UseLogPolling; options.UseThreadInfo = config.UseThreadInfo; // Polling of Tableau repo and streaming tables needs to be executed only on primary nodes. // [...] for the legacy case UseRepoPolling is true by default and RepoTablesPollInterval is 0 to // disable repo polling so this would mean different behaviour with the same config file. options.UseRepoPolling = config.UseRepoPolling && config.RepoTablesPollInterval > 0; // and streaming tables is very similar and related to repo polling options.UseStreamingTables = config.UseRepoPolling && config.StreamingTablesPollInterval > 0; LoadRepositoryFromConfig(config, options); // set the maximum log lines options.LogLinesPerBatch = config.LogLinesPerBatch; options.StreamingTablesPollLimit = config.StreamingTablesPollLimit; } private static void LoadRepositoryFromConfig(PaletteInsightConfiguration config, PaletteInsightAgentOptions options) { if (!options.UseRepoPolling && !options.UseStreamingTables) { return; } // load the tableau repo properties var repoProps = config.TableauRepo; if (repoProps == null) { // Repository credentials are not filled in Config.yml return; } try { options.RepositoryDatabase = new DbConnectionInfo { Server = repoProps.Host, Port = Convert.ToInt32(repoProps.Port), Username = repoProps.User, Password = repoProps.Password, DatabaseName = repoProps.Database }; Log.Info("Found Tableau repo credentials in Config.yml."); } catch (Exception e) { Log.Error(e, "Failed to parse Tableau repository configs! Error:"); } } public static PaletteInsightConfiguration LoadConfigFile(string filename) { try { // deserialize the config using (var reader = File.OpenText(filename)) { IDeserializer deserializer = YamlDeserializer.Create(); var config = deserializer.Deserialize<PaletteInsightConfiguration>(reader); return config; } } catch (Exception e) { Log.Fatal("Error during cofiguration loading: {0} -- {1}", filename, e); return null; } } public static void UpdateWebserviceConfigFromLicense(PaletteInsightAgentOptions options) { // skip if we arent using the webservice if (options.WebserviceConfig == null) return; options.WebserviceConfig.AuthToken = options.AuthToken; } /// <summary> /// Add the tableau repo database details to the options. /// </summary> /// <param name="config"></param> /// <param name="options"></param> /// <param name="tableauRoot"></param> public static bool AddRepoFromWorkgroupYaml(PaletteInsightConfiguration config, string tableauRoot, PaletteInsightAgentOptions options) { var workgroupYmlPath = GetWorkgroupYmlPath(tableauRoot); Workgroup repo = GetRepoFromWorkgroupYaml(workgroupYmlPath, options.PreferPassiveRepository); if (repo == null) { return false; } try { if (IsEncrypted(repo.Password)) { Log.Info("Encrypted readonly password found in workgroup.yml."); // if (Tableau.getVersionNumber() >= TABLEAU_VERSION_2018_2) // { // Log.Warn("Palette Insight cannot decrypt readonly user's password on Tableau Server 2018.2+! Credentials must be provided in Config.yml!"); // return false; // } Log.Info("Getting readonly password with tabadmin command."); repo.Password = Tableau.tabadminRun("get pgsql.readonly_password"); } options.RepositoryDatabase = new DbConnectionInfo { Server = repo.Connection.Host, Port = repo.Connection.Port, Username = repo.Username, Password = repo.Password, DatabaseName = repo.Connection.DatabaseName }; if (config.TableauRepo != null) { Log.Warn("Ignoring Tableau repo settings from config.yml."); } return true; } catch (Exception e) { Log.Error(e, "Failed to acquire Tableau repo connection details! Exception: "); } return false; } #region log folders /// <summary> /// The log folders we are interested in, relative from the Tableau Data Root /// </summary> private static readonly LogFolder[] LOG_PATHS_IN_TABLEAU_DATA_FOLDER = new LogFolder[] { new LogFolder {Directory = @"tabsvc\vizqlserver\Logs", Filter = "*.txt" }, new LogFolder {Directory = @"tabsvc\logs\vizqlserver", Filter = "tabprotosrv*.txt" }, }; /// <summary> /// Adds a watched folder to the list of watched folders. /// </summary> /// <returns>If the folder was added</returns> private static bool AddFolderToWatched(ICollection<PaletteInsightAgentOptions.LogFolderInfo> logFolders, PaletteInsightAgentOptions.LogFolderInfo folder) { var folderValueString = folder.ToValueString(); foreach (var logFolder in logFolders) { // Skip if we already have this folder if (String.Equals(logFolder.ToValueString(), folderValueString)) { Log.Error("Skipping addition of duplicate watched path: {0}", folderValueString); return false; } } // If no matches found, add to the list of dirs logFolders.Add(folder); Log.Info("Watching folder: {0} with filter: {1} with format: {2}", folder.FolderToWatch, folder.DirectoryFilter, folder.LogFormat); return true; } /// <summary> /// Adds the log folders from either the config (if no tableau server is installed), /// or from the registry /// </summary> /// <param name="config"></param> /// <param name="options"></param> /// <param name="tableauRoot"></param> private static void AddLogFoldersToOptions(PaletteInsightConfiguration config, PaletteInsightAgentOptions options, string tableauRoot) { // check and load the log folder paths from the config file, so // the folders listed in there will be definitely watched if (config.Logs != null) { foreach (LogFolder logFolder in config.Logs) { AddFolderToWatched(options.LogFolders, PaletteInsightAgentOptions.LogFolderInfo.Create( logFolder.Directory, logFolder.Filter, logFolder.Format )); } } if (tableauRoot != null) { // otherwise try to add the log folders from the registry setup foreach (var logFolder in LoadDefaultLogFolders()) { var fullPath = Path.GetFullPath(Path.Combine(tableauRoot, logFolder.Directory)); // we check here so we won't add non-existent folders if (!Directory.Exists(fullPath)) { Log.Error("Log folder not found: {0}", fullPath); continue; } AddFolderToWatched(options.LogFolders, PaletteInsightAgentOptions.LogFolderInfo.Create(fullPath, logFolder.Filter, logFolder.Format)); } } } /// <summary> /// Tries to load the default log folders from the log folders yaml file. /// Since failing to load these disables parsing any logs, this /// method throws its errors /// </summary> /// <returns></returns> internal static List<LogFolder> LoadDefaultLogFolders() { // load the defaults from the application // since PaletteInsightAgent always sets the current directory to its location, // we should always be in the correct folder for this to work using (var reader = File.OpenText(LOGFOLDER_DEFAULTS_FILE)) { IDeserializer deserializer = YamlDeserializer.Create(); return deserializer.Deserialize<List<LogFolder>>(reader); } } internal static bool IsEncrypted(string text) { var pattern = new Regex(@"^ENC\(.*\)$"); var matched = pattern.Match(text); return matched.Success; } #endregion /// <summary> /// Helper to create a database configuration /// </summary> /// <param name="databaseConfig"></param> /// <returns></returns> private static DbConnectionInfo CreateDbConnectionInfo(DatabaseConfig databaseConfig) { DbConnectionInfo dbConnInfo = new DbConnectionInfo() { Server = databaseConfig.Host, Port = databaseConfig.Port, Username = databaseConfig.User, Password = databaseConfig.Password, DatabaseName = databaseConfig.Database, CommandTimeout = databaseConfig.CommandTimeout }; if (!dbConnInfo.Valid()) { throw new ConfigurationErrorsException("Missing required database connection information!"); } return dbConnInfo; } #region Tableau Registry info /// <summary> /// Retrieve Tableau's data folder path from the registry or figure it out /// based on its installation folder or fallback and try the usual path. /// </summary> /// <returns></returns> public static string FindTableauDataFolder() { // Primary nodes store the data folder location in the registry, except if // Tableau Server is installed on C: drive string dataFolderPath = SearchRegistryForTableauDataFolder(); if (dataFolderPath != null) { Log.Info("Found Tableau Data folder in registry: {0}", dataFolderPath); return dataFolderPath; } // Look for it in the Tableau installation folder dataFolderPath = SearchDataFolderInInstallationFolder(); if (dataFolderPath != null) { Log.Info("Found Tableau Data folder in installation folder: {0}", dataFolderPath); return dataFolderPath; } // Try the usual path as a last resort. The data folder is located here if you install // Tableau Server on drive C: according to Tableau documentation dataFolderPath = @"C:\ProgramData\Tableau\Tableau Server\data"; if (Directory.Exists(dataFolderPath)) { Log.Info("Found Tableau Data folder at default location: {0}", dataFolderPath); return dataFolderPath; } // No luck at all Log.Error("Could not find Tableau data folder!"); return null; } /// <summary> /// Tries to read Tableau's data folder from the registry /// NOTE: This function works as long as Tableau versions are in X.X format /// </summary> /// <returns>null if no Tableau data folder is found in the registry </returns> private static string SearchRegistryForTableauDataFolder() { // Try all versions of tableau from highest to lowest using (var localKey = Environment.Is64BitOperatingSystem ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) : RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) { RegistryKey tableauKey = localKey.OpenSubKey(@"Software\Tableau"); if (tableauKey == null) { return null; } Version latestTableauVersion = new Version("0.0"); string tableauDataFolder = null; foreach (string key in tableauKey.GetSubKeyNames()) { var pattern = new Regex(@"^Tableau Server ([0-9]+\.[0-9]+)"); var groups = pattern.Match(key).Groups; // groups[0] is the entire match, thus we expect 2 if (groups.Count < 2) { continue; } Version version = new Version(groups[1].Value); if (version > latestTableauVersion) { try { string directoriesRegPath = Path.Combine(key, "Directories"); using (RegistryKey dataFolderKey = tableauKey.OpenSubKey(directoriesRegPath)) { if (dataFolderKey == null) { continue; } Object dataValue = dataFolderKey.GetValue("Data"); if (dataValue == null) { continue; } string possibleDataFolder = dataValue as String; if (!Directory.Exists(possibleDataFolder)) { continue; } latestTableauVersion = version; tableauDataFolder = possibleDataFolder; } } catch (Exception) { // no problem, only means this is not our version continue; } } } tableauKey.Close(); if (tableauDataFolder == null) { return null; } return tableauDataFolder; } } /// <summary> /// Try to find the Tableau data folder in the Tableau Installation folder, /// which is calculated based on the path of the Tableau Server Application /// Manager (tabsvc) service. /// /// For worker nodes this is the way we can discover Tableau data folder, if /// it is not located in the default directory. /// </summary> /// <returns></returns> private static string SearchDataFolderInInstallationFolder() { string tableauInstallFolder = RetrieveTableauInstallationFolder(); if (tableauInstallFolder == null) { Log.Warn("Could not find Tableau installation folder!"); return null; } string dataFolderPath = Path.Combine(tableauInstallFolder, "data"); if (!Directory.Exists(dataFolderPath)) { return null; } return dataFolderPath; } private static string RetrieveTableauInstallationFolder() { string tabsvcPath = GetPathOfService(TABLEAU_SERVER_APPLICATION_SERVICE_NAME); return ExtractTableauInstallationFolder(tabsvcPath); } public static string RetrieveTableauBinFolder() { string tabsvcPath = GetPathOfService(TABLEAU_SERVER_APPLICATION_SERVICE_NAME); return ExtractTableauBinFolder(tabsvcPath); } // This function is created only for unit testing, since it is pretty difficult // to mock static functions in C# internal static string ExtractTableauInstallationFolder(string tabsvcPath) { var matchGroups = ParseTabsvcPath(tabsvcPath); if (matchGroups == null) { Log.Warn("Failed to extract Tableau installation folder from: {0}", tabsvcPath); return null; } return matchGroups[1].Value; } // This function is created only for unit testing, since it is pretty difficult // to mock static functions in C# internal static string ExtractTableauBinFolder(string tabsvcPath) { if (tabsvcPath == null) { Log.Warn("Failed to extract Tableau bin folder as the path to 'tabsvc' service is null!"); return null; } // Extract the installation folder out of the tabsvc path. We are going to // chop tabsvc.exe from the end of the tabsvc path. var pattern = new Regex(@"""?(.*[\\\/]+bin[\\\/]+?)tabsvc.exe.*"); var groups = pattern.Match(tabsvcPath).Groups; // groups[0] is the entire match, thus we expect at least 2 if (groups.Count < 2) { Log.Warn("Failed to extract Tableau bin folder from 'tabsvc' path: '{0}'", tabsvcPath); return null; } return groups[1].Value; } // This function is acquired from StackOverflow: // http://stackoverflow.com/questions/2728578/how-to-get-phyiscal-path-of-windows-service-using-net // (with a bit of more careful object disposal) public static string GetPathOfService(string serviceName) { WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name like '{0}%'", serviceName)); using (ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery)) using (ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get()) { foreach (ManagementObject managementObject in managementObjectCollection) { return managementObject.GetPropertyValue("PathName").ToString(); } } return null; } #endregion #region private Repository parts /// <summary> /// Deserialization struct for the repo config from the workgroup.yml /// </summary> public class Workgroup { [YamlMember(Alias = "pgsql.readonly.enabled")] public bool ReadonlyEnabled { get; set; } [YamlMember(Alias = "pgsql.readonly_username")] public string Username { get; set; } [YamlMember(Alias = "pgsql.readonly_password")] public string Password { get; set; } [YamlMember(Alias = "pgsql.connections.yml")] public string ConnectionsFile { get; set; } [YamlMember(Alias = "pgsql0.host")] public string PgHost0 { get; set; } [YamlMember(Alias = "pgsql0.port")] public int PgPort0 { get; set; } [YamlMember(Alias = "pgsql1.host")] public string PgHost1 { get; set; } [YamlMember(Alias = "pgsql1.port")] public int PgPort1 { get; set; } public TableauConnectionInfo Connection { get; set; } } public class TableauConnectionInfo { [YamlMember(Alias = "pgsql.host")] public string Host { get; set; } [YamlMember(Alias = "pgsql.port")] public int Port { get; set; } // It is not possible to change it @Tableau so we hardcode it for now public readonly string DatabaseName = "workgroup"; } private static bool IsValidRepoData(Workgroup workgroup) { if (!workgroup.ReadonlyEnabled) { Log.Warn("Readonly user is not enabled! Repo credentials must be entered into Config.yml."); return false; } if (workgroup.Username == null) { Log.Error("Tableau repo username is null! Repo credentials must be entered into Config.yml."); return false; } if (workgroup.Password == null) { Log.Error("Tableau repo password is null! Repo credentials must be entered into Config.yml."); return false; } if (workgroup.Connection.Host == null) { Log.Error("Tableau repo hostname is null! Repo credentials must be entered into Config.yml."); return false; } return true; } public static string GetWorkgroupYmlPath(string tableauRoot) { if (tableauRoot == null) { Log.Error("Tableau data folder path must not be null while reading and YAML configs!"); return null; } //Up to Tableau 2018.1 var workgroupYmlPath = Path.Combine(tableauRoot, "tabsvc", "config", "workgroup.yml"); //From Tabaleau 2018.2 if (!File.Exists(workgroupYmlPath)) { try { string[] configFilePaths = Directory.GetFiles(Path.Combine(tableauRoot, "tabsvc", "config"), "workgroup.yml", SearchOption.AllDirectories); foreach (string configPath in configFilePaths) { // The workgroup.yml files are stored in sub-folders of the tabsvc/data/config folder. // We found that the clustercontroller_* folder exists on every node. Previously we used the // pgsql_* folders, but they exist only on the repository nodes. string pattern = @".*clustercontroller_.*"; Match m = Regex.Match(configPath, pattern); if (m.Success) { workgroupYmlPath = configPath; Log.Info("Config file path: {0}", workgroupYmlPath); break; } } } catch (Exception e) { Log.Error(e, "Cannot find workgroup.yml file"); return null; } } return workgroupYmlPath; } public static Workgroup GetRepoFromWorkgroupYaml(string workgroupYmlPath, bool preferPassiveRepo) { if (workgroupYmlPath == null) { Log.Error("Path for workgroup.yml must not be null while reading configs!"); return null; } try { // Get basic info from workgroup yml. Everything else from connections.yml IDeserializer deserializer = YamlDeserializer.Create(); Workgroup workgroup = null; using (var workgroupFile = File.OpenText(workgroupYmlPath)) { workgroup = deserializer.Deserialize<Workgroup>(workgroupFile); using (var connectionsFile = File.OpenText(workgroup.ConnectionsFile)) { workgroup.Connection = deserializer.Deserialize<TableauConnectionInfo>(connectionsFile); // workgroup.Connection.Host always contains the active repo if (preferPassiveRepo) { if (workgroup.PgHost0 != null && workgroup.PgHost1 != null) { // Use passive repo if possible/exists if (workgroup.Connection.Host != workgroup.PgHost0) { workgroup.Connection.Host = workgroup.PgHost0; workgroup.Connection.Port = workgroup.PgPort0; } else { workgroup.Connection.Host = workgroup.PgHost1; workgroup.Connection.Port = workgroup.PgPort1; } Log.Info("Based on workgroup.yml, passive repository host is: '{0}' with port: '{1}'", workgroup.Connection.Host, workgroup.Connection.Port); } else { Log.Info("Passive repo is preferred as target Tableau repo, but '{0}' does not contain passive repo node information", workgroupYmlPath); } } else { Log.Info("Active Tableau repo is configured to be the target repo"); } } if (!IsValidRepoData(workgroup)) { return null; } } return workgroup; } catch (Exception e) { Log.Error(e, "Error while trying to load and parse YAML config from '{0}' Exception: ", workgroupYmlPath); } return null; } internal static GroupCollection ParseTabsvcPath(string tabsvcPath) { if (tabsvcPath == null) { Log.Warn("Failed to extract Tableau Installation folder as the path to 'tabsvc' service is null!"); return null; } // Extract the installation folder out of the tabsvc path. We are going to // chop <one_folder>\bin\tabsvc.exe from the end of the tabsvc path. var pattern = new Regex(@"""?(.*?)[\\\/]+[^\\\/]+[\\\/]+bin[\\\/]+tabsvc.exe.*"); var groups = pattern.Match(tabsvcPath).Groups; // groups[0] is the entire match, thus we expect at least 2 if (groups.Count < 2) { // Onwards Tableau Server 2018.2 the tabsvc.exe location is slightly different. In this case // we are going to chop data\tabsvc\services\<tabsvc_version_folder>\tabsvc\tabsvc.exe from the // end of the tabsvc path. pattern = new Regex(@"""?(.*?)[\\\/]+data[\\\/]+tabsvc[\\\/]+services[\\\/]+([^\\\/]+)[\\\/]+tabsvc[\\\/]+tabsvc.exe.*"); groups = pattern.Match(tabsvcPath).Groups; if (groups.Count < 3) { Log.Warn("Failed to extract Tableau Installation folder from 'tabsvc' path: '{0}'", tabsvcPath); return null; } } return groups; } #endregion #region process defaults /// <summary> /// Tries to load the default process names from the process names yaml file. /// Since failing to load these disables parsing any processs, this /// method throws its errors /// </summary> /// <returns></returns> internal static List<ProcessData> LoadProcessData() { // since PaletteInsightAgent always sets the current directory to its location, // we should always be in the correct folder for this to work using (var reader = File.OpenText(PROCESSES_DEFAULT_FILE)) { IDeserializer deserializer = YamlDeserializer.Create(); return deserializer.Deserialize<List<ProcessData>>(reader); } } private static List<RepoTable> LoadRepositoryTables() { using (var reader = File.OpenText(REPOSITORY_TABLES_FILE)) { IDeserializer deserializer = YamlDeserializer.Create(); return deserializer.Deserialize<List<RepoTable>>(reader); } } #endregion } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ #if DEBUG namespace ASC.Core.Common.Tests { using System; using System.Linq; using ASC.Core.Data; using ASC.Core.Users; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DbUserServiceTest : DbBaseTest<DbUserService> { [ClassInitialize] public void ClearData() { Service.GetUsers(Tenant, default(DateTime)) .ToList() .ForEach(u => Service.RemoveUser(Tenant, u.Value.ID, true)); Service.GetGroups(Tenant, default(DateTime)) .ToList() .ForEach(g => Service.RemoveGroup(Tenant, g.Value.Id, true)); Service.GetUserGroupRefs(Tenant, default(DateTime)) .ToList() .ForEach(r => Service.RemoveUserGroupRef(Tenant, r.Value.UserId, r.Value.GroupId, r.Value.RefType, true)); } [TestMethod] public void CRUDUser() { var user1 = new UserInfo { UserName = "username1", FirstName = "first name", LastName = "last name", BirthDate = new DateTime(2011, 01, 01, 7, 8, 9), Sex = true, Email = "email@mail.ru", Location = "location", Notes = "notes", Status = EmployeeStatus.Active, Title = "title", WorkFromDate = new DateTime(2011, 01, 01, 7, 8, 9), TerminatedDate = new DateTime(2011, 01, 01, 7, 8, 9), CultureName = "de-DE", }; user1.ContactsFromString("contacts"); user1 = Service.SaveUser(Tenant, user1); CompareUsers(user1, Service.GetUser(Tenant, user1.ID)); var user2 = new UserInfo { UserName = "username2", FirstName = "first name", LastName = "last name", }; user2 = Service.SaveUser(Tenant, user2); user2 = Service.SaveUser(Tenant, user2); CompareUsers(user2, Service.GetUser(Tenant, user2.ID)); var duplicateUsername = false; var user3 = new UserInfo { UserName = "username3", FirstName = "first name", LastName = "last name", }; var user4 = new UserInfo { UserName = "username3", FirstName = "first name", LastName = "last name", }; try { user3 = Service.SaveUser(Tenant, user3); user4 = Service.SaveUser(Tenant, user4); } catch (ArgumentOutOfRangeException) { duplicateUsername = true; } Assert.IsTrue(duplicateUsername); Service.RemoveUser(Tenant, user3.ID, false); user4 = Service.SaveUser(Tenant, user4); Service.RemoveUser(Tenant, user3.ID, true); Service.RemoveUser(Tenant, user4.ID, true); var users = Service.GetUsers(Tenant, new DateTime(1900, 1, 1)).Values; CollectionAssert.AreEquivalent(new[] { user1, user2 }, users.ToList()); Service.RemoveUser(Tenant, user2.ID, true); Service.SetUserPhoto(Tenant, user1.ID, null); Assert.AreEqual(0, Service.GetUserPhoto(Tenant, user1.ID).Count()); Service.SetUserPhoto(Tenant, user1.ID, new byte[0]); Assert.AreEqual(0, Service.GetUserPhoto(Tenant, user1.ID).Count()); Service.SetUserPhoto(Tenant, user1.ID, new byte[] { 1, 2, 3 }); CollectionAssert.AreEquivalent(new byte[] { 1, 2, 3 }, Service.GetUserPhoto(Tenant, user1.ID)); //var password = "password"; //Service.SetUserPassword(Tenant, user1.ID, password); //Assert.AreEqual(password, Service.GetUserPassword(Tenant, user1.ID)); //CompareUsers(user1, Service.GetUser(Tenant, user1.Email, Hasher.Base64Hash(password, HashAlg.SHA256))); //Service.RemoveUser(Tenant, user1.ID); //Assert.IsTrue(Service.GetUser(Tenant, user1.ID).Removed); //Service.RemoveUser(Tenant, user1.ID, true); //Assert.AreEqual(0, Service.GetUserPhoto(Tenant, user1.ID).Count()); //Assert.IsNull(Service.GetUserPassword(Tenant, user1.ID)); } [TestMethod] public void CRUDGroup() { var g1 = new Group { Name = "group1", CategoryId = Guid.NewGuid(), }; g1 = Service.SaveGroup(Tenant, g1); CompareGroups(g1, Service.GetGroup(Tenant, g1.Id)); var now = DateTime.UtcNow; var g2 = new Group { Name = "group2", ParentId = g1.Id, }; g2 = Service.SaveGroup(Tenant, g2); CompareGroups(g2, Service.GetGroup(Tenant, g2.Id)); Service.RemoveGroup(Tenant, g1.Id); g1 = Service.GetGroup(Tenant, g1.Id); g2 = Service.GetGroup(Tenant, g2.Id); Assert.IsTrue(g1.Removed); Assert.IsTrue(g2.Removed); CollectionAssert.AreEquivalent(Service.GetGroups(Tenant, now).Values.ToList(), new[] { g1, g2 }); Service.RemoveGroup(Tenant, g1.Id, true); Assert.AreEqual(0, Service.GetGroups(Tenant, new DateTime(1900, 1, 1)).Count()); } [TestMethod] public void CRUDUserGroupRef() { Service.SaveUserGroupRef(Tenant, new UserGroupRef { UserId = Guid.Empty, GroupId = Guid.Empty, RefType = UserGroupRefType.Manager }); Service.RemoveUserGroupRef(Tenant, Guid.Empty, Guid.Empty, UserGroupRefType.Manager); Assert.IsTrue(Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).First().Value.Removed); Service.RemoveUserGroupRef(Tenant, Guid.Empty, Guid.Empty, UserGroupRefType.Manager, true); Assert.AreEqual(0, Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).Count()); var gu1 = Service.SaveUserGroupRef(Tenant, new UserGroupRef { UserId = Guid.Empty, GroupId = Guid.Empty, RefType = UserGroupRefType.Manager }); var gu2 = Service.SaveUserGroupRef(Tenant, new UserGroupRef { UserId = new Guid("00000000-0000-0000-0000-000000000001"), GroupId = new Guid("00000000-0000-0000-0000-000000000002"), RefType = UserGroupRefType.Manager }); CollectionAssert.AreEquivalent(new[] { gu1, gu2 }, Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).Values.ToList()); Service.RemoveUserGroupRef(Tenant, gu1.UserId, gu1.GroupId, UserGroupRefType.Manager, true); Service.RemoveUserGroupRef(Tenant, gu2.UserId, gu2.GroupId, UserGroupRefType.Manager, true); var u = Service.SaveUser(Tenant, new UserInfo { UserName = "username", LastName = "lastname", FirstName = "firstname" }); Service.SaveUserGroupRef(Tenant, new UserGroupRef { UserId = u.ID, GroupId = Guid.Empty, RefType = UserGroupRefType.Manager }); Service.RemoveUser(Tenant, u.ID); Assert.IsTrue(Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).First().Value.Removed); Service.RemoveUser(Tenant, u.ID, true); Assert.AreEqual(0, Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).Count()); var g = Service.SaveGroup(Tenant, new Group { Name = "group1" }); u = Service.SaveUser(Tenant, new UserInfo { UserName = "username", LastName = "lastname", FirstName = "firstname" }); Service.SaveUserGroupRef(Tenant, new UserGroupRef { UserId = u.ID, GroupId = g.Id, RefType = UserGroupRefType.Manager }); u = Service.GetUser(Tenant, u.ID); Service.RemoveGroup(Tenant, g.Id); Assert.IsTrue(Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).First().Value.Removed); Service.SaveUser(Tenant, u); Service.RemoveGroup(Tenant, g.Id, true); Assert.AreEqual(0, Service.GetUserGroupRefs(Tenant, new DateTime(1900, 1, 1)).Count()); } private void CompareUsers(UserInfo u1, UserInfo u2) { Assert.AreEqual(u1.ID, u2.ID); Assert.AreEqual(u1.BirthDate, u2.BirthDate); Assert.AreEqual(u1.ContactsToString(), u2.ContactsToString()); Assert.AreEqual(u1.Email, u2.Email); Assert.AreEqual(u1.FirstName, u2.FirstName); Assert.AreEqual(u1.LastName, u2.LastName); Assert.AreEqual(u1.Location, u2.Location); Assert.AreEqual(u1.Notes, u2.Notes); Assert.AreEqual(u1.Sex, u2.Sex); Assert.AreEqual(u1.Status, u2.Status); Assert.AreEqual(u1.Title, u2.Title); Assert.AreEqual(u1.UserName, u2.UserName); Assert.AreEqual(u1.WorkFromDate, u2.WorkFromDate); Assert.AreEqual(u1.TerminatedDate, u2.TerminatedDate); Assert.AreEqual(u1.Removed, u2.Removed); Assert.AreEqual(u1.CultureName, u2.CultureName); } private void CompareGroups(Group g1, Group g2) { Assert.AreEqual(g1.CategoryId, g2.CategoryId); Assert.AreEqual(g1.Id, g2.Id); Assert.AreEqual(g1.Name, g2.Name); Assert.AreEqual(g1.ParentId, g2.ParentId); Assert.AreEqual(g1.Removed, g2.Removed); } } } #endif
// // DelegateDeserializationCompiler.cs // // Author: // Scott Thomas <lunchtimemama@gmail.com> // // Copyright (c) 2009 Scott Thomas // // 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.Reflection; using Mono.Upnp.Internal; namespace Mono.Upnp.Xml.Compilation { public class DelegateDeserializationCompiler : DeserializationCompiler { delegate object ItemDeserializer (object obj, XmlDeserializationContext context); delegate void ElementDeserializer (object obj, XmlDeserializationContext context, int depth); Dictionary<Type, MethodInfo> type_deserializers; bool has_processed_type_deserializers; PropertyInfo value_property; Dictionary<string, ObjectDeserializer> attribute_deserializers; Dictionary<string, ObjectDeserializer> element_deserializers; public DelegateDeserializationCompiler (XmlDeserializer xmlDeserializer, Type type) : base (xmlDeserializer, type) { } Dictionary<Type, MethodInfo> TypeDeserializers { get { if (!has_processed_type_deserializers) { has_processed_type_deserializers = true; ProcessTypeDeserializers (); } return type_deserializers; } } PropertyInfo ValueProperty { get { CheckHasProcessedType (); return value_property; } } Dictionary<string, ObjectDeserializer> AttributeDeserializers { get { CheckHasProcessedType (); return attribute_deserializers; } } Dictionary<string, ObjectDeserializer> ElementDeserializers { get { CheckHasProcessedType (); return element_deserializers; } } void CheckHasProcessedType () { if (attribute_deserializers == null) { ProcessType (); } } protected override Deserializer CreateDeserializer () { if (Type == typeof (string)) { return context => context.Reader.ReadElementContentAsString (); } else if (Type == typeof (int)) { return context => context.Reader.ReadElementContentAsInt (); } else if (Type == typeof (double)) { return context => context.Reader.ReadElementContentAsDouble (); } else if (Type == typeof (bool)) { return context => context.Reader.ReadElementContentAsBoolean (); } else if (Type == typeof (long)) { return context => context.Reader.ReadElementContentAsLong (); } else if (Type == typeof (float)) { return context => context.Reader.ReadElementContentAsFloat (); } else if (Type == typeof (decimal)) { return context => context.Reader.ReadElementContentAsDecimal (); } else if (Type == typeof (DateTime)) { return context => context.Reader.ReadElementContentAsDateTime (); } else if (Type == typeof (Uri)) { return context => { var url = context.Reader.ReadElementContentAsString (); return url.Length == 0 ? null : new Uri (url); }; } else if (Type.IsEnum) { var map = GetEnumMap (Type); return context => map[context.Reader.ReadElementContentAsString ()]; } else if (Type.IsGenericType && Type.GetGenericTypeDefinition () == typeof (Nullable<>)) { var type = Type.GetGenericArguments ()[0]; var deserializer = GetDeserializerForType (type); var constructor = Type.GetConstructor (new[] { type }); return context => constructor.Invoke (new[] { deserializer (context) }); } else { // TODO check for default ctor if (typeof (IXmlDeserializable).IsAssignableFrom (Type)) { return context => { var obj = Activator.CreateInstance (Type, true); ((IXmlDeserializable)obj).Deserialize (context); return obj; }; } else { var deserializer = AutoDeserializer; return context => { var obj = Activator.CreateInstance (Type, true); deserializer (obj, context); return obj; }; } } } protected override ObjectDeserializer CreateAutoDeserializer () { var attribute_deserializer = CreateAttributeDeserializer (); var element_deserializer = CreateElementDeserializer (); return (obj, context) => { try { var depth = context.Reader.Depth; while (context.Reader.MoveToNextAttribute ()) { try { attribute_deserializer (obj, context); } catch { throw; } } context.Reader.MoveToElement (); element_deserializer (obj, context, depth); } catch { throw; } }; } ObjectDeserializer CreateAttributeDeserializer () { if (typeof (IXmlDeserializable).IsAssignableFrom (Type)) { return (obj, context) => ((IXmlDeserializable)obj).DeserializeAttribute (context); } else { return AttributeAutoDeserializer; } } protected override ObjectDeserializer CreateAttributeAutoDeserializer () { var attribute_deserializers = AttributeDeserializers; if (attribute_deserializers.Count == 0) { return (obj, context) => {}; } else { return (obj, context) => { var name = CreateName (context.Reader.LocalName, context.Reader.NamespaceURI); if (attribute_deserializers.ContainsKey (name)) { attribute_deserializers[name] (obj, context); } }; } } ElementDeserializer CreateElementDeserializer () { if (ValueProperty != null) { var property = ValueProperty; var deserializer = GetDeserializerForType (property.PropertyType); return (obj, context, depth) => property.SetValue (obj, deserializer (context), null); } var element_deserializer = CreateSubElementDeserializer (); return (obj, context, depth) => { while (Helper.ReadToNextElement (context.Reader) && context.Reader.Depth > depth) { var element_reader = context.Reader.ReadSubtree (); element_reader.Read (); try { element_deserializer (obj, CreateDeserializationContext (element_reader)); } catch { throw; } finally { element_reader.Close (); } } }; } ObjectDeserializer CreateSubElementDeserializer () { if (typeof (IXmlDeserializable).IsAssignableFrom (Type)) { return (obj, context) => ((IXmlDeserializable)obj).DeserializeElement (context); } else { return ElementAutoDeserializer; } } protected override ObjectDeserializer CreateElementAutoDeserializer () { var object_deserializers = ElementDeserializers; if (object_deserializers.Count == 0) { return (obj, context) => {}; } else { return (obj, context) => { var name = CreateName (context.Reader.LocalName, context.Reader.NamespaceURI); if (object_deserializers.ContainsKey (name)) { object_deserializers[name] (obj, context); } else if (object_deserializers.ContainsKey (context.Reader.Name)) { object_deserializers[context.Reader.Name] (obj, context); } else { // TODO this is a workaround for mono bug 334752 and another problem context.Reader.Skip (); } }; } } void ProcessTypeDeserializers () { foreach (var @interface in Type.GetInterfaces ()) { if (@interface.IsGenericType && @interface.GetGenericTypeDefinition () == typeof (IXmlDeserializer<>)) { var type = @interface.GetGenericArguments()[0]; if (type_deserializers == null) { type_deserializers = new Dictionary<Type, MethodInfo> (); } else if (type_deserializers.ContainsKey (type)) { // TODO throw } type_deserializers[type] = Type.GetInterfaceMap (@interface).TargetMethods[0]; } } } void ProcessType () { attribute_deserializers = new Dictionary<string, ObjectDeserializer> (); element_deserializers = new Dictionary<string, ObjectDeserializer> (); foreach (var property in Properties) { XmlElementAttribute element_attribute = null; XmlFlagAttribute flag_attribute = null; XmlArrayAttribute array_attribute = null; XmlArrayItemAttribute array_item_attribute = null; XmlAttributeAttribute attribute_attribute = null; foreach (var custom_attribute in property.GetCustomAttributes (false)) { if (custom_attribute is DoNotDeserializeAttribute) { element_attribute = null; flag_attribute = null; array_attribute = null; attribute_attribute = null; value_property = null; break; } var element = custom_attribute as XmlElementAttribute; if (element != null) { element_attribute = element; continue; } var flag = custom_attribute as XmlFlagAttribute; if (flag != null) { flag_attribute = flag; continue; } var array = custom_attribute as XmlArrayAttribute; if (array != null) { array_attribute = array; continue; } var array_item = custom_attribute as XmlArrayItemAttribute; if (array_item != null) { array_item_attribute = array_item; continue; } var attribute = custom_attribute as XmlAttributeAttribute; if (attribute != null) { attribute_attribute = attribute; continue; } if (custom_attribute is XmlValueAttribute) { // TODO check if this isn't null and throw value_property = property; continue; } } if (element_attribute != null) { var deserializer = CreateCustomDeserializer (property) ?? CreateElementDeserializer (property); AddDeserializer (element_deserializers, CreateName (property.Name, element_attribute.Name, element_attribute.Namespace), deserializer); continue; } if (flag_attribute != null) { AddDeserializer (element_deserializers, CreateName (property.Name, flag_attribute.Name, flag_attribute.Namespace), CreateFlagDeserializer (property)); continue; } if (array_attribute != null) { AddDeserializer (element_deserializers, CreateName (property.Name, array_attribute.Name, array_attribute.Namespace), CreateArrayElementDeserializer (property)); continue; } else if (array_item_attribute != null) { var name = array_item_attribute.Name; var @namespace = array_item_attribute.Namespace; if (string.IsNullOrEmpty (name)) { var item_type = GetICollection (property.PropertyType).GetGenericArguments ()[0]; var type_attribute = item_type.GetCustomAttributes (typeof (XmlTypeAttribute), false); if (type_attribute.Length == 0) { name = item_type.Name; } else { var xml_type = (XmlTypeAttribute)type_attribute[0]; name = string.IsNullOrEmpty (xml_type.Name) ? item_type.Name : xml_type.Name; @namespace = xml_type.Namespace; } } AddDeserializer (element_deserializers, CreateName (name, @namespace), CreateArrayItemElementDeserializer (property)); } if (attribute_attribute != null) { var deserializer = CreateCustomDeserializer (property) ?? CreateAttributeDeserializer (property); AddDeserializer (attribute_deserializers, CreateName (property.Name, attribute_attribute.Name, attribute_attribute.Namespace), deserializer); continue; } } } ObjectDeserializer CreateCustomDeserializer (PropertyInfo property) { if (!property.CanWrite) { // TODO throw } if (TypeDeserializers != null && TypeDeserializers.ContainsKey (property.PropertyType)) { var method = TypeDeserializers[property.PropertyType]; return (obj, context) => property.SetValue (obj, method.Invoke (obj, new[] { context }), null); } return null; } ObjectDeserializer CreateAttributeDeserializer (PropertyInfo property) { if (!property.CanWrite) { // TODO throw } var deserializer = CreateAttributeDeserializer (property.PropertyType); return (obj, context) => property.SetValue (obj, deserializer (context), null); } static Deserializer CreateAttributeDeserializer (Type type) { if (type == typeof (string)) { return context => context.Reader.ReadContentAsString (); } else if (type == typeof (int)) { return context => context.Reader.ReadContentAsInt (); } else if (type == typeof (double)) { return context => context.Reader.ReadContentAsDouble (); } else if (type == typeof (bool)) { return context => context.Reader.ReadContentAsBoolean (); } else if (type == typeof (long)) { return context => context.Reader.ReadContentAsLong (); } else if (type == typeof (float)) { return context => context.Reader.ReadContentAsFloat (); } else if (type == typeof (decimal)) { return context => context.Reader.ReadContentAsDecimal (); } else if (type == typeof (DateTime)) { return context => context.Reader.ReadContentAsDateTime (); } else if (type == typeof (Uri)) { return context => new Uri (context.Reader.ReadContentAsString ()); } else if (type.IsEnum) { var map = GetEnumMap (type); return context => map[context.Reader.ReadContentAsString ()]; } else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>)) { var nullable_type = type.GetGenericArguments ()[0]; var deserializer = CreateAttributeDeserializer (nullable_type); var constructor = type.GetConstructor (new[] { nullable_type }); return context => constructor.Invoke (new[] { deserializer (context) }); } else { return context => context.Reader.ReadContentAs (type, null); } } // TODO we could use a trie for this and save some memory static Dictionary<string, object> GetEnumMap (Type type) { var fields = type.GetFields (BindingFlags.Public | BindingFlags.Static); var dictionary = new Dictionary<string, object> (fields.Length); foreach (var field in fields) { var enum_attribute = field.GetCustomAttributes (typeof (XmlEnumAttribute), false); string name; if (enum_attribute.Length!= 0) { name = ((XmlEnumAttribute)enum_attribute[0]).Value; } else { name = field.Name; } dictionary.Add (name, field.GetValue (null)); } return dictionary; } ObjectDeserializer CreateElementDeserializer (PropertyInfo property) { if (!property.CanWrite) { // TODO throw } var next = GetDeserializerForType (property.PropertyType); return (obj, context) => property.SetValue (obj, next (context), null); } ObjectDeserializer CreateFlagDeserializer (PropertyInfo property) { if (!property.CanWrite) { // TODO throw } return (obj, context) => property.SetValue (obj, true, null); } ItemDeserializer CreateItemDeserializer (Type type) { if (TypeDeserializers != null && TypeDeserializers.ContainsKey (type)) { var method = TypeDeserializers[type]; return (obj, context) => method.Invoke (obj, new[] { context }); } else { var deserializer = GetDeserializerForType (type); return (obj, context) => deserializer (context); } } ObjectDeserializer CreateArrayElementDeserializer (PropertyInfo property) { if (!property.CanRead) { // TODO throw } var icollection = GetICollection (property.PropertyType); var add = icollection.GetMethod ("Add"); var item_deserializer = CreateItemDeserializer (icollection.GetGenericArguments ()[0]); return (obj, context) => { var collection = property.GetValue (obj, null); var depth = context.Reader.Depth; while (Helper.ReadToNextElement (context.Reader) && context.Reader.Depth > depth) { var item_reader = context.Reader.ReadSubtree (); item_reader.Read (); try { add.Invoke (collection, new[] { item_deserializer (obj, CreateDeserializationContext (item_reader)) }); } catch { throw; } finally { item_reader.Close (); } } }; } ObjectDeserializer CreateArrayItemElementDeserializer (PropertyInfo property) { if (!property.CanRead) { // TODO throw } var icollection = GetICollection (property.PropertyType); var add = icollection.GetMethod ("Add"); var item_deserializer = CreateItemDeserializer (icollection.GetGenericArguments ()[0]); return (obj, context) => { var collection = property.GetValue (obj, null); add.Invoke (collection, new[] { item_deserializer (obj, context) }); }; } static string CreateName (string name, string @namespace) { return CreateName (null, name, @namespace); } static string CreateName (string backupName, string name, string @namespace) { if (string.IsNullOrEmpty (@namespace)) { return name ?? backupName; } else { return string.Format ("{0}/{1}", name ?? backupName, @namespace); } } static void AddDeserializer (Dictionary<string, ObjectDeserializer> deserializers, string name, ObjectDeserializer deserializer) { if (deserializers.ContainsKey (name)) { // TODO throw } deserializers[name] = deserializer; } static Type GetICollection (Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (ICollection<>)) { return type; } else { var icollection = type.GetInterface ("ICollection`1"); if (icollection != null) { return icollection; } else { // TODO throw return null; } } } } }
#region License // // ElementMapLabel.cs July 2007 // // Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // #endregion #region Using directives using SimpleFramework.Xml.Strategy; using SimpleFramework.Xml.Stream; using SimpleFramework.Xml; using System; #endregion namespace SimpleFramework.Xml.Core { /// <summary> /// The <c>ElementMapLabel</c> represents a label that is used /// to represent an XML element map in a class schema. This element /// list label can be used to convert an XML node into a map object /// of composite or primitive key value pairs. Each element converted /// with the converter this creates must be an XML serializable element. /// </summary> /// <seealso> /// SimpleFramework.Xml.ElementMap /// </seealso> class ElementMapLabel : Label { /// <summary> /// This is the decorator that is associated with the element. /// </summary> private Decorator decorator; /// <summary> /// This references the annotation that the field uses. /// </summary> private ElementMap label; /// <summary> /// This contains the details of the annotated contact object. /// </summary> private Signature detail; /// <summary> /// The entry object contains the details on how to write the map. /// </summary> private Entry entry; /// <summary> /// This is the type of map object this list will instantiate. /// </summary> private Class type; /// <summary> /// Represents the type of objects this map object will hold. /// </summary> private Class[] items; /// <summary> /// This is the name of the XML entry from the annotation. /// </summary> private String parent; /// <summary> /// This is the name of the element for this label instance. /// </summary> private String name; /// <summary> /// Constructor for the <c>ElementMapLabel</c> object. This /// creates a label object, which can be used to convert an XML /// node to a <c>Map</c> of XML serializable objects. /// </summary> /// <param name="contact"> /// this is the contact that this label represents /// </param> /// <param name="label"> /// the annotation that contains the schema details /// </param> public ElementMapLabel(Contact contact, ElementMap label) { this.detail = new Signature(contact, this); this.decorator = new Qualifier(contact); this.entry = new Entry(contact, label); this.type = contact.Type; this.name = label.name(); this.label = label; } /// <summary> /// This is used to acquire the <c>Decorator</c> for this. /// A decorator is an object that adds various details to the /// node without changing the overall structure of the node. For /// example comments and namespaces can be added to the node with /// a decorator as they do not affect the deserialization. /// </summary> /// <returns> /// this returns the decorator associated with this /// </returns> public Decorator Decorator { get { return decorator; } } //public Decorator GetDecorator() { // return decorator; //} /// This method returns a <c>Converter</c> which can be used to /// convert an XML node into an object value and vice versa. The /// converter requires only the context object in order to perform /// serialization or deserialization of the provided XML node. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns an object that is used for conversion /// </returns> public Converter GetConverter(Context context) { Type type = Map; if(!label.inline()) { return new CompositeMap(context, entry, type); } return new CompositeInlineMap(context, entry, type); } /// <summary> /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <param name="context"> /// this is the context used to style the name /// </param> /// <returns> /// returns the name that is used for the XML property /// </returns> public String GetName(Context context) { Style style = context.getStyle(); String name = entry.Entry; if(!label.inline()) { name = detail.GetName(); } return style.getElement(name); } /// <summary> /// This is used to provide a configured empty value used when the /// annotated value is null. This ensures that XML can be created /// with required details regardless of whether values are null or /// not. It also provides a means for sensible default values. /// </summary> /// <param name="context"> /// this is the context object for the serialization /// </param> /// <returns> /// this returns the string to use for default values /// </returns> public Object GetEmpty(Context context) { Type map = new ClassType(type); Factory factory = new MapFactory(context, map); if(!label.empty()) { return factory.getInstance(); } return null; } /// <summary> /// This is used to acquire the dependent type for the annotated /// list. This will simply return the type that the map object is /// composed to hold. This must be a serializable type, that is, /// a type that is annotated with the <c>Root</c> class. /// </summary> /// <returns> /// this returns the component type for the map object /// </returns> public Type Dependent { get { Contact contact = Contact; if(items == null) { items = contact.getDependents(); } if(items == null) { throw new ElementException("Unable to determine type for %s", contact); } if(items.length == 0) { return new ClassType(Object.class); } return new ClassType(items[0]); } } //public Type GetDependent() { // Contact contact = Contact; // if(items == null) { // items = contact.getDependents(); // } // if(items == null) { // throw new ElementException("Unable to determine type for %s", contact); // } // if(items.length == 0) { // return new ClassType(Object.class); // } // return new ClassType(items[0]); //} /// This is used to either provide the entry value provided within /// the annotation or compute a entry value. If the entry string /// is not provided the the entry value is calculated as the type /// of primitive the object is as a simplified class name. /// </summary> /// <returns> /// this returns the name of the XML entry element used /// </returns> public String Entry { get { if(detail.IsEmpty(parent)) { parent = detail.Entry; } return parent; } } //public String GetEntry() { // if(detail.IsEmpty(parent)) { // parent = detail.Entry; // } // return parent; //} /// This is used to acquire the name of the element or attribute /// that is used by the class schema. The name is determined by /// checking for an override within the annotation. If it contains /// a name then that is used, if however the annotation does not /// specify a name the the field or method name is used instead. /// </summary> /// <returns> /// returns the name that is used for the XML property /// </returns> public String Name { get { if(label.inline()) { return entry.Entry; } return detail.GetName(); } } //public String GetName() { // if(label.inline()) { // return entry.Entry; // } // return detail.GetName(); //} /// This returns the map type for this label. The primary type /// is the type of the <c>Map</c> that this creates. The key /// and value types are the types used to populate the primary. /// </summary> /// <returns> /// this returns the map type to use for the label /// </returns> public Type Map { get { return new ClassType(type); } } //public Type GetMap() { // return new ClassType(type); //} /// This acts as a convenience method used to determine the type of /// contact this represents. This is used when an object is written /// to XML. It determines whether a <c>class</c> attribute /// is required within the serialized XML element, that is, if the /// class returned by this is different from the actual value of the /// object to be serialized then that type needs to be remembered. /// </summary> /// <returns> /// this returns the type of the contact class /// </returns> public Class Type { get { return type; } } //public Class GetType() { // return type; //} /// This is used to acquire the contact object for this label. The /// contact retrieved can be used to set any object or primitive that /// has been deserialized, and can also be used to acquire values to /// be serialized in the case of object persistence. All contacts /// that are retrieved from this method will be accessible. /// </summary> /// <returns> /// returns the contact that this label is representing /// </returns> public Contact Contact { get { return detail.Contact; } } //public Contact GetContact() { // return detail.Contact; //} /// This is used to acquire the name of the element or attribute /// as taken from the annotation. If the element or attribute /// explicitly specifies a name then that name is used for the /// XML element or attribute used. If however no overriding name /// is provided then the method or field is used for the name. /// </summary> /// <returns> /// returns the name of the annotation for the contact /// </returns> public String Override { get { return name; } } //public String GetOverride() { // return name; //} /// This is used to determine whether the annotation requires it /// and its children to be written as a CDATA block. This is done /// when a primitive or other such element requires a text value /// and that value needs to be encapsulated within a CDATA block. /// </summary> /// <returns> /// currently the element list does not require CDATA /// </returns> public bool IsData() { return label.data(); } /// <summary> /// This method is used to determine if the label represents an /// attribute. This is used to style the name so that elements /// are styled as elements and attributes are styled as required. /// </summary> /// <returns> /// this is used to determine if this is an attribute /// </returns> public bool IsAttribute() { return false; } /// <summary> /// This is used to determine if the label is a collection. If the /// label represents a collection then any original assignment to /// the field or method can be written to without the need to /// create a new collection. This allows obscure collections to be /// used and also allows initial entries to be maintained. /// </summary> /// <returns> /// true if the label represents a collection value /// </returns> public bool IsCollection() { return true; } /// <summary> /// This is used to determine whether the XML element is required. /// This ensures that if an XML element is missing from a document /// that deserialization can continue. Also, in the process of /// serialization, if a value is null it does not need to be /// written to the resulting XML document. /// </summary> /// <returns> /// true if the label represents a some required data /// </returns> public bool IsRequired() { return label.required(); } /// <summary> /// This is used to determine whether the list has been specified /// as inline. If the list is inline then no overrides are needed /// and the outer XML element for the list is not used. /// </summary> /// <returns> /// this returns whether the annotation is inline /// </returns> public bool IsInline() { return label.inline(); } /// <summary> /// This is used to describe the annotation and method or field /// that this label represents. This is used to provide error /// messages that can be used to debug issues that occur when /// processing a method. This will provide enough information /// such that the problem can be isolated correctly. /// </summary> /// <returns> /// this returns a string representation of the label /// </returns> public String ToString() { return detail.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using Votyra.Core.Images; using Votyra.Core.ImageSamplers; using Votyra.Core.Models; using Votyra.Core.Pooling; using Votyra.Core.TerrainMeshes; using Votyra.Core.Utils; namespace Votyra.Core.TerrainGenerators.TerrainMeshers { public class TerrainMesherWithWalls3b : ITerrainMesher3b { public static readonly Vector3f CenterZeroCell = new Vector3f(0.5f, 0.5f, 0.5f); private static readonly List<SampledData3b> DataWithoutTriangles = new List<SampledData3b>(); private static readonly SampledData3b[] NormalizedSamples = SampledData3b.AllValues.Select(o => ChooseTrianglesForCell(o) .Item1) .ToArray(); private static readonly IReadOnlyCollection<Triangle3f>[] MainPlaneTriangles = SampledData3b.AllValues.Select(o => ChooseTrianglesForCell(o) .Item2) .ToArray(); private static readonly IReadOnlyCollection<Triangle3f>[] XWallTriangles = SampledDataWithWall.AllValues.Select(o => { // normalize data var data = NormalizedSamples[o.Data.Data]; var dataXMinus = NormalizedSamples[o.Wall.Data]; return ChooseXWallTriangles(data, dataXMinus); }) .ToArray(); private static readonly IReadOnlyCollection<Triangle3f>[] YWallTriangles = SampledDataWithWall.AllValues.Select(o => { // normalize data var data = NormalizedSamples[o.Data.Data]; var dataYMinus = NormalizedSamples[o.Wall.Data]; return ChooseYWallTriangles(data, dataYMinus); }) .ToArray(); private static readonly IReadOnlyCollection<Triangle3f>[] ZWallTriangles = SampledDataWithWall.AllValues.Select(o => { // normalize data var data = NormalizedSamples[o.Data.Data]; var dataZMinus = NormalizedSamples[o.Wall.Data]; return ChooseZWallTriangles(data, dataZMinus); }) .ToArray(); private readonly Vector3i _cellInGroupCount; private readonly IImageSampler3 _imageSampler; protected Vector3i groupPosition; protected Vector3i groupSize; protected ITerrainMesh mesh; protected IPooledTerrainMesh pooledMesh; public TerrainMesherWithWalls3b(ITerrainConfig terrainConfig, IImageSampler3 imageSampler) { _imageSampler = imageSampler; _cellInGroupCount = terrainConfig.CellInGroupCount; } protected IImage3b Image { get; private set; } public void Initialize(IImage3b image) { Image = image; } public void AddCell(Vector3i cellInGroup) { var cell = cellInGroup + groupPosition; var data = _imageSampler.Sample(Image, cell); var dataXMinus = _imageSampler.Sample(Image, cell + new Vector3i(-1, 0, 0)); var dataYMinus = _imageSampler.Sample(Image, cell + new Vector3i(0, -1, 0)); var dataZMinus = _imageSampler.Sample(Image, cell + new Vector3i(0, 0, -1)); foreach (var tri in MainPlaneTriangles[data.Data]) { mesh.AddTriangle(cell + tri.A, cell + tri.B, cell + tri.C); } foreach (var tri in XWallTriangles[SampledDataWithWall.GetIndexInAllValues(data, dataXMinus)]) { mesh.AddTriangle(cell + tri.A, cell + tri.B, cell + tri.C); } foreach (var tri in YWallTriangles[SampledDataWithWall.GetIndexInAllValues(data, dataYMinus)]) { mesh.AddTriangle(cell + tri.A, cell + tri.B, cell + tri.C); } foreach (var tri in ZWallTriangles[SampledDataWithWall.GetIndexInAllValues(data, dataZMinus)]) { mesh.AddTriangle(cell + tri.A, cell + tri.B, cell + tri.C); } } public IPooledTerrainMesh GetResultingMesh() => pooledMesh; public void InitializeGroup(Vector3i group, IPooledTerrainMesh cleanPooledMesh) { var bounds = Range3i.FromMinAndSize(group * _cellInGroupCount, _cellInGroupCount) .ToRange3f(); groupPosition = _cellInGroupCount * group; pooledMesh = cleanPooledMesh; mesh = pooledMesh.Mesh; mesh.Initialize(null, null); mesh.Reset(Area3f.FromMinAndSize((group * _cellInGroupCount).ToVector3f(), _cellInGroupCount.ToVector3f())); } private static Tuple<SampledData3b, IReadOnlyCollection<Triangle3f>> ChooseTrianglesForCell(SampledData3b data) { var pos_x0y0z0 = new Vector3f(0, 0, 0); var pos_x0y0z1 = new Vector3f(0, 0, 1); var pos_x0y1z0 = new Vector3f(0, 1, 0); var pos_x0y1z1 = new Vector3f(0, 1, 1); var pos_x1y0z0 = new Vector3f(1, 0, 0); var pos_x1y0z1 = new Vector3f(1, 0, 1); var pos_x1y1z0 = new Vector3f(1, 1, 0); var pos_x1y1z1 = new Vector3f(1, 1, 1); //TODO slopes might be usefull to also do only subset, since there can be some small outlier like: // 1-----1 // /| /| // 1-+---1 | // | 0---+-1 // |/ |/ // 1-----0 SampledData3b rotatedTemplate; Matrix4x4f matrix; if (data.Data == 0 || data.Data == byte.MaxValue) return Tuple.Create(data, Array.Empty<Triangle3f>() as IReadOnlyCollection<Triangle3f>); // else if (SampledData3b.ParseCube(@" // 0-----0 // /| /| // 0-+---0 | // | 1---+-1 // |/ |/ // 1-----1 // ").EqualsRotationInvariant(data, out matrix, false, false, true, false)) // plane // { // matrix = matrix.Inverse; // var isInverted = matrix.Determinant < 0; // return Tuple.Create(data, TerrainMeshExtensions // .GetQuadTriangles( // matrix.MultiplyPoint(pos_x0y0z0), // matrix.MultiplyPoint(pos_x0y1z0), // matrix.MultiplyPoint(pos_x1y0z0), // matrix.MultiplyPoint(pos_x1y1z0), false) // .ChangeOrderIfTrue(isInverted) // .ToArray() as IReadOnlyCollection<Triangle3f>); // } if (SampledData3b.ParseCube(@" 1-----0 /| /| 1-+---0 | | 1---+-1 |/ |/ 1-----1 ") .EqualsRotationInvariant(data, out matrix, false, false, true, false)) //simple slope { matrix = matrix.Inverse; var isInverted = matrix.Determinant < 0; return Tuple.Create(data, TerrainMeshExtensions.GetQuadTriangles(matrix.MultiplyPoint(pos_x0y0z1), matrix.MultiplyPoint(pos_x0y1z1), matrix.MultiplyPoint(pos_x1y0z0), matrix.MultiplyPoint(pos_x1y1z0), false) .ChangeOrderIfTrue(isInverted) .ToArray() as IReadOnlyCollection<Triangle3f>); } if (SampledData3b.ParseCube(@" 1-----0 /| /| 1-+---1 | | 1---+-0 |/ |/ 1-----1 ") .EqualsRotationInvariant(data, out matrix, false, false, true, false)) //diagonal plane { matrix = matrix.Inverse; var isInverted = matrix.Determinant < 0; return Tuple.Create(data, new[] {new Triangle3f(matrix.MultiplyPoint(pos_x1y0z0), matrix.MultiplyPoint(pos_x0y1z0), matrix.MultiplyPoint(pos_x0y1z1)), new Triangle3f(matrix.MultiplyPoint(pos_x1y0z1), matrix.MultiplyPoint(pos_x1y0z0), matrix.MultiplyPoint(pos_x0y1z1))}.ChangeOrderIfTrue(isInverted) .ToArray() as IReadOnlyCollection<Triangle3f>); } if (SampledData3b.ParseCube(@" 0-----1 /| /| 1-+---0 | | 1---+-1 |/ |/ 1-----1 ") .EqualsRotationInvariant(data, out matrix, false, false, true, false)) //dual diagonal slope { matrix = matrix.Inverse; var isInverted = matrix.Determinant < 0; return Tuple.Create(data, new[] {new Triangle3f(matrix.MultiplyPoint(pos_x0y0z1), matrix.MultiplyPoint(pos_x1y0z0), matrix.MultiplyPoint(pos_x1y1z1)), new Triangle3f(matrix.MultiplyPoint(pos_x0y0z1), matrix.MultiplyPoint(pos_x1y1z1), matrix.MultiplyPoint(pos_x0y1z0))}.ChangeOrderIfTrue(isInverted) .ToArray() as IReadOnlyCollection<Triangle3f>); } if (SampledData3b.ParseCube(@" 1-----0 /| /| 1-+---1 | | 1---+-1 |/ |/ 1-----1 ") .IsContainedInRotationInvariant(data, out matrix, out rotatedTemplate, false, false, true, false)) // diagonal slope upper { matrix = matrix.Inverse; var isInverted = matrix.Determinant < 0; return Tuple.Create(rotatedTemplate, new[] {new Triangle3f(matrix.MultiplyPoint(pos_x0y1z1), matrix.MultiplyPoint(pos_x1y0z1), matrix.MultiplyPoint(pos_x1y1z0))}.ChangeOrderIfTrue(isInverted) .ToArray() as IReadOnlyCollection<Triangle3f>); } // else if (SampledData3b.ParseCube(@" // 0-----0 // /| /| // 1-+---0 | // | 1---+-1 // |/ |/ // 1-----1 // ").IsContainedInRotationInvariant(data, out matrix, out rotatedTemplate, false, false, true, false)) // diagonal slope, with bottom // { // matrix = matrix.Inverse; // var isInverted = matrix.Determinant < 0; // return Tuple.Create(rotatedTemplate, new Triangle3f[]{ // new Triangle3f( // matrix.MultiplyPoint(pos_x1y0z0), // matrix.MultiplyPoint(pos_x0y1z0), // matrix.MultiplyPoint(pos_x0y0z1)), // new Triangle3f( // matrix.MultiplyPoint(pos_x1y0z0), // matrix.MultiplyPoint(pos_x1y1z0), // matrix.MultiplyPoint(pos_x0y1z0)) // }.ChangeOrderIfTrue(isInverted) // .ToArray() as IReadOnlyCollection<Triangle3f>); // } if (SampledData3b.ParseCube(@" 0-----0 /| /| 1-+---0 | | 1---+-0 |/ |/ 1-----1 ") .IsContainedInRotationInvariant(data, out matrix, out rotatedTemplate, false, false, true, false)) // diagonal slope, no bottom { matrix = matrix.Inverse; var isInverted = matrix.Determinant < 0; return Tuple.Create(rotatedTemplate, new Triangle3f(matrix.MultiplyPoint(pos_x1y0z0), matrix.MultiplyPoint(pos_x0y1z0), matrix.MultiplyPoint(pos_x0y0z1)).AsEnumerable() .ChangeOrderIfTrue(isInverted) .ToArray() as IReadOnlyCollection<Triangle3f>); } // else if (SampledData3b.ParseCube(@" // 0-----0 // /| /| // 0-+---0 | // | 1---+-0 // |/ |/ // 1-----1 // ").IsContainedInRotationInvariant(data, out matrix, out rotatedTemplate, false, false, true, false)) // partial plane // { // matrix = matrix.Inverse; // var isInverted = matrix.Determinant < 0; // return Tuple.Create(rotatedTemplate, new Triangle3f( // matrix.MultiplyPoint(pos_x0y0z0), // /* Unmerged change from project 'Zenject.Editor' // Before: // matrix.MultiplyPoint(pos_x0y0z0), // matrix.MultiplyPoint(pos_x1y0z0), // matrix.MultiplyPoint(pos_x0y1z0)) // After: // matrix.MultiplyPoint(pos_x1y0z0), // matrix.MultiplyPoint(pos_x0y1z0)) // */ // } return Tuple.Create(new SampledData3b(), Array.Empty<Triangle3f>() as IReadOnlyCollection<Triangle3f>); } private static IReadOnlyCollection<Triangle3f> ChooseXWallTriangles(SampledData3b data, SampledData3b dataXMinus) { var triangles = new List<Triangle3f>(); var centerXMinus = (dataXMinus.Data_x1y0z0 ? 1 : 0) + (dataXMinus.Data_x1y0z1 ? 1 : 0) + (dataXMinus.Data_x1y1z0 ? 1 : 0) + (dataXMinus.Data_x1y1z1 ? 1 : 0) > 2; var centerX = (data.Data_x0y0z0 ? 1 : 0) + (data.Data_x0y0z1 ? 1 : 0) + (data.Data_x0y1z0 ? 1 : 0) + (data.Data_x0y1z1 ? 1 : 0) > 2; var isBottomTri = data.Data_x0y0z0 && data.Data_x0y1z0 && centerX; var isBottomTriMinus = dataXMinus.Data_x1y0z0 && dataXMinus.Data_x1y1z0 && centerXMinus; if (isBottomTri != isBottomTriMinus) triangles.AddTriangle(new Vector3f(0, 0, 0), new Vector3f(0, 1, 0), new Vector3f(0, 0.5f, 0.5f), isBottomTri); var isTopTri = data.Data_x0y0z1 && data.Data_x0y1z1 && centerX; var isTopTriMinus = dataXMinus.Data_x1y0z1 && dataXMinus.Data_x1y1z1 && centerXMinus; if (isTopTri != isTopTriMinus) triangles.AddTriangle(new Vector3f(0, 1, 1), new Vector3f(0, 0, 1), new Vector3f(0, 0.5f, 0.5f), isTopTri); var isLeftTri = data.Data_x0y0z0 && data.Data_x0y0z1 && centerX; var isLeftTriMinus = dataXMinus.Data_x1y0z0 && dataXMinus.Data_x1y0z1 && centerXMinus; if (isLeftTri != isLeftTriMinus) triangles.AddTriangle(new Vector3f(0, 0, 1), new Vector3f(0, 0, 0), new Vector3f(0, 0.5f, 0.5f), isLeftTri); var isRightTri = data.Data_x0y1z0 && data.Data_x0y1z1 && centerX; var isRightTriMinus = dataXMinus.Data_x1y1z0 && dataXMinus.Data_x1y1z1 && centerXMinus; if (isRightTri != isRightTriMinus) triangles.AddTriangle(new Vector3f(0, 1, 0), new Vector3f(0, 1, 1), new Vector3f(0, 0.5f, 0.5f), isRightTri); return triangles; } private static IReadOnlyCollection<Triangle3f> ChooseYWallTriangles(SampledData3b data, SampledData3b dataYMinus) { var triangles = new List<Triangle3f>(); var centerYMinus = (dataYMinus.Data_x0y1z0 ? 1 : 0) + (dataYMinus.Data_x0y1z1 ? 1 : 0) + (dataYMinus.Data_x1y1z0 ? 1 : 0) + (dataYMinus.Data_x1y1z1 ? 1 : 0) > 2; var centerY = (data.Data_x0y0z0 ? 1 : 0) + (data.Data_x0y0z1 ? 1 : 0) + (data.Data_x1y0z0 ? 1 : 0) + (data.Data_x1y0z1 ? 1 : 0) > 2; var isBottomTri = data.Data_x0y0z0 && data.Data_x1y0z0 && centerY; var isBottomTriMinus = dataYMinus.Data_x0y1z0 && dataYMinus.Data_x1y1z0 && centerYMinus; if (isBottomTri != isBottomTriMinus) triangles.AddTriangle(new Vector3f(0, 0, 0), new Vector3f(1, 0, 0), new Vector3f(0.5f, 0, 0.5f), isBottomTriMinus); var isTopTri = data.Data_x0y0z1 && data.Data_x1y0z1 && centerY; var isTopTriMinus = dataYMinus.Data_x0y1z1 && dataYMinus.Data_x1y1z1 && centerYMinus; if (isTopTri != isTopTriMinus) triangles.AddTriangle(new Vector3f(1, 0, 1), new Vector3f(0, 0, 1), new Vector3f(0.5f, 0, 0.5f), isTopTriMinus); var isLeftTri = data.Data_x0y0z0 && data.Data_x0y0z1 && centerY; var isLeftTriMinus = dataYMinus.Data_x0y1z0 && dataYMinus.Data_x0y1z1 && centerYMinus; if (isLeftTri != isLeftTriMinus) triangles.AddTriangle(new Vector3f(0, 0, 1), new Vector3f(0, 0, 0), new Vector3f(0.5f, 0, 0.5f), isLeftTriMinus); var isRightTri = data.Data_x1y0z0 && data.Data_x1y0z1 && centerY; var isRightTriMinus = dataYMinus.Data_x1y1z0 && dataYMinus.Data_x1y1z1 && centerYMinus; if (isRightTri != isRightTriMinus) triangles.AddTriangle(new Vector3f(1, 0, 0), new Vector3f(1, 0, 1), new Vector3f(0.5f, 0, 0.5f), isRightTriMinus); return triangles; } private static IReadOnlyCollection<Triangle3f> ChooseZWallTriangles(SampledData3b data, SampledData3b dataZMinus) { var triangles = new List<Triangle3f>(); var centerZMinus = (dataZMinus.Data_x0y0z1 ? 1 : 0) + (dataZMinus.Data_x0y1z1 ? 1 : 0) + (dataZMinus.Data_x1y0z1 ? 1 : 0) + (dataZMinus.Data_x1y1z1 ? 1 : 0) > 2; var centerZ = (data.Data_x0y0z0 ? 1 : 0) + (data.Data_x0y1z0 ? 1 : 0) + (data.Data_x1y0z0 ? 1 : 0) + (data.Data_x1y1z0 ? 1 : 0) > 2; var isBottomTri = data.Data_x0y0z0 && data.Data_x1y0z0 && centerZ; var isBottomTriMinus = dataZMinus.Data_x0y0z1 && dataZMinus.Data_x1y0z1 && centerZMinus; if (isBottomTri != isBottomTriMinus) triangles.AddTriangle(new Vector3f(0, 0, 0), new Vector3f(1, 0, 0), new Vector3f(0.5f, 0.5f, 0), isBottomTri); var isTopTri = data.Data_x0y1z0 && data.Data_x1y1z0 && centerZ; var isTopTriMinus = dataZMinus.Data_x0y1z1 && dataZMinus.Data_x1y1z1 && centerZMinus; if (isTopTri != isTopTriMinus) triangles.AddTriangle(new Vector3f(1, 1, 0), new Vector3f(0, 1, 0), new Vector3f(0.5f, 0.5f, 0), isTopTri); var isLeftTri = data.Data_x0y0z0 && data.Data_x0y1z0 && centerZ; var isLeftTriMinus = dataZMinus.Data_x0y0z1 && dataZMinus.Data_x0y1z1 && centerZMinus; if (isLeftTri != isLeftTriMinus) triangles.AddTriangle(new Vector3f(0, 1, 0), new Vector3f(0, 0, 0), new Vector3f(0.5f, 0.5f, 0), isLeftTri); var isRightTri = data.Data_x1y0z0 && data.Data_x1y1z0 && centerZ; var isRightTriMinus = dataZMinus.Data_x1y0z1 && dataZMinus.Data_x1y1z1 && centerZMinus; if (isRightTri != isRightTriMinus) triangles.AddTriangle(new Vector3f(1, 0, 0), new Vector3f(1, 1, 0), new Vector3f(0.5f, 0.5f, 0), isRightTri); return triangles; } private struct SampledDataWithWall { public readonly SampledData3b Data; public readonly SampledData3b Wall; public SampledDataWithWall(SampledData3b data, SampledData3b wall) { Data = data; Wall = wall; } public static IEnumerable<SampledDataWithWall> AllValues { get { foreach (var data in SampledData3b.AllValues) { foreach (var wall in SampledData3b.AllValues) { yield return new SampledDataWithWall(data, wall); } } } } public static int GetIndexInAllValues(SampledData3b data, SampledData3b wall) => (data.Data << 8) | wall.Data; } } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Arch.CMessaging.Client.Newtonsoft.Json.Linq; using Arch.CMessaging.Client.Newtonsoft.Json; namespace Avro { /// <summary> /// Class for fields defined in a record /// </summary> public class Field { /// <summary> /// Enum for the sorting order of record fields /// </summary> public enum SortOrder { ascending, descending, ignore } /// <summary> /// Name of the field. /// </summary> public readonly string Name; /// <summary> /// List of aliases for the field name /// </summary> public readonly IList<string> aliases; /// <summary> /// Position of the field within its record. /// </summary> public int Pos { get; private set; } /// <summary> /// Documentation for the field, if any. Null if there is no documentation. /// </summary> public string Documentation { get; private set; } /// <summary> /// The default value for the field stored as JSON object, if defined. Otherwise, null. /// </summary> public JToken DefaultValue { get; private set; } /// <summary> /// Order of the field /// </summary> public SortOrder? Ordering { get; private set; } /// <summary> /// Field type's schema /// </summary> public Schema Schema { get; private set; } /// <summary> /// Custom properties for the field. We don't store the fields custom properties in /// the field type's schema because if the field type is only a reference to the schema /// instead of an actual schema definition, then the schema could already have it's own set /// of custom properties when it was previously defined. /// </summary> private readonly PropertyMap Props; /// <summary> /// Static comparer object for JSON objects such as the fields default value /// </summary> internal static JTokenEqualityComparer JtokenEqual = new JTokenEqualityComparer(); /// <summary> /// A flag to indicate if reader schema has a field that is missing from writer schema and has a default value /// This is set in CanRead() which is always be called before deserializing data /// </summary> /// <summary> /// Constructor for the field class /// </summary> /// <param name="schema">schema for the field type</param> /// <param name="name">name of the field</param> /// <param name="aliases">list of aliases for the name of the field</param> /// <param name="pos">position of the field</param> /// <param name="doc">documentation for the field</param> /// <param name="defaultValue">field's default value if it exists</param> /// <param name="sortorder">sort order of the field</param> internal Field(Schema schema, string name, IList<string> aliases, int pos, string doc, JToken defaultValue, SortOrder sortorder, PropertyMap props) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name", "name cannot be null."); if (null == schema) throw new ArgumentNullException("type", "type cannot be null."); this.Schema = schema; this.Name = name; this.aliases = aliases; this.Pos = pos; this.Documentation = doc; this.DefaultValue = defaultValue; this.Ordering = sortorder; this.Props = props; } /// <summary> /// Writes the Field class in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace for the field</param> protected internal void writeJson(JsonTextWriter writer, SchemaNames names, string encspace) { writer.WriteStartObject(); JsonHelper.writeIfNotNullOrEmpty(writer, "name", this.Name); JsonHelper.writeIfNotNullOrEmpty(writer, "doc", this.Documentation); if (null != this.DefaultValue) { writer.WritePropertyName("default"); this.DefaultValue.WriteTo(writer, null); } if (null != this.Schema) { writer.WritePropertyName("type"); Schema.WriteJson(writer, names, encspace); } if (null != this.Props) this.Props.WriteJson(writer); if (null != aliases) { writer.WritePropertyName("aliases"); writer.WriteStartArray(); foreach (string name in aliases) writer.WriteValue(name); writer.WriteEndArray(); } writer.WriteEndObject(); } /// <summary> /// Parses the 'aliases' property from the given JSON token /// </summary> /// <param name="jtok">JSON object to read</param> /// <returns>List of string that represents the list of alias. If no 'aliases' specified, then it returns null.</returns> internal static IList<string> GetAliases(JToken jtok) { JToken jaliases = jtok["aliases"]; if (null == jaliases) return null; if (jaliases.Type != JTokenType.Array) throw new SchemaParseException("Aliases must be of format JSON array of strings"); var aliases = new List<string>(); foreach (JToken jalias in jaliases) { if (jalias.Type != JTokenType.String) throw new SchemaParseException("Aliases must be of format JSON array of strings"); aliases.Add((string)jalias); } return aliases; } /// <summary> /// Returns the field's custom property value given the property name /// </summary> /// <param name="key">custom property name</param> /// <returns>custom property value</returns> public string GetProperty(string key) { if (null == this.Props) return null; string v; return (this.Props.TryGetValue(key, out v)) ? v : null; } /// <summary> /// Compares two field objects /// </summary> /// <param name="obj">field to compare with this field</param> /// <returns>true if two fields are equal, false otherwise</returns> public override bool Equals(object obj) { if (obj == this) return true; if (obj != null && obj is Field) { Field that = obj as Field; return areEqual(that.Name, Name) && that.Pos == Pos && areEqual(that.Documentation, Documentation) && areEqual(that.Ordering, Ordering) && JtokenEqual.Equals(that.DefaultValue, DefaultValue) && that.Schema.Equals(Schema) && areEqual(that.Props, this.Props); } return false; } /// <summary> /// Compares two objects /// </summary> /// <param name="o1">first object</param> /// <param name="o2">second object</param> /// <returns>true if two objects are equal, false otherwise</returns> private static bool areEqual(object o1, object o2) { return o1 == null ? o2 == null : o1.Equals(o2); } /// <summary> /// Hash code function /// </summary> /// <returns></returns> public override int GetHashCode() { return 17 * Name.GetHashCode() + Pos + 19 * getHashCode(Documentation) + 23 * getHashCode(Ordering) + 29 * getHashCode(DefaultValue) + 31 * Schema.GetHashCode() + 37 * getHashCode(Props); } /// <summary> /// Hash code helper function /// </summary> /// <param name="obj"></param> /// <returns></returns> private static int getHashCode(object obj) { return obj == null ? 0 : obj.GetHashCode(); } } }
using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace System.Interop.Intermediate { [DebuggerDisplay("{DebuggerDisplay}")] class IlReader { private static readonly object s_lock = new object(); private static Dictionary<short, OpCode> s_reflectionmap; private static readonly FieldInfo s_Ilstream; private static readonly FieldInfo s_Lenghtfield; private ReadState _state; private byte[] _il; private int _readoffset; private readonly Dictionary<short, OpCode> _ocmap = GetReflectionOpCodeMap(); private readonly MethodBase _method; private readonly MethodBody _body; private int _instructionsRead; private int _offset; private int _instructionSize; private object _operand; private OpCode _opcode; public enum ReadState { None, Initial, Reading, EOF } static IlReader() { if (Environment.OSVersion.Platform == PlatformID.Unix) // mono { s_Ilstream = typeof(ILGenerator).GetField("code", BindingFlags.NonPublic | BindingFlags.Instance); s_Lenghtfield = typeof(ILGenerator).GetField("code_len", BindingFlags.NonPublic | BindingFlags.Instance); } else { s_Ilstream = typeof(ILGenerator).GetField("m_ILStream", BindingFlags.NonPublic | BindingFlags.Instance); s_Lenghtfield = typeof(ILGenerator).GetField("m_length", BindingFlags.NonPublic | BindingFlags.Instance); } Debug.Assert(s_Ilstream != null && s_Lenghtfield != null); } public IlReader(MethodBase method) { if (method == null) throw new ArgumentNullException("method"); //Utilities.PretendVariableIsUsed(DebuggerDisplay); _method = method; if (!(method is DynamicMethod)) _body = method.GetMethodBody(); int illength; byte[] il; GetILBuffer(method, out il, out illength); if (il.Length != illength) { byte[] orig = il; il = new byte[illength]; Buffer.BlockCopy(orig, 0, il, 0, illength); } Initialize(il); } /// <summary> /// For unit testing. /// </summary> /// <param name="il"></param> public IlReader(byte[] il) { Initialize(il); } private string DebuggerDisplay { get { return string.Format("{0} {1} ({2})", OpCode.Name, Operand, Offset); } } static Dictionary<short, OpCode> GetReflectionOpCodeMap() { if (s_reflectionmap == null) { lock (s_lock) { if (s_reflectionmap == null) { s_reflectionmap = new Dictionary<short, OpCode>(); FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public); foreach (FieldInfo field in fields) { if (field.FieldType != typeof(OpCode)) throw new Exception("Unexpected field type: " + field.FieldType.FullName); OpCode oc = (OpCode)field.GetValue(null); s_reflectionmap.Add(oc.Value, oc); } } } } return s_reflectionmap; } public void GetILBuffer(MethodBase method, out byte[] il, out int ilLength) { if (_method is DynamicMethod) { ILGenerator gen = ((DynamicMethod)_method).GetILGenerator(); il = (byte[])s_Ilstream.GetValue(gen); ilLength = (int)s_Lenghtfield.GetValue(gen); } else { MethodBody body = _method.GetMethodBody(); il = body.GetILAsByteArray(); ilLength = il.Length; } } public ReadState State { get { return _state; } } public int InstructionsRead { get { return _instructionsRead; } } private LocalVariableInfo GetLocalVariable(int index) { if (_body == null) { if (_method is DynamicMethod) throw new NotSupportedException("Use of local variables in DynamicMethod is not supported."); Debug.Fail("DynamicMethod"); } return _body.LocalVariables[index]; } private void Initialize(byte[] il) { _il = il; _state = ReadState.Initial; } public void Reset() { _state = ReadState.Initial; _readoffset = default(int); _operand = default(object); _opcode = default(OpCode); _instructionsRead = default(int); } public bool Read() { if (_readoffset == _il.Length) { _state = ReadState.EOF; return false; } _state = ReadState.Reading; _instructionsRead++; _offset = _readoffset; _operand = null; //if (_opcodestack.Count > 0) //{ // KeyValuePair<IrOpCode, int> pair = _opcodestack.Pop(); // _opcode = pair.Key; // _operand = pair.Value; // // Wouldn't be good if both instructions got the same offset. // // We give the offset to the first of the decomposed instructions, and since we're at this place, we're not at the first one. // _offset = -1; // return true; //} ushort ocval; if (_il[_readoffset] == 0xfe) { if (!(_readoffset + 1 < _il.Length)) throw new Exception("_readoffset + 1 < _il.Length"); ocval = (ushort)((_il[_readoffset] << 8) | _il[_readoffset + 1]); _readoffset += 2; } else { ocval = _il[_readoffset]; _readoffset += 1; } OpCode srOpcode; try { srOpcode = _ocmap[(short)ocval]; } catch (KeyNotFoundException) { throw new IlParseException(string.Format("Opcode bytes {0:x4} from IL offset {1:x6} does not exist in the opcode map. This indicates invalid IL or a bug in this class.", ocval, Offset)); } if (srOpcode.OpCodeType == OpCodeType.Prefix) throw new NotImplementedException("Prefix opcodes are not implemented. Used prefix is: " + srOpcode.Name + "."); try { ReadInstructionArguments(srOpcode); RemoveMacro(ref srOpcode); } catch (Exception e) { throw new IlParseException(string.Format("An error occurred while reading IL starting at offset {0:x4}.", Offset), e); } _opcode = srOpcode; _instructionSize = _readoffset - Offset; // ReadInstructionArguments will have determined a relative offset. if ((OpCode.FlowControl == FlowControl.Branch) || (OpCode.FlowControl == FlowControl.Cond_Branch)) _operand = (Offset + InstructionSize) + (int)_operand; //if (_readoffset == _il.Length) // _state = ReadState.EOF; return true; } /// <summary> /// The offset, in bytes, of the current instruction. /// </summary> public int Offset { get { return _offset; } } /// <summary> /// The size of the current instruction in bytes, including prefixes and tokens etc. /// </summary> public int InstructionSize { get { return _instructionSize; } } /// <summary> /// Finishes reading the specified opcode from the il and prepares the opcode operand. /// </summary> /// <param name="srOpcode"></param> private void ReadInstructionArguments(OpCode srOpcode) { switch (srOpcode.OperandType) { case OperandType.InlineBrTarget: int xtoken; uint xindex; _operand = ReadInt32(); break; case OperandType.InlineField: xtoken = ReadInt32(); _operand = _method.Module.ResolveField(xtoken); break; case OperandType.InlineI: _operand = ReadInt32(); break; case OperandType.InlineI8: _operand = ReadInt64(); break; case OperandType.InlineMethod: xtoken = ReadInt32(); _operand = _method.Module.ResolveMethod(xtoken); break; case OperandType.InlineNone: break; // case OperandType.InlinePhi: // break; case OperandType.InlineR: _operand = ReadDouble(); break; case OperandType.InlineSig: xtoken = ReadInt32(); _operand = _method.Module.ResolveSignature(xtoken); break; case OperandType.InlineString: xtoken = ReadInt32(); _operand = _method.Module.ResolveString(xtoken); break; case OperandType.InlineSwitch: throw new NotImplementedException("Switch is not implemented."); case OperandType.InlineTok: _operand = ReadInt32(); break; case OperandType.InlineType: xtoken = ReadInt32(); _operand = _method.Module.ResolveType(xtoken); break; case OperandType.ShortInlineVar: xindex = (uint)ReadInt8(); if ((srOpcode == OpCodes.Ldarg_S) || (srOpcode == OpCodes.Ldarga_S) || (srOpcode == OpCodes.Starg_S)) _operand = (((_method.CallingConvention & CallingConventions.HasThis) != 0) && (srOpcode != OpCodes.Newobj) ? _method.GetParameters()[xindex - 1] : _method.GetParameters()[xindex]); else { if (!((srOpcode == OpCodes.Ldloc_S) || (srOpcode == OpCodes.Ldloca_S) || (srOpcode == OpCodes.Stloc_S))) throw new Exception("Not loc?!"); _operand = GetLocalVariable((int)xindex); } break; case OperandType.InlineVar: xindex = (uint)ReadInt16(); if ((srOpcode == OpCodes.Ldarg) || (srOpcode == OpCodes.Ldarga) || (srOpcode == OpCodes.Starg)) _operand = (((_method.CallingConvention & CallingConventions.HasThis) != 0) && (srOpcode != OpCodes.Newobj) ? _method.GetParameters()[xindex - 1] : _method.GetParameters()[xindex]); else { if (!((srOpcode == OpCodes.Ldloc) || (srOpcode == OpCodes.Ldloca) || (srOpcode == OpCodes.Stloc))) throw new Exception("Not loc?!"); _operand = GetLocalVariable((int)xindex); } break; case OperandType.ShortInlineBrTarget: _operand = ReadInt8(); break; case OperandType.ShortInlineI: // ldc.i4.s and unaligned prefix. unaligned only uses small positive values, so we can pretend it's signed in both cases. _operand = ReadInt8(); break; case OperandType.ShortInlineR: _operand = ReadSingle(); break; default: throw new IlSemanticErrorException("Unknown operand type: " + srOpcode.OperandType); } } private float ReadSingle() { int i = ReadInt32(); return Utilities.ReinterpretAsSingle(i); } private double ReadDouble() { long l = ReadInt64(); return Utilities.ReinterpretAsDouble(l); } /// <summary> /// Gets rid of macro opcodes except for some of the branches. /// </summary> /// <param name="srOpcode"></param> private void RemoveMacro(ref OpCode srOpcode) { // stloc. { if (srOpcode == OpCodes.Stloc_S) { srOpcode = OpCodes.Stloc; return; } else if ((srOpcode.Value >= OpCodes.Stloc_0.Value) && (srOpcode.Value <= OpCodes.Stloc_3.Value)) { int varindex = srOpcode.Value - OpCodes.Stloc_0.Value; _operand = GetLocalVariable(varindex); srOpcode = OpCodes.Stloc; } } // ldloc. { if (srOpcode == OpCodes.Ldloc_S) { srOpcode = OpCodes.Ldloc; return; } else if ((srOpcode.Value >= OpCodes.Ldloc_0.Value) && (srOpcode.Value <= OpCodes.Ldloc_3.Value)) { int varindex = srOpcode.Value - OpCodes.Ldloc_0.Value; _operand = GetLocalVariable(varindex); srOpcode = OpCodes.Ldloc; return; } } // ldloca. { if (srOpcode == OpCodes.Ldloca_S) { srOpcode = OpCodes.Ldloca; return; } } // starg. { if (srOpcode == OpCodes.Starg_S) { srOpcode = OpCodes.Starg; return; } } // ldarg(a) { // Q: What should _operand be when it's a 'this' argument? if (srOpcode == OpCodes.Ldarg_S) { srOpcode = OpCodes.Ldarg; return; } else if ((srOpcode.Value >= OpCodes.Ldarg_0.Value) && (srOpcode.Value <= OpCodes.Ldarg_3.Value)) { //if (!_method.IsStatic) // throw new NotSupportedException("Instances are not supported."); int index = srOpcode.Value - OpCodes.Ldarg_0.Value; if (((_method.CallingConvention & CallingConventions.HasThis) != 0) && (srOpcode != OpCodes.Newobj)) // if "this" then there is no ParameterInfo to represent the this parameter. _operand = (index != 0 ? _method.GetParameters()[index - 1] : null); else _operand = _method.GetParameters()[index]; srOpcode = OpCodes.Ldarg; return; } else if (srOpcode == OpCodes.Ldarga_S) { srOpcode = OpCodes.Ldarga; return; } } // beq. { if (srOpcode == OpCodes.Beq_S) srOpcode = OpCodes.Beq; // if (srOpcode == OpCodes.Beq) // { // srOpcode = OpCodes.Ceq; // _opcodestack.Push(new KeyValuePair<IROpCode, int>(IROpCodes.Brtrue, (int) _operand)); // _operand = null; // return; // } } // bge(.un) { if (srOpcode == OpCodes.Bge_S) { srOpcode = OpCodes.Bge; return; } if (srOpcode == OpCodes.Bge_Un_S) { srOpcode = OpCodes.Bge_Un; return; } } // bgt(.un) { if (srOpcode == OpCodes.Bgt_S) { srOpcode = OpCodes.Bgt; return; } if (srOpcode == OpCodes.Bgt_Un_S) { srOpcode = OpCodes.Bgt_Un; return; } } // ble(.un) { if (srOpcode == OpCodes.Ble_S) { srOpcode = OpCodes.Ble; return; } if (srOpcode == OpCodes.Ble_Un_S) { srOpcode = OpCodes.Ble_Un; return; } } // blt(.un) { if (srOpcode == OpCodes.Blt_S) { srOpcode = OpCodes.Blt; return; } if (srOpcode == OpCodes.Blt_Un_S) { srOpcode = OpCodes.Blt_Un; return; } } // bne.un { if (srOpcode == OpCodes.Bne_Un_S) { srOpcode = OpCodes.Bne_Un; return; } } // br { if (srOpcode == OpCodes.Br_S) { srOpcode = OpCodes.Br; return; } } // br(false/null/zero). { if (srOpcode == OpCodes.Brfalse_S) { srOpcode = OpCodes.Brfalse; return; } } // br(true/inst). { if (srOpcode == OpCodes.Brtrue_S) { srOpcode = OpCodes.Brtrue; return; } } // ldc. { if ((srOpcode.Value >= OpCodes.Ldc_I4_M1.Value) && (srOpcode.Value <= OpCodes.Ldc_I4_8.Value)) { _operand = srOpcode.Value - OpCodes.Ldc_I4_0.Value; srOpcode = OpCodes.Ldc_I4; return; } else if (srOpcode == OpCodes.Ldc_I4_S) { srOpcode = OpCodes.Ldc_I4; return; } } // leave. { if (srOpcode == OpCodes.Leave_S) { srOpcode = OpCodes.Leave; return; } } if (srOpcode == OpCodes.Ldtoken) { int token = ReadInt32(); _operand = token; return; } } /// <summary> /// Four-byte integers in the IL stream are little-endian. /// </summary> /// <returns></returns> private short ReadInt16() { short i = (short)(_il[_readoffset] | (_il[_readoffset + 1] << 8)); _readoffset += 2; return i; } /// <summary> /// Two-byte integers in the IL stream are little-endian. /// </summary> /// <returns></returns> private int ReadInt32() { int i = ((_il[_readoffset] | (_il[_readoffset + 1] << 8)) | (_il[_readoffset + 2] << 0x10)) | (_il[_readoffset + 3] << 0x18); _readoffset += 4; return i; } private long ReadInt64() { long num3 = (((_il[_readoffset + 0]) | (_il[_readoffset + 1] << 8)) | (_il[_readoffset + 2] << 0x10)) | (uint)(_il[_readoffset + 3] << 0x18); long num4 = (uint)(((_il[_readoffset + 4]) | (_il[_readoffset + 5] << 8)) | (_il[_readoffset + 6] << 0x10)) | (uint)(_il[_readoffset + 7] << 0x18); _readoffset += 8; return num3 | (num4 << 0x20); } /// <summary> /// Reads a single signed byte from the IL and returns it as an int. /// </summary> /// <returns></returns> private int ReadInt8() { return (sbyte)_il[_readoffset++]; } public object Operand { get { return _operand; } } public OpCode OpCode { get { return _opcode; } } } }
using Api.Areas.HelpPage.ModelDescriptions; using Api.Areas.HelpPage.Models; 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; namespace Api.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); } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace VRS.UI.Controls { /// <summary> /// Summary description for WTextBoxBase. /// </summary> [System.ComponentModel.ToolboxItem(false)] public class WTextBoxBase : System.Windows.Forms.TextBox, ISupportInitialize { public event WMessage_EventHandler ProccessMessage; private WEditBox_Mask m_WEditBox_Mask = WEditBox_Mask.Text; private int m_DecPlaces = 2; private int m_DecMinValue = -999999999; private int m_DecMaxValue = 999999999; private bool m_Initing = false; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public WTextBoxBase() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitForm call } #region function Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #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() { components = new System.ComponentModel.Container(); } #endregion #region override WndProc protected override void WndProc(ref Message m) { if(!OnWndProc(ref m)){ base.WndProc(ref m); } } #endregion #region override OnKeyPress protected override void OnKeyPress(KeyPressEventArgs e) { switch(m_WEditBox_Mask) { case WEditBox_Mask.Numeric: e.Handled = !IsNeedeKey_Numeric(e.KeyChar); break; case WEditBox_Mask.Date: e.Handled = Handle_Date(e.KeyChar); break; default: break; } base.OnKeyPress(e); } #endregion #region override OnKeyDown protected override void OnKeyDown(KeyEventArgs e) { if(this.Mask == WEditBox_Mask.Date && e.KeyData == Keys.Delete){ e.Handled = true; } base.OnKeyDown(e); } #endregion #region override OnTextChanged protected override void OnTextChanged(System.EventArgs e) { if(m_WEditBox_Mask == WEditBox_Mask.Numeric){ if(this.Text.StartsWith("-")){ this.ForeColor = Color.Red; } else{ this.ForeColor = Color.Black; } } base.OnTextChanged(e); } #endregion #region function Handle_Date private bool Handle_Date(char keyChar) { if(this.ReadOnly){ return true; } int curIndex = this.SelectionStart; string text = this.Text; int monthIndex = 0; int dayIndex = 3; if(curIndex >= 10 || text.Length < 10){ return true; } //--- Get if day->month->year or month->day->year ---// DateTime t = new DateTime(2000,2,1); string tStr = t.ToShortDateString(); if(tStr.IndexOf("1") > tStr.IndexOf("2")){ dayIndex = 3; monthIndex = 0; } else{ dayIndex = 0; monthIndex = 3; } //--------------------------------------------------// //--- Digit was pressed -------------------------------------// if(char.IsDigit(keyChar)){ string nText = text.Insert(curIndex,keyChar.ToString()); nText = nText.Remove(curIndex+1,1); int newCursPos = ++curIndex; //--- If cursor in month block -------------------------// if(curIndex >= monthIndex && curIndex < monthIndex + 2){ int mPos1Val = Convert.ToInt32(nText.Substring(monthIndex,1)); int mPos2Val = Convert.ToInt32(nText.Substring(monthIndex + 1,1)); // eg. |13 = 03 ('3' was pressed, '|' = cursor position where key pressed) if(mPos1Val > 1){ nText = nText.Insert(monthIndex,"0"); nText = nText.Remove(monthIndex + 1,1); nText = nText.Insert(monthIndex + 1,mPos1Val.ToString()); nText = nText.Remove(monthIndex + 2,1); mPos2Val = mPos1Val; mPos1Val = 0; newCursPos = monthIndex + 3; } // eg. |13 = 10 ('1' was pressed, '|' = cursor position where key pressed) if(mPos1Val == 1 && mPos2Val > 2 && monthIndex == curIndex-1){ nText = nText.Insert(monthIndex + 1,"0"); nText = nText.Remove(monthIndex + 2,1); } // eg. |00 = 01 ('0' was pressed, '|' = cursor position where key pressed) if(mPos1Val == 0 && mPos2Val == 0){ nText = nText.Insert(monthIndex + 1,"1"); nText = nText.Remove(monthIndex + 2,1); } } //----------------------------------------------------------------// //--- If cursor in day block ------------------------------------// if(curIndex >= dayIndex && curIndex < dayIndex + 2){ int dPos1Val = Convert.ToInt32(nText.Substring(dayIndex,1)); int dPos2Val = Convert.ToInt32(nText.Substring(dayIndex + 1,1)); int month = Convert.ToInt32(nText.Substring(monthIndex,2)); int year = Convert.ToInt32(nText.Substring(6,4)); int maxDayPos1Val = 2; int maxDayPos2Val = 0; if(DateTime.DaysInMonth(year,month) >= 30){ maxDayPos1Val = 3; maxDayPos2Val = DateTime.DaysInMonth(year,month)-30; } else{ maxDayPos2Val = DateTime.DaysInMonth(year,month)-20; } // eg. |41 = 04 ('4' was pressed, '|' = cursor position where key pressed) if(dPos1Val > maxDayPos1Val){ nText = nText.Insert(dayIndex,"0"); nText = nText.Remove(dayIndex + 1,1); nText = nText.Insert(dayIndex + 1,dPos1Val.ToString()); nText = nText.Remove(dayIndex + 2,1); dPos2Val = dPos1Val; dPos1Val = 0; newCursPos = dayIndex + 3; } // eg. |33 = 30 ('3' was pressed, '|' = cursor position where key pressed) if(dPos1Val == maxDayPos1Val && dPos2Val > maxDayPos2Val && dayIndex == curIndex-1){ nText = nText.Insert(dayIndex + 1,"0"); nText = nText.Remove(dayIndex + 2,1); } // eg. |00 = 01 ('0' was pressed, '|' = cursor position where key pressed) if(dPos1Val == 0 && dPos2Val == 0){ nText = nText.Insert(dayIndex + 1,"1"); nText = nText.Remove(dayIndex + 2,1); } } //----------------------------------------------------// if(IsDateOk(nText)){ this.Text = nText; if(newCursPos < 9 && (nText.Substring(newCursPos,1) == "," || nText.Substring(newCursPos,1) == "." || nText.Substring(newCursPos,1) == "/")){ newCursPos++; } this.SelectionStart = newCursPos; } } //---- Char was pressed -----------------------// else{ string kChar = keyChar.ToString(); if(kChar == "," || kChar == "."){ if(curIndex > 0 && (text.Substring(curIndex-1,1) != "," || text.Substring(curIndex-1,1) != "." || text.Substring(curIndex-1,1) != "/")){ if(text.IndexOf(".",curIndex) > -1){ this.SelectionStart = text.IndexOf(".",curIndex) + 1; } } } } return true; } #endregion #region function IsNeedeKey_Numeric private bool IsNeedeKey_Numeric(char pressedChar) { if(this.ReadOnly){ return true; } char decSep = Convert.ToChar(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator); string val = this.Text; bool isSeparator = val.IndexOf(decSep) > -1; int length = val.Length; int curPos = this.SelectionStart; int sepPos = val.IndexOf(decSep); //--- Clear selection if any if(this.SelectionLength > 0){ val = val.Remove(this.SelectionStart,this.SelectionLength); length = val.Length; } // If char is number. if(char.IsDigit(pressedChar)){ // Don't allow to add '-' inside number. // Avoiding following numbers '6-12.00'. if(val.IndexOf("-") > -1 && val.IndexOf("-") > curPos-1){ return false; } // If number starts with '0' and pressedChar = '0', don't allow to enter number. // Avoiding following numbers '06'. if(((val.StartsWith("0") && curPos == 1) || (val.StartsWith("-0") && curPos == 2))){ return false; } // Check that decimal places aren't exceeded. if(isSeparator) { // If current position is inside deciaml places '_,x|xx'. if(curPos > sepPos){ if((curPos - sepPos) > m_DecPlaces){ return false; } // If there is maximun number of decimal places. if((length - sepPos) > m_DecPlaces){ string newVal = val.Remove(curPos,1); newVal = newVal.Insert(curPos,pressedChar.ToString()); this.Text = newVal; this.SelectionStart = curPos + 1; return false; } } } // If '0' was pressed. if(pressedChar == '0'){ if(val.StartsWith("-") && length > 1 && curPos == 1){ return false; } if(length > 0 && curPos == 0){ return false; } } //---- Check that minimum and maximum isn't exceeded -----// string nText = val.Insert(curPos,pressedChar.ToString()); decimal decVal = Core.ConvertToDeciaml(nText); if(decVal > m_DecMaxValue || decVal < m_DecMinValue) { return false; } //----------------------------------------------------------// return true; } //------------- Decimal separator '. / ,' or '-' pressed ----------// else{ // Decimal separator pressed and there isn't any. if(pressedChar == decSep && !isSeparator && m_DecPlaces > 0){ // Check that decimal places aren't exceeded, // when setting decimal place in the middle on number. // eg. 232,312 and allowed decimal places = 2. if(length - curPos > m_DecPlaces){ return false; } return true; } // If '-' pressed if(pressedChar == '-'){ if(!val.StartsWith("-") && curPos == 0){ return true; } } // BackSpace pressed. if(pressedChar == '\b'){ return true; } return false; } } #endregion #region function Handle_Ip private void Handle_Ip() { } #endregion #region function IsDateOk private bool IsDateOk(string date) { try { DateTime dummy = Convert.ToDateTime(date); return true; } catch(Exception x) { return false; } } #endregion #region function DateToString private string DateToString(DateTime val) { string sep = System.Globalization.DateTimeFormatInfo.CurrentInfo.DateSeparator; string format = ""; //--- Get if day->month->year or month->day->year ---// DateTime t = new DateTime(2000,2,1); string tStr = t.ToShortDateString(); if(tStr.IndexOf("1") > tStr.IndexOf("2")){ format = "MM" + sep + "dd" + sep + "yyyy"; } else{ format = "dd" + sep + "MM" + sep + "yyyy"; } //--------------------------------------------------// return val.ToString(format); } #endregion #region Properties Implementation /// <summary> /// /// </summary> public WEditBox_Mask Mask { get{ return m_WEditBox_Mask; } set{ m_WEditBox_Mask = value; this.Text = ""; } } /// <summary> /// /// </summary> public int DecimalPlaces { get{ return m_DecPlaces; } set{ m_DecPlaces = value; } } [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ] public DateTime DateValue { get{ if(this.Mask == WEditBox_Mask.Date){ return Convert.ToDateTime(this.Text); } return DateTime.Today; } set{ if(this.Mask == WEditBox_Mask.Date){ this.Text = DateToString(value); } } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public decimal DecValue { get{ if(this.Mask == WEditBox_Mask.Numeric){ return Convert.ToDecimal(this.Text); } else{ return 0; } } set{ if(this.Mask == WEditBox_Mask.Numeric){ this.Text = value.ToString("f" + m_DecPlaces.ToString()); } } } /// <summary> /// /// </summary> [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] public override string Text { get{ return base.Text; } set{ string val = value; if(this.Mask == WEditBox_Mask.Numeric){ if(val.Length == 0){ val = "0"; } char decSep = Convert.ToChar(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator); val = val.Replace(',',decSep); val = val.Replace('.',decSep); val = Core.ConvertToDeciaml(val).ToString("f" + m_DecPlaces.ToString()); } if(this.Mask == WEditBox_Mask.Date){ if(!IsDateOk(val)){ base.Text = DateToString(DateTime.Today); } else{ base.Text = DateToString(Convert.ToDateTime(val)); } return; } base.Text = val; } } public int DecMinValue { get{ return m_DecMinValue; } set{ m_DecMinValue = value; } } public int DecMaxValue { get{ return m_DecMaxValue; } set{ m_DecMaxValue = value; } } #endregion #region Events Implementation public virtual bool OnWndProc(ref Message m) { if(ProccessMessage != null){ return ProccessMessage(this,ref m); } return false; } #endregion #region ISupportInitialize Implementation public void BeginInit() { m_Initing = true; } public void EndInit() { m_Initing = false; if(this.Mask == WEditBox_Mask.Date){ string val = this.Text; if(!IsDateOk(this.Text)){ val = "01.01.2002"; } string sep = System.Globalization.DateTimeFormatInfo.CurrentInfo.DateSeparator; val = val.Replace(".",sep); val = val.Replace("/",sep); this.Text = val; } } #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.Buffers; using System.Globalization; using System.Linq; using System.Numerics; using System.Reflection; using System.Runtime.InteropServices; using Xunit; namespace System.Text.Unicode.Tests { public partial class Utf16UtilityTests { private unsafe delegate char* GetPointerToFirstInvalidCharDel(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment); private static readonly Lazy<GetPointerToFirstInvalidCharDel> _getPointerToFirstInvalidCharFn = CreateGetPointerToFirstInvalidCharFn(); [Theory] [InlineData("", 0, 0)] // empty string is OK [InlineData("X", 1, 1)] [InlineData("XY", 2, 2)] [InlineData("XYZ", 3, 3)] [InlineData("<EACU>", 1, 2)] [InlineData("X<EACU>", 2, 3)] [InlineData("<EACU>X", 2, 3)] [InlineData("<EURO>", 1, 3)] [InlineData("<GRIN>", 1, 4)] [InlineData("X<GRIN>Z", 3, 6)] [InlineData("X<0000>Z", 3, 3)] // null chars are allowed public void GetIndexOfFirstInvalidUtf16Sequence_WithSmallValidBuffers(string unprocessedInput, int expectedRuneCount, int expectedUtf8ByteCount) { GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, -1 /* expectedIdxOfFirstInvalidChar */, expectedRuneCount, expectedUtf8ByteCount); } [Theory] [InlineData("<DC00>", 0, 0, 0)] // standalone low surrogate (at beginning of sequence) [InlineData("X<DC00>", 1, 1, 1)] // standalone low surrogate (preceded by valid ASCII data) [InlineData("<EURO><DC00>", 1, 1, 3)] // standalone low surrogate (preceded by valid non-ASCII data) [InlineData("<D800>", 0, 0, 0)] // standalone high surrogate (missing follow-up low surrogate) [InlineData("<D800>Y", 0, 0, 0)] // standalone high surrogate (followed by ASCII char) [InlineData("<D800><D800>", 0, 0, 0)] // standalone high surrogate (followed by high surrogate) [InlineData("<D800><EURO>", 0, 0, 0)] // standalone high surrogate (followed by valid non-ASCII char) [InlineData("<DC00><DC00>", 0, 0, 0)] // standalone low surrogate (not preceded by a high surrogate) [InlineData("<DC00><D800>", 0, 0, 0)] // standalone low surrogate (not preceded by a high surrogate) [InlineData("<GRIN><DC00><DC00>", 2, 1, 4)] // standalone low surrogate (preceded by a valid surrogate pair) [InlineData("<GRIN><DC00><D800>", 2, 1, 4)] // standalone low surrogate (preceded by a valid surrogate pair) [InlineData("<GRIN><0000><DC00><D800>", 3, 2, 5)] // standalone low surrogate (preceded by a valid null char) public void GetIndexOfFirstInvalidUtf16Sequence_WithSmallInvalidBuffers(string unprocessedInput, int idxOfFirstInvalidChar, int expectedRuneCount, int expectedUtf8ByteCount) { GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, idxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); } [Theory] // chars below presented as hex since Xunit doesn't like invalid UTF-16 string literals [InlineData("<2BB4><218C><1BC0><613F><F9E9><B740><DE38><E689>", 6, 6, 18)] [InlineData("<1854><C980><012C><4797><DD5A><41D0><A104><5464>", 4, 4, 11)] [InlineData("<F1AF><8BD3><5037><BE29><DEFF><3E3A><DD71><6336>", 4, 4, 12)] [InlineData("<B978><0F25><DC23><D3BB><7352><4025><0B93><4107>", 2, 2, 6)] [InlineData("<887C><C980><012C><4797><DD5A><41D0><A104><5464>", 4, 4, 11)] public void GetIndexOfFirstInvalidUtf16Sequence_WithEightRandomCharsContainingUnpairedSurrogates(string unprocessedInput, int idxOfFirstInvalidChar, int expectedRuneCount, int expectedUtf8ByteCount) { GetIndexOfFirstInvalidUtf16Sequence_Test_Core(unprocessedInput, idxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); } [Fact] public void GetIndexOfFirstInvalidUtf16Sequence_WithInvalidSurrogateSequences() { // All ASCII char[] chars = Enumerable.Repeat('x', 128).ToArray(); GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 128, expectedUtf8ByteCount: 128); // Throw a surrogate pair at the beginning chars[0] = '\uD800'; chars[1] = '\uDFFF'; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 127, expectedUtf8ByteCount: 130); // Throw a surrogate pair near the end chars[124] = '\uD800'; chars[125] = '\uDFFF'; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 126, expectedUtf8ByteCount: 132); // Throw a standalone surrogate code point at the *very* end chars[127] = '\uD800'; // high surrogate GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 127, expectedRuneCount: 125, expectedUtf8ByteCount: 131); chars[127] = '\uDFFF'; // low surrogate GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 127, expectedRuneCount: 125, expectedUtf8ByteCount: 131); // Make the final surrogate pair valid chars[126] = '\uD800'; // high surrogate GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 125, expectedUtf8ByteCount: 134); // Throw an invalid surrogate sequence in the middle (straddles a vector boundary) chars[12] = '\u0080'; // 2-byte UTF-8 sequence chars[13] = '\uD800'; // high surrogate chars[14] = '\uD800'; // high surrogate chars[15] = '\uDFFF'; // low surrogate chars[16] = '\uDFFF'; // low surrogate GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 13, expectedRuneCount: 12, expectedUtf8ByteCount: 16); // Correct the surrogate sequence we just added chars[14] = '\uDC00'; // low surrogate chars[15] = '\uDBFF'; // high surrogate GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, -1, expectedRuneCount: 123, expectedUtf8ByteCount: 139); // Corrupt the surrogate pair that's split across a vector boundary chars[16] = 'x'; // ASCII char (remember.. chars[15] is a high surrogate char) GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars, 15, expectedRuneCount: 13, expectedUtf8ByteCount: 20); } [Fact] public void GetIndexOfFirstInvalidUtf16Sequence_WithStandaloneLowSurrogateCharAtStart() { // The input stream will be a vector's worth of ASCII chars, followed by a single standalone low // surrogate char, then padded with U+0000 until it's a multiple of the vector size. // Using Vector<ushort>.Count here as a stand-in for Vector<char>.Count. char[] chars = new char[Vector<ushort>.Count * 2]; for (int i = 0; i < Vector<ushort>.Count; i++) { chars[i] = 'x'; // ASCII char } chars[Vector<ushort>.Count] = '\uDEAD'; // standalone low surrogate char for (int i = 0; i <= Vector<ushort>.Count; i++) { // Expect all ASCII chars to be consumed, low surrogate char to be marked invalid. GetIndexOfFirstInvalidUtf16Sequence_Test_Core(chars[(Vector<ushort>.Count - i)..], i, i, i); } } private static void GetIndexOfFirstInvalidUtf16Sequence_Test_Core(string unprocessedInput, int expectedIdxOfFirstInvalidChar, int expectedRuneCount, long expectedUtf8ByteCount) { char[] processedInput = ProcessInput(unprocessedInput).ToCharArray(); // Run the test normally GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); // Put a bunch of ASCII data at the beginning (to test the call to ASCIIUtility at method entry) processedInput = Enumerable.Repeat('x', 128).Concat(processedInput).ToArray(); if (expectedIdxOfFirstInvalidChar >= 0) { expectedIdxOfFirstInvalidChar += 128; } expectedRuneCount += 128; expectedUtf8ByteCount += 128; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); // Change the first few chars to a mixture of 2-byte and 3-byte UTF-8 sequences // This makes sure the vectorized code paths can properly handle these. processedInput[0] = '\u0080'; // 2-byte UTF-8 sequence processedInput[1] = '\u0800'; // 3-byte UTF-8 sequence processedInput[2] = '\u0080'; // 2-byte UTF-8 sequence processedInput[3] = '\u0800'; // 3-byte UTF-8 sequence processedInput[4] = '\u0080'; // 2-byte UTF-8 sequence processedInput[5] = '\u0800'; // 3-byte UTF-8 sequence processedInput[6] = '\u0080'; // 2-byte UTF-8 sequence processedInput[7] = '\u0800'; // 3-byte UTF-8 sequence expectedUtf8ByteCount += 12; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); // Throw some surrogate pairs into the mix to make sure they're also handled properly // by the vectorized code paths. processedInput[8] = '\u0080'; // 2-byte UTF-8 sequence processedInput[9] = '\u0800'; // 3-byte UTF-8 sequence processedInput[10] = '\u0080'; // 2-byte UTF-8 sequence processedInput[11] = '\u0800'; // 3-byte UTF-8 sequence processedInput[12] = '\u0080'; // 2-byte UTF-8 sequence processedInput[13] = '\uD800'; // high surrogate processedInput[14] = '\uDC00'; // low surrogate processedInput[15] = 'z'; // ASCII char expectedRuneCount--; expectedUtf8ByteCount += 9; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); // Split the next surrogate pair across the vector boundary (so that we // don't inadvertently treat this as a standalone surrogate sequence). processedInput[15] = '\uDBFF'; // high surrogate processedInput[16] = '\uDFFF'; // low surrogate expectedRuneCount--; expectedUtf8ByteCount += 2; GetIndexOfFirstInvalidUtf16Sequence_Test_Core(processedInput, expectedIdxOfFirstInvalidChar, expectedRuneCount, expectedUtf8ByteCount); } private static unsafe void GetIndexOfFirstInvalidUtf16Sequence_Test_Core(char[] input, int expectedRetVal, int expectedRuneCount, long expectedUtf8ByteCount) { // Arrange using BoundedMemory<char> boundedMemory = BoundedMemory.AllocateFromExistingData(input); boundedMemory.MakeReadonly(); // Act int actualRetVal; long actualUtf8CodeUnitCount; int actualRuneCount; fixed (char* pInputBuffer = &MemoryMarshal.GetReference(boundedMemory.Span)) { char* pFirstInvalidChar = _getPointerToFirstInvalidCharFn.Value(pInputBuffer, input.Length, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment); long ptrDiff = pFirstInvalidChar - pInputBuffer; Assert.True((ulong)ptrDiff <= (uint)input.Length, "ptrDiff was outside expected range."); Assert.True(utf8CodeUnitCountAdjustment >= 0, "UTF-16 code unit count adjustment must be non-negative."); Assert.True(scalarCountAdjustment <= 0, "Scalar count adjustment must be 0 or negative."); actualRetVal = (ptrDiff == input.Length) ? -1 : (int)ptrDiff; // The last two 'out' parameters are: // a) The number to be added to the "chars processed" return value to come up with the total UTF-8 code unit count, and // b) The number to be added to the "total UTF-16 code unit count" value to come up with the total scalar count. actualUtf8CodeUnitCount = ptrDiff + utf8CodeUnitCountAdjustment; actualRuneCount = (int)ptrDiff + scalarCountAdjustment; } // Assert Assert.Equal(expectedRetVal, actualRetVal); Assert.Equal(expectedRuneCount, actualRuneCount); Assert.Equal(actualUtf8CodeUnitCount, expectedUtf8ByteCount); } private static Lazy<GetPointerToFirstInvalidCharDel> CreateGetPointerToFirstInvalidCharFn() { return new Lazy<GetPointerToFirstInvalidCharDel>(() => { Type utf16UtilityType = typeof(Utf8).Assembly.GetType("System.Text.Unicode.Utf16Utility"); if (utf16UtilityType is null) { throw new Exception("Couldn't find Utf16Utility type in System.Private.CoreLib."); } MethodInfo methodInfo = utf16UtilityType.GetMethod("GetPointerToFirstInvalidChar", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (methodInfo is null) { throw new Exception("Couldn't find GetPointerToFirstInvalidChar method on Utf8Utility."); } return (GetPointerToFirstInvalidCharDel)methodInfo.CreateDelegate(typeof(GetPointerToFirstInvalidCharDel)); }); } private static string ProcessInput(string input) { input = input.Replace("<EACU>", "\u00E9", StringComparison.Ordinal); // U+00E9 LATIN SMALL LETTER E WITH ACUTE input = input.Replace("<EURO>", "\u20AC", StringComparison.Ordinal); // U+20AC EURO SIGN input = input.Replace("<GRIN>", "\U0001F600", StringComparison.Ordinal); // U+1F600 GRINNING FACE // Replace <ABCD> with \uABCD. This allows us to flow potentially malformed // UTF-16 strings without Xunit. (The unit testing framework gets angry when // we try putting invalid UTF-16 data as inline test data.) int idx; while ((idx = input.IndexOf('<')) >= 0) { input = input[..idx] + (char)ushort.Parse(input.Substring(idx + 1, 4), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture) + input[(idx + 6)..]; } return input; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; namespace Microsoft.Azure.Management.Resources { public partial class FeatureClient : ServiceClient<FeatureClient>, IFeatureClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IFeatures _features; /// <summary> /// Operations for managing preview features. /// </summary> public virtual IFeatures Features { get { return this._features; } } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> public FeatureClient() : base() { this._features = new Features(this); this._apiVersion = "2014-08-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public FeatureClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public FeatureClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public FeatureClient(HttpClient httpClient) : base(httpClient) { this._features = new Features(this); this._apiVersion = "2014-08-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public FeatureClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the FeatureClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public FeatureClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another FeatureClient /// instance /// </summary> /// <param name='client'> /// Instance of FeatureClient to clone to /// </param> protected override void Clone(ServiceClient<FeatureClient> client) { base.Clone(client); if (client is FeatureClient) { FeatureClient clonedClient = ((FeatureClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Xml; using CultureInfo = System.Globalization.CultureInfo; using Debug = System.Diagnostics.Debug; using IEnumerable = System.Collections.IEnumerable; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Enumerable = System.Linq.Enumerable; using IComparer = System.Collections.IComparer; using IEqualityComparer = System.Collections.IEqualityComparer; using StringBuilder = System.Text.StringBuilder; using Encoding = System.Text.Encoding; using Interlocked = System.Threading.Interlocked; using System.Reflection; namespace System.Xml.Linq { internal class XNodeBuilder : XmlWriter { List<object> content; XContainer parent; XName attrName; string attrValue; XContainer root; public XNodeBuilder(XContainer container) { root = container; } public override XmlWriterSettings Settings { get { XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; return settings; } } public override WriteState WriteState { get { throw new NotSupportedException(); } // nop } protected override void Dispose(bool disposing) { if (disposing) { Close(); } } private void Close() { root.Add(content); } public override void Flush() { } public override string LookupPrefix(string namespaceName) { throw new NotSupportedException(); // nop } public override void WriteBase64(byte[] buffer, int index, int count) { throw new NotSupportedException(SR.NotSupported_WriteBase64); } public override void WriteCData(string text) { AddNode(new XCData(text)); } public override void WriteCharEntity(char ch) { AddString(new string(ch, 1)); } public override void WriteChars(char[] buffer, int index, int count) { AddString(new string(buffer, index, count)); } public override void WriteComment(string text) { AddNode(new XComment(text)); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { AddNode(new XDocumentType(name, pubid, sysid, subset)); } public override void WriteEndAttribute() { XAttribute a = new XAttribute(attrName, attrValue); attrName = null; attrValue = null; if (parent != null) { parent.Add(a); } else { Add(a); } } public override void WriteEndDocument() { } public override void WriteEndElement() { parent = ((XElement)parent).parent; } public override void WriteEntityRef(string name) { switch (name) { case "amp": AddString("&"); break; case "apos": AddString("'"); break; case "gt": AddString(">"); break; case "lt": AddString("<"); break; case "quot": AddString("\""); break; default: throw new NotSupportedException(SR.NotSupported_WriteEntityRef); } } public override void WriteFullEndElement() { XElement e = (XElement)parent; if (e.IsEmpty) { e.Add(string.Empty); } parent = e.parent; } public override void WriteProcessingInstruction(string name, string text) { if (name == "xml") { return; } AddNode(new XProcessingInstruction(name, text)); } public override void WriteRaw(char[] buffer, int index, int count) { AddString(new string(buffer, index, count)); } public override void WriteRaw(string data) { AddString(data); } public override void WriteStartAttribute(string prefix, string localName, string namespaceName) { if (prefix == null) throw new ArgumentNullException("prefix"); attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName).GetName(localName); attrValue = string.Empty; } public override void WriteStartDocument() { } public override void WriteStartDocument(bool standalone) { } public override void WriteStartElement(string prefix, string localName, string namespaceName) { AddNode(new XElement(XNamespace.Get(namespaceName).GetName(localName))); } public override void WriteString(string text) { AddString(text); } public override void WriteSurrogateCharEntity(char lowCh, char highCh) { AddString(new string(new char[] { highCh, lowCh })); } public override void WriteValue(DateTimeOffset value) { // For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime. // Our internal writers should use the DateTimeOffset-String conversion from XmlConvert. WriteString(XmlConvert.ToString(value)); } public override void WriteWhitespace(string ws) { AddString(ws); } void Add(object o) { if (content == null) { content = new List<object>(); } content.Add(o); } void AddNode(XNode n) { if (parent != null) { parent.Add(n); } else { Add(n); } XContainer c = n as XContainer; if (c != null) { parent = c; } } void AddString(string s) { if (s == null) { return; } if (attrValue != null) { attrValue += s; } else if (parent != null) { parent.Add(s); } else { Add(s); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: A representation of an IEEE double precision ** floating point number. ** ** ===========================================================*/ namespace System { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Diagnostics.Contracts; [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct Double : IComparable, IFormattable, IConvertible , IComparable<Double>, IEquatable<Double> { internal double m_value; // // Public Constants // public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; // Note Epsilon should be a double whose hex representation is 0x1 // on little endian machines. public const double Epsilon = 4.9406564584124654E-324; public const double NegativeInfinity = (double)-1.0 / (double)(0.0); public const double PositiveInfinity = (double)1.0 / (double)(0.0); public const double NaN = (double)0.0 / (double)0.0; internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000)); [Pure] [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsInfinity(double d) { return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000; } [Pure] [System.Runtime.Versioning.NonVersionable] public static bool IsPositiveInfinity(double d) { //Jit will generate inlineable code with this if (d == double.PositiveInfinity) { return true; } else { return false; } } [Pure] [System.Runtime.Versioning.NonVersionable] public static bool IsNegativeInfinity(double d) { //Jit will generate inlineable code with this if (d == double.NegativeInfinity) { return true; } else { return false; } } [Pure] [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static bool IsNegative(double d) { return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000; } [Pure] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] [System.Runtime.Versioning.NonVersionable] public unsafe static bool IsNaN(double d) { return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L; } // Compares this object to another object, returning an instance of System.Relation. // Null is considered less than any instance. // // If object is not of type Double, this method throws an ArgumentException. // // Returns a value less than zero if this object // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Double) { double d = (double)value; if (m_value < d) return -1; if (m_value > d) return 1; if (m_value == d) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(d) ? 0 : -1); else return 1; } throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDouble")); } public int CompareTo(Double value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else return 1; } // True if obj is another Double with the same value as the current instance. This is // a method of object equality, that only returns true if obj is also a double. public override bool Equals(Object obj) { if (!(obj is Double)) { return false; } double temp = ((Double)obj).m_value; // This code below is written this way for performance reasons i.e the != and == check is intentional. if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } [System.Runtime.Versioning.NonVersionable] public static bool operator ==(Double left, Double right) { return left == right; } [System.Runtime.Versioning.NonVersionable] public static bool operator !=(Double left, Double right) { return left != right; } [System.Runtime.Versioning.NonVersionable] public static bool operator <(Double left, Double right) { return left < right; } [System.Runtime.Versioning.NonVersionable] public static bool operator >(Double left, Double right) { return left > right; } [System.Runtime.Versioning.NonVersionable] public static bool operator <=(Double left, Double right) { return left <= right; } [System.Runtime.Versioning.NonVersionable] public static bool operator >=(Double left, Double right) { return left >= right; } public bool Equals(Double obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } //The hashcode for a double is the absolute value of the integer representation //of that double. // [System.Security.SecuritySafeCritical] public unsafe override int GetHashCode() { double d = m_value; if (d == 0) { // Ensure that 0 and -0 have the same hash code return 0; } long value = *(long*)(&d); return unchecked((int)value) ^ ((int)(value >> 32)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider)); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider)); } public static double Parse(String s) { return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static double Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.CurrentInfo); } public static double Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static double Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } // Parses a double from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // private static double Parse(String s, NumberStyles style, NumberFormatInfo info) { return Number.ParseDouble(s, style, info); } public static bool TryParse(String s, out double result) { return TryParse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out double result) { if (s == null) { result = 0; return false; } bool success = Number.TryParseDouble(s, style, info, out result); if (!success) { String sTrim = s.Trim(); if (sTrim.Equals(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (sTrim.Equals(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (sTrim.Equals(info.NaNSymbol)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Double; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "Char")); } /// <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 Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return m_value; } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.IoT.TimeSeriesInsights { /// <summary> /// Perform operations such as creating, listing, replacing and deleting Time Series hierarchies. /// </summary> public class TimeSeriesInsightsHierarchies { private readonly TimeSeriesHierarchiesRestClient _hierarchiesRestClient; private readonly ClientDiagnostics _clientDiagnostics; /// <summary> /// Initializes a new instance of TimeSeriesInsightsHierarchies. This constructor should only be used for mocking purposes. /// </summary> protected TimeSeriesInsightsHierarchies() { } internal TimeSeriesInsightsHierarchies(TimeSeriesHierarchiesRestClient hierarchiesRestClient, ClientDiagnostics clientDiagnostics) { Argument.AssertNotNull(hierarchiesRestClient, nameof(hierarchiesRestClient)); Argument.AssertNotNull(clientDiagnostics, nameof(clientDiagnostics)); _hierarchiesRestClient = hierarchiesRestClient; _clientDiagnostics = clientDiagnostics; } /// <summary> /// Gets Time Series Insights hierarchies in pages asynchronously. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The pageable list <see cref="AsyncPageable{TimeSeriesHierarchy}"/> of Time Series hierarchies with the http response.</returns> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleGetAllHierarchies" language="csharp"> /// // Get all Time Series hierarchies in the environment /// AsyncPageable&lt;TimeSeriesHierarchy&gt; getAllHierarchies = hierarchiesClient.GetAsync(); /// await foreach (TimeSeriesHierarchy hierarchy in getAllHierarchies) /// { /// Console.WriteLine($&quot;Retrieved Time Series Insights hierarchy with Id: &apos;{hierarchy.Id}&apos; and Name: &apos;{hierarchy.Name}&apos;.&quot;); /// } /// </code> /// </example> public virtual AsyncPageable<TimeSeriesHierarchy> GetAsync( CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { async Task<Page<TimeSeriesHierarchy>> FirstPageFunc(int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetHierarchiesPage> getHierarchiesResponse = await _hierarchiesRestClient .ListAsync(null, null, cancellationToken) .ConfigureAwait(false); return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } async Task<Page<TimeSeriesHierarchy>> NextPageFunc(string nextLink, int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetHierarchiesPage> getHierarchiesResponse = await _hierarchiesRestClient .ListAsync(nextLink, null, cancellationToken) .ConfigureAwait(false); return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series Insights hierarchies in pages synchronously. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The pageable list <see cref="Pageable{TimeSeriesHierarchy}"/> of Time Series hierarchies with the http response.</returns> /// <seealso cref="GetAsync(CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> public virtual Pageable<TimeSeriesHierarchy> Get(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Page<TimeSeriesHierarchy> FirstPageFunc(int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetHierarchiesPage> getHierarchiesResponse = _hierarchiesRestClient.List(null, null, cancellationToken); return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } Page<TimeSeriesHierarchy> NextPageFunc(string nextLink, int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetHierarchiesPage> getHierarchiesResponse = _hierarchiesRestClient.List(nextLink, null, cancellationToken); return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series Insights hierarchies by hierarchy names asynchronously. /// </summary> /// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of hierarchy or error objects corresponding by position to the array in the request. /// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty. /// </exception> public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> GetByNameAsync( IEnumerable<string> timeSeriesHierarchyNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames)); var batchRequest = new HierarchiesBatchRequest() { Get = new HierarchiesRequestBatchGetDelete() }; foreach (string timeSeriesName in timeSeriesHierarchyNames) { batchRequest.Get.Names.Add(timeSeriesName); } Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series Insights hierarchies by hierarchy names synchronously. /// </summary> /// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of hierarchy or error objects corresponding by position to the array in the request. /// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="GetByNameAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty. /// </exception> public virtual Response<TimeSeriesHierarchyOperationResult[]> GetByName( IEnumerable<string> timeSeriesHierarchyNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames)); var batchRequest = new HierarchiesBatchRequest() { Get = new HierarchiesRequestBatchGetDelete() }; foreach (string timeSeriesName in timeSeriesHierarchyNames) { batchRequest.Get.Names.Add(timeSeriesName); } Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series Insights hierarchies by hierarchy Ids asynchronously. /// </summary> /// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of hierarchy or error objects corresponding by position to the array in the request. /// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty. /// </exception> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleGetHierarchiesById" language="csharp"> /// var tsiHierarchyIds = new List&lt;string&gt; /// { /// &quot;sampleHierarchyId&quot; /// }; /// /// Response&lt;TimeSeriesHierarchyOperationResult[]&gt; getHierarchiesByIdsResult = await hierarchiesClient /// .GetByIdAsync(tsiHierarchyIds); /// /// // The response of calling the API contains a list of hieararchy or error objects corresponding by position to the input parameter array in the request. /// // If the error object is set to null, this means the operation was a success. /// for (int i = 0; i &lt; getHierarchiesByIdsResult.Value.Length; i++) /// { /// if (getHierarchiesByIdsResult.Value[i].Error == null) /// { /// Console.WriteLine($&quot;Retrieved Time Series hieararchy with Id: &apos;{getHierarchiesByIdsResult.Value[i].Hierarchy.Id}&apos;.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Failed to retrieve a Time Series hieararchy due to &apos;{getHierarchiesByIdsResult.Value[i].Error.Message}&apos;.&quot;); /// } /// } /// </code> /// </example> public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> GetByIdAsync( IEnumerable<string> timeSeriesHierarchyIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds)); var batchRequest = new HierarchiesBatchRequest() { Get = new HierarchiesRequestBatchGetDelete() }; foreach (string hierarchyId in timeSeriesHierarchyIds) { batchRequest.Get.HierarchyIds.Add(hierarchyId); } Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series Insights hierarchies by hierarchy Ids synchronously. /// </summary> /// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of hierarchy or error objects corresponding by position to the array in the request. /// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="GetByIdAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty. /// </exception> public virtual Response<TimeSeriesHierarchyOperationResult[]> GetById( IEnumerable<string> timeSeriesHierarchyIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds)); var batchRequest = new HierarchiesBatchRequest() { Get = new HierarchiesRequestBatchGetDelete() }; foreach (string hierarchyId in timeSeriesHierarchyIds) { batchRequest.Get.HierarchyIds.Add(hierarchyId); } Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates Time Series Insights hierarchies asynchronously. If a provided hierarchy is already in use, then this will attempt to replace the existing hierarchy with the provided Time Series hierarchy. /// </summary> /// <param name="timeSeriesHierarchies">The Time Series Insights hierarchies to be created or replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the <paramref name="timeSeriesHierarchies"/> array in the request. /// An error object will be set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is empty. /// </exception> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleCreateHierarchies" language="csharp"> /// TimeSeriesInsightsHierarchies hierarchiesClient = client.GetHierarchiesClient(); /// /// var hierarchySource = new TimeSeriesHierarchySource(); /// hierarchySource.InstanceFieldNames.Add(&quot;hierarchyLevel1&quot;); /// /// var tsiHierarchy = new TimeSeriesHierarchy(&quot;sampleHierarchy&quot;, hierarchySource) /// { /// Id = &quot;sampleHierarchyId&quot; /// }; /// /// var timeSeriesHierarchies = new List&lt;TimeSeriesHierarchy&gt; /// { /// tsiHierarchy /// }; /// /// // Create Time Series hierarchies /// Response&lt;TimeSeriesHierarchyOperationResult[]&gt; createHierarchiesResult = await hierarchiesClient /// .CreateOrReplaceAsync(timeSeriesHierarchies); /// /// // The response of calling the API contains a list of error objects corresponding by position to the input parameter array in the request. /// // If the error object is set to null, this means the operation was a success. /// for (int i = 0; i &lt; createHierarchiesResult.Value.Length; i++) /// { /// if (createHierarchiesResult.Value[i].Error == null) /// { /// Console.WriteLine($&quot;Created Time Series hierarchy successfully.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Failed to create a Time Series hierarchy: {createHierarchiesResult.Value[i].Error.Message}.&quot;); /// } /// } /// </code> /// </example> public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> CreateOrReplaceAsync( IEnumerable<TimeSeriesHierarchy> timeSeriesHierarchies, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics .CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchies, nameof(timeSeriesHierarchies)); var batchRequest = new HierarchiesBatchRequest(); foreach (TimeSeriesHierarchy hierarchy in timeSeriesHierarchies) { batchRequest.Put.Add(hierarchy); } Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error); return Response.FromValue(executeBatchResponse.Value.Put.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates Time Series Insights hierarchies synchronously. If a provided hierarchy is already in use, then this will attempt to replace the existing hierarchy with the provided Time Series hierarchy. /// </summary> /// <param name="timeSeriesHierarchies">The Time Series Insights hierarchies to be created or replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of hierarchies or error objects corresponding by position to the <paramref name="timeSeriesHierarchies"/> array in the request. /// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="CreateOrReplaceAsync(IEnumerable{TimeSeriesHierarchy}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is empty. /// </exception> public virtual Response<TimeSeriesHierarchyOperationResult[]> CreateOrReplace( IEnumerable<TimeSeriesHierarchy> timeSeriesHierarchies, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchies, nameof(timeSeriesHierarchies)); var batchRequest = new HierarchiesBatchRequest(); foreach (TimeSeriesHierarchy hierarchy in timeSeriesHierarchies) { batchRequest.Put.Add(hierarchy); } Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error); return Response.FromValue(executeBatchResponse.Value.Put.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series Insights hierarchies by hierarchy names asynchronously. /// </summary> /// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the input array in the request. null when the operation is successful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty. /// </exception> public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByNameAsync( IEnumerable<string> timeSeriesHierarchyNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames)); var batchRequest = new HierarchiesBatchRequest { Delete = new HierarchiesRequestBatchGetDelete() }; foreach (string timeSeriesName in timeSeriesHierarchyNames) { batchRequest.Delete.Names.Add(timeSeriesName); } Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series Insights hierarchies by hierarchy names synchronously. /// </summary> /// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the input array in the request. null when the operation is successful. /// </returns> /// <seealso cref="DeleteByNameAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty. /// </exception> public virtual Response<TimeSeriesOperationError[]> DeleteByName( IEnumerable<string> timeSeriesHierarchyNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames)); var batchRequest = new HierarchiesBatchRequest { Delete = new HierarchiesRequestBatchGetDelete() }; foreach (string timeSeriesName in timeSeriesHierarchyNames) { batchRequest.Delete.Names.Add(timeSeriesName); } Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series Insights hierarchies by hierarchy Ids asynchronously. /// </summary> /// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the input array in the request. null when the operation is successful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty. /// </exception> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleDeleteHierarchiesById" language="csharp"> /// // Delete Time Series hierarchies with Ids /// var tsiHierarchyIdsToDelete = new List&lt;string&gt; /// { /// &quot;sampleHiearchyId&quot; /// }; /// /// Response&lt;TimeSeriesOperationError[]&gt; deleteHierarchiesResponse = await hierarchiesClient /// .DeleteByIdAsync(tsiHierarchyIdsToDelete); /// /// // The response of calling the API contains a list of error objects corresponding by position to the input parameter /// // array in the request. If the error object is set to null, this means the operation was a success. /// foreach (TimeSeriesOperationError result in deleteHierarchiesResponse.Value) /// { /// if (result != null) /// { /// Console.WriteLine($&quot;Failed to delete a Time Series Insights hierarchy: {result.Message}.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Deleted a Time Series Insights hierarchy successfully.&quot;); /// } /// } /// </code> /// </example> public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByIdAsync( IEnumerable<string> timeSeriesHierarchyIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds)); var batchRequest = new HierarchiesBatchRequest { Delete = new HierarchiesRequestBatchGetDelete() }; foreach (string hierarchyId in timeSeriesHierarchyIds) { batchRequest.Delete.HierarchyIds.Add(hierarchyId); } Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series instances from the environment by Time Series Ids synchronously. /// </summary> /// <param name="timeSeriesHierarchyIds">List of Ids of the Time Series instances to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the input array in the request. null when the operation is successful. /// </returns> /// <seealso cref="DeleteByIdAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty. /// </exception> public virtual Response<TimeSeriesOperationError[]> DeleteById( IEnumerable<string> timeSeriesHierarchyIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds)); var batchRequest = new HierarchiesBatchRequest { Delete = new HierarchiesRequestBatchGetDelete() }; foreach (string hierarchyId in timeSeriesHierarchyIds ?? Enumerable.Empty<string>()) { batchRequest.Delete.HierarchyIds.Add(hierarchyId); } Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } } }
using System; using System.Collections.Generic; using System.IO; using Moq; using NuGet.Test.Mocks; using Xunit; using NuGet.Test.Utility; namespace NuGet.Test { public class PackageManagerTest { [Fact] public void CtorThrowsIfDependenciesAreNull() { // Act & Assert ExceptionAssert.ThrowsArgNull(() => new PackageManager(null, new DefaultPackagePathResolver("foo"), new MockProjectSystem(), new MockPackageRepository()), "sourceRepository"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), null, new MockProjectSystem(), new MockPackageRepository()), "pathResolver"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), null, new MockPackageRepository()), "fileSystem"); ExceptionAssert.ThrowsArgNull(() => new PackageManager(new MockPackageRepository(), new DefaultPackagePathResolver("foo"), new MockProjectSystem(), null), "localRepository"); } [Fact] public void InstallingPackageWithUnknownDependencyAndIgnoreDepencenciesInstallsPackageWithoutDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: true, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.False(localRepository.Exists(packageC)); } [Fact] public void UninstallingUnknownPackageThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UninstallPackage("foo"), "Unable to find package 'foo'."); } [Fact] public void UninstallingUnknownNullOrEmptyPackageIdThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage((string)null), "packageId"); ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.UninstallPackage(String.Empty), "packageId"); } [Fact] public void UninstallingPackageWithNoDependents() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); var package = PackageUtility.CreatePackage("foo", "1.2.33"); localRepository.AddPackage(package); // Act packageManager.UninstallPackage("foo"); // Assert Assert.False(packageManager.LocalRepository.Exists(package)); } [Fact] public void InstallingUnknownPackageThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.InstallPackage("unknown"), "Unable to find package 'unknown'."); } [Fact] public void InstallPackageNullOrEmptyPackageIdThrows() { // Arrange PackageManager packageManager = CreatePackageManager(); // Act & Assert ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage((string)null), "packageId"); ExceptionAssert.ThrowsArgNullOrEmpty(() => packageManager.InstallPackage(String.Empty), "packageId"); } [Fact] public void InstallPackageAddsAllFilesToFileSystem() { // Arrange var projectSystem = new MockProjectSystem(); var sourceRepository = new MockPackageRepository(); var pathResolver = new DefaultPackagePathResolver(projectSystem); var packageManager = new PackageManager(sourceRepository, pathResolver, projectSystem, new LocalPackageRepository(pathResolver, projectSystem)); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", new[] { "contentFile", @"sub\contentFile" }, new[] { @"lib\reference.dll" }, new[] { @"readme.txt" }); sourceRepository.AddPackage(packageA); // Act packageManager.InstallPackage("A"); // Assert Assert.Equal(0, projectSystem.References.Count); Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"A.1.0\content\contentFile")); Assert.True(projectSystem.FileExists(@"A.1.0\content\sub\contentFile")); Assert.True(projectSystem.FileExists(@"A.1.0\lib\reference.dll")); Assert.True(projectSystem.FileExists(@"A.1.0\tools\readme.txt")); Assert.True(projectSystem.FileExists(@"A.1.0\A.1.0.nupkg")); } [Fact] public void InstallingSatellitePackageCopiesFilesIntoRuntimePackageFolderWhenRuntimeIsInstalledAsADependency() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml" }, dependencies: new[] { new PackageDependency("foo", VersionUtility.ParseVersionSpec("[1.0.0]")) }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); } [Fact] public void InstallingSatellitePackageCopiesFilesIntoRuntimePackageFolderWhenRuntimeIsAlreadyInstalled() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml" }, dependencies: new[] { new PackageDependency("foo", VersionUtility.ParseVersionSpec("[1.0.0]")) }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(5, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); } [Fact] public void InstallingSatellitePackageOnlyCopiesCultureSpecificLibFolderContents() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }, content: new[] { @"english.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml", @"lib\japanese.xml" }, content: new[] { @"english.txt", @"japanese.txt" }, dependencies: new[] { new PackageDependency("foo", VersionUtility.ParseVersionSpec("[1.0.0]")) }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); // Assert Assert.Equal(9, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\japanese.txt")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\japanese.xml")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.True(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\content\japanese.txt")); } [Fact] public void UninstallingSatellitePackageRemovesFilesFromRuntimePackageFolder() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\foo.dll" }, content: new[] { @"english.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\foo.resources.dll", @"lib\ja-jp\foo.xml", @"lib\japanese.xml" }, content: new[] { @"english.txt", @"japanese.txt" }, dependencies: new[] { new PackageDependency("foo") }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); packageManager.UninstallPackage("foo.ja-jp"); // Assert Assert.Equal(2, projectSystem.Paths.Count); Assert.True(projectSystem.FileExists(@"foo.1.0.0\content\english.txt")); Assert.True(projectSystem.FileExists(@"foo.1.0.0\lib\foo.dll")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\english.txt")); Assert.False (projectSystem.FileExists(@"foo.ja-jp.1.0.0\content\japanese.txt")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.resources.dll")); Assert.False(projectSystem.FileExists(@"foo.ja-jp.1.0.0\lib\ja-jp\foo.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\japanese.xml")); Assert.False(projectSystem.FileExists(@"foo.1.0.0\content\japanese.txt")); } /// <summary> /// This test demonstrates that satellite packages that have satellite files /// that match the files in the runtime package can cause the runtime package's /// file to be removed when the satellite package is uninstalled. /// </summary> /// <remarks> /// This is an acceptable limitation of the design: during uninstallation of the satellite package, /// we don't check the runtime package to see if files qualified as satellite files /// already existed in the runtime package. /// <para> /// And as the uninstall.ps1 end-to-end tests demonstrate, the only way this collision can cause the /// runtime package's file to be removed is when the files are exact matches of one another. Otherwise, /// the file will be recognized as different, and it won't be uninstalled when uninstalling ja-jp. /// </para> /// </remarks> [Fact] public void UninstallingSatellitePackageRemovesCollidingRuntimeFiles() { // Arrange // Create a runtime package and a satellite package that has a dependency on the runtime package, and uses the // local suffix convention. var runtimePackage = PackageUtility.CreatePackage("foo", "1.0.0", assemblyReferences: new[] { @"lib\ja-jp\collision.txt" }); var satellitePackage = PackageUtility.CreatePackage("foo.ja-jp", "1.0.0", language: "ja-jp", satelliteAssemblies: new[] { @"lib\ja-jp\collision.txt" }, dependencies: new[] { new PackageDependency("foo", VersionUtility.ParseVersionSpec("[1.0.0]")) }); var projectSystem = new MockProjectSystem(); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(runtimePackage); sourceRepository.AddPackage(satellitePackage); // Act packageManager.InstallPackage("foo"); packageManager.InstallPackage("foo.ja-jp"); packageManager.UninstallPackage("foo.ja-jp"); // Assert Assert.Equal(0, projectSystem.Paths.Count); Assert.False(projectSystem.FileExists(@"foo.1.0.0\lib\ja-jp\collision.txt")); } [Fact] public void UninstallingPackageUninstallsPackageButNotDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); // Act packageManager.UninstallPackage("A"); // Assert Assert.False(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB)); } [Fact] public void ReInstallingPackageAfterUninstallingDependencyShouldReinstallAllDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C") }); var packageC = PackageUtility.CreatePackage("C", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A"); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageThrowsExceptionPackageIsNotInstalled() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new Mock<IProjectSystem>(); projectSystem.Setup(m => m.AddFile(@"A.1.0\content\file", It.IsAny<Stream>())).Throws<UnauthorizedAccessException>(); projectSystem.Setup(m => m.Root).Returns("FakeRoot"); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem.Object), projectSystem.Object, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", new[] { "file" }); sourceRepository.AddPackage(packageA); // Act ExceptionAssert.Throws<UnauthorizedAccessException>(() => packageManager.InstallPackage("A")); // Assert Assert.False(packageManager.LocalRepository.Exists(packageA)); } [Fact] public void UpdatePackageUninstallsPackageAndInstallsNewPackage() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A10 = PackageUtility.CreatePackage("A", "1.0"); IPackage A20 = PackageUtility.CreatePackage("A", "2.0"); localRepository.Add(A10); sourceRepository.Add(A20); // Act packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false); // Assert Assert.False(localRepository.Exists("A", new SemanticVersion("1.0"))); Assert.True(localRepository.Exists("A", new SemanticVersion("2.0"))); } [Fact] public void UpdatePackageThrowsIfPackageNotInstalled() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A20 = PackageUtility.CreatePackage("A", "2.0"); sourceRepository.Add(A20); // Act ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false), "Unable to find package 'A'."); } [Fact] public void UpdatePackageDoesNothingIfNoUpdatesAvailable() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); PackageManager packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage A10 = PackageUtility.CreatePackage("A", "1.0"); localRepository.Add(A10); // Act packageManager.UpdatePackage("A", updateDependencies: true, allowPrereleaseVersions: false); // Assert Assert.True(localRepository.Exists("A", new SemanticVersion("1.0"))); } [Fact] public void InstallPackageInstallsPrereleasePackages() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0-beta", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageDisregardTargetFrameworkOfDependencies() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager( sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C", null) }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageInstallsPackagesWithPrereleaseDependenciesIfFlagIsSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: true); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageThrowsIfDependencyIsPrereleaseAndFlagIsNotSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>( () => packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: false), "Unable to resolve dependency 'C'."); } [Fact] public void InstallPackageInstallsLowerReleaseVersionIfPrereleaseFlagIsNotSet() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); IPackage packageA = PackageUtility.CreatePackage("A", "1.0.0", dependencies: new[] { new PackageDependency("C") }); IPackage packageC_RC = PackageUtility.CreatePackage("C", "1.0.0-RC-1"); IPackage packageC = PackageUtility.CreatePackage("C", "0.9"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageC_RC); // Act packageManager.InstallPackage("A", version: null, ignoreDependencies: false, allowPrereleaseVersions: false); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageC)); } [Fact] public void InstallPackageConsidersAlreadyInstalledPrereleasePackagesWhenResolvingDependencies() { // Arrange var packageB_05 = PackageUtility.CreatePackage("B", "0.5.0"); var packageB_10a = PackageUtility.CreatePackage("B", "1.0.0-a"); var packageA = PackageUtility.CreatePackage("A", dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("[0.5.0, 2.0.0)")) }); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var projectSystem = new MockProjectSystem(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(projectSystem), projectSystem, localRepository); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB_10a); sourceRepository.AddPackage(packageB_05); // Act // The allowPrereleaseVersions flag should be irrelevant since we specify a version. packageManager.InstallPackage("B", version: new SemanticVersion("1.0.0-a"), ignoreDependencies: false, allowPrereleaseVersions: false); // Verify we actually did install B.1.0.0a Assert.True(localRepository.Exists(packageB_10a)); packageManager.InstallPackage("A"); // Assert Assert.True(localRepository.Exists(packageA)); Assert.True(localRepository.Exists(packageB_10a)); } [Fact] public void InstallPackageNotifiesBatchProcessorWhenExpandingPackageFiles() { // Arrange var package = PackageUtility.CreatePackage("B", "0.5.0", content: new[] { "content.txt" }, assemblyReferences: new[] { "Ref.dll" }); var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var fileSystem = new Mock<MockFileSystem> { CallBase = true }; var batchProcessor = fileSystem.As<IBatchProcessor<string>>(); batchProcessor.Setup(s => s.BeginProcessing(It.IsAny<IEnumerable<string>>(), PackageAction.Install)) .Callback((IEnumerable<string> files, PackageAction _) => Assert.Equal(new[] { PathFixUtility.FixPath(@"content\content.txt"), "Ref.dll" }, files)) .Verifiable(); batchProcessor.Setup(s => s.EndProcessing()).Verifiable(); var packageManager = new PackageManager(sourceRepository, new DefaultPackagePathResolver(fileSystem.Object), fileSystem.Object, localRepository); sourceRepository.AddPackage(package); // Act packageManager.InstallPackage("B"); // Assert Assert.True(localRepository.Exists(package)); batchProcessor.Verify(); } private PackageManager CreatePackageManager() { var projectSystem = new MockProjectSystem(); return new PackageManager( new MockPackageRepository(), new DefaultPackagePathResolver(projectSystem), projectSystem, new MockPackageRepository()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; public struct VT { public float[,] float2darr; public float[, ,] float3darr; public float[,] float2darr_b; public float[, ,] float3darr_b; } public class CL { public float[,] float2darr = { { 0, -1 }, { 0, 0 } }; public float[, ,] float3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; public float[,] float2darr_b = { { 0, 1 }, { 0, 0 } }; public float[, ,] float3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; } public class floatMDArrTest { static float[,] float2darr = { { 0, -1 }, { 0, 0 } }; static float[, ,] float3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; static float[,] float2darr_b = { { 0, 1 }, { 0, 0 } }; static float[, ,] float3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static float[][,] ja1 = new float[2][,]; static float[][, ,] ja2 = new float[2][, ,]; static float[][,] ja1_b = new float[2][,]; static float[][, ,] ja2_b = new float[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.float2darr = new float[,] { { 0, -1 }, { 0, 0 } }; vt1.float3darr = new float[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; vt1.float2darr_b = new float[,] { { 0, 1 }, { 0, 0 } }; vt1.float3darr_b = new float[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new float[,] { { 0, -1 }, { 0, 0 } }; ja2[1] = new float[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; ja1_b[0] = new float[,] { { 0, 1 }, { 0, 0 } }; ja2_b[1] = new float[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; float result = -1; // 2D if (result != float2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.float2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.float2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != float3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.float3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.float3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.float2darr_b[0, 1] is: {0}", vt1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.float2darr_b[0, 1] is: {0}", cl1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("float3darr_b[1,0,1] is: {0}", float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.float3darr_b[1,0,1] is: {0}", vt1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.float3darr_b[1,0,1] is: {0}", cl1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.float2darr_b[0, 1] is: {0}", vt1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.float2darr_b[0, 1] is: {0}", cl1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("float3darr_b[1,0,1] is: {0}", float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.float3darr_b[1,0,1] is: {0}", vt1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.float3darr_b[1,0,1] is: {0}", cl1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToDecimal tests decimal Decimal_result = -1; // 2D if (Decimal_result != Convert.ToDecimal(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToDouble tests double Double_result = -1; // 2D if (Double_result != Convert.ToDouble(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToInt32 tests int Int32_result = -1; // 2D if (Int32_result != Convert.ToInt32(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToInt64 tests long Int64_result = -1; // 2D if (Int64_result != Convert.ToInt64(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int64_result != Convert.ToInt64(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToSByte tests sbyte SByte_result = -1; // 2D if (SByte_result != Convert.ToSByte(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToInt16 tests short Int16_result = -1; // 2D if (Int16_result != Convert.ToInt16(float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.float2darr[0, 1] is: {0}", vt1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.float2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.float2darr[0, 1] is: {0}", cl1.float2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("float3darr[1,0,1] is: {0}", float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.float3darr[1,0,1] is: {0}", vt1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.float3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.float3darr[1,0,1] is: {0}", cl1.float3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToUInt32 tests uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.float2darr_b[0, 1] is: {0}", vt1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.float2darr_b[0, 1] is: {0}", cl1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("float3darr_b[1,0,1] is: {0}", float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.float3darr_b[1,0,1] is: {0}", vt1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.float3darr_b[1,0,1] is: {0}", cl1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.float2darr_b[0, 1] is: {0}", vt1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.float2darr_b[0, 1] is: {0}", cl1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("float3darr_b[1,0,1] is: {0}", float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.float3darr_b[1,0,1] is: {0}", vt1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.float3darr_b[1,0,1] is: {0}", cl1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //SingleToUInt16 tests ushort UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.float2darr_b[0, 1] is: {0}", vt1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.float2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.float2darr_b[0, 1] is: {0}", cl1.float2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("float3darr_b[1,0,1] is: {0}", float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.float3darr_b[1,0,1] is: {0}", vt1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.float3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.float3darr_b[1,0,1] is: {0}", cl1.float3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace MidiGremlin.Internal { internal class ChannelAllocator { //Music in storage, not ready to be played yet. A queue with last to exit first in index to make modification to end fast private readonly List<SingleBeatWithChannel> _storage = new List<SingleBeatWithChannel>(); //Music in storage that have begun playing but requires more events in the near future private readonly List<SimpleMidiMessage> _partialQueue = new List<SimpleMidiMessage>(); //What instrument are active on each channel private readonly InstrumentType[] _channelInstruments = new InstrumentType[16]; private const int DRUM_CHANNEL = 9; public const double NoMessageTime = double.MaxValue; public SimpleMidiMessage GetNext() { //If both lists are empty. if (Empty) { throw new NoMoreMusicException(); } //If _storage is empty or if the next object to play is in progressQueque. if (_storage.Count == 0 || (_partialQueue.Count != 0 && _partialQueue.Last().Timestamp <= _storage.Last().ToneStartTime)) { return _partialQueue.PopLast(); } else //Get new message from _storage. { SingleBeatWithChannel beatWithChannel = _storage.PopLast(); //If the right channel is already assigned. if (beatWithChannel.InstrumentType == _channelInstruments[beatWithChannel.Channel]) { //X, Y reverse order as list should be in that order _partialQueue.MergeInsert(StopMidiMessage(beatWithChannel), CompareSimpleMidi); return StartMidiMessage(beatWithChannel); } else //If a channel needs to be allocated before playing. { _channelInstruments[beatWithChannel.Channel] = beatWithChannel.InstrumentType; _partialQueue.MergeInsert(StartMidiMessage(beatWithChannel), CompareSimpleMidi); _partialQueue.MergeInsert(StopMidiMessage(beatWithChannel), CompareSimpleMidi); return ChangeChannelMidiMessage(beatWithChannel); } } } /// <summary> /// Add SingleBeats to list of SingleBeats to play, and assign the channel that it might play on. /// </summary> /// <param name="input">List of SingleBeats sorted by start-time.</param> public void Add(List<SingleBeat> input) { InstrumentType[] lastUsedInstruments = new InstrumentType[16]; Array.Copy(_channelInstruments, lastUsedInstruments, 16); //Array containing the time that the corresponding channel will be free. double[] finishTimes = CreateFinishTimesArray(); int storageProgress = _storage.Count; foreach (SingleBeat toAdd in input) { //Find the element in _storage that comes just before us while (0 < storageProgress && _storage[storageProgress - 1].ToneStartTime < toAdd.ToneStartTime) { storageProgress--; int channel = _storage[storageProgress].Channel; finishTimes[channel] = Math.Max(_storage[storageProgress].ToneEndTime, finishTimes[channel]); lastUsedInstruments[channel] = _storage[storageProgress].InstrumentType; } int usedChannel = lastUsedInstruments.IndexOf(toAdd.instrumentType); if (usedChannel == -1) //If no free channel is found, find one or die { //If this is a drum, only DRUM_CHANNEL can be used. //Otherwise, everything but DRUM_CHANNEL can be used. Func<int, bool> correctChannelType; if (toAdd.instrumentType.IsDrum()) correctChannelType = (i => i == DRUM_CHANNEL); else correctChannelType = (i => i != DRUM_CHANNEL); int result = finishTimes .Select((value, index) => new { index, value}) .Where(x => correctChannelType(x.index) && x.value <= toAdd.ToneStartTime) //Int default is 0, so 1 is added to distinguish between this and the first channel. .Select(x => x.index + 1).FirstOrDefault(); if (result == default(int)) { //won't be free, do whatever throw new OutOfChannelsException(); } else { usedChannel = result - 1; lastUsedInstruments[usedChannel] = toAdd.instrumentType; } } finishTimes[usedChannel] = Math.Max(toAdd.ToneEndTime, finishTimes[usedChannel]); _storage.Insert(storageProgress, toAdd.WithChannel((byte) usedChannel)); } } public double NextTimeStamp { get { if (Empty) { return NoMessageTime; } if (_storage.Count == 0) { return _partialQueue[_partialQueue.Count - 1].Timestamp; } if (_partialQueue.Count == 0) { return _storage[_storage.Count - 1].ToneStartTime; } return Math.Min(_storage[_storage.Count - 1].ToneStartTime, _partialQueue[_partialQueue.Count - 1].Timestamp); } } public bool Empty => _partialQueue.Count == 0 && _storage.Count == 0; private int CompareSimpleMidi(SimpleMidiMessage lhs, SimpleMidiMessage rhs) { int first = lhs.Timestamp.CompareTo(rhs.Timestamp); if (first != 0) return first; int lhsType = (lhs.Data & 0xf0) >> 4; int rhsType = (rhs.Data & 0xf0) >> 4; int second = lhsType.CompareTo(rhsType); return second; } /// <summary> Returns an array where each element represents the time that the corresponding channel will be free. (looks at _progressQueue only) </summary> /// <returns> An array where each element represents the time that the corresponding channel will be free. </returns> private double[] CreateFinishTimesArray() { double[] ret = new double[16]; foreach (SimpleMidiMessage message in _partialQueue) { ret[message.Channel] = Math.Max(ret[message.Channel], message.Timestamp); } return ret; } private int MakeMidiEvent(byte midiEventType, byte channel, byte tone, byte toneVelocity) { int data = 0; data |= channel << 0; data |= midiEventType << 4; data |= tone << 8; data |= toneVelocity << 16; return data; } private SimpleMidiMessage ChangeChannelMidiMessage(SingleBeatWithChannel beatWithChannel) { return new SimpleMidiMessage(MakeMidiEvent(0xC, beatWithChannel.Channel, (byte)((int)beatWithChannel.InstrumentType & 0x7F), 0), beatWithChannel.ToneStartTime); } private SimpleMidiMessage StartMidiMessage(SingleBeatWithChannel beatWithChannel) { return new SimpleMidiMessage(MakeMidiEvent(0x9, beatWithChannel.Channel, beatWithChannel.Tone, beatWithChannel.ToneVelocity), beatWithChannel.ToneStartTime); } private SimpleMidiMessage StopMidiMessage(SingleBeatWithChannel beatWithChannel) { return new SimpleMidiMessage(MakeMidiEvent(0x8, beatWithChannel.Channel, beatWithChannel.Tone, beatWithChannel.ToneVelocity), beatWithChannel.ToneEndTime); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace BusinessApps.O365ProjectsApp.Job { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/* VRManagerScript * MiddleVR * (c) MiddleVR */ using UnityEngine; using MiddleVR_Unity3D; [AddComponentMenu("")] public class VRManagerScript : MonoBehaviour { public enum ENavigation{ None, Joystick, Elastic, GrabWorld } public enum EVirtualHandMapping{ Direct, Gogo } public enum EManipulation{ None, Ray, Homer } // Public readable parameters [HideInInspector] public float WandAxisHorizontal = 0.0f; [HideInInspector] public float WandAxisVertical = 0.0f; [HideInInspector] public bool WandButton0 = false; [HideInInspector] public bool WandButton1 = false; [HideInInspector] public bool WandButton2 = false; [HideInInspector] public bool WandButton3 = false; [HideInInspector] public bool WandButton4 = false; [HideInInspector] public bool WandButton5 = false; [HideInInspector] public double DeltaTime = 0.0f; private vrCommand m_startParticlesCommand = null; // Exposed parameters: public string ConfigFile = "c:\\config.vrx"; public GameObject VRSystemCenterNode = null; public GameObject TemplateCamera = null; public bool ShowWand = true; [SerializeField] private bool m_UseVRMenu = false; public bool UseVRMenu { get { return m_UseVRMenu; } set { _EnableVRMenu(value); } } public ENavigation Navigation = ENavigation.Joystick; public EManipulation Manipulation = EManipulation.Ray; public EVirtualHandMapping VirtualHandMapping = EVirtualHandMapping.Direct; [SerializeField] private bool m_ShowScreenProximityWarnings = false; public bool ShowScreenProximityWarnings { get { return m_ShowScreenProximityWarnings; } set { _EnableProximityWarning(value); } } [SerializeField] private bool m_Fly = false; public bool Fly { get { return m_Fly; } set { _EnableNavigationFly(value); } } [SerializeField] private bool m_NavigationCollisions = false; public bool NavigationCollisions { get { return m_NavigationCollisions; } set { _EnableNavigationCollision(value); } } [SerializeField] private bool m_ManipulationReturnObjects = false; public bool ManipulationReturnObjects { get { return m_ManipulationReturnObjects; } set { _EnableManipulationReturnObjects(value); } } [SerializeField] private bool m_ShowFPS = true; public bool ShowFPS { get { return m_ShowFPS; } set { _EnableFPSDisplay(value); } } public bool DisableExistingCameras = true; public bool GrabExistingNodes = false; public bool DebugNodes = false; public bool DebugScreens = false; public bool QuitOnEsc = true; public bool DontChangeWindowGeometry = false; public bool SimpleCluster = true; public bool SimpleClusterParticles = true; public bool ForceQuality = false; public int ForceQualityIndex = 3; public bool CustomLicense = false; public string CustomLicenseName; public string CustomLicenseCode; // Private members private vrKernel m_Kernel = null; private vrDeviceManager m_DeviceMgr = null; private vrDisplayManager m_DisplayMgr = null; private vrClusterManager m_ClusterMgr = null; private GameObject m_Wand = null; private GameObject m_VRMenu = null; private bool m_isInit = false; private bool m_isGeometrySet = false; private bool m_displayLog = false; private int m_AntiAliasingLevel = 0; private bool m_NeedDelayedRenderingReset = false; private int m_RenderingResetDelay = 1; private GUIText m_GUI = null; private bool[] mouseButtons = new bool[3]; private uint m_FirstFrameAfterReset = 0; private bool m_InteractionsInitialized = false; private vrCommand m_QuitCommand = null; // Public methods public void Log(string text) { MVRTools.Log(text); } public bool IsKeyPressed(uint iKey) { return m_DeviceMgr.IsKeyPressed(iKey); } public bool IsMouseButtonPressed(uint iButtonIndex) { return m_DeviceMgr.IsMouseButtonPressed(iButtonIndex); } public float GetMouseAxisValue(uint iAxisIndex) { return m_DeviceMgr.GetMouseAxisValue(iAxisIndex); } // Private methods private void InitializeVR() { mouseButtons[0] = mouseButtons[1] = mouseButtons[2] = false; if (m_displayLog) { GameObject gui = new GameObject(); m_GUI = gui.AddComponent<GUIText>() as GUIText; gui.transform.localPosition = new UnityEngine.Vector3(0.5f, 0.0f, 0.0f); m_GUI.pixelOffset = new UnityEngine.Vector2(15, 0); m_GUI.anchor = TextAnchor.LowerCenter; } MVRTools.IsEditor = Application.isEditor; if( MiddleVR.VRKernel != null ) { MVRTools.Log(3, "[ ] VRKernel already alive, reset Unity Manager."); MVRTools.VRReset(); m_isInit = true; // Not needed because this is the first execution of this script instance // m_isGeometrySet = false; m_FirstFrameAfterReset = MiddleVR.VRKernel.GetFrame(); } else { if( CustomLicense ) { MVRTools.CustomLicense = true; MVRTools.CustomLicenseName = CustomLicenseName; MVRTools.CustomLicenseCode = CustomLicenseCode; } m_isInit = MVRTools.VRInitialize(ConfigFile); } if (SimpleClusterParticles) { _SetParticlesSeeds(); } // Get AA from vrx configuration file m_AntiAliasingLevel = (int)MiddleVR.VRDisplayMgr.GetAntiAliasing(); DumpOptions(); if (!m_isInit) { GameObject gui = new GameObject(); m_GUI = gui.AddComponent<GUIText>() as GUIText; gui.transform.localPosition = new UnityEngine.Vector3(0.2f, 0.0f, 0.0f); m_GUI.pixelOffset = new UnityEngine.Vector2(0, 0); m_GUI.anchor = TextAnchor.LowerLeft; string txt = m_Kernel.GetLogString(true); print(txt); m_GUI.text = txt; return; } m_Kernel = MiddleVR.VRKernel; m_DeviceMgr = MiddleVR.VRDeviceMgr; m_DisplayMgr = MiddleVR.VRDisplayMgr; m_ClusterMgr = MiddleVR.VRClusterMgr; if (SimpleCluster) { SetupSimpleCluster(); } if (DisableExistingCameras) { Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[]; foreach (Camera cam in cameras) { if (cam.targetTexture == null) { cam.enabled = false; } } } MVRNodesCreator.Instance.CreateNodes(VRSystemCenterNode, DebugNodes, DebugScreens, GrabExistingNodes, TemplateCamera); MVRTools.CreateViewportsAndCameras(DontChangeWindowGeometry, true); MVRTools.Log(4, "[<] End of VR initialization script"); } protected void Awake() { // Attempt to collect objects from previous level System.GC.Collect(); System.GC.WaitForPendingFinalizers(); // Second call to work around a possible mono bug (see https://bugzilla.xamarin.com/show_bug.cgi?id=20503 ) System.GC.WaitForPendingFinalizers(); MVRNodesMapper.CreateInstance(); MVRNodesCreator.CreateInstance(); InitializeVR(); } protected void Start () { MVRTools.Log(4, "[>] VR Manager Start."); m_Kernel.DeleteLateObjects(); // Reset Manager's position so text display is correct. transform.position = new UnityEngine.Vector3(0, 0, 0); transform.rotation = new Quaternion(); transform.localScale = new UnityEngine.Vector3(1, 1, 1); m_Wand = GameObject.Find("VRWand"); m_VRMenu = GameObject.Find("VRMenu"); ShowWandGeometry(ShowWand); _EnableProximityWarning(m_ShowScreenProximityWarnings); _EnableFPSDisplay(m_ShowFPS); _EnableNavigationFly(m_Fly); _EnableNavigationCollision(m_NavigationCollisions); _EnableManipulationReturnObjects(m_ManipulationReturnObjects); _EnableVRMenu(m_UseVRMenu); if (ForceQuality) { QualitySettings.SetQualityLevel(ForceQualityIndex); } // Manage VSync after the quality settings MVRTools.ManageVSync(); // Set AA from vrx configuration file QualitySettings.antiAliasing = m_AntiAliasingLevel; // Check if MiddleVR Reset is needed if (!Application.isEditor && (ForceQuality || QualitySettings.antiAliasing > 1)) { bool useOpenGLQuadbuffer = m_DisplayMgr.GetActiveViewport(0).GetStereo() && (m_DisplayMgr.GetActiveViewport(0).GetStereoMode() == 0); //VRStereoMode_QuadBuffer = 0 if (useOpenGLQuadbuffer || m_ClusterMgr.GetForceOpenGLConversion()) { m_NeedDelayedRenderingReset = true; m_RenderingResetDelay = 1; } } m_QuitCommand = new vrCommand("VRManager.QuitApplicationCommand", _QuitApplicationCommandHandler); MVRTools.Log(4, "[<] End of VR Manager Start."); } private vrValue StartParticlesCommandHandler(vrValue iValue) { // We get all the randomSeed / playOnAwake of the master's particle systems // to sync the slaves. ParticleSystem[] particles = GameObject.FindObjectsOfType(typeof(ParticleSystem)) as ParticleSystem[]; for (uint i = 0, iEnd = iValue.GetListItemsNb(), particlesCnt = (uint)particles.GetLength(0); i < iEnd && i < particlesCnt; ++i) { particles[i].randomSeed = (uint)iValue.GetListItem(i).GetListItem(0).GetInt(); if (iValue.GetListItem(i).GetListItem(1).GetBool()) { particles[i].Play(); } } return null; } private void _SetParticlesSeeds() { if (MiddleVR.VRClusterMgr.IsCluster()) { // Creating the list of randomSeed / is playOnAwake to sync the seeds // of each particle systems to the master vrValue particlesDataList = vrValue.CreateList(); foreach (ParticleSystem particle in GameObject.FindObjectsOfType(typeof(ParticleSystem)) as ParticleSystem[]) { if (MiddleVR.VRClusterMgr.IsServer()) { vrValue particleData = vrValue.CreateList(); particleData.AddListItem((int)particle.randomSeed); particleData.AddListItem(particle.playOnAwake); particlesDataList.AddListItem(particleData); } // We reset the particle systems to sync them in every nodes of the cluster particle.Clear(); particle.Stop(); particle.time = .0f; } m_startParticlesCommand = new vrCommand("startParticleCommand", StartParticlesCommandHandler); if (MiddleVR.VRClusterMgr.IsServer()) { m_startParticlesCommand.Do(particlesDataList); } } } private void _SetNavigation(ENavigation iNavigation) { Navigation = iNavigation; VRInteractionNavigationWandJoystick navigationWandJoystick = m_Wand.GetComponent<VRInteractionNavigationWandJoystick>(); VRInteractionNavigationElastic navigationElastic = m_Wand.GetComponent<VRInteractionNavigationElastic>(); VRInteractionNavigationGrabWorld navigationGrabWorld = m_Wand.GetComponent<VRInteractionNavigationGrabWorld>(); if (navigationWandJoystick == null || navigationElastic == null || navigationGrabWorld == null) { MVRTools.Log(2, "[~] Some navigation scripts are missing on the Wand."); return; } if (navigationWandJoystick.GetInteraction() == null || navigationElastic.GetInteraction() == null || navigationGrabWorld.GetInteraction() == null) { MVRTools.Log(2, "[~] Some navigation interactions are not initialized."); return; } switch (Navigation) { case ENavigation.None: MiddleVR.VRInteractionMgr.Deactivate(navigationWandJoystick.GetInteraction()); MiddleVR.VRInteractionMgr.Deactivate(navigationElastic.GetInteraction()); MiddleVR.VRInteractionMgr.Deactivate(navigationGrabWorld.GetInteraction()); break; case ENavigation.Joystick: MiddleVR.VRInteractionMgr.Activate(navigationWandJoystick.GetInteraction()); break; case ENavigation.Elastic: MiddleVR.VRInteractionMgr.Activate(navigationElastic.GetInteraction()); break; case ENavigation.GrabWorld: MiddleVR.VRInteractionMgr.Activate(navigationGrabWorld.GetInteraction()); break; default: break; } } private void _SetManipulation(EManipulation iManpulation) { Manipulation = iManpulation; VRInteractionManipulationRay manipulationRay = m_Wand.GetComponent<VRInteractionManipulationRay>(); VRInteractionManipulationHomer manipulationHomer = m_Wand.GetComponent<VRInteractionManipulationHomer>(); if (manipulationRay == null || manipulationHomer == null) { MVRTools.Log(2, "[~] Some manipulation scripts are missing on the Wand."); return; } switch (Manipulation) { case EManipulation.None: MiddleVR.VRInteractionMgr.Deactivate(manipulationRay.GetInteraction()); MiddleVR.VRInteractionMgr.Deactivate(manipulationHomer.GetInteraction()); break; case EManipulation.Ray: MiddleVR.VRInteractionMgr.Activate(manipulationRay.GetInteraction()); break; case EManipulation.Homer: MiddleVR.VRInteractionMgr.Activate(manipulationHomer.GetInteraction()); break; default: break; } } private void _SetVirtualHandMapping(EVirtualHandMapping iVirtualHandMapping) { VirtualHandMapping = iVirtualHandMapping; VRInteractionVirtualHandGogo virtualHandGogo = m_Wand.GetComponent<VRInteractionVirtualHandGogo>(); if (virtualHandGogo == null) { MVRTools.Log(2, "[~] The virtual hand Gogo script is missing on the Wand."); return; } switch (VirtualHandMapping) { case EVirtualHandMapping.Direct: MiddleVR.VRInteractionMgr.Deactivate(virtualHandGogo.GetInteraction()); break; case EVirtualHandMapping.Gogo: MiddleVR.VRInteractionMgr.Activate(virtualHandGogo.GetInteraction()); break; default: break; } } private void _EnableProximityWarning(bool iShow) { m_ShowScreenProximityWarnings = iShow; VRInteractionScreenProximityWarning proximityWarning = m_Wand.GetComponent<VRInteractionScreenProximityWarning>(); if (proximityWarning != null) { proximityWarning.enabled = m_ShowScreenProximityWarnings; } } private void _EnableFPSDisplay(bool iEnable) { m_ShowFPS = iEnable; this.GetComponent<GUIText>().enabled = m_ShowFPS; } private void _EnableVRMenu(bool iEnable) { m_UseVRMenu = iEnable; if (m_VRMenu != null) { m_VRMenu.GetComponent<VRMenuManager>().UseVRMenu(m_UseVRMenu); } } private void _EnableNavigationFly(bool iEnable) { m_Fly = iEnable; VRInteractionNavigationElastic navigationElastic = m_Wand.GetComponent<VRInteractionNavigationElastic>(); if (navigationElastic != null) { navigationElastic.Fly = m_Fly; } VRInteractionNavigationWandJoystick navigationWandJoystick = m_Wand.GetComponent<VRInteractionNavigationWandJoystick>(); if (navigationWandJoystick != null) { navigationWandJoystick.Fly = m_Fly; } vrInteractionManager interactionMgr = vrInteractionManager.GetInstance(); for (uint i = 0, iEnd = interactionMgr.GetInteractionsNb(); i < iEnd; ++i) { vrProperty flyProp = interactionMgr.GetInteractionByIndex(i).GetProperty("Fly"); if (flyProp != null) { flyProp.SetBool(m_Fly); } } } private void _EnableNavigationCollision(bool iEnable) { m_NavigationCollisions = iEnable; VRNavigationCollision navigationCollision = m_Wand.GetComponent<VRNavigationCollision>(); if (navigationCollision != null) { navigationCollision.enabled = m_NavigationCollisions; } } private void _EnableManipulationReturnObjects(bool iEnable) { m_ManipulationReturnObjects = iEnable; VRInteractionManipulationReturnObjects returnObjects = m_Wand.GetComponent<VRInteractionManipulationReturnObjects>(); if (returnObjects != null) { returnObjects.enabled = m_ManipulationReturnObjects; } } public void ShowWandGeometry(bool iShow) { if (m_Wand != null) { m_Wand.GetComponent<VRWand>().Show(iShow); } } private void UpdateInput() { vrButtons wandButtons = m_DeviceMgr.GetWandButtons(); if (wandButtons != null) { uint buttonNb = wandButtons.GetButtonsNb(); if (buttonNb > 0) { WandButton0 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton0()); } if (buttonNb > 1) { WandButton1 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton1()); } if (buttonNb > 2) { WandButton2 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton2()); } if (buttonNb > 3) { WandButton3 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton3()); } if (buttonNb > 4) { WandButton4 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton4()); } if (buttonNb > 5) { WandButton5 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton5()); } } WandAxisHorizontal = m_DeviceMgr.GetWandHorizontalAxisValue(); WandAxisVertical = m_DeviceMgr.GetWandVerticalAxisValue(); } // Update is called once per frame protected void Update() { //MVRTools.Log("VRManagerUpdate"); // Initialize interactions if( !m_InteractionsInitialized ) { _SetNavigation(Navigation); _SetManipulation(Manipulation); _SetVirtualHandMapping(VirtualHandMapping); m_InteractionsInitialized = true; } MVRNodesMapper nodesMapper = MVRNodesMapper.Instance; nodesMapper.UpdateNodesUnityToMiddleVR(); if (m_isInit) { MVRTools.Log(4, "[>] Unity Update - Start"); if (m_Kernel.GetFrame() >= m_FirstFrameAfterReset+1 && !m_isGeometrySet && !Application.isEditor) { if (!DontChangeWindowGeometry) { m_DisplayMgr.SetUnityWindowGeometry(); } m_isGeometrySet = true; } if (m_Kernel.GetFrame() == 0) { // Set the random seed in kernel for dispatching only during start-up. // With clustering, a client will be set by a call to kernel.Update(). if (!m_ClusterMgr.IsCluster() || (m_ClusterMgr.IsCluster() && m_ClusterMgr.IsServer())) { // The cast is safe because the seed is always positive. uint seed = (uint) UnityEngine.Random.seed; m_Kernel._SetRandomSeed(seed); } } m_Kernel.Update(); if (m_Kernel.GetFrame() == 0) { // Set the random seed in a client only during start-up. if (m_ClusterMgr.IsCluster() && m_ClusterMgr.IsClient()) { // The cast is safe because the seed comes from // a previous value of Unity. int seed = (int) m_Kernel.GetRandomSeed(); UnityEngine.Random.seed = seed; } } UpdateInput(); if (ShowFPS) { this.GetComponent<GUIText>().text = m_Kernel.GetFPS().ToString("f2"); } nodesMapper.UpdateNodesMiddleVRToUnity(false); MVRTools.UpdateCameraProperties(); if (m_displayLog) { string txt = m_Kernel.GetLogString(true); print(txt); m_GUI.text = txt; } vrKeyboard keyb = m_DeviceMgr.GetKeyboard(); if (keyb != null) { if (keyb.IsKeyPressed(MiddleVR.VRK_LSHIFT) || keyb.IsKeyPressed(MiddleVR.VRK_RSHIFT)) { if (keyb.IsKeyToggled(MiddleVR.VRK_D)) { ShowFPS = !ShowFPS; } if (keyb.IsKeyToggled(MiddleVR.VRK_W) || keyb.IsKeyToggled(MiddleVR.VRK_Z)) { ShowWand = !ShowWand; ShowWandGeometry(ShowWand); } // Toggle Fly mode on interactions if (keyb.IsKeyToggled(MiddleVR.VRK_F)) { Fly = !Fly; } // Navigation mode switch if (keyb.IsKeyToggled(MiddleVR.VRK_N)) { vrInteraction navigation = _GetNextInteraction("ContinuousNavigation"); if (navigation != null) { MiddleVR.VRInteractionMgr.Activate(navigation); } } } } DeltaTime = m_Kernel.GetDeltaTime(); MVRTools.Log(4, "[<] Unity Update - End"); } else { //Debug.LogWarning("[ ] If you have an error mentioning 'DLLNotFoundException: MiddleVR_CSharp', please restart Unity. If this does not fix the problem, please make sure MiddleVR is in the PATH environment variable."); } // If QualityLevel changed, we have to reset the Unity Manager if( m_NeedDelayedRenderingReset ) { if( m_RenderingResetDelay == 0 ) { MVRTools.Log(3,"[ ] Graphic quality forced, reset Unity Manager."); MVRTools.VRReset(); MVRTools.CreateViewportsAndCameras(DontChangeWindowGeometry, true); m_isGeometrySet = false; m_NeedDelayedRenderingReset = false; } else { --m_RenderingResetDelay; } } } private void AddClusterScripts(GameObject iObject) { MVRTools.Log(2, "[ ] Adding cluster sharing scripts to " + iObject.name); if (iObject.GetComponent<VRShareTransform>() == null) { iObject.AddComponent<VRShareTransform>(); } } private void SetupSimpleCluster() { if (m_ClusterMgr.IsCluster()) { // Rigid bodies Rigidbody[] bodies = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[]; foreach (Rigidbody body in bodies) { if (!body.isKinematic) { GameObject iObject = body.gameObject; AddClusterScripts(iObject); } } // Character controller CharacterController[] ctrls = FindObjectsOfType(typeof(CharacterController)) as CharacterController[]; foreach (CharacterController ctrl in ctrls) { GameObject iObject = ctrl.gameObject; AddClusterScripts(iObject); } } } private void DumpOptions() { MVRTools.Log(3, "[ ] Dumping VRManager's options:"); MVRTools.Log(3, "[ ] - Config File : " + ConfigFile); MVRTools.Log(3, "[ ] - System Center Node : " + VRSystemCenterNode); MVRTools.Log(3, "[ ] - Template Camera : " + TemplateCamera); MVRTools.Log(3, "[ ] - Show Wand : " + ShowWand); MVRTools.Log(3, "[ ] - Show FPS : " + ShowFPS); MVRTools.Log(3, "[ ] - Disable Existing Cameras : " + DisableExistingCameras); MVRTools.Log(3, "[ ] - Grab Existing Nodes : " + GrabExistingNodes); MVRTools.Log(3, "[ ] - Debug Nodes : " + DebugNodes); MVRTools.Log(3, "[ ] - Debug Screens : " + DebugScreens); MVRTools.Log(3, "[ ] - Quit On Esc : " + QuitOnEsc); MVRTools.Log(3, "[ ] - Don't Change Window Geometry : " + DontChangeWindowGeometry); MVRTools.Log(3, "[ ] - Simple Cluster : " + SimpleCluster); MVRTools.Log(3, "[ ] - Simple Cluster Particles : " + SimpleClusterParticles ); MVRTools.Log(3, "[ ] - Force Quality : " + ForceQuality ); MVRTools.Log(3, "[ ] - Force QualityIndex : " + ForceQualityIndex ); MVRTools.Log(3, "[ ] - Anti-Aliasing Level : " + m_AntiAliasingLevel ); MVRTools.Log(3, "[ ] - Custom License : " + CustomLicense ); MVRTools.Log(3, "[ ] - Custom License Name : " + CustomLicenseName ); } private vrInteraction _GetNextInteraction(string iTag) { vrInteraction nextInteraction = null; vrInteraction activeInteraction = MiddleVR.VRInteractionMgr.GetActiveInteractionByTag("ContinuousNavigation"); if (activeInteraction != null) { // Found active interaction, search for the next one uint interactionsNb = MiddleVR.VRInteractionMgr.GetInteractionsNb(); uint index = MiddleVR.VRInteractionMgr.GetInteractionIndex(activeInteraction); for (uint i = 0; i < interactionsNb - 1; ++i) { // We loop in the interactions list to find the next interaction with the right tag uint nextIndex = (index + 1 + i) % interactionsNb; vrInteraction interaction = MiddleVR.VRInteractionMgr.GetInteractionByIndex(nextIndex); if (interaction != null && interaction.TagsContain("ContinuousNavigation")) { nextInteraction = interaction; break; } } } else { // No active interaction, try to activate the first if existing nextInteraction = MiddleVR.VRInteractionMgr.GetInteractionByTag("ContinuousNavigation", 0); } return nextInteraction; } public void QuitApplication() { MVRTools.Log(3,"[ ] Execute QuitCommand."); // Call cluster command so that all cluster nodes quit m_QuitCommand.Do(new vrValue()); } private vrValue _QuitApplicationCommandHandler(vrValue iValue) { MVRTools.Log(3, "[ ] Received QuitApplicationCommand"); MVRTools.Log("[ ] Unity says we're quitting."); MiddleVR.VRKernel.SetQuitting(); Application.Quit(); return null; } protected void OnApplicationQuit() { MVRNodesCreator.DestroyInstance(); MVRNodesMapper.DestroyInstance(); MVRTools.VRDestroy(Application.isEditor); } protected void OnDestroy() { MiddleVR.DisposeObject(ref m_startParticlesCommand); } }
// Copyright (c) 2015 Alachisoft // // 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.Net; using System.Collections; using Alachisoft.NCache.Runtime.Serialization.IO; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Util; using Alachisoft.NCache.Common.Net; using System.IO; namespace Alachisoft.NCache.Caching.Statistics { /// <summary> /// Info class that holds statistics related to cluster. /// </summary> [Serializable] public class ClusterCacheStatistics : CacheStatistics, ICloneable,ICompactSerializable { /// <summary> The name of the group participating in the cluster. </summary> private string _groupName; /// <summary> The name of the group participating in the cluster. </summary> private string _channelType; /// <summary> The number of nodes in the cluster that are providers or consumers, i.e., group members. </summary> private int _memberCount; /// <summary> The number of nodes in the cluster that are storage enabled. </summary> private int _serverCount; /// <summary> The number of nodes in the cluster that are unknown, i.e., different cache scheme. </summary> private int _otherCount; /// <summary> The statistics of the local node. </summary> private NodeInfo _localNode; /// <summary> The statistics of individual nodes. </summary> private ArrayList _nodeInfos; ///<summary>Data affinity of the entire cluster.</summary> private ArrayList _clusterDataAffinity = new ArrayList(); ///<summary>A map that gives the list of all data groups mapped at the node.</summary> private Hashtable _datagroupsAtPartition = new Hashtable(); ///<summary>A map that gives the list of all nodes that have mapping for a group.</summary> private Hashtable _partitionsHavingDatagroup = new Hashtable(); ///<summary>A map that gives the list of all nodes belonging to the same subgroup i.e. partition.</summary> private Hashtable _subgroupNodes = new Hashtable(); /// <summary> /// Constructor. /// </summary> public ClusterCacheStatistics() {} /// <summary> /// Copy constructor. /// </summary> /// <param name="stat"></param> protected ClusterCacheStatistics(ClusterCacheStatistics stat):base(stat) { lock(stat) { this._groupName = stat._groupName; this._channelType = stat._channelType; this._memberCount = stat._memberCount; this._serverCount = stat._serverCount; this._otherCount = stat._otherCount; this._localNode = stat._localNode == null ? null:stat._localNode.Clone() as NodeInfo; if(stat._nodeInfos != null) { this._nodeInfos = new ArrayList(stat._nodeInfos.Count); for(int i=0; i<stat._nodeInfos.Count; i++) { this._nodeInfos.Add(((NodeInfo)stat._nodeInfos[i]).Clone() as NodeInfo); } } if (stat.ClusterDataAffinity != null) this.ClusterDataAffinity = (ArrayList)stat.ClusterDataAffinity.Clone(); if (stat.PartitionsHavingDatagroup != null) this.PartitionsHavingDatagroup = (Hashtable)stat.PartitionsHavingDatagroup.Clone(); if (stat.DatagroupsAtPartition != null) this.DatagroupsAtPartition = (Hashtable)stat.DatagroupsAtPartition.Clone(); if (stat.SubgroupNodes != null) this.SubgroupNodes = (Hashtable)stat.SubgroupNodes.Clone(); } } public override long MaxSize { get { return this.LocalNode.Statistics.MaxSize; } set { if(this.LocalNode != null) this.LocalNode.Statistics.MaxSize = value; } } /// <summary> /// The name of the group participating in the cluster. /// </summary> public string GroupName { get { return _groupName; } set { _groupName = value; } } /// <summary> /// The clustering scheme. /// </summary> public string ChannelType { get { return _channelType; } set { _channelType = value; } } /// <summary> /// The total number of nodes in the cluster. /// </summary> public int ClusterSize { get { return MemberCount + OtherCount; } } /// <summary> /// The number of nodes in the cluster that are providers or consumers, i.e., group members. /// </summary> public int MemberCount { get { return _memberCount; } set { _memberCount = value; } } /// <summary> /// The number of nodes in the cluster that are storage enabled. /// </summary> public int ServerCount { get { return _serverCount; } set { _serverCount = value; } } /// <summary> /// The number of nodes in the cluster that are unknown, i.e., different cache scheme. /// </summary> public int OtherCount { get { return _otherCount; } set { _otherCount = value; } } /// <summary> /// The statistics of the local node. /// </summary> public NodeInfo LocalNode { get { return _localNode; } set { _localNode = value; } } /// <summary> /// The statistics of the local node. /// </summary> public ArrayList Nodes { get { return _nodeInfos; } set { _nodeInfos = value; } } /// <summary> /// Gets/Sets teh data affinity of the cluster. /// </summary> public ArrayList ClusterDataAffinity { get { return _clusterDataAffinity; } set { _clusterDataAffinity = value; } } public Hashtable DatagroupsAtPartition { get { return _datagroupsAtPartition; } set { _datagroupsAtPartition = value; } } public Hashtable PartitionsHavingDatagroup { get { return _partitionsHavingDatagroup; } set { _partitionsHavingDatagroup = value; } } public Hashtable SubgroupNodes { get { return _subgroupNodes; } set { _subgroupNodes = value; } } #region / --- ICloneable --- / /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public override object Clone() { return new ClusterCacheStatistics(this); } #endregion /// <summary> /// Adds a new node to the node list /// </summary> /// <param name="info"></param> protected internal NodeInfo GetNode(Address address) { lock(this) { if(_nodeInfos != null) for(int i=0 ;i<_nodeInfos.Count; i++) { if(((NodeInfo)_nodeInfos[i]).Address.CompareTo(address) == 0) return _nodeInfos[i] as NodeInfo; } } return null; } /// <summary> /// Sets the values of the server/member/other counts /// </summary> /// <param name="server"></param> /// <param name="member"></param> /// <param name="other"></param> protected internal void SetServerCounts(int servCnt, int memCnt, int otherCnt) { lock(this) { _serverCount = servCnt; _memberCount = memCnt; _otherCount = otherCnt; } } /// <summary> /// returns the string representation of the statistics. /// </summary> /// <returns></returns> public override string ToString() { lock(this) { System.Text.StringBuilder ret = new System.Text.StringBuilder(); ret.Append("Cluster[" + base.ToString() + ", Nm:" + GroupName + ", "); ret.Append("S:" + ServerCount.ToString() + ", "); ret.Append("M:" + MemberCount.ToString() + ", "); ret.Append("O:" + OtherCount.ToString() + ", "); if(_localNode != null) ret.Append("Local" + _localNode.ToString()); foreach(NodeInfo i in _nodeInfos) { ret.Append(", " + i.ToString()); } ret.Append("]"); return ret.ToString(); } } #region / --- ICompactSerializable --- / public override void Deserialize(CompactReader reader) { base.Deserialize(reader); _groupName = reader.ReadObject() as string; _channelType = reader.ReadObject() as string; _memberCount = reader.ReadInt32(); _serverCount = reader.ReadInt32(); _otherCount = reader.ReadInt32(); _localNode = NodeInfo.ReadNodeInfo(reader); _nodeInfos = (ArrayList)reader.ReadObject(); } public override void Serialize(CompactWriter writer) { base.Serialize(writer); writer.WriteObject(_groupName); writer.WriteObject(_channelType); writer.Write(_memberCount); writer.Write(_serverCount); writer.Write(_otherCount); NodeInfo.WriteNodeInfo(writer, _localNode); writer.WriteObject(_nodeInfos); } #endregion } }
using Lucene.Net.Support; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; /// <summary> /// A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum /// score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries. /// This is useful when searching for a word in multiple fields with different boost factors (so that the fields cannot be /// combined equivalently into a single search field). We want the primary score to be the one associated with the highest boost, /// not the sum of the field scores (as <see cref="BooleanQuery"/> would give). /// <para/> /// If the query is "albino elephant" this ensures that "albino" matching one field and "elephant" matching /// another gets a higher score than "albino" matching both fields. /// <para/> /// To get this result, use both <see cref="BooleanQuery"/> and <see cref="DisjunctionMaxQuery"/>: for each term a <see cref="DisjunctionMaxQuery"/> searches for it in /// each field, while the set of these <see cref="DisjunctionMaxQuery"/>'s is combined into a <see cref="BooleanQuery"/>. /// The tie breaker capability allows results that include the same term in multiple fields to be judged better than results that /// include this term in only the best of those multiple fields, without confusing this with the better case of two different terms /// in the multiple fields. /// <para/> /// Collection initializer note: To create and populate a <see cref="DisjunctionMaxQuery"/> /// in a single statement, you can use the following example as a guide: /// /// <code> /// var disjunctionMaxQuery = new DisjunctionMaxQuery(0.1f) { /// new TermQuery(new Term("field1", "albino")), /// new TermQuery(new Term("field2", "elephant")) /// }; /// </code> /// </summary> public class DisjunctionMaxQuery : Query, IEnumerable<Query> { /// <summary> /// The subqueries /// </summary> private EquatableList<Query> disjuncts = new EquatableList<Query>(); /// <summary> /// Multiple of the non-max disjunct scores added into our final score. Non-zero values support tie-breaking. /// </summary> private float tieBreakerMultiplier = 0.0f; /// <summary> /// Creates a new empty <see cref="DisjunctionMaxQuery"/>. Use <see cref="Add(Query)"/> to add the subqueries. </summary> /// <param name="tieBreakerMultiplier"> The score of each non-maximum disjunct for a document is multiplied by this weight /// and added into the final score. If non-zero, the value should be small, on the order of 0.1, which says that /// 10 occurrences of word in a lower-scored field that is also in a higher scored field is just as good as a unique /// word in the lower scored field (i.e., one that is not in any higher scored field). </param> public DisjunctionMaxQuery(float tieBreakerMultiplier) { this.tieBreakerMultiplier = tieBreakerMultiplier; } /// <summary> /// Creates a new <see cref="DisjunctionMaxQuery"/> </summary> /// <param name="disjuncts"> A <see cref="T:ICollection{Query}"/> of all the disjuncts to add </param> /// <param name="tieBreakerMultiplier"> The weight to give to each matching non-maximum disjunct </param> public DisjunctionMaxQuery(ICollection<Query> disjuncts, float tieBreakerMultiplier) { this.tieBreakerMultiplier = tieBreakerMultiplier; Add(disjuncts); } /// <summary> /// Add a subquery to this disjunction </summary> /// <param name="query"> The disjunct added </param> public virtual void Add(Query query) { disjuncts.Add(query); } /// <summary> /// Add a collection of disjuncts to this disjunction /// via <see cref="T:IEnumerable{Query}"/> </summary> /// <param name="disjuncts"> A collection of queries to add as disjuncts. </param> public virtual void Add(ICollection<Query> disjuncts) { this.disjuncts.AddRange(disjuncts); } /// <returns> An <see cref="T:IEnumerator{Query}"/> over the disjuncts </returns> public virtual IEnumerator<Query> GetEnumerator() { return disjuncts.GetEnumerator(); } // LUCENENET specific IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <returns> The disjuncts. </returns> public virtual IList<Query> Disjuncts { get { return disjuncts; } } /// <returns> Tie breaker value for multiple matches. </returns> public virtual float TieBreakerMultiplier { get { return tieBreakerMultiplier; } } /// <summary> /// Expert: the Weight for DisjunctionMaxQuery, used to /// normalize, score and explain these queries. /// /// <para>NOTE: this API and implementation is subject to /// change suddenly in the next release.</para> /// </summary> protected class DisjunctionMaxWeight : Weight { private readonly DisjunctionMaxQuery outerInstance; /// <summary> /// The <see cref="Weight"/>s for our subqueries, in 1-1 correspondence with disjuncts </summary> protected List<Weight> m_weights = new List<Weight>(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts /// <summary> /// Construct the <see cref="Weight"/> for this <see cref="Search.Query"/> searched by <paramref name="searcher"/>. Recursively construct subquery weights. </summary> public DisjunctionMaxWeight(DisjunctionMaxQuery outerInstance, IndexSearcher searcher) { this.outerInstance = outerInstance; foreach (Query disjunctQuery in outerInstance.disjuncts) { m_weights.Add(disjunctQuery.CreateWeight(searcher)); } } /// <summary> /// Return our associated <see cref="DisjunctionMaxQuery"/> </summary> public override Query Query { get { return outerInstance; } } /// <summary> /// Compute the sub of squared weights of us applied to our subqueries. Used for normalization. </summary> public override float GetValueForNormalization() { float max = 0.0f, sum = 0.0f; foreach (Weight currentWeight in m_weights) { float sub = currentWeight.GetValueForNormalization(); sum += sub; max = Math.Max(max, sub); } float boost = outerInstance.Boost; return (((sum - max) * outerInstance.tieBreakerMultiplier * outerInstance.tieBreakerMultiplier) + max) * boost * boost; } /// <summary> /// Apply the computed normalization factor to our subqueries </summary> public override void Normalize(float norm, float topLevelBoost) { topLevelBoost *= outerInstance.Boost; // Incorporate our boost foreach (Weight wt in m_weights) { wt.Normalize(norm, topLevelBoost); } } /// <summary> /// Create the scorer used to score our associated <see cref="DisjunctionMaxQuery"/> </summary> public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { IList<Scorer> scorers = new List<Scorer>(); foreach (Weight w in m_weights) { // we will advance() subscorers Scorer subScorer = w.GetScorer(context, acceptDocs); if (subScorer != null) { scorers.Add(subScorer); } } if (scorers.Count == 0) { // no sub-scorers had any documents return null; } DisjunctionMaxScorer result = new DisjunctionMaxScorer(this, outerInstance.tieBreakerMultiplier, scorers.ToArray()); return result; } /// <summary> /// Explain the score we computed for doc </summary> public override Explanation Explain(AtomicReaderContext context, int doc) { if (outerInstance.disjuncts.Count == 1) { return m_weights[0].Explain(context, doc); } ComplexExplanation result = new ComplexExplanation(); float max = 0.0f, sum = 0.0f; result.Description = outerInstance.tieBreakerMultiplier == 0.0f ? "max of:" : "max plus " + outerInstance.tieBreakerMultiplier + " times others of:"; foreach (Weight wt in m_weights) { Explanation e = wt.Explain(context, doc); if (e.IsMatch) { result.Match = true; result.AddDetail(e); sum += e.Value; max = Math.Max(max, e.Value); } } result.Value = max + (sum - max) * outerInstance.tieBreakerMultiplier; return result; } } // end of DisjunctionMaxWeight inner class /// <summary> /// Create the <see cref="Weight"/> used to score us </summary> public override Weight CreateWeight(IndexSearcher searcher) { return new DisjunctionMaxWeight(this, searcher); } /// <summary> /// Optimize our representation and our subqueries representations </summary> /// <param name="reader"> The <see cref="IndexReader"/> we query </param> /// <returns> An optimized copy of us (which may not be a copy if there is nothing to optimize) </returns> public override Query Rewrite(IndexReader reader) { int numDisjunctions = disjuncts.Count; if (numDisjunctions == 1) { Query singleton = disjuncts[0]; Query result = singleton.Rewrite(reader); if (Boost != 1.0f) { if (result == singleton) { result = (Query)result.Clone(); } result.Boost = Boost * result.Boost; } return result; } DisjunctionMaxQuery clone = null; for (int i = 0; i < numDisjunctions; i++) { Query clause = disjuncts[i]; Query rewrite = clause.Rewrite(reader); if (rewrite != clause) { if (clone == null) { clone = (DisjunctionMaxQuery)this.Clone(); } clone.disjuncts[i] = rewrite; } } if (clone != null) { return clone; } else { return this; } } /// <summary> /// Create a shallow copy of us -- used in rewriting if necessary </summary> /// <returns> A copy of us (but reuse, don't copy, our subqueries) </returns> public override object Clone() { DisjunctionMaxQuery clone = (DisjunctionMaxQuery)base.Clone(); clone.disjuncts = (EquatableList<Query>)this.disjuncts.Clone(); return clone; } /// <summary> /// Expert: adds all terms occurring in this query to the terms set. Only /// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form. /// </summary> /// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception> public override void ExtractTerms(ISet<Term> terms) { foreach (Query query in disjuncts) { query.ExtractTerms(terms); } } /// <summary> /// Prettyprint us. </summary> /// <param name="field"> The field to which we are applied </param> /// <returns> A string that shows what we do, of the form "(disjunct1 | disjunct2 | ... | disjunctn)^boost" </returns> public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); buffer.Append("("); int numDisjunctions = disjuncts.Count; for (int i = 0; i < numDisjunctions; i++) { Query subquery = disjuncts[i]; if (subquery is BooleanQuery) // wrap sub-bools in parens { buffer.Append("("); buffer.Append(subquery.ToString(field)); buffer.Append(")"); } else { buffer.Append(subquery.ToString(field)); } if (i != numDisjunctions - 1) { buffer.Append(" | "); } } buffer.Append(")"); if (tieBreakerMultiplier != 0.0f) { buffer.Append("~"); buffer.Append(tieBreakerMultiplier); } if (Boost != 1.0) { buffer.Append("^"); buffer.Append(Boost); } return buffer.ToString(); } /// <summary> /// Return <c>true</c> if we represent the same query as <paramref name="o"/> </summary> /// <param name="o"> Another object </param> /// <returns> <c>true</c> if <paramref name="o"/> is a <see cref="DisjunctionMaxQuery"/> with the same boost and the same subqueries, in the same order, as us </returns> public override bool Equals(object o) { if (!(o is DisjunctionMaxQuery)) { return false; } DisjunctionMaxQuery other = (DisjunctionMaxQuery)o; return this.Boost == other.Boost && this.tieBreakerMultiplier == other.tieBreakerMultiplier && this.disjuncts.Equals(other.disjuncts); } /// <summary> /// Compute a hash code for hashing us </summary> /// <returns> the hash code </returns> public override int GetHashCode() { return Number.SingleToInt32Bits(Boost) + Number.SingleToInt32Bits(tieBreakerMultiplier) + disjuncts.GetHashCode(); } } }
using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using Microsoft.Build.BuildEngine; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using NuPattern.Reflection; using NuPattern.VisualStudio.Properties; using VsWebSite; namespace NuPattern.VisualStudio.Solution.Hierarchy { /// <summary> /// Project Node in the current solution /// </summary> /// internal class ProjectNode : HierarchyNode { /// <summary> /// Visual Studio Project /// </summary> private IVsProject project; protected IVsProject Project { get { return project; } } /// <summary> /// Builds a project node from the project Guid /// </summary> /// <param name="vsSolution"></param> /// <param name="projectGuid"></param> [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")] [SecurityCritical] public ProjectNode(IVsSolution vsSolution, Guid projectGuid) : base(vsSolution, projectGuid) { this.project = this.Hierarchy as IVsProject; Debug.Assert(ItemId == VSConstants.VSITEMID_ROOT); } /// <summary> /// Builds a project node from the a parent node /// </summary> /// <param name="parent"></param> /// <param name="itemid"></param> [SecurityCritical] private ProjectNode(HierarchyNode parent, uint itemid) : base(parent, itemid) { this.project = this.Hierarchy as IVsProject; Debug.Assert(project != null); } /// <summary> /// Determines whether this instance [can add item] the specified name. /// </summary> /// <param name="name">The name.</param> /// <returns> /// <c>true</c> if this instance [can add item] the specified name; otherwise, <c>false</c>. /// </returns> public static bool CanAddItem(string name) { Guard.NotNullOrEmpty(() => name, name); return IsValidFullPathName(name); } /// <summary> /// Adds a new item in the project /// </summary> /// <param name="name"></param> /// <returns></returns> [SecurityCritical] public HierarchyNode AddItem(string name) { Guard.NotNullOrEmpty(() => name, name); if (!CanAddItem(name)) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Resources.ProjectNode_InvalidFileName, name)); } FileInfo fileInfo = null; string subFolder = string.Empty; if (System.IO.Path.IsPathRooted(name)) { fileInfo = new FileInfo(name); } else { fileInfo = new FileInfo(System.IO.Path.Combine(ProjectDir, name)); int subFolderIndex = name.LastIndexOf(System.IO.Path.DirectorySeparatorChar); if (subFolderIndex != -1) { subFolder = name.Substring(0, subFolderIndex); } } if (fileInfo.Name.Equals(fileInfo.Extension, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, Resources.ProjectNode_CannotCreateItemWithEmptyName)); } if (!File.Exists(fileInfo.FullName)) { Directory.CreateDirectory(fileInfo.Directory.FullName); File.Create(fileInfo.FullName).Dispose(); } uint itemId = VSConstants.VSITEMID_NIL; int found = 1; VSDOCUMENTPRIORITY docPri = VSDOCUMENTPRIORITY.DP_Standard; int hr = project.IsDocumentInProject(fileInfo.FullName, out found, new VSDOCUMENTPRIORITY[] { docPri }, out itemId); Marshal.ThrowExceptionForHR(hr); if (found == 0) { VSADDRESULT result = VSADDRESULT.ADDRESULT_Cancel; uint folderId = this.ItemId; HierarchyNode subFolderNode = FindSubfolder(subFolder); if (subFolderNode != null) { folderId = subFolderNode.ItemId; } hr = project.AddItem(folderId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, fileInfo.Name, 1, new string[] { fileInfo.FullName }, IntPtr.Zero, new VSADDRESULT[] { result }); Marshal.ThrowExceptionForHR(hr); } hr = project.IsDocumentInProject(fileInfo.FullName, out found, new VSDOCUMENTPRIORITY[] { docPri }, out itemId); Marshal.ThrowExceptionForHR(hr); if (found == 1) { return new HierarchyNode(this, itemId); } return null; } /// <summary> /// Finds the sub folder. /// </summary> /// <param name="subfolder">The sub folder.</param> /// <returns></returns> [SecurityCritical] public ProjectNode FindSubfolder(string subfolder) { if (!string.IsNullOrEmpty(subfolder)) { string[] folders = subfolder.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); ProjectNode folderNode = this; foreach (string folder in folders) { folderNode = folderNode.FindOrCreateFolder(folder); if (folderNode == null) { break; } } return folderNode; } return null; } /// <summary> /// Finds or create a folder. /// </summary> /// <param name="folderName">Name of the folder.</param> /// <returns></returns> [SecurityCritical] public ProjectNode FindOrCreateFolder(string folderName) { if (string.IsNullOrEmpty(folderName) || folderName == @".") { return this; } DirectoryInfo di = new DirectoryInfo(System.IO.Path.Combine(this.RelativePath, folderName)); HierarchyNode subFolder = FindByName(di.Name); if (subFolder == null) { if (!Directory.Exists(di.FullName)) { Directory.CreateDirectory(di.FullName); } VSADDRESULT result = VSADDRESULT.ADDRESULT_Cancel; int hr = project.AddItem(this.ItemId, (VSADDITEMOPERATION.VSADDITEMOP_OPENFILE), di.Name, 1, new string[] { di.FullName }, IntPtr.Zero, new VSADDRESULT[] { result }); Marshal.ThrowExceptionForHR(hr); } subFolder = FindByName(di.Name); if (subFolder != null) { return new ProjectNode(subFolder, subFolder.ItemId); } return null; } /// <summary> /// Opens an item using the default view /// </summary> /// <param name="child"></param> /// <returns></returns> [SecurityCritical] public IVsWindowFrame OpenItem(HierarchyNode child) { Guard.NotNull(() => child, child); Guid logicalView = VSConstants.LOGVIEWID_Primary; IntPtr existingDocData = IntPtr.Zero; IVsWindowFrame windowFrame; int hr = project.OpenItem(child.ItemId, ref logicalView, existingDocData, out windowFrame); Marshal.ThrowExceptionForHR(hr); return windowFrame; } #pragma warning disable 0618 /// <summary> /// Gets the MSBuild project /// </summary> public Project MSBuildProject { get { return Engine.GlobalEngine.GetLoadedProject(Path); } } /// <summary> /// Gets the msbuild item /// </summary> /// <param name="includeSpec"></param> /// <returns></returns> public BuildItem GetBuildItem(string includeSpec) { Guard.NotNullOrEmpty(() => includeSpec, includeSpec); string currentDir = @"." + System.IO.Path.DirectorySeparatorChar; if (includeSpec.StartsWith(currentDir, StringComparison.OrdinalIgnoreCase)) { includeSpec = includeSpec.Substring(currentDir.Length); } Project msbuildProject = MSBuildProject; foreach (BuildItemGroup group in msbuildProject.ItemGroups) { foreach (BuildItem buildItem in group) { if (buildItem.Include == includeSpec) { return buildItem; } } } return null; } #pragma warning restore 0618 /// <summary> /// Gets the project reference of a project. /// </summary> /// <value>The projref of project.</value> public string ProjectReferenceOfProject { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { string result = string.Empty; int hr = Solution.GetProjrefOfProject(Hierarchy, out result); Marshal.ThrowExceptionForHR(hr); return result; } } /// <summary> /// Gets the VS project. /// </summary> /// <value>The VS project.</value> private EnvDTE.Project VSProject { get { return ExtObject as EnvDTE.Project; } } /// <summary> /// Returns the language of the underlying project, if available. /// </summary> public string Language { [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] get { if (VSProject == null) { return null; } else { if (VSProject.Object is VSLangProj.VSProject) { return ProjectNode.GetLanguageFromProject(((VSLangProj.VSProject)VSProject.Object).Project); } else if (VSProject.Object is VsWebSite.VSWebSite) { return ProjectNode.GetLanguageFromProject(((VsWebSite.VSWebSite)VSProject.Object).Project); } } return null; } } /// <summary> /// Adds the assembly reference. /// </summary> /// <param name="assemblyPath">The assembly path.</param> public void AddAssemblyReference(string assemblyPath) { Guard.NotNullOrEmpty(() => assemblyPath, assemblyPath); if (VSProject != null) { if (VSProject.Object is VSLangProj.VSProject) { VSLangProj.References references = ((VSLangProj.VSProject)VSProject.Object).References; if (references != null) { references.Add(assemblyPath); } } else if (VSProject.Object is VsWebSite.VSWebSite) { VsWebSite.AssemblyReferences references = ((VsWebSite.VSWebSite)VSProject.Object).References; if (references != null) { if (System.IO.Path.IsPathRooted(assemblyPath)) { references.AddFromFile(assemblyPath); } else { references.AddFromGAC(assemblyPath); } } } } } /// <summary> /// Adds the project reference. /// </summary> /// <param name="projectId">The project id.</param> public void AddProjectReference(Guid projectId) { if (ProjectGuid == projectId) { return; } ProjectNode referencedProject = new ProjectNode(Solution, projectId); if (VSProject != null) { if (VSProject.Object is VSLangProj.VSProject) { VSLangProj.References references = ((VSLangProj.VSProject)VSProject.Object).References; if (references != null && referencedProject.ExtObject is EnvDTE.Project) { references.AddProject(referencedProject.ExtObject as EnvDTE.Project); } } else if (VSProject.Object is VsWebSite.VSWebSite) { VsWebSite.AssemblyReferences references = ((VsWebSite.VSWebSite)VSProject.Object).References; if (references != null && referencedProject.ExtObject is EnvDTE.Project) { try { references.AddFromProject(referencedProject.ExtObject as EnvDTE.Project); } catch (COMException) { //Web projects throws exceptions if the reference already exists } } } } } /// <summary> /// Gets the evaluated property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> public string GetEvaluatedProperty(string propertyName) { return ProjectNode.GetEvaluatedProperty(this.VSProject, propertyName, false); } /// <summary> /// Gets the evaluated property. /// </summary> public string GetEvaluatedProperty(string propertyName, bool throwIfNotFound) { return ProjectNode.GetEvaluatedProperty(this.VSProject, propertyName, throwIfNotFound); } /// <summary> /// Gets the evaluated property. /// </summary> /// <param name="project">The project.</param> /// <param name="propertyName">Name of the property.</param> /// <returns></returns> public static string GetEvaluatedProperty(EnvDTE.Project project, string propertyName) { return ProjectNode.GetEvaluatedProperty(project, propertyName, false); } /// <summary> /// Gets the evaluated property. /// </summary> /// <param name="project">The project.</param> /// <param name="propertyName">Name of the property.</param> /// <param name="throwIfNotFound">When 'true', it throws an error if the property wasn't found.</param> /// <returns></returns> public static string GetEvaluatedProperty(EnvDTE.Project project, string propertyName, bool throwIfNotFound) { if (project == null) { return string.Empty; } Guard.NotNullOrEmpty(() => propertyName, propertyName); string value = string.Empty; foreach (EnvDTE.Property prop in project.Properties) { if (prop.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase)) { value = prop.Value.ToString(); break; } } if (throwIfNotFound) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.ProjectNode_PropertyNameNotFound, propertyName, project.Name)); } else { return (value ?? string.Empty); } } /// <summary> /// Gets the language from project. /// </summary> /// <param name="project">The project.</param> /// <returns></returns>\ [SecurityCritical] public static string GetLanguageFromProject(EnvDTE.Project project) { Guard.NotNull(() => project, project); if (project.CodeModel != null) { return project.CodeModel.Language; } CodeDomProvider provider = DteHelper.GetCodeDomProvider(project); if (provider is Microsoft.CSharp.CSharpCodeProvider) { return EnvDTE.CodeModelLanguageConstants.vsCMLanguageCSharp; } else if (provider is Microsoft.VisualBasic.VBCodeProvider) { return EnvDTE.CodeModelLanguageConstants.vsCMLanguageVB; } return null; } } internal static class DteHelper { [SecurityCritical] public static CodeDomProvider GetCodeDomProvider(EnvDTE.Project project) { if (project != null) { return CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(GetDefaultExtension(project))); } return CodeDomProvider.CreateProvider("C#"); } private static string GetDefaultExtension(EnvDTE.Project project) { if (!IsWebProject(project)) { return GetDefaultExtensionFromNonWebProject(project); } if (!IsWebCSharpProject(project)) { return @".vb"; } return @".cs"; } // FxCop: The reason for project properties retrieval failures may be varied. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // FxCop: Need to try target as different types. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] private static bool IsWebCSharpProject(object target) { EnvDTE.Project containingProject = null; if (target is EnvDTE.Project) { containingProject = (EnvDTE.Project)target; } else if (target is EnvDTE.ProjectItem) { containingProject = ((EnvDTE.ProjectItem)target).ContainingProject; } if (((containingProject != null) && IsWebProject(containingProject)) && (containingProject.Properties != null)) { try { EnvDTE.Property property = containingProject.Properties.Item(Reflector<WebSiteProperties>.GetPropertyName(x => x.CurrentWebsiteLanguage)); return ((property.Value != null) && property.Value.ToString().Equals(@"Visual C#", StringComparison.OrdinalIgnoreCase)); } catch (Exception exception) { Trace.TraceError(exception.ToString()); return false; } } return false; } private static string GetDefaultExtensionFromNonWebProject(EnvDTE.Project project) { Guard.NotNull(() => project, project); if (project.Kind.Equals(@"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", StringComparison.OrdinalIgnoreCase)) { return @".cs"; } if (project.Kind.Equals(@"{F184B08F-C81C-45F6-A57F-5ABD9991F28F}", StringComparison.OrdinalIgnoreCase)) { throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Resources.ProjectNode_UnsupportedProjectKind, new object[] { project.Name })); } return @".vb"; } private static bool IsWebProject(EnvDTE.Project project) { return (project.Kind.Equals(@"{E24C65DC-7377-472b-9ABA-BC803B73C61A}", StringComparison.OrdinalIgnoreCase)); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using AsmResolver.Collections; using AsmResolver.DotNet.Collections; using AsmResolver.DotNet.Signatures.Types; using AsmResolver.PE; using AsmResolver.PE.Debug; using AsmResolver.PE.DotNet; using AsmResolver.PE.DotNet.Metadata.Guid; using AsmResolver.PE.DotNet.Metadata.Strings; using AsmResolver.PE.DotNet.Metadata.Tables; using AsmResolver.PE.DotNet.Metadata.Tables.Rows; using AsmResolver.PE.DotNet.Metadata.UserStrings; using AsmResolver.PE.Win32Resources; namespace AsmResolver.DotNet.Serialized { /// <summary> /// Represents a lazily initialized implementation of <see cref="ModuleDefinition"/> that is read from a /// .NET metadata image. /// </summary> public partial class SerializedModuleDefinition : ModuleDefinition { private readonly ModuleDefinitionRow _row; /// <summary> /// Interprets a PE image as a .NET module. /// </summary> /// <param name="peImage">The image to interpret as a .NET module.</param> /// <param name="readerParameters">The parameters to use while reading the module.</param> public SerializedModuleDefinition(IPEImage peImage, ModuleReaderParameters readerParameters) : base(new MetadataToken(TableIndex.Module, 1)) { if (peImage is null) throw new ArgumentNullException(nameof(peImage)); if (readerParameters is null) throw new ArgumentNullException(nameof(readerParameters)); var metadata = peImage.DotNetDirectory?.Metadata; if (metadata is null) throw new BadImageFormatException("Input PE image does not contain a .NET metadata directory."); var tablesStream = metadata.GetStream<TablesStream>(); if (tablesStream is null) throw new BadImageFormatException(".NET metadata directory does not define a tables stream."); var moduleTable = tablesStream.GetTable<ModuleDefinitionRow>(TableIndex.Module); if (!moduleTable.TryGetByRid(1, out _row)) throw new BadImageFormatException("Module definition table does not contain any rows."); // Store parameters in fields. ReaderContext = new ModuleReaderContext(peImage, this, readerParameters); // Copy over PE header fields. FilePath = peImage.FilePath; MachineType = peImage.MachineType; FileCharacteristics = peImage.Characteristics; PEKind = peImage.PEKind; SubSystem = peImage.SubSystem; DllCharacteristics = peImage.DllCharacteristics; TimeDateStamp = peImage.TimeDateStamp; // Copy over "simple" columns. Generation = _row.Generation; Attributes = peImage.DotNetDirectory!.Flags; // Initialize member factory. _memberFactory = new CachedSerializedMemberFactory(ReaderContext); // Find assembly definition and corlib assembly. Assembly = FindParentAssembly(); CorLibTypeFactory = CreateCorLibTypeFactory(); OriginalTargetRuntime = DetectTargetRuntime(); MetadataResolver = new DefaultMetadataResolver(CreateAssemblyResolver( readerParameters.PEReaderParameters.FileService)); // Prepare lazy RID lists. _fieldLists = new LazyRidListRelation<TypeDefinitionRow>(metadata, TableIndex.TypeDef, (rid, _) => rid, tablesStream.GetFieldRange); _methodLists = new LazyRidListRelation<TypeDefinitionRow>(metadata, TableIndex.TypeDef, (rid, _) => rid, tablesStream.GetMethodRange); _paramLists = new LazyRidListRelation<MethodDefinitionRow>(metadata, TableIndex.Method, (rid, _) => rid, tablesStream.GetParameterRange); _propertyLists = new LazyRidListRelation<PropertyMapRow>(metadata, TableIndex.PropertyMap, (_, map) => map.Parent, tablesStream.GetPropertyRange); _eventLists = new LazyRidListRelation<EventMapRow>(metadata, TableIndex.EventMap, (_, map) => map.Parent, tablesStream.GetEventRange); } /// <inheritdoc /> public override IDotNetDirectory DotNetDirectory => ReaderContext.Image.DotNetDirectory!; /// <summary> /// Gets the reading context that is used for reading the contents of the module. /// </summary> public ModuleReaderContext ReaderContext { get; } /// <inheritdoc /> public override IMetadataMember LookupMember(MetadataToken token) => !TryLookupMember(token, out var member) ? throw new ArgumentException($"Cannot resolve metadata token {token}.") : member; /// <inheritdoc /> public override bool TryLookupMember(MetadataToken token, [NotNullWhen(true)] out IMetadataMember? member) => _memberFactory.TryLookupMember(token, out member); /// <inheritdoc /> public override string LookupString(MetadataToken token) => !TryLookupString(token, out var member) ? throw new ArgumentException($"Cannot resolve string token {token}.") : member; /// <inheritdoc /> public override bool TryLookupString(MetadataToken token, [NotNullWhen(true)] out string? value) { if (!ReaderContext.Metadata.TryGetStream<UserStringsStream>(out var userStringsStream)) { value = null; return false; } value = userStringsStream.GetStringByIndex(token.Rid); return value is not null; } /// <inheritdoc /> public override IndexEncoder GetIndexEncoder(CodedIndex codedIndex) => ReaderContext.Metadata.GetStream<TablesStream>().GetIndexEncoder(codedIndex); /// <inheritdoc /> public override IEnumerable<TypeReference> GetImportedTypeReferences() { var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.TypeRef); for (uint rid = 1; rid <= table.Count; rid++) { if (TryLookupMember(new MetadataToken(TableIndex.TypeRef, rid), out var member) && member is TypeReference reference) { yield return reference; } } } /// <inheritdoc /> public override IEnumerable<MemberReference> GetImportedMemberReferences() { var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.MemberRef); for (uint rid = 1; rid <= table.Count; rid++) { if (TryLookupMember(new MetadataToken(TableIndex.MemberRef, rid), out var member) && member is MemberReference reference) { yield return reference; } } } /// <inheritdoc /> protected override Utf8String? GetName() { return ReaderContext.Metadata.TryGetStream<StringsStream>(out var stringsStream) ? stringsStream.GetStringByIndex(_row.Name) : null; } /// <inheritdoc /> protected override Guid GetMvid() { return ReaderContext.Metadata.TryGetStream<GuidStream>(out var guidStream) ? guidStream.GetGuidByIndex(_row.Mvid) : Guid.Empty; } /// <inheritdoc /> protected override Guid GetEncId() { return ReaderContext.Metadata.TryGetStream<GuidStream>(out var guidStream) ? guidStream.GetGuidByIndex(_row.EncId) : Guid.Empty; } /// <inheritdoc /> protected override Guid GetEncBaseId() { return ReaderContext.Metadata.TryGetStream<GuidStream>(out var guidStream) ? guidStream.GetGuidByIndex(_row.EncBaseId) : Guid.Empty; } /// <inheritdoc /> protected override IList<TypeDefinition> GetTopLevelTypes() { EnsureTypeDefinitionTreeInitialized(); var types = new OwnedCollection<ModuleDefinition, TypeDefinition>(this); var typeDefTable = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable<TypeDefinitionRow>(TableIndex.TypeDef); for (int i = 0; i < typeDefTable.Count; i++) { uint rid = (uint) i + 1; if (_typeDefTree.GetKey(rid) == 0) { var token = new MetadataToken(TableIndex.TypeDef, rid); types.Add(_memberFactory.LookupTypeDefinition(token)!); } } return types; } /// <inheritdoc /> protected override IList<AssemblyReference> GetAssemblyReferences() { var result = new OwnedCollection<ModuleDefinition, AssemblyReference>(this); var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable<AssemblyReferenceRow>(TableIndex.AssemblyRef); // Don't use the member factory here, this method may be called before the member factory is initialized. for (int i = 0; i < table.Count; i++) { var token = new MetadataToken(TableIndex.AssemblyRef, (uint) i + 1); result.Add(new SerializedAssemblyReference(ReaderContext, token, table[i])); } return result; } /// <inheritdoc /> protected override IList<ModuleReference> GetModuleReferences() { var result = new OwnedCollection<ModuleDefinition, ModuleReference>(this); var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.ModuleRef); for (int i = 0; i < table.Count; i++) { var token = new MetadataToken(TableIndex.ModuleRef, (uint) i + 1); if (_memberFactory.TryLookupMember(token, out var member) && member is ModuleReference module) result.Add(module); } return result; } /// <inheritdoc /> protected override IList<FileReference> GetFileReferences() { var result = new OwnedCollection<ModuleDefinition, FileReference>(this); var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.File); for (int i = 0; i < table.Count; i++) { var token = new MetadataToken(TableIndex.File, (uint) i + 1); if (_memberFactory.TryLookupMember(token, out var member) && member is FileReference file) result.Add(file); } return result; } /// <inheritdoc /> protected override IList<ManifestResource> GetResources() { var result = new OwnedCollection<ModuleDefinition, ManifestResource>(this); var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.ManifestResource); for (int i = 0; i < table.Count; i++) { var token = new MetadataToken(TableIndex.ManifestResource, (uint) i + 1); if (_memberFactory.TryLookupMember(token, out var member) && member is ManifestResource resource) result.Add(resource); } return result; } /// <inheritdoc /> protected override IList<ExportedType> GetExportedTypes() { var result = new OwnedCollection<ModuleDefinition, ExportedType>(this); var table = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable(TableIndex.ExportedType); for (int i = 0; i < table.Count; i++) { var token = new MetadataToken(TableIndex.ExportedType, (uint) i + 1); if (_memberFactory.TryLookupMember(token, out var member) && member is ExportedType exportedType) result.Add(exportedType); } return result; } /// <inheritdoc /> protected override string GetRuntimeVersion() => ReaderContext.Metadata!.VersionString; /// <inheritdoc /> protected override IManagedEntrypoint? GetManagedEntrypoint() { if ((DotNetDirectory.Flags & DotNetDirectoryFlags.NativeEntrypoint) != 0) { // TODO: native entrypoints. return null; } if (DotNetDirectory.Entrypoint != 0) return LookupMember(DotNetDirectory.Entrypoint) as IManagedEntrypoint; return null; } /// <inheritdoc /> protected override IResourceDirectory? GetNativeResources() => ReaderContext.Image.Resources; /// <inheritdoc /> protected override IList<DebugDataEntry> GetDebugData() => new List<DebugDataEntry>(ReaderContext.Image.DebugData); private AssemblyDefinition? FindParentAssembly() { var assemblyTable = ReaderContext.Metadata .GetStream<TablesStream>() .GetTable<AssemblyDefinitionRow>(); if (assemblyTable.Count > 0) { var assembly = new SerializedAssemblyDefinition( ReaderContext, new MetadataToken(TableIndex.Assembly, 1), assemblyTable[0], this); return assembly; } return null; } private CorLibTypeFactory CreateCorLibTypeFactory() { return FindMostRecentCorLib() is { } corLib ? new CorLibTypeFactory(corLib) : CorLibTypeFactory.CreateMscorlib40TypeFactory(this); } private IResolutionScope? FindMostRecentCorLib() { // TODO: perhaps check public key tokens. IResolutionScope? mostRecentCorLib = null; var mostRecentVersion = new Version(); foreach (var reference in AssemblyReferences) { if (reference.Name is not null && KnownCorLibs.KnownCorLibNames.Contains(reference.Name)) { if (mostRecentVersion < reference.Version) mostRecentCorLib = reference; } } if (mostRecentCorLib is null && Assembly is {Name: { } name }) { if (KnownCorLibs.KnownCorLibNames.Contains(name)) mostRecentCorLib = this; } return mostRecentCorLib; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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; using System.Linq; using QuantConnect.Util; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using QuantConnect.Securities.Positions; namespace QuantConnect.Securities.Option.StrategyMatcher { /// <summary> /// Provides indexing of option contracts /// </summary> public class OptionPositionCollection : IEnumerable<OptionPosition> { /// <summary> /// Gets an empty instance of <see cref="OptionPositionCollection"/> /// </summary> public static OptionPositionCollection Empty { get; } = new OptionPositionCollection( ImmutableDictionary<Symbol, OptionPosition>.Empty, ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>>.Empty, ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>>.Empty, ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>>.Empty, ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>>.Empty ); private readonly ImmutableDictionary<Symbol, OptionPosition> _positions; private readonly ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>> _rights; private readonly ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>> _sides; private readonly ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>> _strikes; private readonly ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>> _expirations; /// <summary> /// Gets the underlying security's symbol /// </summary> public Symbol Underlying => UnderlyingPosition.Symbol ?? Symbol.Empty; /// <summary> /// Gets the total count of unique positions, including the underlying /// </summary> public int Count => _positions.Count; /// <summary> /// Gets whether or not there's any positions in this collection. /// </summary> public bool IsEmpty => _positions.IsEmpty; /// <summary> /// Gets the quantity of underlying shares held /// TODO : Change to UnderlyingLots /// </summary> public int UnderlyingQuantity => UnderlyingPosition.Quantity; /// <summary> /// Gets the number of unique put contracts held (long or short) /// </summary> public int UniquePuts => _rights[OptionRight.Put].Count; /// <summary> /// Gets the unique number of expirations /// </summary> public int UniqueExpirations => _expirations.Count; /// <summary> /// Gets the number of unique call contracts held (long or short) /// </summary> public int UniqueCalls => _rights[OptionRight.Call].Count; /// <summary> /// Determines if this collection contains a position in the underlying /// </summary> public bool HasUnderlying => UnderlyingQuantity != 0; /// <summary> /// Gets the <see cref="Underlying"/> position /// </summary> public OptionPosition UnderlyingPosition { get; } /// <summary> /// Gets all unique strike prices in the collection, in ascending order. /// </summary> public IEnumerable<decimal> Strikes => _strikes.Keys; /// <summary> /// Gets all unique expiration dates in the collection, in chronological order. /// </summary> public IEnumerable<DateTime> Expirations => _expirations.Keys; /// <summary> /// Initializes a new instance of the <see cref="OptionPositionCollection"/> class /// </summary> /// <param name="positions">All positions</param> /// <param name="rights">Index of position symbols by option right</param> /// <param name="sides">Index of position symbols by position side (short/long/none)</param> /// <param name="strikes">Index of position symbols by strike price</param> /// <param name="expirations">Index of position symbols by expiration</param> public OptionPositionCollection( ImmutableDictionary<Symbol, OptionPosition> positions, ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>> rights, ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>> sides, ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>> strikes, ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>> expirations ) { _sides = sides; _rights = rights; _strikes = strikes; _positions = positions; _expirations = expirations; if (_rights.Count != 2) { // ensure we always have both rights indexed, even if empty ImmutableHashSet<Symbol> value; if (!_rights.TryGetValue(OptionRight.Call, out value)) { _rights = _rights.SetItem(OptionRight.Call, ImmutableHashSet<Symbol>.Empty); } if (!_rights.TryGetValue(OptionRight.Put, out value)) { _rights = _rights.SetItem(OptionRight.Put, ImmutableHashSet<Symbol>.Empty); } } if (_sides.Count != 3) { // ensure we always have all three sides indexed, even if empty ImmutableHashSet<Symbol> value; if (!_sides.TryGetValue(PositionSide.None, out value)) { _sides = _sides.SetItem(PositionSide.None, ImmutableHashSet<Symbol>.Empty); } if (!_sides.TryGetValue(PositionSide.Short, out value)) { _sides = _sides.SetItem(PositionSide.Short, ImmutableHashSet<Symbol>.Empty); } if (!_sides.TryGetValue(PositionSide.Long, out value)) { _sides = _sides.SetItem(PositionSide.Long, ImmutableHashSet<Symbol>.Empty); } } if (!positions.IsEmpty) { // assumption here is that 'positions' includes the underlying equity position and // ONLY option contracts, so all symbols have the underlying equity symbol embedded // via the Underlying property, except of course, for the underlying itself. var underlying = positions.First().Key; if (underlying.HasUnderlying) { underlying = underlying.Underlying; } // OptionPosition is struct, so no worry about null ref via .Quantity var underlyingQuantity = positions.GetValueOrDefault(underlying).Quantity; UnderlyingPosition = new OptionPosition(underlying, underlyingQuantity); } #if DEBUG var errors = Validate().ToList(); if (errors.Count > 0) { throw new ArgumentException("OptionPositionCollection validation failed: " + Environment.NewLine + string.Join(Environment.NewLine, errors) ); } #endif } /// <summary> /// Determines if a position is held in the specified <paramref name="symbol"/> /// </summary> public bool HasPosition(Symbol symbol) { OptionPosition position; return TryGetPosition(symbol, out position) && position.Quantity != 0; } /// <summary> /// Retrieves the <see cref="OptionPosition"/> for the specified <paramref name="symbol"/> /// if one exists in this collection. /// </summary> public bool TryGetPosition(Symbol symbol, out OptionPosition position) { return _positions.TryGetValue(symbol, out position); } /// <summary> /// Creates a new <see cref="OptionPositionCollection"/> from the specified enumerable of <paramref name="positions"/> /// </summary> public static OptionPositionCollection FromPositions(IEnumerable<OptionPosition> positions) { return Empty.AddRange(positions); } /// <summary> /// Creates a new <see cref="OptionPositionCollection"/> from the specified enumerable of <paramref name="positions"/> /// </summary> public static OptionPositionCollection FromPositions(IEnumerable<IPosition> positions, decimal contractMultiplier) { return Empty.AddRange(positions.Select(position => { var quantity = (int)position.Quantity; if (position.Symbol.SecurityType.HasOptions()) { quantity = (int) (quantity / contractMultiplier); } return new OptionPosition(position.Symbol, quantity); })); } /// <summary> /// Creates a new <see cref="OptionPositionCollection"/> from the specified <paramref name="holdings"/>, /// filtering based on the <paramref name="underlying"/> /// </summary> public static OptionPositionCollection Create(Symbol underlying, decimal contractMultiplier, IEnumerable<SecurityHolding> holdings) { var positions = Empty; foreach (var holding in holdings) { var symbol = holding.Symbol; if (!symbol.HasUnderlying) { if (symbol == underlying) { var underlyingLots = (int) (holding.Quantity / contractMultiplier); positions = positions.Add(new OptionPosition(symbol, underlyingLots)); } continue; } if (symbol.Underlying != underlying) { continue; } var position = new OptionPosition(symbol, (int) holding.Quantity); positions = positions.Add(position); } return positions; } /// <summary> /// Creates a new collection that is the result of adding the specified <paramref name="position"/> to this collection. /// </summary> public OptionPositionCollection Add(OptionPosition position) { if (!position.HasQuantity) { // adding nothing doesn't change the collection return this; } var sides = _sides; var rights = _rights; var strikes = _strikes; var positions = _positions; var expirations = _expirations; var exists = false; OptionPosition existing; var symbol = position.Symbol; if (positions.TryGetValue(symbol, out existing)) { exists = true; position += existing; } if (position.HasQuantity) { positions = positions.SetItem(symbol, position); if (!exists && symbol.HasUnderlying) { // update indexes when adding a new option contract sides = sides.Add(position.Side, symbol); rights = rights.Add(position.Right, symbol); strikes = strikes.Add(position.Strike, symbol); positions = positions.SetItem(symbol, position); expirations = expirations.Add(position.Expiration, symbol); } } else { // if the position's quantity went to zero, remove it entirely from the collection when // removing, be sure to remove strike/expiration indexes. we purposefully keep the rights // index populated, even with a zero count entry because it's bounded to 2 items (put/call) positions = positions.Remove(symbol); if (symbol.HasUnderlying) { // keep call/put entries even if goes to zero var rightsValue = rights[position.Right].Remove(symbol); rights = rights.SetItem(position.Right, rightsValue); // keep short/none/long entries even if goes to zero var sidesValue = sides[position.Side].Remove(symbol); sides = sides.SetItem(position.Side, sidesValue); var strikesValue = strikes[position.Strike].Remove(symbol); strikes = strikesValue.Count > 0 ? strikes.SetItem(position.Strike, strikesValue) : strikes.Remove(position.Strike); var expirationsValue = expirations[position.Expiration].Remove(symbol); expirations = expirationsValue.Count > 0 ? expirations.SetItem(position.Expiration, expirationsValue) : expirations.Remove(position.Expiration); } } return new OptionPositionCollection(positions, rights, sides, strikes, expirations); } /// <summary> /// Creates a new collection that is the result of removing the specified <paramref name="position"/> /// </summary> public OptionPositionCollection Remove(OptionPosition position) { return Add(position.Negate()); } /// <summary> /// Creates a new collection that is the result of adding the specified <paramref name="positions"/> to this collection. /// </summary> public OptionPositionCollection AddRange(params OptionPosition[] positions) { return AddRange((IEnumerable<OptionPosition>) positions); } /// <summary> /// Creates a new collection that is the result of adding the specified <paramref name="positions"/> to this collection. /// </summary> public OptionPositionCollection AddRange(IEnumerable<OptionPosition> positions) { return positions.Aggregate(this, (current, position) => current + position); } /// <summary> /// Creates a new collection that is the result of removing the specified <paramref name="positions"/> /// </summary> public OptionPositionCollection RemoveRange(IEnumerable<OptionPosition> positions) { return AddRange(positions.Select(position => position.Negate())); } /// <summary> /// Slices this collection, returning a new collection containing only /// positions with the specified <paramref name="right"/> /// </summary> public OptionPositionCollection Slice(OptionRight right, bool includeUnderlying = true) { var rights = _rights.Remove(right.Invert()); var positions = ImmutableDictionary<Symbol, OptionPosition>.Empty; if (includeUnderlying && HasUnderlying) { positions = positions.Add(Underlying, UnderlyingPosition); } var sides = ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>>.Empty; var strikes = ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>>.Empty; var expirations = ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>>.Empty; foreach (var symbol in rights.SelectMany(kvp => kvp.Value)) { var position = _positions[symbol]; sides = sides.Add(position.Side, symbol); positions = positions.Add(symbol, position); strikes = strikes.Add(position.Strike, symbol); expirations = expirations.Add(position.Expiration, symbol); } return new OptionPositionCollection(positions, rights, sides, strikes, expirations); } /// <summary> /// Slices this collection, returning a new collection containing only /// positions with the specified <paramref name="side"/> /// </summary> public OptionPositionCollection Slice(PositionSide side, bool includeUnderlying = true) { var otherSides = GetOtherSides(side); var sides = _sides.Remove(otherSides[0]).Remove(otherSides[1]); var positions = ImmutableDictionary<Symbol, OptionPosition>.Empty; if (includeUnderlying && HasUnderlying) { positions = positions.Add(Underlying, UnderlyingPosition); } var rights = ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>>.Empty; var strikes = ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>>.Empty; var expirations = ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>>.Empty; foreach (var symbol in sides.SelectMany(kvp => kvp.Value)) { var position = _positions[symbol]; rights = rights.Add(position.Right, symbol); positions = positions.Add(symbol, position); strikes = strikes.Add(position.Strike, symbol); expirations = expirations.Add(position.Expiration, symbol); } return new OptionPositionCollection(positions, rights, sides, strikes, expirations); } /// <summary> /// Slices this collection, returning a new collection containing only /// positions matching the specified <paramref name="comparison"/> and <paramref name="strike"/> /// </summary> public OptionPositionCollection Slice(BinaryComparison comparison, decimal strike, bool includeUnderlying = true) { var strikes = comparison.Filter(_strikes, strike); if (strikes.IsEmpty) { return includeUnderlying && HasUnderlying ? Empty.Add(UnderlyingPosition) : Empty; } var positions = ImmutableDictionary<Symbol, OptionPosition>.Empty; if (includeUnderlying) { OptionPosition underlyingPosition; if (_positions.TryGetValue(Underlying, out underlyingPosition)) { positions = positions.Add(Underlying, underlyingPosition); } } var sides = ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>>.Empty; var rights = ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>>.Empty; var expirations = ImmutableSortedDictionary<DateTime, ImmutableHashSet<Symbol>>.Empty; foreach (var symbol in strikes.SelectMany(kvp => kvp.Value)) { var position = _positions[symbol]; sides = sides.Add(position.Side, symbol); positions = positions.Add(symbol, position); rights = rights.Add(symbol.ID.OptionRight, symbol); expirations = expirations.Add(symbol.ID.Date, symbol); } return new OptionPositionCollection(positions, rights, sides, strikes, expirations); } /// <summary> /// Slices this collection, returning a new collection containing only /// positions matching the specified <paramref name="comparison"/> and <paramref name="expiration"/> /// </summary> public OptionPositionCollection Slice(BinaryComparison comparison, DateTime expiration, bool includeUnderlying = true) { var expirations = comparison.Filter(_expirations, expiration); if (expirations.IsEmpty) { return includeUnderlying && HasUnderlying ? Empty.Add(UnderlyingPosition) : Empty; } var positions = ImmutableDictionary<Symbol, OptionPosition>.Empty; if (includeUnderlying) { OptionPosition underlyingPosition; if (_positions.TryGetValue(Underlying, out underlyingPosition)) { positions = positions.Add(Underlying, underlyingPosition); } } var sides = ImmutableDictionary<PositionSide, ImmutableHashSet<Symbol>>.Empty; var rights = ImmutableDictionary<OptionRight, ImmutableHashSet<Symbol>>.Empty; var strikes = ImmutableSortedDictionary<decimal, ImmutableHashSet<Symbol>>.Empty; foreach (var symbol in expirations.SelectMany(kvp => kvp.Value)) { var position = _positions[symbol]; sides = sides.Add(position.Side, symbol); positions = positions.Add(symbol, position); rights = rights.Add(symbol.ID.OptionRight, symbol); strikes = strikes.Add(symbol.ID.StrikePrice, symbol); } return new OptionPositionCollection(positions, rights, sides, strikes, expirations); } /// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="symbols"/> /// </summary> public IEnumerable<OptionPosition> ForSymbols(IEnumerable<Symbol> symbols) { foreach (var symbol in symbols) { OptionPosition position; if (_positions.TryGetValue(symbol, out position)) { yield return position; } } } /// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="right"/> /// </summary> public IEnumerable<OptionPosition> ForRight(OptionRight right) { ImmutableHashSet<Symbol> symbols; return _rights.TryGetValue(right, out symbols) ? ForSymbols(symbols) : Enumerable.Empty<OptionPosition>(); } /// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="side"/> /// </summary> public IEnumerable<OptionPosition> ForSide(PositionSide side) { ImmutableHashSet<Symbol> symbols; return _sides.TryGetValue(side, out symbols) ? ForSymbols(symbols) : Enumerable.Empty<OptionPosition>(); } /// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="strike"/> /// </summary> public IEnumerable<OptionPosition> ForStrike(decimal strike) { ImmutableHashSet<Symbol> symbols; return _strikes.TryGetValue(strike, out symbols) ? ForSymbols(symbols) : Enumerable.Empty<OptionPosition>(); } /// <summary> /// Returns the set of <see cref="OptionPosition"/> with the specified <paramref name="expiration"/> /// </summary> public IEnumerable<OptionPosition> ForExpiration(DateTime expiration) { ImmutableHashSet<Symbol> symbols; return _expirations.TryGetValue(expiration, out symbols) ? ForSymbols(symbols) : Enumerable.Empty<OptionPosition>(); } /// <summary>Returns a string that represents the current object.</summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { if (Count == 0) { return "Empty"; } return HasUnderlying ? $"{UnderlyingQuantity} {Underlying.Value}: {_positions.Count - 1} contract positions" : $"{Underlying.Value}: {_positions.Count} contract positions"; } /// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator<OptionPosition> GetEnumerator() { return _positions.Select(kvp => kvp.Value).GetEnumerator(); } /// <summary> /// Validates this collection returning an enumerable of validation errors. /// This should only be invoked via tests and is automatically invoked via /// the constructor in DEBUG builds. /// </summary> internal IEnumerable<string> Validate() { foreach (var kvp in _positions) { var position = kvp.Value; var symbol = position.Symbol; if (position.Quantity == 0) { yield return $"{position}: Quantity == 0"; } if (!symbol.HasUnderlying) { continue; } ImmutableHashSet<Symbol> strikes; if (!_strikes.TryGetValue(position.Strike, out strikes) || !strikes.Contains(symbol)) { yield return $"{position}: Not indexed by strike price"; } ImmutableHashSet<Symbol> expirations; if (!_expirations.TryGetValue(position.Expiration, out expirations) || !expirations.Contains(symbol)) { yield return $"{position}: Not indexed by expiration date"; } } } private static readonly PositionSide[] OtherSidesForNone = {PositionSide.Short, PositionSide.Long}; private static readonly PositionSide[] OtherSidesForShort = {PositionSide.None, PositionSide.Long}; private static readonly PositionSide[] OtherSidesForLong = {PositionSide.Short, PositionSide.None}; private static PositionSide[] GetOtherSides(PositionSide side) { switch (side) { case PositionSide.Short: return OtherSidesForShort; case PositionSide.None: return OtherSidesForNone; case PositionSide.Long: return OtherSidesForLong; default: throw new ArgumentOutOfRangeException(nameof(side), side, null); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// OptionPositionCollection + Operator /// </summary> /// <param name="positions">Collection to add to</param> /// <param name="position">OptionPosition to add</param> /// <returns>OptionPositionCollection with the new position added</returns> public static OptionPositionCollection operator+(OptionPositionCollection positions, OptionPosition position) { return positions.Add(position); } /// <summary> /// OptionPositionCollection - Operator /// </summary> /// <param name="positions">Collection to remove from</param> /// <param name="position">OptionPosition to remove</param> /// <returns>OptionPositionCollection with the position removed</returns> public static OptionPositionCollection operator-(OptionPositionCollection positions, OptionPosition position) { return positions.Remove(position); } } }
// String.cs // Script#/Libraries/CoreLib // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; namespace System { /// <summary> /// Equivalent to the String type in Javascript. /// </summary> [IgnoreNamespace] [Imported(ObeysTypeSystem = true)] public sealed class String : IComparable<String>, IEquatable<String> { public String() {} public String(String other) {} [InlineCode("{$System.Script}.stringFromChar({$System.String}.fromCharCode({ch}), {count})")] public String(char ch, int count) {} [InlineCode("{$System.String}.fromCharCode.apply(null, {value})")] public String(char[] value) {} [InlineCode("{$System.String}.fromCharCode.apply(null, {value}.slice({startIndex}, {startIndex} + {length}))")] public String(char[] value, int startIndex, int length) {} [IndexerName("Chars")] public char this[int index] { [InlineCode("{this}.charCodeAt({index})")] get { return '\0'; } } [NonScriptable] public IEnumerator<char> GetEnumerator() { return null; } /// <summary> /// An empty zero-length string. /// </summary> [InlineConstant] public const String Empty = ""; /// <summary> /// The number of characters in the string. /// </summary> [IntrinsicProperty] public int Length { get { return 0; } } /// <summary> /// Retrieves the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character within the string.</returns> public string CharAt(int index) { return null; } /// <summary> /// Retrieves the character code of the character at the specified position. /// </summary> /// <param name="index">The specified 0-based position.</param> /// <returns>The character code of the character within the string.</returns> public char CharCodeAt(int index) { return '\0'; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2})")] public static int Compare(string s1, string s2) { return 0; } [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase})")] public static int Compare(string s1, string s2, bool ignoreCase) { return 0; } [InlineCode("{$System.Script}.compareStrings({this}, {s}, {ignoreCase})")] public int CompareTo(string s, bool ignoreCase) { return 0; } [InlineCode("[{s1}, {s2}].join('')")] public static string Concat(string s1, string s2) { return null; } [InlineCode("[{s1}, {s2}, {s3}].join('')")] public static string Concat(string s1, string s2, string s3) { return null; } [InlineCode("[{s1}, {s2}, {s3}, {s4}].join('')")] public static string Concat(string s1, string s2, string s3, string s4) { return null; } /// <summary> /// Concatenates a set of individual strings into a single string. /// </summary> /// <param name="strings">The sequence of strings</param> /// <returns>The concatenated string.</returns> [InlineCode("{strings}.join('')")] public static string Concat(params string[] strings) { return null; } [InlineCode("[{o1}, {o2}].join('')")] public static string Concat(object o1, object o2) { return null; } [InlineCode("[{o1}, {o2}, {o3}].join('')")] public static string Concat(object o1, object o2, object o3) { return null; } [InlineCode("[{o1}, {o2}, {o3}, {o4}].join('')")] public static string Concat(object o1, object o2, object o3, object o4) { return null; } [InlineCode("{o}.join('')")] public static string Concat(params object[] o) { return null; } [InlineCode("[{o}].join('')")] public static string Concat(object o) { return null; } /// <summary> /// Returns the unencoded version of a complete encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURI")] public static string DecodeUri(string s) { return null; } /// <summary> /// Returns the unencoded version of a single part or component of an encoded URI. /// </summary> /// <returns>The unencoded string.</returns> [ScriptAlias("decodeURIComponent")] public static string DecodeUriComponent(string s) { return null; } /// <summary> /// Encodes the complete URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURI")] public static string EncodeUri(string s) { return null; } /// <summary> /// Encodes a single part or component of a URI. /// </summary> /// <returns>The encoded string.</returns> [ScriptAlias("encodeURIComponent")] public static string EncodeUriComponent(string s) { return null; } /// <summary> /// Determines if the string ends with the specified character. /// </summary> /// <param name="ch">The character to test for.</param> /// <returns>true if the string ends with the character; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool EndsWith(char ch) { return false; } /// <summary> /// Determines if the string ends with the specified substring or suffix. /// </summary> /// <param name="suffix">The string to test for.</param> /// <returns>true if the string ends with the suffix; false otherwise.</returns> [InlineCode("{$System.Script}.endsWithString({this}, {suffix})")] public bool EndsWith(string suffix) { return false; } /// <summary> /// Determines if the strings are equal. /// </summary> /// <returns>true if the string s1 = s2; false otherwise.</returns> [InlineCode("{$System.Script}.compareStrings({s1}, {s2}, {ignoreCase}) === 0")] public static bool Equals(string s1, string s2, bool ignoreCase) { return false; } /// <summary> /// Encodes a string by replacing punctuation, spaces etc. with their escaped equivalents. /// </summary> /// <returns>The escaped string.</returns> [ScriptAlias("escape") ] public static string Escape(string s) { return null; } [InlineCode("{$System.Script}.formatString({format}, {*values})", NonExpandedFormCode = "{$System.Script}.formatString.apply(null, [{format}].concat({values}))")] public static string Format(string format, params object[] values) { return null; } [ExpandParams] public static string FromCharCode(params char[] charCode) { return null; } [InlineCode("{$System.Script}.htmlDecode({this})")] public string HtmlDecode() { return null; } [InlineCode("{$System.Script}.htmlEncode({this})")] public string HtmlEncode() { return null; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}))")] public int IndexOf(char ch) { return 0; } public int IndexOf(string subString) { return 0; } [InlineCode("{this}.indexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int IndexOf(char ch, int startIndex) { return 0; } public int IndexOf(string ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfString({this}, {$System.String}.fromCharCode({ch}), {startIndex}, {count})")] public int IndexOf(char ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.indexOfString({this}, {ch}, {startIndex}, {count})")] public int IndexOf(string ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch})")] public int IndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex})")] public int IndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.indexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int IndexOfAny(char[] ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.insertString({this}, {index}, {value})")] public string Insert(int index, string value) { return null; } [InlineCode("{$System.Script}.isNullOrEmptyString({s})")] public static bool IsNullOrEmpty(string s) { return false; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}))")] public int LastIndexOf(char ch) { return 0; } public int LastIndexOf(string subString) { return 0; } public int LastIndexOf(string subString, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfString({this}, {$System.String}.fromCharCode({ch}), {startIndex}, {count})")] public int LastIndexOf(char ch, int startIndex, int count) { return 0; } [InlineCode("{$System.Script}.lastIndexOfString({this}, {subString}, {startIndex}, {count})")] public int LastIndexOf(string subString, int startIndex, int count) { return 0; } [InlineCode("{this}.lastIndexOf({$System.String}.fromCharCode({ch}), {startIndex})")] public int LastIndexOf(char ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch})")] public int LastIndexOfAny(params char[] ch) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex})")] public int LastIndexOfAny(char[] ch, int startIndex) { return 0; } [InlineCode("{$System.Script}.lastIndexOfAnyString({this}, {ch}, {startIndex}, {count})")] public int LastIndexOfAny(char[] ch, int startIndex, int count) { return 0; } public int LocaleCompare(string string2) { return 0; } [InlineCode("{$System.Script}.localeFormatString({format}, {*values})")] public static string LocaleFormat(string format, params object[] values) { return null; } public string[] Match(Regex regex) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth})")] public string PadLeft(int totalWidth) { return null; } [InlineCode("{$System.Script}.padLeftString({this}, {totalWidth}, {ch})")] public string PadLeft(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth})")] public string PadRight(int totalWidth) { return null; } [InlineCode("{$System.Script}.padRightString({this}, {totalWidth}, {ch})")] public string PadRight(int totalWidth, char ch) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index})")] public string Remove(int index) { return null; } [InlineCode("{$System.Script}.removeString({this}, {index}, {count})")] public string Remove(int index, int count) { return null; } [InlineCode("{$System.Script}.replaceAllString({this}, {oldText}, {replaceText})")] public string Replace(string oldText, string replaceText) { return null; } [InlineCode("{$System.Script}.replaceAllString({this}, {$System.String}.fromCharCode({oldChar}), {$System.String}.fromCharCode({replaceChar}))")] public string Replace(char oldChar, char replaceChar) { return null; } [ScriptName("replace")] public string ReplaceFirst(string oldText, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, string replaceText) { return null; } [ScriptName("replace")] public string Replace(Regex regex, StringReplaceCallback callback) { return null; } public int Search(Regex regex) { return 0; } public string[] Split(string separator) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}))")] public string[] Split(char separator) { return null; } [ScriptName("split")] public string[] JsSplit(string separator, int limit) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}.map(function(i) {{ return {$System.String}.fromCharCode(i); }}))")] public string[] Split(char[] separator) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}.map(function(i) {{ return {$System.String}.fromCharCode(i); }}), {limit})")] public string[] Split(char[] separator, int limit) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}.map(function(i) {{ return {$System.String}.fromCharCode(i); }}), {limit}, {options})")] public string[] Split(char[] separator, int limit, StringSplitOptions options) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}.map(function(i) {{ return {$System.String}.fromCharCode(i); }}), null, {options})")] public string[] Split(char[] separator, StringSplitOptions options) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}, null, {options})")] public string[] Split(string[] separator, StringSplitOptions options) { return null; } [InlineCode("{$System.Script}.netSplit({this}, {separator}, {limit}, {options})")] public string[] Split(string[] separator, int limit, StringSplitOptions options) { return null; } [InlineCode("{this}.split({$System.String}.fromCharCode({separator}), {limit})")] public string[] JsSplit(char separator, int limit) { return null; } public string[] Split(Regex regex) { return null; } [ScriptName("split")] public string[] JsSplit(Regex regex, int limit) { return null; } [InlineCode("{$System.Script}.startsWithString({this}, {$System.String}.fromCharCode({ch}))")] public bool StartsWith(char ch) { return false; } [InlineCode("{$System.Script}.startsWithString({this}, {prefix})")] public bool StartsWith(string prefix) { return false; } public string Substr(int startIndex) { return null; } public string Substr(int startIndex, int length) { return null; } public string Substring(int startIndex) { return null; } [ScriptName("substr")] public string Substring(int startIndex, int length) { return null; } [ScriptName("substring")] public string JsSubstring(int startIndex, int end) { return null; } public string ToLocaleLowerCase() { return null; } public string ToLocaleUpperCase() { return null; } public string ToLowerCase() { return null; } [ScriptName("toLowerCase")] public string ToLower() { return null; } public string ToUpperCase() { return null; } [ScriptName("toUpperCase")] public string ToUpper() { return null; } public string Trim() { return null; } [InlineCode("{$System.Script}.trimString({this}, {values})")] public string Trim(params char[] values) { return null; } [InlineCode("{$System.Script}.trimStartString({this}, {values})")] public string TrimStart(params char[] values) { return null; } [InlineCode("{$System.Script}.trimEndString({this}, {values})")] public string TrimEnd(params char[] values) { return null; } [InlineCode("{$System.Script}.trimStartString({this})")] public string TrimStart() { return null; } [InlineCode("{$System.Script}.trimEndString({this})")] public string TrimEnd() { return null; } /// <summary> /// Decodes a string by replacing escaped parts with their equivalent textual representation. /// </summary> /// <returns>The unescaped string.</returns> [ScriptAlias("unescape")] public static string Unescape(string s) { return null; } [IntrinsicOperator] public static bool operator ==(string s1, string s2) { return false; } [IntrinsicOperator] public static bool operator !=(string s1, string s2) { return false; } [InlineCode("{$System.Script}.compare({this}, {other})")] public int CompareTo(string other) { return 0; } [InlineCode("{$System.Script}.equalsT({this}, {other})")] public bool Equals(string other) { return false; } [InlineCode("{$System.Script}.equalsT({a}, {b})")] public static bool Equals(string a, string b) { return false; } [InlineCode("{args}.join({separator})")] public static string Join(string separator, params string[] args) { return null; } [InlineCode("{args}.join({separator})")] public static string Join(string separator, params Object[] args) { return null; } [InlineCode("{$System.Script}.arrayFromEnumerable({args}).join({separator})")] public static string Join(string separator, IEnumerable<string> args) { return null; } [InlineCode("{$System.Script}.arrayFromEnumerable({args}).join({separator})")] public static string Join<T>(string separator, IEnumerable<T> args) { return null; } [InlineCode("{args}.slice({startIndex}, {startIndex} + {count}).join({separator})")] public static string Join(string separator, string[] args, int startIndex, int count) { return null; } [InlineCode("({this}.indexOf({value}) !== -1)")] public bool Contains(string value) { return false; } [InlineCode("{this}.split('').map(function(s) {{ return s.charCodeAt(0); }})")] public char[] ToCharArray() { return null; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewValley; using System; using System.Collections.Generic; using System.Linq; namespace StardewValleyMods.CategorizeChests.Interface.Widgets { /// <summary> /// A positioned, resizable element in the interface /// that can also contain other elements. /// </summary> public class Widget { Widget _Parent; public Widget Parent { get => _Parent; set { _Parent = value; OnParent(value); } } List<Widget> _Children = new List<Widget>(); public IEnumerable<Widget> Children => _Children; public Point Position { get; set; } public int X { get => Position.X; set { Position = new Point(value, Position.Y); } } public int Y { get => Position.Y; set { Position = new Point(Position.X, value); } } int _Width; public int Width { get => _Width; set { _Width = value; OnDimensionsChanged(); } } int _Height; public int Height { get { return _Height; } set { _Height = value; OnDimensionsChanged(); } } public Widget() { Position = Point.Zero; Width = 1; Height = 1; } protected virtual void OnParent(Widget parent) { } public virtual void Draw(SpriteBatch batch) { DrawChildren(batch); } protected void DrawChildren(SpriteBatch batch) { foreach (var child in Children) { child.Draw(batch); } } public Rectangle LocalBounds => new Rectangle(0, 0, Width, Height); public Rectangle GlobalBounds => new Rectangle(GlobalPosition.X, GlobalPosition.Y, Width, Height); public Point GlobalPosition => Globalize(Point.Zero); public bool Contains(Point point) { return point.X >= Position.X && point.X <= Position.X + Width && point.Y >= Position.Y && point.Y <= Position.Y + Height; } public Point Globalize(Point point) { var global = new Point(point.X + Position.X, point.Y + Position.Y); return Parent != null ? Parent.Globalize(global) : global; } public virtual bool ReceiveKeyPress(Keys input) { return PropagateKeyPress(input); } public virtual bool ReceiveLeftClick(Point point) { return PropagateLeftClick(point); } public virtual bool ReceiveCursorHover(Point point) { return PropagateCursorHover(point); } public virtual bool ReceiveScrollWheelAction(int amount) { return PropagateScrollWheelAction(amount); } protected bool PropagateKeyPress(Keys input) { foreach (var child in Children) { var handled = child.ReceiveKeyPress(input); if (handled) return true; } return false; } protected bool PropagateScrollWheelAction(int amount) { foreach (var child in Children) { var handled = child.ReceiveScrollWheelAction(amount); if (handled) return true; } return false; } protected bool PropagateLeftClick(Point point) { foreach (var child in Children) { var localPoint = new Point(point.X - child.Position.X, point.Y - child.Position.Y); if (child.LocalBounds.Contains(localPoint)) { var handled = child.ReceiveLeftClick(localPoint); if (handled) return true; } } return false; } protected bool PropagateCursorHover(Point point) { foreach (var child in Children) { var localPoint = new Point(point.X - child.Position.X, point.Y - child.Position.Y); if (child.LocalBounds.Contains(localPoint)) { var handled = child.ReceiveCursorHover(localPoint); if (handled) return true; } } return false; } public T AddChild<T>(T child) where T : Widget { child.Parent = this; _Children.Add(child); OnContentsChanged(); return child; } public void RemoveChild(Widget child) { _Children.Remove(child); child.Parent = null; OnContentsChanged(); } public void RemoveChildren() { RemoveChildren(c => true); } public void RemoveChildren(Predicate<Widget> shouldRemove) { foreach (var child in Children.Where(c => shouldRemove(c))) { child.Parent = null; } _Children.RemoveAll(shouldRemove); OnContentsChanged(); } protected virtual void OnContentsChanged() { } protected virtual void OnDimensionsChanged() { } public void CenterHorizontally() { var containerWidth = (Parent != null) ? Parent.Width : Game1.viewport.Width; // TODO X = containerWidth / 2 - Width / 2; } public void CenterVertically() { var containerHeight = (Parent != null) ? Parent.Height : Game1.viewport.Height; // TODO Y = containerHeight / 2 - Height / 2; } } }
//--------------------------------------------------------------------- // <copyright file="ObjectHelper.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Data.Mapping; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Data.Common.Utils; using System.IO; namespace System.Data.Metadata.Edm { /// <summary> /// Helper Class for EDM Metadata - this class contains all the helper methods /// which needs access to internal methods. The other partial class contains all /// helper methods which just uses public methods/properties. The reason why we /// did this for allowing view gen to happen at compile time - all the helper /// methods that view gen or mapping uses are in the other helper class. Rest of the /// methods are in this class /// </summary> internal static partial class Helper { #region Fields // List of all the static empty list used all over the code internal static readonly ReadOnlyCollection<KeyValuePair<string, object>> EmptyKeyValueStringObjectList = new ReadOnlyCollection<KeyValuePair<string, object>>(new KeyValuePair<string, object>[0]); internal static readonly ReadOnlyCollection<string> EmptyStringList = new ReadOnlyCollection<string>(new string[0]); internal static readonly ReadOnlyCollection<FacetDescription> EmptyFacetDescriptionEnumerable = new ReadOnlyCollection<FacetDescription>(new FacetDescription[0]); internal static readonly ReadOnlyCollection<EdmFunction> EmptyEdmFunctionReadOnlyCollection = new ReadOnlyCollection<EdmFunction>(new EdmFunction[0]); internal static readonly ReadOnlyCollection<PrimitiveType> EmptyPrimitiveTypeReadOnlyCollection = new ReadOnlyCollection<PrimitiveType>(new PrimitiveType[0]); internal static readonly KeyValuePair<string, object>[] EmptyKeyValueStringObjectArray = new KeyValuePair<string, object>[0]; internal const char PeriodSymbol = '.'; internal const char CommaSymbol = ','; #endregion #region Methods /// <summary> /// Returns the single error message from the list of errors /// </summary> /// <param name="errors"></param> /// <returns></returns> static internal string CombineErrorMessage(IEnumerable<System.Data.Metadata.Edm.EdmSchemaError> errors) { Debug.Assert(errors != null); StringBuilder sb = new StringBuilder(System.Environment.NewLine); int count = 0; foreach (System.Data.Metadata.Edm.EdmSchemaError error in errors) { //Don't append a new line at the beginning of the messages if ((count++) != 0) { sb.Append(System.Environment.NewLine); } sb.Append(error.ToString()); } Debug.Assert(count!=0, "Empty Error List"); return sb.ToString(); } /// <summary> /// Returns the single error message from the list of errors /// </summary> /// <param name="errors"></param> /// <returns></returns> static internal string CombineErrorMessage(IEnumerable<EdmItemError> errors) { StringBuilder sb = new StringBuilder(System.Environment.NewLine); int count = 0; foreach (EdmItemError error in errors) { // Only add the new line if this is not the first error if ((count++) != 0) { sb.Append(System.Environment.NewLine); } sb.Append(error.Message); } return sb.ToString(); } // requires: enumerations must have the same number of members // effects: returns paired enumeration values internal static IEnumerable<KeyValuePair<T, S>> PairEnumerations<T, S>(IBaseList<T> left, IEnumerable<S> right) { IEnumerator leftEnumerator = left.GetEnumerator(); IEnumerator<S> rightEnumerator = right.GetEnumerator(); while (leftEnumerator.MoveNext() && rightEnumerator.MoveNext()) { yield return new KeyValuePair<T, S>((T)leftEnumerator.Current, rightEnumerator.Current); } yield break; } /// <summary> /// Returns a model (C-Space) typeusage for the given typeusage. if the type is already in c-space, it returns /// the given typeusage. The typeUsage returned is created by invoking the provider service to map from provider /// specific type to model type. /// </summary> /// <param name="typeUsage">typeusage</param> /// <returns>the respective Model (C-Space) typeusage</returns> static internal TypeUsage GetModelTypeUsage(TypeUsage typeUsage) { return typeUsage.GetModelTypeUsage(); } /// <summary> /// Returns a model (C-Space) typeusage for the given member typeusage. if the type is already in c-space, it returns /// the given typeusage. The typeUsage returned is created by invoking the provider service to map from provider /// specific type to model type. /// </summary> /// <param name="member">EdmMember</param> /// <returns>the respective Model (C-Space) typeusage</returns> static internal TypeUsage GetModelTypeUsage(EdmMember member) { return GetModelTypeUsage(member.TypeUsage); } /// <summary> /// Checks if the edm type in the cspace type usage maps to some sspace type (called it S1). If S1 is equivalent or /// promotable to the store type in sspace type usage, then it creates a new type usage with S1 and copies all facets /// if necessary /// </summary> /// <param name="edmProperty">Edm property containing the cspace member type information</param> /// <param name="columnProperty">edm property containing the sspace member type information</param> /// <param name="fileName">name of the mapping file from which this information was loaded from</param> /// <param name="lineInfo">lineInfo containing the line information about the cspace and sspace property mapping</param> /// <param name="parsingErrors">List of parsing errors - we need to add any new error to this list</param> /// <param name="storeItemCollection">store item collection</param> /// <returns></returns> internal static TypeUsage ValidateAndConvertTypeUsage(EdmProperty edmProperty, EdmProperty columnProperty, Xml.IXmlLineInfo lineInfo, string sourceLocation, List<EdmSchemaError> parsingErrors, StoreItemCollection storeItemCollection) { Debug.Assert(edmProperty.TypeUsage.EdmType.DataSpace == DataSpace.CSpace, "cspace property must have a cspace type"); Debug.Assert(columnProperty.TypeUsage.EdmType.DataSpace == DataSpace.SSpace, "sspace type usage must have a sspace type"); Debug.Assert( Helper.IsScalarType(edmProperty.TypeUsage.EdmType), "cspace property must be of a primitive or enumeration type"); Debug.Assert(Helper.IsPrimitiveType(columnProperty.TypeUsage.EdmType), "sspace property must contain a primitive type"); TypeUsage mappedStoreType = ValidateAndConvertTypeUsage(edmProperty, lineInfo, sourceLocation, edmProperty.TypeUsage, columnProperty.TypeUsage, parsingErrors, storeItemCollection); return mappedStoreType; } internal static TypeUsage ValidateAndConvertTypeUsage(EdmMember edmMember, Xml.IXmlLineInfo lineInfo, string sourceLocation, TypeUsage cspaceType, TypeUsage sspaceType, List<EdmSchemaError> parsingErrors, StoreItemCollection storeItemCollection) { // if we are already C-Space, dont call the provider. this can happen for functions. TypeUsage modelEquivalentSspace = sspaceType; if (sspaceType.EdmType.DataSpace == DataSpace.SSpace) { modelEquivalentSspace = sspaceType.GetModelTypeUsage(); } // check that cspace type is subtype of c-space equivalent type from the ssdl definition if (ValidateScalarTypesAreCompatible(cspaceType, modelEquivalentSspace)) { return modelEquivalentSspace; } return null; } #endregion /// <summary> /// Validates whether cspace and sspace types are compatible. /// </summary> /// <param name="cspaceType">Type in C-Space. Must be a primitive or enumeration type.</param> /// <param name="storeType">C-Space equivalent of S-space Type. Must be a primitive type.</param> /// <returns> /// <c>true</c> if the types are compatible. <c>false</c> otherwise. /// </returns> /// <remarks> /// This methods validate whether cspace and sspace types are compatible. The types are /// compatible if: /// both are primitive and the cspace type is a subtype of sspace type /// or /// cspace type is an enumeration type whose underlying type is a subtype of sspace type. /// </remarks> private static bool ValidateScalarTypesAreCompatible(TypeUsage cspaceType, TypeUsage storeType) { Debug.Assert(cspaceType != null, "cspaceType != null"); Debug.Assert(storeType != null, "storeType != null"); Debug.Assert(cspaceType.EdmType.DataSpace == DataSpace.CSpace, "cspace property must have a cspace type"); Debug.Assert(storeType.EdmType.DataSpace == DataSpace.CSpace, "storeType type usage must have a sspace type"); Debug.Assert( Helper.IsScalarType(cspaceType.EdmType), "cspace property must be of a primitive or enumeration type"); Debug.Assert(Helper.IsPrimitiveType(storeType.EdmType), "storeType property must be a primitive type"); if (Helper.IsEnumType(cspaceType.EdmType)) { // For enum cspace type check whether its underlying type is a subtype of the store type. Note that // TypeSemantics.IsSubTypeOf uses only TypeUsage.EdmType for primitive types so there is no need to copy facets // from the enum type property to the underlying type TypeUsage created here since they wouldn't be used anyways. return TypeSemantics.IsSubTypeOf(TypeUsage.Create(Helper.GetUnderlyingEdmTypeForEnumType(cspaceType.EdmType)), storeType); } return TypeSemantics.IsSubTypeOf(cspaceType, storeType); } } }
using System; using System.Linq; using System.Collections.Generic; using System.Text; using GrandTheftMultiplayer.Server.API; using GrandTheftMultiplayer.Server.Constant; using GrandTheftMultiplayer.Server.Elements; using GrandTheftMultiplayer.Server.Managers; using GrandTheftMultiplayer.Shared; using GrandTheftMultiplayer.Shared.Math; namespace GTFuel { public class FreeroamScript : Script { public FreeroamScript() { API.onClientEventTrigger += onClientEventTrigger; } private static Random Rnd = new Random(); public Dictionary<Client, List<NetHandle>> VehicleHistory = new Dictionary<Client, List<NetHandle>>(); public Dictionary<string, string> AnimationList = new Dictionary<string, string> { {"finger", "mp_player_intfinger mp_player_int_finger"}, {"guitar", "anim@mp_player_intcelebrationmale@air_guitar air_guitar"}, {"shagging", "anim@mp_player_intcelebrationmale@air_shagging air_shagging"}, {"synth", "anim@mp_player_intcelebrationmale@air_synth air_synth"}, {"kiss", "anim@mp_player_intcelebrationmale@blow_kiss blow_kiss"}, {"bro", "anim@mp_player_intcelebrationmale@bro_love bro_love"}, {"chicken", "anim@mp_player_intcelebrationmale@chicken_taunt chicken_taunt"}, {"chin", "anim@mp_player_intcelebrationmale@chin_brush chin_brush"}, {"dj", "anim@mp_player_intcelebrationmale@dj dj"}, {"dock", "anim@mp_player_intcelebrationmale@dock dock"}, {"facepalm", "anim@mp_player_intcelebrationmale@face_palm face_palm"}, {"fingerkiss", "anim@mp_player_intcelebrationmale@finger_kiss finger_kiss"}, {"freakout", "anim@mp_player_intcelebrationmale@freakout freakout"}, {"jazzhands", "anim@mp_player_intcelebrationmale@jazz_hands jazz_hands"}, {"knuckle", "anim@mp_player_intcelebrationmale@knuckle_crunch knuckle_crunch"}, {"nose", "anim@mp_player_intcelebrationmale@nose_pick nose_pick"}, {"no", "anim@mp_player_intcelebrationmale@no_way no_way"}, {"peace", "anim@mp_player_intcelebrationmale@peace peace"}, {"photo", "anim@mp_player_intcelebrationmale@photography photography"}, {"rock", "anim@mp_player_intcelebrationmale@rock rock"}, {"salute", "anim@mp_player_intcelebrationmale@salute salute"}, {"shush", "anim@mp_player_intcelebrationmale@shush shush"}, {"slowclap", "anim@mp_player_intcelebrationmale@slow_clap slow_clap"}, {"surrender", "anim@mp_player_intcelebrationmale@surrender surrender"}, {"thumbs", "anim@mp_player_intcelebrationmale@thumbs_up thumbs_up"}, {"taunt", "anim@mp_player_intcelebrationmale@thumb_on_ears thumb_on_ears"}, {"vsign", "anim@mp_player_intcelebrationmale@v_sign v_sign"}, {"wank", "anim@mp_player_intcelebrationmale@wank wank"}, {"wave", "anim@mp_player_intcelebrationmale@wave wave"}, {"loco", "anim@mp_player_intcelebrationmale@you_loco you_loco"}, {"handsup", "missminuteman_1ig_2 handsup_base"}, }; public List<VehicleHash> BannedVehicles = new List<VehicleHash> { VehicleHash.CargoPlane, }; public List<Vector3> SpawnPositions = new List<Vector3> { new Vector3(-237.172, -650.3887, 33.30411), new Vector3(-276.9281, -642.3959, 33.20348), new Vector3(-284.7394, -679.6924, 33.27827), new Vector3(-219.5132, -697.4506, 33.67715), new Vector3(-172.2065, -666.7617, 40.48457), new Vector3(-344.8585, -691.2588, 32.73247), }; public void onClientEventTrigger(Client sender, string name, object[] args) { if (name == "CREATE_VEHICLE") { int model = (int)args[0]; if (!Enum.IsDefined(typeof(VehicleHash), model)) return; //var rot = API.getEntityRotation(sender.handle); //var veh = API.createVehicle((VehicleHash)model, sender.position, new Vector3(0, 0, rot.Z), 0, 0); NetHandle Vehicle = API.getPlayerVehicle(sender); int VehicleID = Vehicle.Value; VehicleFuelScript vfs = new VehicleFuelScript(VehicleID, sender, model); if (VehicleHistory.ContainsKey(sender)) { VehicleHistory[sender].Add(vfs.veh); if (VehicleHistory[sender].Count > 3) { API.deleteEntity(VehicleHistory[sender][0]); VehicleHistory[sender].RemoveAt(0); } } else { VehicleHistory.Add(sender, new List<NetHandle> { vfs.veh }); } API.setPlayerIntoVehicle(sender, vfs.veh, -1); } else if (name == "REQUEST_WEAPON") { int hash = (int)args[0]; API.givePlayerWeapon(sender, (WeaponHash)hash, 100, false, false); } } [Command("me", GreedyArg = true)] public void MeCommand(Client sender, string text) { API.sendChatMessageToAll("~#C2A2DA~", sender.name + " " + text); } [Command("spec")] public void SpectatorCommand(Client sender, Client target) { API.setPlayerToSpectatePlayer(sender, target); } [Command("unspec")] public void StopSpectatingCommand(Client sender) { API.unspectatePlayer(sender); } [Command("loadipl")] public void LoadIplCommand(Client sender, string ipl) { API.requestIpl(ipl); API.consoleOutput("LOADED IPL " + ipl); API.sendChatMessageToPlayer(sender, "Loaded IPL ~b~" + ipl + "~w~."); } [Command("removeipl")] public void RemoveIplCommand(Client sender, string ipl) { API.removeIpl(ipl); API.consoleOutput("REMOVED IPL " + ipl); API.sendChatMessageToPlayer(sender, "Removed IPL ~b~" + ipl + "~w~."); } [Command("blackout")] public void BlackoutCommand(Client sender, bool blackout) { API.sendNativeToAllPlayers(0x1268615ACE24D504, blackout); } [Command("dimension")] public void ChangeDimension(Client sender, int dimension) { API.setEntityDimension(sender.handle, dimension); } [Command("mod")] public void SetCarModificationCommand(Client sender, int modIndex, int modVar) { if (!sender.vehicle.IsNull) { API.setVehicleMod(sender.vehicle, modIndex, modVar); API.sendChatMessageToPlayer(sender, "Mod applied successfully!"); } else { API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!"); } } [Command("clothes")] public void SetPedClothesCommand(Client sender, int slot, int drawable, int texture) { API.setPlayerClothes(sender, slot, drawable, texture); API.sendChatMessageToPlayer(sender, "Clothes applied successfully!"); } [Command("props")] public void SetPedAccessoriesCommand(Client sender, int slot, int drawable, int texture) { API.setPlayerAccessory(sender, slot, drawable, texture); API.sendChatMessageToPlayer(sender, "Props applied successfully!"); } [Command("colors")] public void GameVehicleColorsCommand(Client sender, int primaryColor, int secondaryColor) { if (!sender.vehicle.IsNull) { API.setVehiclePrimaryColor(sender.vehicle, primaryColor); API.setVehicleSecondaryColor(sender.vehicle, secondaryColor); API.sendChatMessageToPlayer(sender, "Colors applied successfully!"); } else { API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!"); } } private Dictionary<Client, NetHandle> cars = new Dictionary<Client, NetHandle>(); private Dictionary<Client, NetHandle> shields = new Dictionary<Client, NetHandle>(); [Command("detach")] public void detachtest(Client sender) { if (cars.ContainsKey(sender)) { API.deleteEntity(cars[sender]); cars.Remove(sender); } if (labels.ContainsKey(sender)) { API.deleteEntity(labels[sender]); labels.Remove(sender); } if (shields.ContainsKey(sender)) { API.deleteEntity(shields[sender]); shields.Remove(sender); } } [Command("attachveh")] public void attachtest2(Client sender, VehicleHash veh) { if (cars.ContainsKey(sender)) { API.deleteEntity(cars[sender]); cars.Remove(sender); } var prop = API.createVehicle(veh, API.getEntityPosition(sender.handle), new Vector3(), 0, 0); API.attachEntityToEntity(prop, sender.handle, null, new Vector3(), new Vector3()); cars.Add(sender, prop); } private Dictionary<Client, NetHandle> labels = new Dictionary<Client, NetHandle>(); [Command("attachlabel")] public void attachtest3(Client sender, string message) { if (labels.ContainsKey(sender)) { API.deleteEntity(labels[sender]); labels.Remove(sender); } var prop = API.createTextLabel(message, API.getEntityPosition(sender.handle), 50f, 0.4f, true); API.attachEntityToEntity(prop, sender.handle, null, new Vector3(0, 0, 1f), new Vector3()); labels.Add(sender, prop); } [Command("attachmarker")] public void attachtest4(Client sender) { var prop = API.createMarker(0, API.getEntityPosition(sender.handle), new Vector3(), new Vector3(), new Vector3(1f, 1f, 1f), 255, 255, 255, 255); API.attachEntityToEntity(prop, sender.handle, null, new Vector3(), new Vector3()); } [Command("shield")] public void attachtest5(Client sender) { if (shields.ContainsKey(sender)) { API.deleteEntity(shields[sender]); shields.Remove(sender); } var prop = API.createObject(API.getHashKey("prop_riot_shield"), API.getEntityPosition(sender.handle), new Vector3()); API.attachEntityToEntity(prop, sender.handle, "SKEL_L_Hand", new Vector3(0, 0, 0), new Vector3(0f, 0f, 0f)); shields.Add(sender, prop); } [Command("attachrpg")] public void attachtest1(Client sender) { var prop = API.createObject(API.getHashKey("w_lr_rpg"), API.getEntityPosition(sender.handle), new Vector3()); API.attachEntityToEntity(prop, sender.handle, "SKEL_SPINE3", new Vector3(-0.13f, -0.231f, 0.07f), new Vector3(0f, 200f, 10f)); } [Command("colorsrgb")] public void CustomVehicleColorsCommand(Client sender, int primaryRed, int primaryGreen, int primaryBlue, int secondaryRed, int secondaryGreen, int secondaryBlue) { if (!sender.vehicle.IsNull) { API.setVehicleCustomPrimaryColor(sender.vehicle, primaryRed, primaryGreen, primaryBlue); API.setVehicleCustomSecondaryColor(sender.vehicle, secondaryRed, secondaryGreen, secondaryBlue); API.sendChatMessageToPlayer(sender, "Colors applied successfully!"); } else { API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!"); } } [Command("anim", "~y~USAGE: ~w~/anim [animation]\n" + "~y~USAGE: ~w~/anim help for animation list.\n" + "~y~USAGE: ~w~/anim stop to stop current animation.")] public void SetPlayerAnim(Client sender, string animation) { if (animation == "help") { string helpText = AnimationList.Aggregate(new StringBuilder(), (sb, kvp) => sb.Append(kvp.Key + " "), sb => sb.ToString()); API.sendChatMessageToPlayer(sender, "~b~Available animations:"); var split = helpText.Split(); for (int i = 0; i < split.Length; i += 5) { string output = ""; if (split.Length > i) output += split[i] + " "; if (split.Length > i + 1) output += split[i + 1] + " "; if (split.Length > i + 2) output += split[i + 2] + " "; if (split.Length > i + 3) output += split[i + 3] + " "; if (split.Length > i + 4) output += split[i + 4] + " "; if (!string.IsNullOrWhiteSpace(output)) API.sendChatMessageToPlayer(sender, "~b~>> ~w~" + output); } } else if (animation == "stop") { API.stopPlayerAnimation(sender); } else if (!AnimationList.ContainsKey(animation)) { API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~Animation not found!"); } else { var flag = 0; if (animation == "handsup") flag = 1; API.playPlayerAnimation(sender, flag, AnimationList[animation].Split()[0], AnimationList[animation].Split()[1]); } } private Client getVehicleOwner(NetHandle vehicle) { foreach (var client in VehicleHistory.Keys) { foreach (var v in VehicleHistory[client]) { if (v.Value == vehicle.Value) return client; } } return null; } private string getRandomNumberPlate(Client client = null) { if (client != null) { string strClientName = client.name; if (strClientName.Length <= 8) return strClientName.ToUpper(); } string strCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string strRet = ""; for (int i = 0; i < 8; i++) { strRet += strCharacters[Rnd.Next(strCharacters.Length)]; } return strRet; } [Command("car", Alias = "v")] public void SpawnCarCommand(Client sender, VehicleHash model) { if (BannedVehicles.Contains(model)) { sender.sendChatMessage("The vehicle ~r~" + model.ToString() + "~s~ is ~r~banned~s~!"); return; } if (sender.vehicle != null && sender.vehicleSeat == -1) { NetHandle hv = sender.vehicle.handle; var owner = getVehicleOwner(hv); if (owner != null && VehicleHistory.ContainsKey(owner)) { VehicleHistory[owner].Remove(hv); } sender.vehicle.delete(); } var veh = API.createVehicle(model, sender.position, new Vector3(0, 0, sender.rotation.Z), 0, 0); veh.primaryColor = Rnd.Next(158); veh.secondaryColor = Rnd.Next(158); veh.numberPlate = getRandomNumberPlate(sender); veh.numberPlateStyle = Rnd.Next(6); if (VehicleHistory.ContainsKey(sender)) { VehicleHistory[sender].Add(veh); if (VehicleHistory[sender].Count > 3) { API.deleteEntity(VehicleHistory[sender][0]); VehicleHistory[sender].RemoveAt(0); } } else { VehicleHistory.Add(sender, new List<NetHandle> { veh }); } API.setPlayerIntoVehicle(sender, veh, -1); } [Command("repair", Alias = "r")] public void RepairCarCommand(Client sender) { var veh = sender.vehicle; if (veh == null) return; veh.repair(); } [Command("clearvehicles", Alias = "vc")] public void ClearVehiclesCommand(Client sender) { if (!VehicleHistory.ContainsKey(sender)) return; foreach (var veh in VehicleHistory[sender]) API.deleteEntity(veh); VehicleHistory[sender].Clear(); } [Command("skin")] public void ChangeSkinCommand(Client sender, PedHash model) { API.setPlayerSkin(sender, model); API.sendNativeToPlayer(sender, Hash.SET_PED_DEFAULT_COMPONENT_VARIATION, sender.handle); } [Command("pic")] public void SpawnPickupCommand(Client sender, PickupHash pickup) { API.createPickup(pickup, new Vector3(sender.position.X + 10, sender.position.Y, sender.position.Z), new Vector3(), 100, 0); } [Command("countdown")] public void StartGlobalCountdownCommand(Client sender) { API.triggerClientEventForAll("startCountdown"); } [Command("tp")] public void TeleportPlayerToPlayerCommand(Client sender, Client target) { var pos = API.getEntityPosition(sender.handle); API.createParticleEffectOnPosition("scr_rcbarry1", "scr_alien_teleport", pos, new Vector3(), 1f); API.setEntityPosition(sender.handle, API.getEntityPosition(target.handle)); } [Command("weapon", Alias = "w,gun")] public void GiveWeaponCommand(Client sender, WeaponHash weapon) { API.givePlayerWeapon(sender, weapon, 9999, true, true); } [Command("weaponcomponent", Alias = "wcomp,wc")] public void GiveWeaponComponentCmd(Client sender, WeaponComponent component) { API.givePlayerWeaponComponent(sender, API.getPlayerCurrentWeapon(sender), component); } [Command("weapontint", Alias = "wtint")] public void SetWeaponTintCmd(Client sender, WeaponTint tint) { API.setPlayerWeaponTint(sender, API.getPlayerCurrentWeapon(sender), tint); } [Command("mine")] public void PlaceMine(Client sender, float MineRange = 10f) { var pos = API.getEntityPosition(sender); var playerDimension = API.getEntityDimension(sender); var prop = API.createObject(API.getHashKey("prop_bomb_01"), pos - new Vector3(0, 0, 1f), new Vector3(), playerDimension); var shape = API.createSphereColShape(pos, MineRange); shape.dimension = playerDimension; } [Command("shape")] public void Shaope(Client sender) { var pos = API.getEntityPosition(sender); var playerDimension = API.getEntityDimension(sender); var shape = API.createSphereColShape(pos, 100f); shape.dimension = playerDimension; } } }
using System; using System.Text; namespace SharpCompress.Compressor.PPMd.H { internal class SubAllocator { public virtual int FakeUnitsStart { get { return fakeUnitsStart; } set { this.fakeUnitsStart = value; } } public virtual int HeapEnd { get { return heapEnd; } } public virtual int PText { get { return pText; } set { pText = value; } } public virtual int UnitsStart { get { return unitsStart; } set { this.unitsStart = value; } } public virtual byte[] Heap { get { return heap; } } //UPGRADE_NOTE: Final was removed from the declaration of 'N4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public const int N1 = 4; public const int N2 = 4; public const int N3 = 4; public static readonly int N4 = (128 + 3 - 1*N1 - 2*N2 - 3*N3)/4; //UPGRADE_NOTE: Final was removed from the declaration of 'N_INDEXES '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public static readonly int N_INDEXES = N1 + N2 + N3 + N4; //UPGRADE_NOTE: Final was removed from the declaration of 'UNIT_SIZE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" //UPGRADE_NOTE: The initialization of 'UNIT_SIZE' was moved to static method 'SharpCompress.Unpack.PPM.SubAllocator'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" public static readonly int UNIT_SIZE; public const int FIXED_UNIT_SIZE = 12; private int subAllocatorSize; // byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; private int[] indx2Units = new int[N_INDEXES]; private int[] units2Indx = new int[128]; private int glueCount; // byte *HeapStart,*LoUnit, *HiUnit; private int heapStart, loUnit, hiUnit; //UPGRADE_NOTE: Final was removed from the declaration of 'freeList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private RarNode[] freeList = new RarNode[N_INDEXES]; // byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; private int pText, unitsStart, heapEnd, fakeUnitsStart; private byte[] heap; private int freeListPos; private int tempMemBlockPos; // Temp fields private RarNode tempRarNode = null; private RarMemBlock tempRarMemBlock1 = null; private RarMemBlock tempRarMemBlock2 = null; private RarMemBlock tempRarMemBlock3 = null; public SubAllocator() { clean(); } public virtual void clean() { subAllocatorSize = 0; } private void insertNode(int p, int indx) { RarNode temp = tempRarNode; temp.Address = p; temp.SetNext(freeList[indx].GetNext()); freeList[indx].SetNext(temp); } public virtual void incPText() { pText++; } private int removeNode(int indx) { int retVal = freeList[indx].GetNext(); RarNode temp = tempRarNode; temp.Address = retVal; freeList[indx].SetNext(temp.GetNext()); return retVal; } private int U2B(int NU) { return UNIT_SIZE*NU; } /* memblockptr */ private int MBPtr(int BasePtr, int Items) { return (BasePtr + U2B(Items)); } private void splitBlock(int pv, int oldIndx, int newIndx) { int i, uDiff = indx2Units[oldIndx] - indx2Units[newIndx]; int p = pv + U2B(indx2Units[newIndx]); if (indx2Units[i = units2Indx[uDiff - 1]] != uDiff) { insertNode(p, --i); p += U2B(i = indx2Units[i]); uDiff -= i; } insertNode(p, units2Indx[uDiff - 1]); } public virtual void stopSubAllocator() { if (subAllocatorSize != 0) { subAllocatorSize = 0; //ArrayFactory.BYTES_FACTORY.recycle(heap); heap = null; heapStart = 1; // rarfree(HeapStart); // Free temp fields tempRarNode = null; tempRarMemBlock1 = null; tempRarMemBlock2 = null; tempRarMemBlock3 = null; } } public virtual int GetAllocatedMemory() { return subAllocatorSize; } public virtual bool startSubAllocator(int SASize) { int t = SASize; if (subAllocatorSize == t) { return true; } stopSubAllocator(); int allocSize = t/FIXED_UNIT_SIZE*UNIT_SIZE + UNIT_SIZE; // adding space for freelist (needed for poiters) // 1+ for null pointer int realAllocSize = 1 + allocSize + 4*N_INDEXES; // adding space for an additional memblock tempMemBlockPos = realAllocSize; realAllocSize += RarMemBlock.size; heap = new byte[realAllocSize]; heapStart = 1; heapEnd = heapStart + allocSize - UNIT_SIZE; subAllocatorSize = t; // Bug fixed freeListPos = heapStart + allocSize; //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" //assert(realAllocSize - tempMemBlockPos == RarMemBlock.size): realAllocSize //+ + tempMemBlockPos + + RarMemBlock.size; // Init freeList for (int i = 0, pos = freeListPos; i < freeList.Length; i++, pos += RarNode.size) { freeList[i] = new RarNode(heap); freeList[i].Address = pos; } // Init temp fields tempRarNode = new RarNode(heap); tempRarMemBlock1 = new RarMemBlock(heap); tempRarMemBlock2 = new RarMemBlock(heap); tempRarMemBlock3 = new RarMemBlock(heap); return true; } private void glueFreeBlocks() { RarMemBlock s0 = tempRarMemBlock1; s0.Address = tempMemBlockPos; RarMemBlock p = tempRarMemBlock2; RarMemBlock p1 = tempRarMemBlock3; int i, k, sz; if (loUnit != hiUnit) { heap[loUnit] = 0; } for (i = 0, s0.SetPrev(s0), s0.SetNext(s0); i < N_INDEXES; i++) { while (freeList[i].GetNext() != 0) { p.Address = removeNode(i); // =(RAR_MEM_BLK*)RemoveNode(i); p.InsertAt(s0); // p->insertAt(&s0); p.Stamp = 0xFFFF; // p->Stamp=0xFFFF; p.SetNU(indx2Units[i]); // p->NU=Indx2Units[i]; } } for (p.Address = s0.GetNext(); p.Address != s0.Address; p.Address = p.GetNext()) { // while ((p1=MBPtr(p,p->NU))->Stamp == 0xFFFF && int(p->NU)+p1->NU // < 0x10000) // Bug fixed p1.Address = MBPtr(p.Address, p.GetNU()); while (p1.Stamp == 0xFFFF && p.GetNU() + p1.GetNU() < 0x10000) { p1.Remove(); p.SetNU(p.GetNU() + p1.GetNU()); // ->NU += p1->NU; p1.Address = MBPtr(p.Address, p.GetNU()); } } // while ((p=s0.next) != &s0) // Bug fixed p.Address = s0.GetNext(); while (p.Address != s0.Address) { for (p.Remove(), sz = p.GetNU(); sz > 128; sz -= 128, p.Address = MBPtr(p.Address, 128)) { insertNode(p.Address, N_INDEXES - 1); } if (indx2Units[i = units2Indx[sz - 1]] != sz) { k = sz - indx2Units[--i]; insertNode(MBPtr(p.Address, sz - k), k - 1); } insertNode(p.Address, i); p.Address = s0.GetNext(); } } private int allocUnitsRare(int indx) { if (glueCount == 0) { glueCount = 255; glueFreeBlocks(); if (freeList[indx].GetNext() != 0) { return removeNode(indx); } } int i = indx; do { if (++i == N_INDEXES) { glueCount--; i = U2B(indx2Units[indx]); int j = FIXED_UNIT_SIZE*indx2Units[indx]; if (fakeUnitsStart - pText > j) { fakeUnitsStart -= j; unitsStart -= i; return unitsStart; } return (0); } } while (freeList[i].GetNext() == 0); int retVal = removeNode(i); splitBlock(retVal, i, indx); return retVal; } public virtual int allocUnits(int NU) { int indx = units2Indx[NU - 1]; if (freeList[indx].GetNext() != 0) { return removeNode(indx); } int retVal = loUnit; loUnit += U2B(indx2Units[indx]); if (loUnit <= hiUnit) { return retVal; } loUnit -= U2B(indx2Units[indx]); return allocUnitsRare(indx); } public virtual int allocContext() { if (hiUnit != loUnit) return (hiUnit -= UNIT_SIZE); if (freeList[0].GetNext() != 0) { return removeNode(0); } return allocUnitsRare(0); } public virtual int expandUnits(int oldPtr, int OldNU) { int i0 = units2Indx[OldNU - 1]; int i1 = units2Indx[OldNU - 1 + 1]; if (i0 == i1) { return oldPtr; } int ptr = allocUnits(OldNU + 1); if (ptr != 0) { // memcpy(ptr,OldPtr,U2B(OldNU)); Array.Copy(heap, oldPtr, heap, ptr, U2B(OldNU)); insertNode(oldPtr, i0); } return ptr; } public virtual int shrinkUnits(int oldPtr, int oldNU, int newNU) { // System.out.println("SubAllocator.shrinkUnits(" + OldPtr + ", " + // OldNU + ", " + NewNU + ")"); int i0 = units2Indx[oldNU - 1]; int i1 = units2Indx[newNU - 1]; if (i0 == i1) { return oldPtr; } if (freeList[i1].GetNext() != 0) { int ptr = removeNode(i1); // memcpy(ptr,OldPtr,U2B(NewNU)); // for (int i = 0; i < U2B(NewNU); i++) { // heap[ptr + i] = heap[OldPtr + i]; // } Array.Copy(heap, oldPtr, heap, ptr, U2B(newNU)); insertNode(oldPtr, i0); return ptr; } else { splitBlock(oldPtr, i0, i1); return oldPtr; } } public virtual void freeUnits(int ptr, int OldNU) { insertNode(ptr, units2Indx[OldNU - 1]); } public virtual void decPText(int dPText) { PText = PText - dPText; } public virtual void initSubAllocator() { int i, k; Utility.Fill(heap, freeListPos, freeListPos + sizeOfFreeList(), (byte) 0); pText = heapStart; int size2 = FIXED_UNIT_SIZE*(subAllocatorSize/8/FIXED_UNIT_SIZE*7); int realSize2 = size2/FIXED_UNIT_SIZE*UNIT_SIZE; int size1 = subAllocatorSize - size2; int realSize1 = size1/FIXED_UNIT_SIZE*UNIT_SIZE + size1%FIXED_UNIT_SIZE; hiUnit = heapStart + subAllocatorSize; loUnit = unitsStart = heapStart + realSize1; fakeUnitsStart = heapStart + size1; hiUnit = loUnit + realSize2; for (i = 0, k = 1; i < N1; i++, k += 1) { indx2Units[i] = k & 0xff; } for (k++; i < N1 + N2; i++, k += 2) { indx2Units[i] = k & 0xff; } for (k++; i < N1 + N2 + N3; i++, k += 3) { indx2Units[i] = k & 0xff; } for (k++; i < (N1 + N2 + N3 + N4); i++, k += 4) { indx2Units[i] = k & 0xff; } for (glueCount = 0, k = 0, i = 0; k < 128; k++) { i += ((indx2Units[i] < (k + 1)) ? 1 : 0); units2Indx[k] = i & 0xff; } } private int sizeOfFreeList() { return freeList.Length*RarNode.size; } // Debug // public void dumpHeap() { // File file = new File("P:\\test\\heapdumpj"); // OutputStream out = null; // try { // out = new FileOutputStream(file); // out.write(heap, heapStart, heapEnd - heapStart); // out.flush(); // System.out.println("Heap dumped to " + file.getAbsolutePath()); // } // catch (IOException e) { // e.printStackTrace(); // } // finally { // FileUtil.close(out); // } // } // Debug public override System.String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("SubAllocator["); buffer.Append("\n subAllocatorSize="); buffer.Append(subAllocatorSize); buffer.Append("\n glueCount="); buffer.Append(glueCount); buffer.Append("\n heapStart="); buffer.Append(heapStart); buffer.Append("\n loUnit="); buffer.Append(loUnit); buffer.Append("\n hiUnit="); buffer.Append(hiUnit); buffer.Append("\n pText="); buffer.Append(pText); buffer.Append("\n unitsStart="); buffer.Append(unitsStart); buffer.Append("\n]"); return buffer.ToString(); } static SubAllocator() { UNIT_SIZE = System.Math.Max(PPMContext.size, RarMemBlock.size); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace _01bScaffolding.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using System.Text; using PooledStringBuilder = Microsoft.CodeAnalysis.Collections.PooledStringBuilder; using ExceptionUtilities = Roslyn.Utilities.ExceptionUtilities; using System.Reflection; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Displays a value in the C# style. /// </summary> /// <remarks> /// Separate from <see cref="T:Microsoft.CodeAnalysis.CSharp.SymbolDisplay"/> because we want to link this functionality into /// the Formatter project and we don't want it to be public there. /// </remarks> /// <seealso cref="T:Microsoft.CodeAnalysis.VisualBasic.Symbols.ObjectDisplay"/> internal static class ObjectDisplay { /// <summary> /// Returns a C# string literal with the given value. /// </summary> /// <param name="value">The value that the resulting string literal should have.</param> /// <param name="quote">True to put (double) quotes around the string literal.</param> /// <returns>A string literal with the given value.</returns> /// <remarks> /// Escapes non-printable characters. /// </remarks> public static string FormatLiteral(string value, ObjectDisplayOptions options) { if (value == null) { throw new ArgumentNullException("value"); } return FormatString(value, quote ? '"' : '\0', escapeNonPrintable: true); } /// <summary> /// Returns a C# character literal with the given value. /// </summary> /// <param name="c">The value that the resulting character literal should have.</param> /// <param name="quote">True to put (single) quotes around the character literal.</param> /// <returns>A character literal with the given value.</returns> /// <remarks> /// Escapes non-printable characters. /// </remarks> public static string FormatLiteral(char c, ObjectDisplayOptions options) { return FormatLiteral(c, quote, includeCodePoints: false, useHexadecimalNumbers: false); } /// <summary> /// Returns a string representation of an object of primitive type. /// </summary> /// <param name="obj">A value to display as a string.</param> /// <param name="quoteStrings">Whether or not to quote string literals.</param> /// <param name="useHexadecimalNumbers">Whether or not to display integral literals in hexadecimal.</param> /// <returns>A string representation of an object of primitive type (or null if the type is not supported).</returns> /// <remarks> /// Handles <see cref="bool"/>, <see cref="string"/>, <see cref="char"/>, <see cref="sbyte"/> /// <see cref="byte"/>, <see cref="short"/>, <see cref="ushort"/>, <see cref="int"/>, <see cref="uint"/>, /// <see cref="long"/>, <see cref="ulong"/>, <see cref="double"/>, <see cref="float"/>, <see cref="decimal"/>, /// and <c>null</c>. /// </remarks> public static string FormatPrimitive(object obj, bool quoteStrings, bool useHexadecimalNumbers) { if (obj == null) { return NullLiteral; } Type type = obj.GetType(); if (type.GetTypeInfo().IsEnum) { type = Enum.GetUnderlyingType(type); } if (type == typeof(int)) { return FormatLiteral((int)obj, useHexadecimalNumbers); } if (type == typeof(string)) { return FormatLiteral((string)obj, quoteStrings); } if (type == typeof(bool)) { return FormatLiteral((bool)obj); } if (type == typeof(char)) { return FormatLiteral((char)obj, quoteStrings); } if (type == typeof(byte)) { return FormatLiteral((byte)obj, useHexadecimalNumbers); } if (type == typeof(short)) { return FormatLiteral((short)obj, useHexadecimalNumbers); } if (type == typeof(long)) { return FormatLiteral((long)obj, useHexadecimalNumbers); } if (type == typeof(double)) { return FormatLiteral((double)obj); } if (type == typeof(ulong)) { return FormatLiteral((ulong)obj, useHexadecimalNumbers); } if (type == typeof(uint)) { return FormatLiteral((uint)obj, useHexadecimalNumbers); } if (type == typeof(ushort)) { return FormatLiteral((ushort)obj, useHexadecimalNumbers); } if (type == typeof(sbyte)) { return FormatLiteral((sbyte)obj, useHexadecimalNumbers); } if (type == typeof(float)) { return FormatLiteral((float)obj); } if (type == typeof(decimal)) { return FormatLiteral((decimal)obj); } return null; } internal static string NullLiteral { get { return "null"; } } internal static string FormatLiteral(bool value) { return value ? "true" : "false"; } internal static string FormatString(string str, char quote, bool escapeNonPrintable) { PooledStringBuilder pooledBuilder = null; StringBuilder sb = null; int lastEscape = -1; for (int i = 0; i < str.Length; i++) { char c = str[i]; char replaceWith = '\0'; bool unicodeEscape = false; switch (c) { case '\\': replaceWith = c; break; case '\0': replaceWith = '0'; break; case '\r': replaceWith = 'r'; break; case '\n': replaceWith = 'n'; break; case '\t': replaceWith = 't'; break; case '\b': replaceWith = 'b'; break; case '\v': replaceWith = 'v'; break; default: if (quote == c) { replaceWith = c; break; } if (escapeNonPrintable) { switch (CharUnicodeInfo.GetUnicodeCategory(c)) { case UnicodeCategory.OtherNotAssigned: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Control: unicodeEscape = true; break; } } break; } if (unicodeEscape || replaceWith != '\0') { if (pooledBuilder == null) { pooledBuilder = PooledStringBuilder.GetInstance(); sb = pooledBuilder.Builder; if (quote != 0) { sb.Append(quote); } } sb.Append(str, lastEscape + 1, i - (lastEscape + 1)); sb.Append('\\'); if (unicodeEscape) { sb.Append('u'); sb.Append(((int)c).ToString("x4")); } else { sb.Append(replaceWith); } lastEscape = i; } } if (sb != null) { sb.Append(str, lastEscape + 1, str.Length - (lastEscape + 1)); if (quote != 0) { sb.Append(quote); } return pooledBuilder.ToStringAndFree(); } switch (quote) { case '"': return String.Concat("\"", str, "\""); case '\'': return String.Concat("'", str, "'"); case '\0': return str; } throw ExceptionUtilities.Unreachable; } /// <summary> /// Returns a C# character literal with the given value. /// </summary> /// <param name="c">The value that the resulting character literal should have.</param> /// <param name="quote">True to put (single) quotes around the character literal.</param> /// <param name="includeCodePoints">True to include the code point before the character literal.</param> /// <param name="useHexadecimalNumbers">True to use hexadecimal for the code point. Ignored if <paramref name="includeCodePoints"/> is false.</param> /// <returns>A character literal with the given value.</returns> internal static string FormatLiteral(char c, bool quote, bool includeCodePoints, bool useHexadecimalNumbers) { var result = FormatString(c.ToString(), quote ? '\'' : '\0', escapeNonPrintable: !includeCodePoints); if (includeCodePoints) { var codepoint = useHexadecimalNumbers ? "0x" + ((int)c).ToString("x4") : ((int)c).ToString(); return codepoint + " " + result; } return result; } internal static string FormatLiteral(sbyte value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { // Special Case: for sbyte and short, specifically, negatives are shown // with extra precision. return "0x" + (value >= 0 ? value.ToString("x2") : ((int)value).ToString("x8")); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(byte value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x2"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(short value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { // Special Case: for sbyte and short, specifically, negatives are shown // with extra precision. return "0x" + (value >= 0 ? value.ToString("x4") : ((int)value).ToString("x8")); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(ushort value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x4"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(int value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x8"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(uint value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x8"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(long value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x16"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(ulong value, bool useHexadecimalNumbers) { if (useHexadecimalNumbers) { return "0x" + value.ToString("x16"); } else { return value.ToString(CultureInfo.InvariantCulture); } } internal static string FormatLiteral(double value) { return value.ToString("R", CultureInfo.InvariantCulture); } internal static string FormatLiteral(float value) { return value.ToString("R", CultureInfo.InvariantCulture); } internal static string FormatLiteral(decimal value) { return value.ToString(CultureInfo.InvariantCulture); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core.Pipeline; namespace Azure.Core { /// <summary> /// A helper class used to build long-running operation instances. In order to use this helper: /// <list type="number"> /// <item>Make sure your LRO implements the <see cref="IOperation{T}"/> interface.</item> /// <item>Add a private <see cref="OperationInternal{T}"/> field to your LRO, and instantiate it during construction.</item> /// <item>Delegate method calls to the <see cref="OperationInternal{T}"/> implementations.</item> /// </list> /// Supported members: /// <list type="bullet"> /// <item><see cref="HasValue"/></item> /// <item><see cref="HasCompleted"/></item> /// <item><see cref="Value"/></item> /// <item><see cref="RawResponse"/>, used for <see cref="Operation.GetRawResponse"/></item> /// <item><see cref="UpdateStatus"/></item> /// <item><see cref="UpdateStatusAsync(CancellationToken)"/></item> /// <item><see cref="WaitForCompletionAsync(CancellationToken)"/></item> /// <item><see cref="WaitForCompletionAsync(TimeSpan, CancellationToken)"/></item> /// </list> /// </summary> /// <typeparam name="T">The final result of the long-running operation. Must match the type used in <see cref="Operation{T}"/>.</typeparam> internal class OperationInternal<T> { private const string RetryAfterHeaderName = "Retry-After"; private const string RetryAfterMsHeaderName = "retry-after-ms"; private const string XRetryAfterMsHeaderName = "x-ms-retry-after-ms"; private readonly IOperation<T> _operation; private readonly ClientDiagnostics _diagnostics; private readonly string _updateStatusScopeName; private readonly IReadOnlyDictionary<string, string> _scopeAttributes; private T _value; private RequestFailedException _operationFailedException; /// <summary> /// Initializes a new instance of the <see cref="OperationInternal{T}"/> class. /// </summary> /// <param name="clientDiagnostics">Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client.</param> /// <param name="operation">The long-running operation making use of this class. Passing "<c>this</c>" is expected.</param> /// <param name="rawResponse"> /// The initial value of <see cref="RawResponse"/>. Usually, long-running operation objects can be instantiated in two ways: /// <list type="bullet"> /// <item> /// When calling a client's "<c>Start&lt;OperationName&gt;</c>" method, a service call is made to start the operation, and an <see cref="Operation{T}"/> instance is returned. /// In this case, the response received from this service call can be passed here. /// </item> /// <item> /// When a user instantiates an <see cref="Operation{T}"/> directly using a public constructor, there's no previous service call. In this case, passing <c>null</c> is expected. /// </item> /// </list> /// </param> /// <param name="operationTypeName"> /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left <c>null</c>, the type name will be inferred based on the /// parameter <paramref name="operation"/>. /// </param> /// <param name="scopeAttributes">The attributes to use during diagnostic scope creation.</param> public OperationInternal(ClientDiagnostics clientDiagnostics, IOperation<T> operation, Response rawResponse, string operationTypeName = null, IEnumerable<KeyValuePair<string, string>> scopeAttributes = null) { operationTypeName ??= operation.GetType().Name; _operation = operation; _diagnostics = clientDiagnostics; _updateStatusScopeName = $"{operationTypeName}.UpdateStatus"; _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); RawResponse = rawResponse; DefaultPollingInterval = TimeSpan.FromSeconds(1); } /// <summary> /// Returns <c>true</c> if the long-running operation completed successfully and has produced a final result. /// <example>Usage example: /// <code> /// public bool HasValue => _operationInternal.HasValue; /// </code> /// </example> /// </summary> public bool HasValue { get; private set; } /// <summary> /// Returns <c>true</c> if the long-running operation has completed. /// <example>Usage example: /// <code> /// public bool HasCompleted => _operationInternal.HasCompleted; /// </code> /// </example> /// </summary> public bool HasCompleted { get; private set; } /// <summary> /// The final result of the long-running operation. /// <example>Usage example: /// <code> /// public T Value => _operationInternal.Value; /// </code> /// </example> /// </summary> /// <exception cref="InvalidOperationException">Thrown when the operation has not completed yet.</exception> /// <exception cref="RequestFailedException">Thrown when the operation has completed with failures.</exception> public T Value { get { if (HasValue) { return _value; } else if (_operationFailedException != null) { throw _operationFailedException; } else { throw new InvalidOperationException("The operation has not completed yet."); } } private set { _value = value; HasValue = true; } } /// <summary> /// The last HTTP response received from the server. Its update already handled in calls to "<c>UpdateStatus</c>" and /// "<c>WaitForCompletionAsync</c>", but custom methods not supported by this class, such as "<c>CancelOperation</c>", /// must update it as well. /// <example>Usage example: /// <code> /// public Response GetRawResponse() => _operationInternal.RawResponse; /// </code> /// </example> /// </summary> public Response RawResponse { get; set; } /// <summary> /// Can be set to control the default interval used between service calls in <see cref="WaitForCompletionAsync(CancellationToken)"/>. /// Defaults to 1 second. /// </summary> public TimeSpan DefaultPollingInterval { get; set; } /// <summary> /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed /// tracing. The default scope name can be changed with the "<c>operationTypeName</c>" parameter passed to the constructor. /// <example>Usage example: /// <code> /// public async ValueTask&lt;Response&gt; UpdateStatusAsync(CancellationToken cancellationToken) => /// await _operationInternal.UpdateStatusAsync(cancellationToken).ConfigureAwait(false); /// </code> /// </example> /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The HTTP response received from the server.</returns> /// <remarks> /// After a successful run, this method will update <see cref="RawResponse"/> and might update <see cref="HasCompleted"/>, /// <see cref="HasValue"/>, and <see cref="Value"/>. /// </remarks> /// <exception cref="RequestFailedException">Thrown if there's been any issues during the connection, or if the operation has completed with failures.</exception> public async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken) => await UpdateStatusAsync(async: true, cancellationToken).ConfigureAwait(false); /// <summary> /// Calls the server to get the latest status of the long-running operation, handling diagnostic scope creation for distributed /// tracing. The default scope name can be changed with the "<c>operationTypeName</c>" parameter passed to the constructor. /// <example>Usage example: /// <code> /// public Response UpdateStatus(CancellationToken cancellationToken) => _operationInternal.UpdateStatus(cancellationToken); /// </code> /// </example> /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The HTTP response received from the server.</returns> /// <remarks> /// After a successful run, this method will update <see cref="RawResponse"/> and might update <see cref="HasCompleted"/>, /// <see cref="HasValue"/>, and <see cref="Value"/>. /// </remarks> /// <exception cref="RequestFailedException">Thrown if there's been any issues during the connection, or if the operation has completed with failures.</exception> public Response UpdateStatus(CancellationToken cancellationToken) => UpdateStatusAsync(async: false, cancellationToken).EnsureCompleted(); /// <summary> /// Periodically calls <see cref="UpdateStatusAsync(CancellationToken)"/> until the long-running operation completes. The interval /// between calls is defined by the property <see cref="DefaultPollingInterval"/>, but it can change based on information returned /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll /// for status change until the specified time has passed. In this case, the maximum value between the <see cref="DefaultPollingInterval"/> /// property and the retry-after header is choosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", /// and "x-ms-retry-after-ms". /// <example>Usage example: /// <code> /// public async ValueTask&lt;Response&lt;T&gt;&gt; WaitForCompletionAsync(CancellationToken cancellationToken) => /// await _operationInternal.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); /// </code> /// </example> /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The last HTTP response received from the server, including the final result of the long-running operation.</returns> /// <exception cref="RequestFailedException">Thrown if there's been any issues during the connection, or if the operation has completed with failures.</exception> public async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken) => await WaitForCompletionAsync(DefaultPollingInterval, cancellationToken).ConfigureAwait(false); /// <summary> /// Periodically calls <see cref="UpdateStatusAsync(CancellationToken)"/> until the long-running operation completes. The interval /// between calls is defined by the parameter <paramref name="pollingInterval"/>, but it can change based on information returned /// from the server. After each service call, a retry-after header may be returned to communicate that there is no reason to poll /// for status change until the specified time has passed. In this case, the maximum value between the <paramref name="pollingInterval"/> /// parameter and the retry-after header is choosen as the wait interval. Headers supported are: "Retry-After", "retry-after-ms", /// and "x-ms-retry-after-ms". /// <example>Usage example: /// <code> /// public async ValueTask&lt;Response&lt;T&gt;&gt; WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) => /// await _operationInternal.WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(false); /// </code> /// </example> /// </summary> /// <param name="pollingInterval">The interval between status requests to the server.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The last HTTP response received from the server, including the final result of the long-running operation.</returns> /// <exception cref="RequestFailedException">Thrown if there's been any issues during the connection, or if the operation has completed with failures.</exception> public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken) { while (true) { Response response = await UpdateStatusAsync(cancellationToken).ConfigureAwait(false); if (HasCompleted) { return Response.FromValue(Value, response); } TimeSpan serverDelay = GetServerDelay(response); TimeSpan delay = serverDelay > pollingInterval ? serverDelay : pollingInterval; await WaitAsync(delay, cancellationToken).ConfigureAwait(false); } } protected virtual async Task WaitAsync(TimeSpan delay, CancellationToken cancellationToken) => await Task.Delay(delay, cancellationToken).ConfigureAwait(false); private async ValueTask<Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken) { using DiagnosticScope scope = _diagnostics.CreateScope(_updateStatusScopeName); if (_scopeAttributes != null) { foreach (KeyValuePair<string, string> attribute in _scopeAttributes) { scope.AddAttribute(attribute.Key, attribute.Value); } } scope.Start(); try { return await UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } private async ValueTask<Response> UpdateStateAsync(bool async, CancellationToken cancellationToken) { OperationState<T> state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); RawResponse = state.RawResponse; if (state.HasCompleted) { if (state.HasSucceeded) { Value = state.Value; HasCompleted = true; } else { _operationFailedException = state.OperationFailedException ?? (async ? await _diagnostics.CreateRequestFailedExceptionAsync(state.RawResponse).ConfigureAwait(false) : _diagnostics.CreateRequestFailedException(state.RawResponse)); HasCompleted = true; throw _operationFailedException; } } return state.RawResponse; } private static TimeSpan GetServerDelay(Response response) { if (response.Headers.TryGetValue(RetryAfterMsHeaderName, out string retryAfterValue) || response.Headers.TryGetValue(XRetryAfterMsHeaderName, out retryAfterValue)) { if (int.TryParse(retryAfterValue, out int serverDelayInMilliseconds)) { return TimeSpan.FromMilliseconds(serverDelayInMilliseconds); } } if (response.Headers.TryGetValue(RetryAfterHeaderName, out retryAfterValue)) { if (int.TryParse(retryAfterValue, out int serverDelayInSeconds)) { return TimeSpan.FromSeconds(serverDelayInSeconds); } } return TimeSpan.Zero; } } /// <summary> /// An interface used by <see cref="OperationInternal{T}"/> for making service calls and updating state. It's expected that /// your long-running operation classes implement this interface. /// </summary> /// <typeparam name="T">The final result of the long-running operation. Must match the type used in <see cref="Operation{T}"/>.</typeparam> internal interface IOperation<T> { /// <summary> /// Calls the service and updates the state of the long-running operation. Properties directly handled by the /// <see cref="OperationInternal{T}"/> class, such as <see cref="OperationInternal{T}.RawResponse"/> or /// <see cref="OperationInternal{T}.Value"/>, don't need to be updated. Operation-specific properties, such /// as "<c>CreateOn</c>" or "<c>LastModified</c>", must be manually updated by the operation implementing this /// method. /// <example>Usage example: /// <code> /// async ValueTask&lt;OperationState&lt;T&gt;&gt; IOperation&lt;T&gt;.UpdateStateAsync(bool async, CancellationToken cancellationToken)<br/> /// {<br/> /// Response&lt;R&gt; response = async ? &lt;async service call&gt; : &lt;sync service call&gt;;<br/> /// if (&lt;operation succeeded&gt;) return OperationState&lt;T&gt;.Success(response.GetRawResponse(), &lt;parse response&gt;);<br/> /// if (&lt;operation failed&gt;) return OperationState&lt;T&gt;.Failure(response.GetRawResponse());<br/> /// return OperationState&lt;T&gt;.Pending(response.GetRawResponse());<br/> /// } /// </code> /// </example> /// </summary> /// <param name="async"><c>true</c> if the call should be executed asynchronously. Otherwise, <c>false</c>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns> /// A structure indicating the current operation state. The <see cref="OperationState{T}"/> structure must be instantiated by one of /// its static methods: /// <list type="bullet"> /// <item>Use <see cref="OperationState{T}.Success"/> when the operation has completed successfully.</item> /// <item>Use <see cref="OperationState{T}.Failure"/> when the operation has completed with failures.</item> /// <item>Use <see cref="OperationState{T}.Pending"/> when the operation has not completed yet.</item> /// </list> /// </returns> ValueTask<OperationState<T>> UpdateStateAsync(bool async, CancellationToken cancellationToken); } /// <summary> /// A helper structure passed to <see cref="OperationInternal{T}"/> to indicate the current operation state. This structure must be /// instantiated by one of its static methods, depending on the operation state: /// <list type="bullet"> /// <item>Use <see cref="OperationState{T}.Success"/> when the operation has completed successfully.</item> /// <item>Use <see cref="OperationState{T}.Failure"/> when the operation has completed with failures.</item> /// <item>Use <see cref="OperationState{T}.Pending"/> when the operation has not completed yet.</item> /// </list> /// </summary> /// <typeparam name="T">The final result of the long-running operation. Must match the type used in <see cref="Operation{T}"/>.</typeparam> internal readonly struct OperationState<T> { private OperationState(Response rawResponse, bool hasCompleted, bool hasSucceeded, T value, RequestFailedException operationFailedException) { RawResponse = rawResponse; HasCompleted = hasCompleted; HasSucceeded = hasSucceeded; Value = value; OperationFailedException = operationFailedException; } public Response RawResponse { get; } public bool HasCompleted { get; } public bool HasSucceeded { get; } public T Value { get; } public RequestFailedException OperationFailedException { get; } /// <summary> /// Instantiates an <see cref="OperationState{T}"/> indicating the operation has completed successfully. /// </summary> /// <param name="rawResponse">The HTTP response obtained during the status update.</param> /// <param name="value">The final result of the long-running operation.</param> /// <returns>A new <see cref="OperationState{T}"/> instance.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="rawResponse"/> or <paramref name="value"/> is <c>null</c>.</exception> public static OperationState<T> Success(Response rawResponse, T value) { Argument.AssertNotNull(rawResponse, nameof(rawResponse)); if (value is null) { throw new ArgumentNullException(nameof(value)); } return new OperationState<T>(rawResponse, true, true, value, default); } /// <summary> /// Instantiates an <see cref="OperationState{T}"/> indicating the operation has completed with failures. /// </summary> /// <param name="rawResponse">The HTTP response obtained during the status update.</param> /// <param name="operationFailedException"> /// The exception to throw from <c>UpdateStatus</c> because of the operation failure. The same exception will be thrown when /// <see cref="OperationInternal{T}.Value"/> is called. If left <c>null</c>, a default exception is created based on the /// <paramref name="rawResponse"/> parameter. /// </param> /// <returns>A new <see cref="OperationState{T}"/> instance.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="rawResponse"/> is <c>null</c>.</exception> public static OperationState<T> Failure(Response rawResponse, RequestFailedException operationFailedException = null) { Argument.AssertNotNull(rawResponse, nameof(rawResponse)); return new OperationState<T>(rawResponse, true, false, default, operationFailedException); } /// <summary> /// Instantiates an <see cref="OperationState{T}"/> indicating the operation has not completed yet. /// </summary> /// <param name="rawResponse">The HTTP response obtained during the status update.</param> /// <returns>A new <see cref="OperationState{T}"/> instance.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="rawResponse"/> is <c>null</c>.</exception> public static OperationState<T> Pending(Response rawResponse) { Argument.AssertNotNull(rawResponse, nameof(rawResponse)); return new OperationState<T>(rawResponse, false, default, default, default); } } }
#region Using using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Windows.Forms; using TribalWars.Browsers.Control; using Janus.Windows.UI.CommandBars; using System.Drawing; using System.Linq; using TribalWars.Controls; using TribalWars.Maps; using TribalWars.Maps.AttackPlans; using TribalWars.Maps.AttackPlans.EventArg; using TribalWars.Maps.Manipulators.Implementations.Church; using TribalWars.Maps.Manipulators.Managers; using TribalWars.Tools; using TribalWars.Tools.JanusExtensions; using TribalWars.Villages.Units; using TribalWars.Worlds; using TribalWars.Worlds.Events; #endregion namespace TribalWars.Villages.ContextMenu { /// <summary> /// ContextMenu with general Village operations /// </summary> public class VillageContextMenu : IContextMenu { #region Constants /// <summary> /// Hack for forcing the MainForm to open the details quickpane /// </summary> public const string OnDetailsHack = "HACK_SWITCH_TO_DETAILS_PANE"; #endregion #region Fields private readonly Village _village; private readonly UIContextMenu _menu; private readonly Map _map; private readonly Action _onVillageTypeChangeDelegate; private readonly AttackPlan _attackPlan; private readonly AttackPlanFrom _attacker; private readonly bool _isActiveAttackPlan; #endregion #region Constructors public VillageContextMenu(Map map, Village village, Action onVillageTypeChangeDelegate = null) { _village = village; _map = map; _onVillageTypeChangeDelegate = onVillageTypeChangeDelegate; _attackPlan = World.Default.Map.Manipulators.AttackManipulator.GetPlan(_village, out _isActiveAttackPlan, out _attacker, false); _menu = JanusContextMenu.Create(); AddAttackPlanItems(); _menu.AddSeparator(); if (map.Display.IsVisible(village)) { _menu.AddCommand(ControlsRes.ContextMenu_QuickDetails, OnPinPoint, Properties.Resources.LeftNavigation_QuickFind); } _menu.AddCommand(ControlsRes.ContextMenu_PinpointAndCenter, OnPinpointAndCenter, Properties.Resources.TeleportIcon); _menu.AddSeparator(); _menu.AddSetVillageTypeCommand(OnVillageTypeChange, village); if (World.Default.Settings.Church) { var church = _map.Manipulators.ChurchManipulator.GetChurch(_village); AddChurchCommands(_menu, church, ChurchChange_Click); } if (village.HasPlayer) { _menu.AddSeparator(); _menu.AddPlayerContextCommands(map, village.Player, false); if (village.HasTribe) { _menu.AddTribeContextCommands(map, village.Player.Tribe); } if (village.PreviousVillageDetails != null && village.PreviousVillageDetails.Player != village.Player && village.PreviousVillageDetails.Player != null) { var oldPlayer = World.Default.GetPlayer(village.PreviousVillageDetails.Player.Name); _menu.AddPlayerNobledContextCommands(map, oldPlayer ?? village.PreviousVillageDetails.Player, true); } } _menu.AddSeparator(); _menu.AddCommand(ControlsRes.ContextMenu_TwStats, OnTwStats); _menu.AddCommand(ControlsRes.ContextMenu_ToClipboard, OnToClipboard, Properties.Resources.clipboard); _menu.AddCommand(ControlsRes.ContextMenu_ToBbCode, OnBbCode, Properties.Resources.clipboard); } private void AddAttackPlanItems() { bool isAttackPlannerActive = World.Default.Map.Manipulators.AttackManipulator == World.Default.Map.Manipulators.CurrentManipulator; if (isAttackPlannerActive && _attacker != null) { _menu.AddCommand(ControlsRes.VillageContextMenu_AddToAttackPlan, OnAddAttacker, UnitImages.Ram); if (_isActiveAttackPlan && _attacker != null) { _menu.AddCommand(ControlsRes.VillageContextMenu_DeleteFromAttackPlan, OnDeleteAttacker, Properties.Resources.Delete); } _menu.AddSeparator(); } if (_attackPlan != null) { int planCount = World.Default.Map.Manipulators.AttackManipulator.GetPlans().Count(x => x.Target == _village || x.Attacks.Any(attack => attack.Attacker == _village)); if (!_isActiveAttackPlan || planCount > 1) { string selectPlan = ControlsRes.VillageContextMenu_SelectAttackPlan; if (planCount > 1) { selectPlan += string.Format(" ({0})", planCount); } _menu.AddCommand(selectPlan, OnSelectAttackPlan, Properties.Resources.FlagGreen); } AddAttackPlanNewItem(); if (isAttackPlannerActive && (_isActiveAttackPlan || planCount > 0) && _attacker == null) { _menu.AddCommand(ControlsRes.VillageContextMenu_DeleteAttackPlan, OnDeleteAttackPlan, Properties.Resources.Delete); } } else { AddAttackPlanNewItem(); } } private void AddAttackPlanNewItem() { if (World.Default.You == _village.Player || (World.Default.You.HasTribe && _village.HasTribe && World.Default.You.Tribe == _village.Player.Tribe)) { _menu.AddCommand(ControlsRes.VillageContextMenu_NewAttackPlan, OnAttack, Properties.Resources.Defense); } else { _menu.AddCommand(ControlsRes.VillageContextMenu_NewAttackPlan, OnAttack, Buildings.BuildingImages.Barracks); } } public static void AddChurchCommands(UIContextMenu menu, ChurchInfo church, CommandEventHandler handler) { Debug.Assert(World.Default.Settings.Church); string commandText = ControlsRes.Church + (church == null ? "" : string.Format(" ({0})", church.ChurchLevel)); var containerCommand = new UICommand("", commandText) { Image = Properties.Resources.Church }; containerCommand.Commands.AddRange(CreateChurchLevelCommands(handler, church)); if (church != null) { containerCommand.Commands.AddSeparator(); containerCommand.Commands.AddChangeColorCommand("Color", church.Color, ChurchInfo.DefaultColor, (sender, selectedColor) => church.Color = selectedColor); } menu.Commands.Add(containerCommand); } private static UICommand[] CreateChurchLevelCommands(CommandEventHandler handler, ChurchInfo church) { var churchLevelCommands = new List<UICommand>(); for (int i = 0; i <= 3; i++) { churchLevelCommands.Add(CreateChurchLevelCommand(handler, i, church == null ? -1 : church.ChurchLevel)); } return churchLevelCommands.ToArray(); } private static UICommand CreateChurchLevelCommand(CommandEventHandler handler, int level, int churchLevel) { string text = level == 0 ? ControlsRes.Church_None : string.Format(ControlsRes.Church_Level, level); var cmd = new UICommand("", text) { IsChecked = level == churchLevel, Tag = level }; cmd.Click += handler; return cmd; } #endregion #region Public Methods /// <summary> /// Shows the ContextMenuStrip /// </summary> public void Show(Control control, Point position) { _menu.Show(control, position); } public bool IsVisible() { return _menu.IsVisible; } #endregion #region EventHandlers private void ChurchChange_Click(object sender, CommandEventArgs e) { var level = (int) e.Command.Tag; _map.EventPublisher.ChurchChange(_village, level); if (_onVillageTypeChangeDelegate != null) { _onVillageTypeChangeDelegate(); } } private void OnVillageTypeChange(object sender, CommandEventArgs e) { var changeTo = (VillageType)e.Command.Tag; _village.TogglePurpose(changeTo); _map.Invalidate(); if (_onVillageTypeChangeDelegate != null) { _onVillageTypeChangeDelegate(); } } /// <summary> /// Pinpoints and centers the target village /// </summary> private void OnPinpointAndCenter(object sender, CommandEventArgs e) { World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default); World.Default.Map.EventPublisher.SelectVillages(OnDetailsHack, _village, VillageTools.PinPoint); World.Default.Map.SetCenter(_village.Location); } /// <summary> /// Select village on the map /// </summary> private void OnPinPoint(object sender, CommandEventArgs e) { World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Default); World.Default.Map.EventPublisher.SelectVillages(OnDetailsHack, _village, VillageTools.PinPoint); } /// <summary> /// Put village location on clipboard /// </summary> private void OnToClipboard(object sender, CommandEventArgs e) { WinForms.ToClipboard(_village.LocationString); } /// <summary> /// Put village BBCode on clipboard /// </summary> private void OnBbCode(object sender, CommandEventArgs e) { WinForms.ToClipboard(_village.BbCode()); } /// <summary> /// Browses to the target village /// </summary> private void OnTwStats(object sender, CommandEventArgs e) { World.Default.EventPublisher.BrowseUri(null, DestinationEnum.TwStatsVillage, _village.Id.ToString(CultureInfo.InvariantCulture)); } private void OnAttack(object sender, CommandEventArgs e) { World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack); World.Default.Map.EventPublisher.AttackAddTarget(this, _village); } private void OnDeleteAttackPlan(object sender, CommandEventArgs e) { World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack); World.Default.Map.EventPublisher.AttackRemoveTarget(this, _attackPlan); } private void OnAddAttacker(object sender, CommandEventArgs e) { Debug.Assert(World.Default.Map.Manipulators.AttackManipulator.ActivePlan != null && _village != null); World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack); World.Default.Map.EventPublisher.AttackUpdateTarget(this, AttackUpdateEventArgs.AddAttackFrom(new AttackPlanFrom(World.Default.Map.Manipulators.AttackManipulator.ActivePlan, _village, WorldUnits.Default[World.Default.Map.Manipulators.AttackManipulator.DefaultSpeed]))); } private void OnDeleteAttacker(object sender, CommandEventArgs e) { Debug.Assert(_attacker != null); World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack); World.Default.Map.EventPublisher.AttackUpdateTarget(this, AttackUpdateEventArgs.DeleteAttackFrom(_attacker)); } private void OnSelectAttackPlan(object sender, CommandEventArgs e) { World.Default.Map.Manipulators.SetManipulator(ManipulatorManagerTypes.Attack); AttackPlanFrom dummy; bool dummy2; var nextPlan = World.Default.Map.Manipulators.AttackManipulator.GetPlan(_village, out dummy2, out dummy, true); World.Default.Map.EventPublisher.AttackSelect(this, nextPlan); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// This is the default XPath/XQuery data model cache implementation. It will be used whenever /// the user does not supply his own XPathNavigator implementation. /// </summary> internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo { private XPathNode[] _pageCurrent; private XPathNode[] _pageParent; private int _idxCurrent; private int _idxParent; private string _atomizedLocalName; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed /// text node, then the parent is a virtualized parent (may be different than .Parent on the current node). /// </summary> public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) { Debug.Assert(pageCurrent != null && idxCurrent != 0); Debug.Assert((pageParent == null) == (idxParent == 0)); _pageCurrent = pageCurrent; _pageParent = pageParent; _idxCurrent = idxCurrent; _idxParent = idxParent; } /// <summary> /// Copy constructor. /// </summary> public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent) { _atomizedLocalName = nav._atomizedLocalName; } //----------------------------------------------- // XPathItem //----------------------------------------------- /// <summary> /// Get the string value of the current node, computed using data model dm:string-value rules. /// If the node has a typed value, return the string representation of the value. If the node /// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise, /// concatenate all text node descendants of the current node. /// </summary> public override string Value { get { string value; XPathNode[] page, pageEnd; int idx, idxEnd; // Try to get the pre-computed string value of the node value = _pageCurrent[_idxCurrent].Value; if (value != null) return value; #if DEBUG switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: Debug.Fail("ReadStringValue() should have taken care of these node types."); break; case XPathNodeType.Text: Debug.Assert(_idxParent != 0 && _pageParent[_idxParent].HasCollapsedText, "ReadStringValue() should have taken care of anything but collapsed text."); break; } #endif // If current node is collapsed text, then parent element has a simple text value if (_idxParent != 0) { Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text); return _pageParent[_idxParent].Value; } // Must be node with complex content, so concatenate the string values of all text descendants string s = string.Empty; StringBuilder bldr = null; // Get all text nodes which follow the current node in document order, but which are still descendants page = pageEnd = _pageCurrent; idx = idxEnd = _idxCurrent; if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) { pageEnd = null; idxEnd = 0; } while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) { Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText); if (s.Length == 0) { s = page[idx].Value; } else { if (bldr == null) { bldr = new StringBuilder(); bldr.Append(s); } bldr.Append(page[idx].Value); } } return (bldr != null) ? bldr.ToString() : s; } } //----------------------------------------------- // XPathNavigator //----------------------------------------------- /// <summary> /// Create a copy of this navigator, positioned to the same node in the tree. /// </summary> public override XPathNavigator Clone() { return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent); } /// <summary> /// Get the XPath node type of the current node. /// </summary> public override XPathNodeType NodeType { get { return _pageCurrent[_idxCurrent].NodeType; } } /// <summary> /// Get the local name portion of the current node's name. /// </summary> public override string LocalName { get { return _pageCurrent[_idxCurrent].LocalName; } } /// <summary> /// Get the namespace portion of the current node's name. /// </summary> public override string NamespaceURI { get { return _pageCurrent[_idxCurrent].NamespaceUri; } } /// <summary> /// Get the name of the current node. /// </summary> public override string Name { get { return _pageCurrent[_idxCurrent].Name; } } /// <summary> /// Get the prefix portion of the current node's name. /// </summary> public override string Prefix { get { return _pageCurrent[_idxCurrent].Prefix; } } /// <summary> /// Get the base URI of the current node. /// </summary> public override string BaseURI { get { XPathNode[] page; int idx; if (_idxParent != 0) { // Get BaseUri of parent for attribute, namespace, and collapsed text nodes page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } do { switch (page[idx].NodeType) { case XPathNodeType.Element: case XPathNodeType.Root: case XPathNodeType.ProcessingInstruction: // BaseUri is always stored with Elements, Roots, and PIs return page[idx].BaseUri; } // Get BaseUri of parent idx = page[idx].GetParent(out page); } while (idx != 0); return string.Empty; } } /// <summary> /// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form. /// </summary> public override bool IsEmptyElement { get { return _pageCurrent[_idxCurrent].AllowShortcutTag; } } /// <summary> /// Return the xml name table which was used to atomize all prefixes, local-names, and /// namespace uris in the document. /// </summary> public override XmlNameTable NameTable { get { return _pageCurrent[_idxCurrent].Document.NameTable; } } /// <summary> /// Position the navigator on the first attribute of the current node and return true. If no attributes /// can be found, return false. /// </summary> public override bool MoveToFirstAttribute() { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found, /// return false. /// </summary> public override bool MoveToNextAttribute() { return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// True if the current node has one or more attributes. /// </summary> public override bool HasAttributes { get { return _pageCurrent[_idxCurrent].HasAttribute; } } /// <summary> /// Position the navigator on the attribute with the specified name and return true. If no matching /// attribute can be found, return false. Don't assume the name parts are atomized with respect /// to this document. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// Position the navigator on the namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { XPathNode[] page; int idx; if (namespaceScope == XPathNamespaceScope.Local) { // Get local namespaces only idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page); } else { // Get all in-scope namespaces idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page); } while (idx != 0) { // Don't include the xmlns:xml namespace node if scope is ExcludeXml if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) { _pageParent = _pageCurrent; _idxParent = _idxCurrent; _pageCurrent = page; _idxCurrent = idx; return true; } // Skip past xmlns:xml idx = page[idx].GetSibling(out page); } return false; } /// <summary> /// Position the navigator on the next namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XPathNode[] page = _pageCurrent, pageParent; int idx = _idxCurrent, idxParent; // If current node is not a namespace node, return false if (page[idx].NodeType != XPathNodeType.Namespace) return false; while (true) { // Get next namespace sibling idx = page[idx].GetSibling(out page); // If there are no more nodes, return false if (idx == 0) return false; switch (scope) { case XPathNamespaceScope.Local: // Once parent changes, there are no longer any local namespaces idxParent = page[idx].GetParent(out pageParent); if (idxParent != _idxParent || (object)pageParent != (object)_pageParent) return false; break; case XPathNamespaceScope.ExcludeXml: // If node is xmlns:xml, then skip it if (page[idx].IsXmlNamespaceNode) continue; break; } // Found a matching next namespace node, so return it break; } _pageCurrent = page; _idxCurrent = idx; return true; } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the next content node. Return false if there are no more content nodes. /// </summary> public override bool MoveToNext() { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the previous (sibling) content node. Return false if there are no previous content nodes. /// </summary> public override bool MoveToPrevious() { // If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do // not have previous siblings. if (_idxParent != 0) return false; return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Move to the first content-typed child of the current node. Return false if the current /// node has no content children. /// </summary> public override bool MoveToFirstChild() { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position the navigator on the parent of the current node. If the current node has no parent, /// return false. /// </summary> public override bool MoveToParent() { if (_idxParent != 0) { // 1. For attribute nodes, element parent is always stored in order to make node-order // comparison simpler. // 2. For namespace nodes, parent is always stored in navigator in order to virtualize // XPath 1.0 namespaces. // 3. For collapsed text nodes, element parent is always stored in navigator. Debug.Assert(_pageParent != null); _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position this navigator to the same position as the "other" navigator. If the "other" navigator /// is not of the same type as this navigator, then return false. /// </summary> public override bool MoveTo(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { _pageCurrent = that._pageCurrent; _idxCurrent = that._idxCurrent; _pageParent = that._pageParent; _idxParent = that._idxParent; return true; } return false; } /// <summary> /// Position to the navigator to the element whose id is equal to the specified "id" string. /// </summary> public override bool MoveToId(string id) { XPathNode[] page; int idx; idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page); if (idx != 0) { // Move to ID element and clear parent state Debug.Assert(page[idx].NodeType == XPathNodeType.Element); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; return true; } return false; } /// <summary> /// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false /// if not, or if the "other" navigator is not the same type as this navigator. /// </summary> public override bool IsSamePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent && _idxParent == that._idxParent && _pageParent == that._pageParent; } return false; } /// <summary> /// Returns true if the current node has children. /// </summary> public override bool HasChildren { get { return _pageCurrent[_idxCurrent].HasContentChild; } } /// <summary> /// Position the navigator on the root node of the current document. /// </summary> public override void MoveToRoot() { if (_idxParent != 0) { // Clear parent state _pageParent = null; _idxParent = 0; } _idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent); } /// <summary> /// Move to the first element child of the current node with the specified name. Return false /// if the current node has no matching element children. /// </summary> public override bool MoveToChild(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first element sibling of the current node with the specified name. Return false /// if the current node has no matching element siblings. /// </summary> public override bool MoveToNext(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first content child of the current node with the specified type. Return false /// if the current node has no matching children. /// </summary> public override bool MoveToChild(XPathNodeType type) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node if (type != XPathNodeType.Text && type != XPathNodeType.All) return false; // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the first content sibling of the current node with the specified type. Return false /// if the current node has no matching siblings. /// </summary> public override bool MoveToNext(XPathNodeType type) { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the next element that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// Return false if the current node has no matching following elements. /// </summary> public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNode[] pageEnd; int idxEnd; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Get node on which scan ends (null if rest of document should be scanned) idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType /// Return false if the current node has no matching following nodes. /// </summary> public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathDocumentNavigator endTiny = end as XPathDocumentNavigator; XPathNode[] page, pageEnd; int idx, idxEnd; // If searching for text, make sure to handle collapsed text nodes correctly if (type == XPathNodeType.Text || type == XPathNodeType.All) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end" if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent) { // "end" is positioned to a virtual attribute, namespace, or text node return false; } _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } if (type == XPathNodeType.Text) { // Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, true, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } // If ending node is a virtual node, and current node is its parent, then we're done if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd) return false; // Get all virtual (collapsed) and physical text nodes which follow the current node if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) return false; if (page[idx].NodeType == XPathNodeType.Element) { // Virtualize collapsed text nodes Debug.Assert(page[idx].HasCollapsedText); _idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent); _pageParent = page; _idxParent = idx; } else { // Physical text node Debug.Assert(page[idx].IsText); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; } return true; } } // Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType. /// </summary> public override XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathDocumentKindChildIterator(this, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified QName. /// </summary> public override XPathNodeIterator SelectChildren(string name, string namespaceURI) { // If local name is wildcard, then call XPathNavigator.SelectChildren if (name == null || name.Length == 0) return base.SelectChildren(name, namespaceURI); return new XPathDocumentElementChildIterator(this, name, namespaceURI); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// XPathNodeType. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDocumentKindDescendantIterator(this, type, matchSelf); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// QName. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { // If local name is wildcard, then call XPathNavigator.SelectDescendants if (name == null || name.Length == 0) return base.SelectDescendants(name, namespaceURI, matchSelf); return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf); } /// <summary> /// Returns: /// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the /// navigator's are not positioned on nodes in the same document. /// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node /// in document order. /// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node /// in document order. /// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator. /// </summary> public override XmlNodeOrder ComparePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document; XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document; if ((object)thisDoc == (object)thatDoc) { int locThis = GetPrimaryLocation(); int locThat = that.GetPrimaryLocation(); if (locThis == locThat) { locThis = GetSecondaryLocation(); locThat = that.GetSecondaryLocation(); if (locThis == locThat) return XmlNodeOrder.Same; } return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After; } } return XmlNodeOrder.Unknown; } /// <summary> /// Return true if the "other" navigator's current node is a descendant of this navigator's current node. /// </summary> public override bool IsDescendant(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathNode[] pageThat; int idxThat; // If that current node's parent is virtualized, then start with the virtual parent if (that._idxParent != 0) { pageThat = that._pageParent; idxThat = that._idxParent; } else { idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat); } while (idxThat != 0) { if (idxThat == _idxCurrent && pageThat == _pageCurrent) return true; idxThat = pageThat[idxThat].GetParent(out pageThat); } } return false; } /// <summary> /// Construct a primary location for this navigator. The location is an integer that can be /// easily compared with other locations in the same document in order to determine the relative /// document order of two nodes. If two locations compare equal, then secondary locations should /// be compared. /// </summary> private int GetPrimaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so primary location should be derived from current node return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); } // Yes, so primary location should be derived from parent node return XPathNodeHelper.GetLocation(_pageParent, _idxParent); } /// <summary> /// Construct a secondary location for this navigator. This location should only be used if /// primary locations previously compared equal. /// </summary> private int GetSecondaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so secondary location is int.MinValue (always first) return int.MinValue; } // Yes, so secondary location should be derived from current node // This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values return _pageCurrent[_idxCurrent].NodeType switch { // Namespace nodes come first (make location negative, but greater than int.MinValue) XPathNodeType.Namespace => int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent), // Attribute nodes come next (location is always positive) XPathNodeType.Attribute => XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent), // Collapsed text nodes are always last _ => int.MaxValue, }; } /// <summary> /// Create a unique id for the current node. This is used by the generate-id() function. /// </summary> internal override string UniqueId { get { // 32-bit integer is split into 5-bit groups, the maximum number of groups is 7 char[] buf = new char[1 + 7 + 1 + 7]; int idx = 0; int loc; // Ensure distinguishing attributes, namespaces and child nodes buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType]; // If the current node is virtualized, code its parent if (_idxParent != 0) { loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); buf[idx++] = '0'; } // Code the node itself loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); return new string(buf, 0, idx); } } public override object UnderlyingObject { get { // Since we don't have any underlying PUBLIC object // the best one we can return is a clone of the navigator. // Note that it should be a clone as the user might Move the returned navigator // around and thus cause unexpected behavior of the caller of this class (For example the validator) return this.Clone(); } } //----------------------------------------------- // IXmlLineInfo //----------------------------------------------- /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> public bool HasLineInfo() { return _pageCurrent[_idxCurrent].Document.HasLineInfo; } /// <summary> /// Return the source line number of the current node. /// </summary> public int LineNumber { get { // If the current node is a collapsed text node, then return parent element's line number if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].LineNumber; return _pageCurrent[_idxCurrent].LineNumber; } } /// <summary> /// Return the source line position of the current node. /// </summary> public int LinePosition { get { // If the current node is a collapsed text node, then get position from parent element if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].CollapsedLinePosition; return _pageCurrent[_idxCurrent].LinePosition; } } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Get hashcode based on current position of the navigator. /// </summary> public int GetPositionHashCode() { return _idxCurrent ^ _idxParent; } /// <summary> /// Return true if navigator is positioned to an element having the specified name. /// </summary> public bool IsElementMatch(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Cannot be an element if parent is stored if (_idxParent != 0) return false; return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI); } /// <summary> /// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & GetKindMask(typ)) != 0); } /// <summary> /// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it /// is positioned to a non-virtual node. If "end" is positioned to a virtual node: /// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent /// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1. /// </summary> private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) { // If ending navigator is positioned to a node in another document, then return null if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document) { // If the ending navigator is not positioned on a virtual node, then return its current node if (end._idxParent == 0) { pageEnd = end._pageCurrent; return end._idxCurrent; } // If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the // next physical node instead, as the results will be the same. pageEnd = end._pageParent; return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1; } // No following, so set pageEnd to null and return an index of 0 pageEnd = null; return 0; } } }
#if UNITY_2018 using System.IO; using System.Linq; using System.Collections; using System.Collections.Generic; using NSubstitute; using NUnit.Framework; using PatchKit.Unity.Patcher; using PatchKit.Unity.Utilities; using UnityEngine; using PatchKit.Unity.Patcher.AppData.Remote.Downloaders; using PatchKit.Api.Models.Main; using PatchKit.Network; using PatchKit.Unity.Patcher.AppData.Remote; public class ChunkedHttpDownloaderTest { const long DataSize = 1103; const long ChunkSize = 64; const long PartSize = 128; private ResourceUrl _url; private ChunksData _chunksData; [Test] public void ByteRangesTests() { var fullRange = BytesRangeUtils.Full(); var outer = BytesRangeUtils.Make(0, 100); var inner = BytesRangeUtils.Make(10, 90); var innerInside = BytesRangeUtils.Make(50, 60); var innerRightSideOverlap = BytesRangeUtils.Make(50, 95); var innerLeftSideOverlap = BytesRangeUtils.Make(5, 15); Assert.That(outer.Contains(inner)); var localizedRightOverlap = innerRightSideOverlap.LocalizeTo(inner); var localizedLeftOverlap = innerLeftSideOverlap.LocalizeTo(inner); Assert.That(localizedRightOverlap, Is.EqualTo(BytesRangeUtils.Make(40, -1))); Assert.That(localizedLeftOverlap, Is.EqualTo(BytesRangeUtils.Make(0, 5))); var localizedFull = fullRange.LocalizeTo(inner); Assert.That(localizedFull, Is.EqualTo(BytesRangeUtils.Full())); var localizedInner = innerInside.LocalizeTo(inner); Assert.That(localizedInner, Is.EqualTo(BytesRangeUtils.Make(40, 50))); } [SetUp] public void SetUp() { _url = new ResourceUrl { Url = "test.com/someData", MetaUrl = "test.com/someMetaData", Country = "GB", PartSize = PartSize }; List<Chunk> chunks = new List<Chunk>(); for (int i = 0; i < (DataSize / ChunkSize); i++) { chunks.Add(new Chunk { Hash=new byte[] {0x20} // TODO: Generate random bytes here }); } _chunksData = new ChunksData { ChunkSize = ChunkSize, Chunks = chunks.ToArray() }; } [Test] public void ChunksCalculations_WithSpecifiedRange_1() { BytesRange range = BytesRangeUtils.Make(9, 315); var chunksRange =range.Chunkify(_chunksData); Assert.That(chunksRange.Start, Is.EqualTo(0)); Assert.That(chunksRange.End, Is.EqualTo(ChunkSize * 5 - 1)); Assert.That(chunksRange.Contains(range)); } [Test] public void ChunksCalculations_WithSpecifiedRange_2() { BytesRange range = BytesRangeUtils.Make(450, 830); var chunksRange = range.Chunkify(_chunksData); Assert.That(chunksRange.Start, Is.EqualTo(ChunkSize * 7)); Assert.That(chunksRange.End, Is.EqualTo(ChunkSize * 13 - 1)); Assert.That(chunksRange.Contains(range)); } [Test] public void ChunksCalculations_WithFullRange() { BytesRange range = BytesRangeUtils.Full(); var chunksRange = range.Chunkify(_chunksData); Assert.That(chunksRange.Start, Is.EqualTo(0)); Assert.That(chunksRange.End, Is.EqualTo(-1)); Assert.That(chunksRange.Contains(range)); } [Test] public void ChunksCalculations_RangeIsExactWithChunks() { BytesRange range = BytesRangeUtils.Make(ChunkSize, (ChunkSize * 3) - 1); // Exactly 3 chunks var chunksRange = range.Chunkify(_chunksData); Assert.That(chunksRange, Is.EqualTo(range)); } [Test] public void ChunksCalculations_WithRangeExactlyAsDataSize() { BytesRange range = BytesRangeUtils.Make(0, DataSize); var chunksRange = range.Chunkify(_chunksData); Assert.That(chunksRange.Start, Is.EqualTo(0)); Assert.That(chunksRange.End, Is.EqualTo(DataSize)); } [Test] public void JobQueuing_WithFullRange() { BytesRange range = BytesRangeUtils.Full(); var jobs = ChunkedHttpDownloader.BuildDownloadJobQueue(_url, 0, range, DataSize, _chunksData).ToList(); int expectedJobCount = (int) (DataSize / PartSize) + 1; Assert.That(jobs.Count, Is.EqualTo(expectedJobCount)); var firstJob = jobs[0]; Assert.That(firstJob.Range.Start, Is.EqualTo(0)); Assert.That(firstJob.Range.End, Is.EqualTo(-1)); var lastJob = jobs[expectedJobCount - 1]; Assert.That(lastJob.Range.Start, Is.EqualTo(0)); Assert.That(lastJob.Range.End, Is.EqualTo(-1)); } [Test] public void JobQueuing_WithSpecifiedRange() { BytesRange range = BytesRangeUtils.Make(450, 830); var jobs = ChunkedHttpDownloader.BuildDownloadJobQueue(_url, 0,range, DataSize, _chunksData).ToList(); Assert.That(jobs.Count, Is.EqualTo(4)); var firstJob = jobs[0]; Assert.That(firstJob.Url, Is.EqualTo("test.com/someData.3")); Assert.That(firstJob.Range.Start, Is.EqualTo(64)); Assert.That(firstJob.Range.End, Is.EqualTo(-1)); var middleJob = jobs[1]; Assert.That(middleJob.Url, Is.EqualTo("test.com/someData.4")); Assert.That(middleJob.Range.Start, Is.EqualTo(0)); Assert.That(middleJob.Range.End, Is.EqualTo(-1)); var lastJob = jobs[3]; Assert.That(lastJob.Url, Is.EqualTo("test.com/someData.6")); Assert.That(lastJob.Range.Start, Is.EqualTo(0)); Assert.That(lastJob.Range.End, Is.EqualTo(63)); } [Test] public void JobQueuing_WithSpecifiedRangeAndOffset() { BytesRange range = BytesRangeUtils.Make(450, 830); long offset = 512; var jobs = ChunkedHttpDownloader.BuildDownloadJobQueue(_url, offset,range, DataSize, _chunksData).ToList(); Assert.That(jobs.Count, Is.EqualTo(3)); var firstJob = jobs[0]; Assert.That(firstJob.Url, Is.EqualTo("test.com/someData.4")); Assert.That(firstJob.Range.Start, Is.EqualTo(0)); Assert.That(firstJob.Range.End, Is.EqualTo(-1)); var middleJob = jobs[1]; Assert.That(middleJob.Url, Is.EqualTo("test.com/someData.5")); Assert.That(middleJob.Range.Start, Is.EqualTo(0)); Assert.That(middleJob.Range.End, Is.EqualTo(-1)); var lastJob = jobs[2]; Assert.That(lastJob.Url, Is.EqualTo("test.com/someData.6")); Assert.That(lastJob.Range.Start, Is.EqualTo(0)); Assert.That(lastJob.Range.End, Is.EqualTo(63)); } [Test] public void JobQueuing_SinglePartScenario() { BytesRange range = BytesRangeUtils.Make(315, 380); var jobs = ChunkedHttpDownloader.BuildDownloadJobQueue(_url, 0,range, DataSize, _chunksData).ToList(); Assert.That(jobs.Count, Is.EqualTo(1)); var job = jobs[0]; Assert.That(job.Url, Is.EqualTo("test.com/someData.2")); Assert.That(job.Range.Start, Is.EqualTo(0)); Assert.That(job.Range.End, Is.EqualTo(-1).Or.EqualTo(127)); } } #endif
using System; using System.Linq; using SME; namespace UnitTester { /// <summary> /// Tests a bunch of assignment operators /// </summary> public class AssignmentOperators : Test { public AssignmentOperators() { outputs = new int[inputs.Length]; int init_tmp = 0; for (int i = 0; i < inputs.Length; i++) { init_tmp -= inputs[i]; init_tmp &= 0x7FFF_FFFE; outputs[i] = init_tmp; } } int tmp = 0; int max_val = int.MaxValue; protected override void OnTick() { output.valid = input.valid; tmp -= input.value; tmp &= 0x7FFF_FFFF; tmp *= 1; tmp %= max_val; tmp >>= 1; tmp <<= 1; tmp ^= 0; output.value = tmp; } } /// <summary> /// Tests whether SME can translate a member reference to base /// </summary> public class BaseMemberReference : ThisMemberReference { public BaseMemberReference() : base() { } protected override void OnTick() { output.valid = base.valid; output.value = base.value + base.const_val; base.valid = input.valid; base.value = input.value; } } /// <summary> /// Tests whether checked and unchecked expressions are correctly handled. /// </summary> public class CheckedAndUnchecked : Test { protected override void OnTick() { output.valid = input.valid; uint tmp = unchecked((uint)input.value); output.value = checked((int)(tmp & 0x7FFFFFFF)); } } /// <summary> /// Tests whether a ternary (conditional) expression is rendered correctly /// </summary> public class ConditionalExpressionTest : Test { public ConditionalExpressionTest() { outputs = inputs.Select(x => x % 2 == 0 ? x : ~x).ToArray(); } protected override void OnTick() { output.valid = input.valid; output.value = input.value % 2 == 0 ? input.value : ~input.value; } } /// <summary> /// Tests whether a method is correctly ignored, so not rendered in VHDL. /// </summary> public class IgnoreMethod : Test { [Ignore] private int BoringMethod(int input) { return input + 42; } } /// <summary> /// Tests an invocation expression /// </summary> public class InvocationExpression : Test { private void LocalMethod() { output.valid = input.valid; output.value = input.value; } protected override void OnTick() { LocalMethod(); } } /// <summary> /// Tests whether some operators are correctly translated. The list is /// based on what wasn't already hit during running the other samples. /// </summary> public class MissingOperators : Test { public MissingOperators() { outputs = inputs .Select(x => ~(x & 0x7FFF_FFFE)) .ToArray(); } protected override void OnTick() { output.valid = input.valid; int tmp = input.value & 0x7FFF_FFFF; tmp = tmp >> 1; tmp = tmp << 1; tmp++; tmp--; output.value = ~tmp; } } /// <summary> /// Tests whether a public readonly or constant variable is correctly /// parsed. /// </summary> public class PublicReadonlyOrConstant : Test { public PublicReadonlyOrConstant() { outputs = inputs.Select(x => x + ro_value + c_value).ToArray(); } public readonly int ro_value = 42; public const int c_value = 33; protected override void OnTick() { output.valid = input.valid; output.value = input.value + ro_value + c_value; } } /// <summary> /// Tests whether SME can translate a member reference with process type /// prefix /// </summary> public class SelfTypeMemberReference : Test { public SelfTypeMemberReference() { outputs = inputs.Select(x => x + const_val).ToArray(); } private static readonly int const_val = 1; protected override void OnTick() { output.valid = input.valid; output.value = input.value + SelfTypeMemberReference.const_val; } } /// <summary> /// Tests whether SimulationOnly() is truely ignored. /// </summary> public class SimulationOnlyTest : Test { protected override void OnTick() { output.valid = input.valid; output.value = input.value; SimulationOnly(() => inputs[0] = inputs[0]); } } /// <summary> /// Helper class containing static fields and methods /// </summary> public class StaticHelper { public static int StaticMethod(int input) // TODO Static methods outside of processes aren't rendered correctly { return input + 42; } } /// <summary> /// Member access to a static method /// </summary> public class StaticMethod : Test { public StaticMethod() { outputs = inputs.Select(x => x + 42).ToArray(); } public static int LocalStaticMethod(int input) // TODO generated method can be simplified { return input + 42; } protected override void OnTick() { output.valid = input.valid; output.value = StaticMethod.LocalStaticMethod(input.value); } } /// <summary> /// Tests whether SME can translate a member reference to this /// </summary> public class ThisMemberReference : Test { public ThisMemberReference() { outputs = inputs.Select(x => x + const_val).ToArray(); } protected bool valid = false; protected int value = 0; protected readonly int const_val = 1; protected override void OnTick() { output.valid = this.valid; output.value = this.value + const_val; this.valid = input.valid; this.value = input.value; } } // Missing tests // TODO constant array // TODO BusProperty? // TODO IRuntimeBus.Manager ? // TODO divided clock ? // TODO Using clocked buses // TODO array of buses // TODO auto loading buses (or rather: remove this feature?) // TODO Scope.RegisterBus() ? // TODO Scope.LoadBus() ? // TODO SingletonBus ? // TODO Scope.FindProcess() ? // TODO Scope.RecursiveLookup() ? // TODO Scope.ScopeKey ?? It should return the root scope, if there's no scope key, so I'm guessing multiple scopes? // TODO Adding a preloader to a simulation // TODO Simulation.Run(Assembly) (should be removed?) // TODO Generic typing with own types (SME.AST.ParseProcesses.ResolveGenericType) // TODO build an AST with a custom subclass (Why would you do this?) // TODO Parse an parameter?? (SME.AST.ParseProcesses) // TODO Parse a variable?? (SME.AST.ParseProcesses) // TODO ArrayCreationExpression // TODO UsingStatement // TODO GotoStatement // TODO LabeledStatement // TODO Local decleration of a bus type (Is this allowed?? Maybe in an aliasing sort of fashion) // TODO Local declaration with multiple values // TODO ResolveArrayLengthOrPrimitive() (SME.AST.ParseProcessStatement) // TODO arithmetic operations with float or double (Although it isn't fully implemented yet.) // TODO Generic types // TODO Load type array? (I'm guessing custom types) // TODO Bool type // TODO sbyte type // TODO long type // TODO float type // TODO double type // TODO SME.Signal // TODO Custom type inside an OnTick // TODO public static constant ? // TODO TryLocateElement(Method) (SME.AST) // TODO Variable in Ontick (hasn't this been done??) // TODO Property // TODO SME.AST.ParseProcesses.LocateBus() ?? // TODO State process without any awaits // TODO State process with a for loop without any awaits // TODO State process with a for loop, whose body isn't a block statement // TODO State process which has a series of normal statements, amongst which one has to be an await // TODO SME.AST.BuildStateMachine.ToBlockStatement() with an empty set of statements given?? // TODO State process which has a cycle from while loops. In other words, it tries to go back to itself, when it is trying to inline statements, which it can't (and shouldn't). // TODO Switch statement, which uses goto // TODO Self casting (SME.AST.Transform.RemoveDoubleCast) // TODO SME.BusSignal // TODO SME.Parameter // TODO WrappingExpression // TODO EmptyArrayCreateExpression // TODO JSON trace ?? // TODO Trigger the warning in SimpleDualPortMemory // TODO Trigger the warning in TrueDualPortMemory // TODO Simulation.BuildGraph(render_buses: false) // TODO Trigger a trace file, which contains U and X // TODO enum in trace (on buses) // TODO sbyte in trace (on buses) // TODO short in trace (on buses) // TODO ushort in trace (on buses) // TODO long in trace (on buses) // TODO native components, rather than inferred // TODO SME.VHDL.BaseTemplate // TODO Shared signals ?? // TODO Buses, which are both in and out buses?? // TODO Non-clocked process with multiple processes writing to it's buses // TODO Intermediate signals, which are also topleveloutput // TODO (public?) Constant field in a nested process // TODO non-static for loop // TODO VHDLTypes.INTEGER << VHDLTypes.INTEGER or VHDLTypes.INTEGER >> VHDLTypes.INTEGER // TODO << CastExpression() // TODO RemoveNonstaticSwitchLabels so a switch with conversion expressions in their case? // TODO Unary operator, which is not a ++ or -- // TODO UntagleElseStatements // TODO VHDLComponentAttribute // TODO All of the VHDL.* types // TODO A process with the same name as the project. (I'm sure this is normally hit, but not during testing.) // TODO A bus signal with a keyword as name (SME.VHDL.Naming line 119) // TODO VendorAltera attribute // TODO VendorSimulation attribute // TODO Simulation.Render() -- rather than .BuildVHDL() // TODO Cast expression // TODO Direction expression // TODO Array of std_logic (bool) // TODO Array of std_logic_vector // TODO Primitive bool // TODO A network with only components // TODO top-level bool // TODO top-level signed // TODO top-level std_logic_vector // TODO top-level custom type // TODO Fields with no default value (So it should be chosen from the type) // TODO VHDL records (C# struct? or is it a dictionary?) // TODO assigning to a bus signal through a memberreference (structs in a signal?) // TODO assigning to a bus signal through an indexer expression // TODO Array field, which has no default value. (This shouldn't be allowed?) // TODO custom renderer // TODO ExternalComponent, add case for byte and sbyte // TODO Array as parameter // TODO Array property // TODO IntPtr ?? // TODO UIntPtr ?? }
// This file is part of the C5 Generic Collection Library for C# and CLI // See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details. // C5 examples: RegExp -> NFA -> DFA -> Graph // Java 2000-10-07, GC# 2001-10-23, C# 2.0 2003-09-03, C# 2.0+C5 2004-08-08 // This file contains, in order: // * Helper class HashSet<T> defined in terms of C5 classes. // * A class Nfa for representing an NFA (a nondeterministic finite // automaton), and for converting it to a DFA (a deterministic // finite automaton). Most complexity is in this class. // * A class Dfa for representing a DFA, a deterministic finite // automaton, and for writing a dot input file representing the DFA. // * Classes for representing regular expressions, and for building an // NFA from a regular expression // * A test class that creates an NFA, a DFA, and a dot input file // for a number of small regular expressions. The DFAs are // not minimized. namespace C5.UserGuideExamples; // ---------------------------------------------------------------------- // Regular expressions, NFAs, DFAs, and dot graphs // sestoft@dina.kvl.dk * // Java 2001-07-10 * C# 2001-10-22 * Gen C# 2001-10-23, 2003-09-03 // In the Generic C# 2.0 version we // use Queue<int> and Queue<HashSet<int>> for worklists // use HashSet<int> for pre-DFA states // use ArrayList<Transition> for NFA transition relations // use HashDictionary<HashSet<int>, HashDictionary<string, HashSet<int>>> // and HashDictionary<int, HashDictionary<string, int>> for DFA transition relations /* Class Nfa and conversion from NFA to DFA --------------------------- A nondeterministic finite automaton (NFA) is represented as a dictionary mapping a state number (int) to an arraylist of Transitions, a Transition being a pair of a label lab (a string, null meaning epsilon) and a target state (an int). A DFA is created from an NFA in two steps: (1) Construct a DFA whose each of whose states is composite, namely a set of NFA states (HashSet of int). This is done by methods CompositeDfaTrans and EpsilonClose. (2) Replace composite states (HashSet of int) by simple states (int). This is done by methods Rename and MkRenamer. Method CompositeDfaTrans works as follows: Create the epsilon-closure S0 (a HashSet of ints) of the start state s0, and put it in a worklist (a Queue). Create an empty DFA transition relation, which is a dictionary mapping a composite state (an epsilon-closed set of ints) to a dictionary mapping a label (a non-null string) to a composite state. Repeatedly choose a composite state S from the worklist. If it is not already in the keyset of the DFA transition relation, compute for every non-epsilon label lab the set T of states reachable by that label from some state s in S. Compute the epsilon-closure Tclose of every such state T and put it on the worklist. Then add the transition S -lab-> Tclose to the DFA transition relation, for every lab. Method EpsilonClose works as follows: Given a set S of states. Put the states of S in a worklist. Repeatedly choose a state s from the worklist, and consider all epsilon-transitions s -eps-> s' from s. If s' is in S already, then do nothing; otherwise add s' to S and the worklist. When the worklist is empty, S is epsilon-closed; return S. Method MkRenamer works as follows: Given a dictionary mapping a set of int to something, create an injective dictionary mapping from set of int to int, by choosing a fresh int for every key in the given dictionary. Method Rename works as follows: Given a dictionary mapping a set of int to a dictionary mapping a string to set of int, use the result of MkRenamer to replace all sets of ints by ints. */ internal class Nfa { public int Start { get; } public int Exit { get; } public IDictionary<int, ArrayList<Transition>> Trans { get; } public Nfa(int startState, int exitState) { Start = startState; Exit = exitState; Trans = new HashDictionary<int, ArrayList<Transition>>(); if (!startState.Equals(exitState)) { Trans.Add(exitState, new ArrayList<Transition>()); } } public void AddTrans(int s1, string lab, int s2) { ArrayList<Transition> s1Trans; if (Trans.Contains(s1)) { s1Trans = Trans[s1]; } else { s1Trans = new ArrayList<Transition>(); Trans.Add(s1, s1Trans); } s1Trans.Add(new Transition(lab, s2)); } public void AddTrans(System.Collections.Generic.KeyValuePair<int, ArrayList<Transition>> tr) { // Assumption: if tr is in trans, it maps to an empty list (end state) Trans.Remove(tr.Key); Trans.Add(tr.Key, tr.Value); } public override string ToString() { return $"NFA start={Start} exit={Exit}"; } // Construct the transition relation of a composite-state DFA from // an NFA with start state s0 and transition relation trans (a // dictionary mapping int to arraylist of Transition). The start // state of the constructed DFA is the epsilon closure of s0, and // its transition relation is a dictionary mapping a composite state // (a set of ints) to a dictionary mapping a label (a string) to a // composite state (a set of ints). private static IDictionary<HashSet<int>, IDictionary<string, HashSet<int>>> CompositeDfaTrans(int s0, IDictionary<int, ArrayList<Transition>> trans) { var S0 = EpsilonClose(new HashSet<int> { s0 }, trans); var worklist = new CircularQueue<HashSet<int>>(); worklist.Enqueue(S0); // The transition relation of the DFA var res = new HashDictionary<HashSet<int>, IDictionary<string, HashSet<int>>>(); while (!worklist.IsEmpty) { HashSet<int> S = worklist.Dequeue(); if (!res.Contains(S)) { // The S -lab-> T transition relation being constructed for a given S IDictionary<string, HashSet<int>> STrans = new HashDictionary<string, HashSet<int>>(); // For all s in S, consider all transitions s -lab-> t foreach (int s in S) { // For all non-epsilon transitions s -lab-> t, add t to T foreach (Transition tr in trans[s]) { if (tr.Lab != null) { // Non-epsilon transition HashSet<int> toState; if (STrans.Contains(tr.Lab)) // Already a transition on lab { toState = STrans[tr.Lab]; } else // No transitions on lab yet { toState = new HashSet<int>(); STrans.Add(tr.Lab, toState); } toState.Add(tr.Target); } } } // Epsilon-close all T such that S -lab-> T, and put on worklist var STransClosed = new HashDictionary<string, HashSet<int>>(); foreach (var entry in STrans) { var Tclose = EpsilonClose(entry.Value, trans); STransClosed.Add(entry.Key, Tclose); worklist.Enqueue(Tclose); } res.Add(S, STransClosed); } } return res; } // Compute epsilon-closure of state set S in transition relation trans. private static HashSet<int> EpsilonClose(HashSet<int> set, IDictionary<int, ArrayList<Transition>> trans) { // The worklist initially contains all S members var worklist = new CircularQueue<int>(); set.Apply(worklist.Enqueue); var res = new HashSet<int>(); res.AddAll(set); while (!worklist.IsEmpty) { var s = worklist.Dequeue(); foreach (var tr in trans[s]) { if (tr.Lab == null && !res.Contains(tr.Target)) { res.Add(tr.Target); worklist.Enqueue(tr.Target); } } } return res; } // Compute a renamer, which is a dictionary mapping set of int to int private static IDictionary<HashSet<int>, int> MkRenamer(ICollectionValue<HashSet<int>> states) { var renamer = new HashDictionary<HashSet<int>, int>(); var count = 0; foreach (var k in states) { renamer.Add(k, count++); } return renamer; } // Using a renamer (a dictionary mapping set of int to int), replace // composite (set of int) states with simple (int) states in the // transition relation trans, which is a dictionary mapping set of // int to a dictionary mapping from string to set of int. The // result is a dictionary mapping from int to a dictionary mapping // from string to int. private static IDictionary<int, IDictionary<string, int>> Rename(IDictionary<HashSet<int>, int> renamer, IDictionary<HashSet<int>, IDictionary<string, HashSet<int>>> trans) { var newtrans = new HashDictionary<int, IDictionary<string, int>>(); foreach (var entry in trans) { var k = entry.Key; var newktrans = new HashDictionary<string, int>(); foreach (var tr in entry.Value) { newktrans.Add(tr.Key, renamer[tr.Value]); } newtrans.Add(renamer[k], newktrans); } return newtrans; } private static HashSet<int> AcceptStates(ICollectionValue<HashSet<int>> states, IDictionary<HashSet<int>, int> renamer, int exit) { var acceptStates = new HashSet<int>(); foreach (var state in states) { if (state.Contains(exit)) { acceptStates.Add(renamer[state]); } } return acceptStates; } public Dfa ToDfa() { var cDfaTrans = CompositeDfaTrans(Start, Trans); var cDfaStart = EpsilonClose(new HashSet<int> { Start }, Trans); var cDfaStates = cDfaTrans.Keys; var renamer = MkRenamer(cDfaStates); var simpleDfaTrans = Rename(renamer, cDfaTrans); var simpleDfaStart = renamer[cDfaStart]; var simpleDfaAccept = AcceptStates(cDfaStates, renamer, Exit); return new Dfa(simpleDfaStart, simpleDfaAccept, simpleDfaTrans); } // Nested class for creating distinctly named states when constructing NFAs public class NameSource { private static int _nextName = 0; public int Next() { return _nextName++; } } // Write an input file for the dot program. You can find dot at // http://www.research.att.com/sw/tools/graphviz/ public void WriteDot(string filename) { using (var writer = new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))) { writer.WriteLine("// Format this file as a Postscript file with "); writer.WriteLine("// dot " + filename + " -Tps -o out.ps\n"); writer.WriteLine("digraph nfa {"); writer.WriteLine("size=\"11,8.25\";"); writer.WriteLine("rotate=90;"); writer.WriteLine("rankdir=LR;"); writer.WriteLine("start [style=invis];"); // Invisible start node writer.WriteLine("start -> d" + Start); // Edge into start state // The accept state has a double circle writer.WriteLine("d" + Exit + " [peripheries=2];"); // The transitions foreach (var entry in Trans) { var s1 = entry.Key; for (var i = 0; i < entry.Value.Count; i++) { var s1Trans = entry.Value[i]; var lab = s1Trans.Lab ?? "eps"; var s2 = s1Trans.Target; writer.WriteLine("d" + s1 + " -> d" + s2 + " [label=\"" + lab + "\"];"); } } writer.WriteLine("}"); } } } // Class Transition, a transition from one state to another ---------- public class Transition { public string Lab { get; } public int Target { get; } public Transition(string lab, int target) { Lab = lab; Target = target; } public override string ToString() { return $"-{Lab}-> {Target}"; } } // Class Dfa, deterministic finite automata -------------------------- /* A deterministic finite automaton (DFA) is represented as a dictionary mapping state number (int) to a dictionary mapping label (a non-null string) to a target state (an int). */ internal class Dfa { public int Start { get; } public HashSet<int> Accept { get; } public IDictionary<int, IDictionary<string, int>> Trans { get; } public Dfa(int startState, HashSet<int> acceptStates, IDictionary<int, IDictionary<string, int>> trans) { Start = startState; Accept = acceptStates; Trans = trans; } public override string ToString() { return $"DFA start={Start}{Environment.NewLine}accept={Accept}"; } // Write an input file for the dot program. You can find dot at // http://www.research.att.com/sw/tools/graphviz/ public void WriteDot(string filename) { using (var writer = new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.Write))) { writer.WriteLine("// Format this file as a Postscript file with "); writer.WriteLine("// dot " + filename + " -Tps -o out.ps\n"); writer.WriteLine("digraph dfa {"); writer.WriteLine("size=\"11,8.25\";"); writer.WriteLine("rotate=90;"); writer.WriteLine("rankdir=LR;"); writer.WriteLine("start [style=invis];"); // Invisible start node writer.WriteLine("start -> d" + Start); // Edge into start state // Accept states are double circles foreach (var state in Trans.Keys) { if (Accept.Contains(state)) { writer.WriteLine("d" + state + " [peripheries=2];"); } } // The transitions foreach (var entry in Trans) { var s1 = entry.Key; foreach (var s1Trans in entry.Value) { var lab = s1Trans.Key; var s2 = s1Trans.Value; writer.WriteLine($"d{s1} -> d{s2} [label=\"{lab}\"];"); } } writer.WriteLine("}"); } } } // Regular expressions ---------------------------------------------- // // Abstract syntax of regular expressions // r ::= A | r1 r2 | (r1|r2) | r* // internal abstract class RegexBase { public abstract Nfa MkNfa(Nfa.NameSource names); } internal class Eps : RegexBase { // The resulting nfa0 has form s0s -eps-> s0e public override Nfa MkNfa(Nfa.NameSource names) { var s0s = names.Next(); var s0e = names.Next(); var nfa0 = new Nfa(s0s, s0e); nfa0.AddTrans(s0s, null, s0e); return nfa0; } } internal class Sym : RegexBase { private readonly string _sym; public Sym(string sym) { _sym = sym; } // The resulting nfa0 has form s0s -sym-> s0e public override Nfa MkNfa(Nfa.NameSource names) { var s0s = names.Next(); var s0e = names.Next(); var nfa0 = new Nfa(s0s, s0e); nfa0.AddTrans(s0s, _sym, s0e); return nfa0; } } internal class Seq : RegexBase { private readonly RegexBase _r1; private readonly RegexBase _r2; public Seq(RegexBase r1, RegexBase r2) { _r1 = r1; _r2 = r2; } // If nfa1 has form s1s ----> s1e // and nfa2 has form s2s ----> s2e // then nfa0 has form s1s ----> s1e -eps-> s2s ----> s2e public override Nfa MkNfa(Nfa.NameSource names) { var nfa1 = _r1.MkNfa(names); var nfa2 = _r2.MkNfa(names); var nfa0 = new Nfa(nfa1.Start, nfa2.Exit); foreach (var entry in nfa1.Trans) { nfa0.AddTrans(entry); } foreach (var entry in nfa2.Trans) { nfa0.AddTrans(entry); } nfa0.AddTrans(nfa1.Exit, null, nfa2.Start); return nfa0; } } internal class Alt : RegexBase { private readonly RegexBase _r1; private readonly RegexBase _r2; public Alt(RegexBase r1, RegexBase r2) { _r1 = r1; _r2 = r2; } // If nfa1 has form s1s ----> s1e // and nfa2 has form s2s ----> s2e // then nfa0 has form s0s -eps-> s1s ----> s1e -eps-> s0e // s0s -eps-> s2s ----> s2e -eps-> s0e public override Nfa MkNfa(Nfa.NameSource names) { var nfa1 = _r1.MkNfa(names); var nfa2 = _r2.MkNfa(names); var s0s = names.Next(); var s0e = names.Next(); var nfa0 = new Nfa(s0s, s0e); foreach (var entry in nfa1.Trans) { nfa0.AddTrans(entry); } foreach (var entry in nfa2.Trans) { nfa0.AddTrans(entry); } nfa0.AddTrans(s0s, null, nfa1.Start); nfa0.AddTrans(s0s, null, nfa2.Start); nfa0.AddTrans(nfa1.Exit, null, s0e); nfa0.AddTrans(nfa2.Exit, null, s0e); return nfa0; } } internal class Star : RegexBase { private readonly RegexBase _r; public Star(RegexBase r) { _r = r; } // If nfa1 has form s1s ----> s1e // then nfa0 has form s0s ----> s0s // s0s -eps-> s1s // s1e -eps-> s0s public override Nfa MkNfa(Nfa.NameSource names) { var nfa1 = _r.MkNfa(names); var s0s = names.Next(); var nfa0 = new Nfa(s0s, s0s); foreach (var entry in nfa1.Trans) { nfa0.AddTrans(entry); } nfa0.AddTrans(s0s, null, nfa1.Start); nfa0.AddTrans(nfa1.Exit, null, s0s); return nfa0; } } // Trying the RE->NFA->DFA translation on three regular expressions internal class GNfaToDfa { public static void Main() { var a = new Sym("A"); var b = new Sym("B"); _ = new Sym("C"); var abStar = new Star(new Alt(a, b)); var bb = new Seq(b, b); var r = new Seq(abStar, new Seq(a, b)); // The regular expression (a|b)*ab BuildAndShow("ex1", r); // The regular expression ((a|b)*ab)* BuildAndShow("ex2", new Star(r)); // The regular expression ((a|b)*ab)((a|b)*ab) BuildAndShow("ex3", new Seq(r, r)); // The regular expression (a|b)*abb, from ASU 1986 p 136 BuildAndShow("ex4", new Seq(abStar, new Seq(a, bb))); // SML reals: sign?((digit+(\.digit+)?))([eE]sign?digit+)? var d = new Sym("digit"); var dPlus = new Seq(d, new Star(d)); var s = new Sym("sign"); var sOpt = new Alt(s, new Eps()); var dot = new Sym("."); var dotDigOpt = new Alt(new Eps(), new Seq(dot, dPlus)); var mant = new Seq(sOpt, new Seq(dPlus, dotDigOpt)); var e = new Sym("e"); var exp = new Alt(new Eps(), new Seq(e, new Seq(sOpt, dPlus))); var smlReal = new Seq(mant, exp); BuildAndShow("ex5", smlReal); } public static void BuildAndShow(string fileprefix, RegexBase r) { var nfa = r.MkNfa(new Nfa.NameSource()); Console.WriteLine(nfa); Console.WriteLine("Writing NFA graph to file"); nfa.WriteDot(fileprefix + "nfa.dot"); Console.WriteLine("---"); var dfa = nfa.ToDfa(); Console.WriteLine(dfa); Console.WriteLine("Writing DFA graph to file"); dfa.WriteDot(fileprefix + "dfa.dot"); Console.WriteLine(); } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) Ville Palo // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using Xunit; using System.Xml; using System.Data.SqlTypes; using System.Globalization; namespace System.Data.Tests.SqlTypes { public class SqlBooleanTest { private SqlBoolean _sqlTrue; private SqlBoolean _sqlFalse; public SqlBooleanTest() { _sqlTrue = new SqlBoolean(true); _sqlFalse = new SqlBoolean(false); } [Fact] public void Create() { SqlBoolean SqlTrue2 = new SqlBoolean(1); SqlBoolean SqlFalse2 = new SqlBoolean(0); Assert.True(_sqlTrue.Value); Assert.True(SqlTrue2.Value); Assert.True(!_sqlFalse.Value); Assert.True(!SqlFalse2.Value); } //// // PUBLIC STATIC METHODS // // And [Fact] public void And() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); // One result value SqlBoolean sqlResult; // true && false sqlResult = SqlBoolean.And(_sqlTrue, _sqlFalse); Assert.True(!sqlResult.Value); sqlResult = SqlBoolean.And(_sqlFalse, _sqlTrue); Assert.True(!sqlResult.Value); // true && true sqlResult = SqlBoolean.And(_sqlTrue, SqlTrue2); Assert.True(sqlResult.Value); sqlResult = SqlBoolean.And(_sqlTrue, _sqlTrue); Assert.True(sqlResult.Value); // false && false sqlResult = SqlBoolean.And(_sqlFalse, SqlFalse2); Assert.True(!sqlResult.Value); sqlResult = SqlBoolean.And(_sqlFalse, _sqlFalse); Assert.True(!sqlResult.Value); } // NotEquals [Fact] public void NotEquals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true != false SqlResult = SqlBoolean.NotEquals(_sqlTrue, _sqlFalse); Assert.True(SqlResult.Value); SqlResult = SqlBoolean.NotEquals(_sqlFalse, _sqlTrue); Assert.True(SqlResult.Value); // true != true SqlResult = SqlBoolean.NotEquals(_sqlTrue, _sqlTrue); Assert.True(!SqlResult.Value); SqlResult = SqlBoolean.NotEquals(_sqlTrue, SqlTrue2); Assert.True(!SqlResult.Value); // false != false SqlResult = SqlBoolean.NotEquals(_sqlFalse, _sqlFalse); Assert.True(!SqlResult.Value); SqlResult = SqlBoolean.NotEquals(_sqlTrue, SqlTrue2); Assert.True(!SqlResult.Value); // If either instance of SqlBoolean is null, the Value of the SqlBoolean will be Null. SqlResult = SqlBoolean.NotEquals(SqlBoolean.Null, _sqlFalse); Assert.True(SqlResult.IsNull); SqlResult = SqlBoolean.NotEquals(_sqlTrue, SqlBoolean.Null); Assert.True(SqlResult.IsNull); } // OnesComplement [Fact] public void OnesComplement() { SqlBoolean SqlFalse2 = SqlBoolean.OnesComplement(_sqlTrue); Assert.True(!SqlFalse2.Value); SqlBoolean SqlTrue2 = SqlBoolean.OnesComplement(_sqlFalse); Assert.True(SqlTrue2.Value); } // Or [Fact] public void Or() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true || false SqlResult = SqlBoolean.Or(_sqlTrue, _sqlFalse); Assert.True(SqlResult.Value); SqlResult = SqlBoolean.Or(_sqlFalse, _sqlTrue); Assert.True(SqlResult.Value); // true || true SqlResult = SqlBoolean.Or(_sqlTrue, _sqlTrue); Assert.True(SqlResult.Value); SqlResult = SqlBoolean.Or(_sqlTrue, SqlTrue2); Assert.True(SqlResult.Value); // false || false SqlResult = SqlBoolean.Or(_sqlFalse, _sqlFalse); Assert.True(!SqlResult.Value); SqlResult = SqlBoolean.Or(_sqlFalse, SqlFalse2); Assert.True(!SqlResult.Value); } // Parse [Fact] public void Parse() { string error = "Parse method does not work correctly "; Assert.True(SqlBoolean.Parse("True").Value); Assert.True(SqlBoolean.Parse(" True").Value); Assert.True(SqlBoolean.Parse("True ").Value); Assert.True(SqlBoolean.Parse("tRuE").Value); Assert.True(!SqlBoolean.Parse("False").Value); Assert.True(!SqlBoolean.Parse(" False").Value); Assert.True(!SqlBoolean.Parse("False ").Value); Assert.True(!SqlBoolean.Parse("fAlSe").Value); } // Xor [Fact] public void Xor() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; // true ^ false SqlResult = SqlBoolean.Xor(_sqlTrue, _sqlFalse); Assert.True(SqlResult.Value); SqlResult = SqlBoolean.Xor(_sqlFalse, _sqlTrue); Assert.True(SqlResult.Value); // true ^ true SqlResult = SqlBoolean.Xor(_sqlTrue, SqlTrue2); Assert.True(!SqlResult.Value); // false ^ false SqlResult = SqlBoolean.Xor(_sqlFalse, SqlFalse2); Assert.True(!SqlResult.Value); } // static Equals [Fact] public void StaticEquals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); string error = "Static Equals method does not work correctly "; Assert.True(SqlBoolean.Equals(_sqlTrue, SqlTrue2).Value); Assert.True(SqlBoolean.Equals(_sqlFalse, SqlFalse2).Value); Assert.True(!SqlBoolean.Equals(_sqlTrue, _sqlFalse).Value); Assert.True(!SqlBoolean.Equals(_sqlFalse, _sqlTrue).Value); Assert.Equal(SqlBoolean.Null, SqlBoolean.Equals(SqlBoolean.Null, _sqlFalse)); Assert.Equal(SqlBoolean.Null, SqlBoolean.Equals(_sqlTrue, SqlBoolean.Null)); } // // END OF STATIC METHODS //// //// // PUBLIC METHODS // // CompareTo [Fact] public void CompareTo() { string error = "CompareTo method does not work correctly"; Assert.True((_sqlTrue.CompareTo(SqlBoolean.Null) > 0)); Assert.True((_sqlTrue.CompareTo(_sqlFalse) > 0)); Assert.True((_sqlFalse.CompareTo(_sqlTrue) < 0)); Assert.True((_sqlFalse.CompareTo(_sqlFalse) == 0)); } // Equals [Fact] public void Equals() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); string error = "Equals method does not work correctly "; Assert.True(_sqlTrue.Equals(SqlTrue2)); Assert.True(_sqlFalse.Equals(SqlFalse2)); Assert.True(!_sqlTrue.Equals(_sqlFalse)); Assert.True(!_sqlFalse.Equals(_sqlTrue)); Assert.False(_sqlTrue.Equals(SqlBoolean.Null)); Assert.False(_sqlFalse.Equals(SqlBoolean.Null)); Assert.True(!_sqlTrue.Equals(null)); Assert.True(SqlBoolean.Null.Equals(SqlBoolean.Null)); Assert.False(SqlBoolean.Null.Equals(_sqlTrue)); Assert.False(SqlBoolean.Null.Equals(_sqlFalse)); } [Fact] public void GetHashCodeTest() { Assert.Equal(1, _sqlTrue.GetHashCode()); Assert.Equal(0, _sqlFalse.GetHashCode()); } // GetType [Fact] public void GetTypeTest() { Assert.Equal("System.Data.SqlTypes.SqlBoolean", _sqlTrue.GetType().ToString()); } // ToSqlByte [Fact] public void ToSqlByte() { SqlByte SqlTestByte; string error = "ToSqlByte method does not work correctly "; SqlTestByte = _sqlTrue.ToSqlByte(); Assert.Equal((byte)1, SqlTestByte.Value); SqlTestByte = _sqlFalse.ToSqlByte(); Assert.Equal((byte)0, SqlTestByte.Value); } // ToSqlDecimal [Fact] public void ToSqlDecimal() { SqlDecimal SqlTestDecimal; string error = "ToSqlDecimal method does not work correctly "; SqlTestDecimal = _sqlTrue.ToSqlDecimal(); Assert.Equal(1, SqlTestDecimal.Value); SqlTestDecimal = _sqlFalse.ToSqlDecimal(); Assert.Equal(0, SqlTestDecimal.Value); } // ToSqlDouble [Fact] public void ToSqlDouble() { SqlDouble SqlTestDouble; string error = "ToSqlDouble method does not work correctly "; SqlTestDouble = _sqlTrue.ToSqlDouble(); Assert.Equal(1, SqlTestDouble.Value); SqlTestDouble = _sqlFalse.ToSqlDouble(); Assert.Equal(0, SqlTestDouble.Value); } // ToSqlInt16 [Fact] public void ToSqlInt16() { SqlInt16 SqlTestInt16; string error = "ToSqlInt16 method does not work correctly "; SqlTestInt16 = _sqlTrue.ToSqlInt16(); Assert.Equal((short)1, SqlTestInt16.Value); SqlTestInt16 = _sqlFalse.ToSqlInt16(); Assert.Equal((short)0, SqlTestInt16.Value); } // ToSqlInt32 [Fact] public void ToSqlInt32() { SqlInt32 SqlTestInt32; string error = "ToSqlInt32 method does not work correctly "; SqlTestInt32 = _sqlTrue.ToSqlInt32(); Assert.Equal(1, SqlTestInt32.Value); SqlTestInt32 = _sqlFalse.ToSqlInt32(); Assert.Equal(0, SqlTestInt32.Value); } // ToSqlInt64 [Fact] public void ToSqlInt64() { SqlInt64 SqlTestInt64; string error = "ToSqlInt64 method does not work correctly "; SqlTestInt64 = _sqlTrue.ToSqlInt64(); Assert.Equal(1, SqlTestInt64.Value); SqlTestInt64 = _sqlFalse.ToSqlInt64(); Assert.Equal(0, SqlTestInt64.Value); } // ToSqlMoney [Fact] public void ToSqlMoney() { SqlMoney SqlTestMoney; string error = "ToSqlMoney method does not work correctly "; SqlTestMoney = _sqlTrue.ToSqlMoney(); Assert.Equal(1.0000M, SqlTestMoney.Value); SqlTestMoney = _sqlFalse.ToSqlMoney(); Assert.Equal(0, SqlTestMoney.Value); } // ToSqlSingle [Fact] public void ToSqlsingle() { SqlSingle SqlTestSingle; string error = "ToSqlSingle method does not work correctly "; SqlTestSingle = _sqlTrue.ToSqlSingle(); Assert.Equal(1, SqlTestSingle.Value); SqlTestSingle = _sqlFalse.ToSqlSingle(); Assert.Equal(0, SqlTestSingle.Value); } // ToSqlString [Fact] public void ToSqlString() { SqlString SqlTestString; string error = "ToSqlString method does not work correctly "; SqlTestString = _sqlTrue.ToSqlString(); Assert.Equal("True", SqlTestString.Value); SqlTestString = _sqlFalse.ToSqlString(); Assert.Equal("False", SqlTestString.Value); } // ToString [Fact] public void ToStringTest() { SqlString TestString; string error = "ToString method does not work correctly "; TestString = _sqlTrue.ToString(); Assert.Equal("True", TestString.Value); TestString = _sqlFalse.ToSqlString(); Assert.Equal("False", TestString.Value); } // END OF PUBLIC METHODS //// //// // OPERATORS // BitwixeAnd operator [Fact] public void BitwiseAndOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; string error = "BitwiseAnd operator does not work correctly "; SqlResult = _sqlTrue & _sqlFalse; Assert.True(!SqlResult.Value); SqlResult = _sqlFalse & _sqlTrue; Assert.True(!SqlResult.Value); SqlResult = _sqlTrue & SqlTrue2; Assert.True(SqlResult.Value); SqlResult = _sqlFalse & SqlFalse2; Assert.True(!SqlResult.Value); } // BitwixeOr operator [Fact] public void BitwiseOrOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; string error = "BitwiseOr operator does not work correctly "; SqlResult = _sqlTrue | _sqlFalse; Assert.True(SqlResult.Value); SqlResult = _sqlFalse | _sqlTrue; Assert.True(SqlResult.Value); SqlResult = _sqlTrue | SqlTrue2; Assert.True(SqlResult.Value); SqlResult = _sqlFalse | SqlFalse2; Assert.True(!SqlResult.Value); } // Equality operator [Fact] public void EqualityOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; string error = "Equality operator does not work correctly "; SqlResult = _sqlTrue == _sqlFalse; Assert.True(!SqlResult.Value); SqlResult = _sqlFalse == _sqlTrue; Assert.True(!SqlResult.Value); SqlResult = _sqlTrue == SqlTrue2; Assert.True(SqlResult.Value); SqlResult = _sqlFalse == SqlFalse2; Assert.True(SqlResult.Value); SqlResult = _sqlFalse == SqlBoolean.Null; Assert.True(SqlResult.IsNull); //SqlResult = SqlBoolean.Null == SqlBoolean.Null; Assert.True(SqlResult.IsNull); } // ExlusiveOr operator [Fact] public void ExlusiveOrOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); SqlBoolean SqlResult; string error = "ExclusiveOr operator does not work correctly "; SqlResult = _sqlTrue ^ _sqlFalse; Assert.True(SqlResult.Value); SqlResult = _sqlFalse | _sqlTrue; Assert.True(SqlResult.Value); SqlResult = _sqlTrue ^ SqlTrue2; Assert.True(!SqlResult.Value); SqlResult = _sqlFalse ^ SqlFalse2; Assert.True(!SqlResult.Value); } // false operator [Fact] public void FalseOperator() { string error = "false operator does not work correctly "; Assert.Equal(SqlBoolean.False, (!_sqlTrue)); Assert.Equal(SqlBoolean.True, (!_sqlFalse)); } // Inequality operator [Fact] public void InequalityOperator() { SqlBoolean SqlTrue2 = new SqlBoolean(true); SqlBoolean SqlFalse2 = new SqlBoolean(false); string error = "Inequality operator does not work correctly"; Assert.Equal(SqlBoolean.False, _sqlTrue != true); Assert.Equal(SqlBoolean.False, _sqlTrue != SqlTrue2); Assert.Equal(SqlBoolean.False, _sqlFalse != false); Assert.Equal(SqlBoolean.False, _sqlFalse != SqlFalse2); Assert.Equal(SqlBoolean.True, _sqlTrue != _sqlFalse); Assert.Equal(SqlBoolean.True, _sqlFalse != _sqlTrue); Assert.Equal(SqlBoolean.Null, SqlBoolean.Null != _sqlTrue); Assert.Equal(SqlBoolean.Null, _sqlFalse != SqlBoolean.Null); } // Logical Not operator [Fact] public void LogicalNotOperator() { string error = "Logical Not operator does not work correctly"; Assert.Equal(SqlBoolean.False, !_sqlTrue); Assert.Equal(SqlBoolean.True, !_sqlFalse); } // OnesComplement operator [Fact] public void OnesComplementOperator() { string error = "Ones complement operator does not work correctly"; SqlBoolean SqlResult; SqlResult = ~_sqlTrue; Assert.True(!SqlResult.Value); SqlResult = ~_sqlFalse; Assert.True(SqlResult.Value); } // true operator [Fact] public void TrueOperator() { string error = "true operator does not work correctly "; Assert.Equal(SqlBoolean.True, (_sqlTrue)); Assert.Equal(SqlBoolean.False, (_sqlFalse)); } // SqlBoolean to Boolean [Fact] public void SqlBooleanToBoolean() { string error = "SqlBooleanToBoolean operator does not work correctly "; bool TestBoolean = (bool)_sqlTrue; Assert.True(TestBoolean); TestBoolean = (bool)_sqlFalse; Assert.True(!TestBoolean); } // SqlByte to SqlBoolean [Fact] public void SqlByteToSqlBoolean() { SqlByte SqlTestByte; SqlBoolean SqlTestBoolean; string error = "SqlByteToSqlBoolean operator does not work correctly "; SqlTestByte = new SqlByte(1); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert.True(SqlTestBoolean.Value); SqlTestByte = new SqlByte(2); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert.True(SqlTestBoolean.Value); SqlTestByte = new SqlByte(0); SqlTestBoolean = (SqlBoolean)SqlTestByte; Assert.True(!SqlTestBoolean.Value); } // SqlDecimal to SqlBoolean [Fact] public void SqlDecimalToSqlBoolean() { SqlDecimal SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlDecimalToSqlBoolean operator does not work correctly "; SqlTest = new SqlDecimal(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlDecimal(19); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlDecimal(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlDouble to SqlBoolean [Fact] public void SqlDoubleToSqlBoolean() { SqlDouble SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlDoubleToSqlBoolean operator does not work correctly "; SqlTest = new SqlDouble(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlDouble(-19.8); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlDouble(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlIn16 to SqlBoolean [Fact] public void SqlInt16ToSqlBoolean() { SqlInt16 SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlInt16ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt16(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt16(-143); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt16(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlInt32 to SqlBoolean [Fact] public void SqlInt32ToSqlBoolean() { SqlInt32 SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlInt32ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt32(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt32(1430); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt32(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlInt64 to SqlBoolean [Fact] public void SqlInt64ToSqlBoolean() { SqlInt64 SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlInt64ToSqlBoolean operator does not work correctly "; SqlTest = new SqlInt64(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt64(-14305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlInt64(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlMoney to SqlBoolean [Fact] public void SqlMoneyToSqlBoolean() { SqlMoney SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlMoneyToSqlBoolean operator does not work correctly "; SqlTest = new SqlMoney(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlMoney(1305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlMoney(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlSingle to SqlBoolean [Fact] public void SqlSingleToSqlBoolean() { SqlSingle SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlSingleToSqlBoolean operator does not work correctly "; SqlTest = new SqlSingle(1); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlSingle(1305); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlSingle(-305.3); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlSingle(0); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // SqlString to SqlBoolean [Fact] public void SqlStringToSqlBoolean() { SqlString SqlTest; SqlBoolean SqlTestBoolean; string error = "SqlSingleToSqlBoolean operator does not work correctly "; SqlTest = new SqlString("true"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlString("TRUE"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlString("True"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(SqlTestBoolean.Value); SqlTest = new SqlString("false"); SqlTestBoolean = (SqlBoolean)SqlTest; Assert.True(!SqlTestBoolean.Value); } // Boolean to SqlBoolean [Fact] public void BooleanToSqlBoolean() { SqlBoolean SqlTestBoolean; bool btrue = true; bool bfalse = false; string error = "BooleanToSqlBoolean operator does not work correctly "; bool SqlTest = true; SqlTestBoolean = SqlTest; Assert.True(SqlTestBoolean.Value); SqlTestBoolean = btrue; Assert.True(SqlTestBoolean.Value); SqlTest = false; SqlTestBoolean = SqlTest; Assert.True(!SqlTestBoolean.Value); SqlTestBoolean = bfalse; Assert.True(!SqlTestBoolean.Value); } // END OF OPERATORS //// //// // PROPERTIES // ByteValue property [Fact] public void ByteValueProperty() { string error = "ByteValue property does not work correctly "; Assert.Equal((byte)1, _sqlTrue.ByteValue); Assert.Equal((byte)0, _sqlFalse.ByteValue); } // IsFalse property [Fact] public void IsFalseProperty() { string error = "IsFalse property does not work correctly "; Assert.True(!_sqlTrue.IsFalse); Assert.True(_sqlFalse.IsFalse); } // IsNull property [Fact] public void IsNullProperty() { string error = "IsNull property does not work correctly "; Assert.True(!_sqlTrue.IsNull); Assert.True(!_sqlFalse.IsNull); Assert.True(SqlBoolean.Null.IsNull); } // IsTrue property [Fact] public void IsTrueProperty() { string error = "IsTrue property does not work correctly "; Assert.True(_sqlTrue.IsTrue); Assert.True(!_sqlFalse.IsTrue); } // Value property [Fact] public void ValueProperty() { string error = "Value property does not work correctly "; Assert.True(_sqlTrue.Value); Assert.True(!_sqlFalse.Value); } // END OF PROPERTIEs //// //// // FIELDS [Fact] public void FalseField() { Assert.True(!SqlBoolean.False.Value); } [Fact] public void NullField() { Assert.True(SqlBoolean.Null.IsNull); } [Fact] public void OneField() { Assert.Equal((byte)1, SqlBoolean.One.ByteValue); } [Fact] public void TrueField() { Assert.True(SqlBoolean.True.Value); } [Fact] public void ZeroField() { Assert.Equal((byte)0, SqlBoolean.Zero.ByteValue); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlBoolean.GetXsdType(null); Assert.Equal("boolean", qualifiedName.Name); } [Fact] public void GreaterThanTest() { SqlBoolean x = new SqlBoolean(-1); SqlBoolean y = new SqlBoolean(true); SqlBoolean z = new SqlBoolean(); SqlBoolean z1 = new SqlBoolean(0); Assert.False((x > y).Value); Assert.Equal(x > z, SqlBoolean.Null); Assert.True((x > z1).Value); Assert.Equal(y > z, SqlBoolean.Null); Assert.False((y > x).Value); Assert.True((y > z1).Value); Assert.Equal(z > z1, SqlBoolean.Null); Assert.Equal(z > x, SqlBoolean.Null); Assert.Equal(z > y, SqlBoolean.Null); Assert.Equal(z1 > z, SqlBoolean.Null); Assert.False((z1 > x).Value); Assert.False((z1 > y).Value); } [Fact] public void GreaterThanOrEqualTest() { SqlBoolean x = new SqlBoolean(-1); SqlBoolean y = new SqlBoolean(true); SqlBoolean z = new SqlBoolean(); SqlBoolean z1 = new SqlBoolean(0); Assert.True((x >= y).Value); Assert.Equal(x >= z, SqlBoolean.Null); Assert.True((x >= z1).Value); Assert.Equal(y >= z, SqlBoolean.Null); Assert.True((y >= x).Value); Assert.True((y >= z1).Value); Assert.Equal(z >= z1, SqlBoolean.Null); Assert.Equal(z >= x, SqlBoolean.Null); Assert.Equal(z >= y, SqlBoolean.Null); Assert.Equal(z1 >= z, SqlBoolean.Null); Assert.False((z1 >= x).Value); Assert.False((z1 >= y).Value); } [Fact] public void LessThanTest() { SqlBoolean x = new SqlBoolean(-1); SqlBoolean y = new SqlBoolean(true); SqlBoolean z = new SqlBoolean(); SqlBoolean z1 = new SqlBoolean(0); Assert.False((x < y).Value); Assert.Equal(x < z, SqlBoolean.Null); Assert.False((x < z1).Value); Assert.Equal(y < z, SqlBoolean.Null); Assert.False((y < x).Value); Assert.False((y < z1).Value); Assert.Equal(z < z1, SqlBoolean.Null); Assert.Equal(z < x, SqlBoolean.Null); Assert.Equal(z < y, SqlBoolean.Null); Assert.Equal(z1 < z, SqlBoolean.Null); Assert.True((z1 < x).Value); Assert.True((z1 < y).Value); } [Fact] public void LessThanOrEqualTest() { SqlBoolean x = new SqlBoolean(-1); SqlBoolean y = new SqlBoolean(true); SqlBoolean z = new SqlBoolean(); SqlBoolean z1 = new SqlBoolean(0); Assert.True((x <= y).Value); Assert.Equal(x <= z, SqlBoolean.Null); Assert.False((x <= z1).Value); Assert.Equal(y <= z, SqlBoolean.Null); Assert.True((y <= x).Value); Assert.False((y <= z1).Value); Assert.Equal(z <= z1, SqlBoolean.Null); Assert.Equal(z <= x, SqlBoolean.Null); Assert.Equal(z <= y, SqlBoolean.Null); Assert.Equal(z1 <= z, SqlBoolean.Null); Assert.True((z1 <= x).Value); Assert.True((z1 <= y).Value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // Enables instruction counting and displaying stats at process exit. // #define STATS using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Dynamic.Utils; namespace System.Linq.Expressions.Interpreter { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [DebuggerTypeProxy(typeof(InstructionArray.DebugView))] internal struct InstructionArray { internal readonly int MaxStackDepth; internal readonly int MaxContinuationDepth; internal readonly Instruction[] Instructions; internal readonly object[] Objects; internal readonly RuntimeLabel[] Labels; // list of (instruction index, cookie) sorted by instruction index: internal readonly List<KeyValuePair<int, object>> DebugCookies; internal InstructionArray(int maxStackDepth, int maxContinuationDepth, Instruction[] instructions, object[] objects, RuntimeLabel[] labels, List<KeyValuePair<int, object>> debugCookies) { MaxStackDepth = maxStackDepth; MaxContinuationDepth = maxContinuationDepth; Instructions = instructions; DebugCookies = debugCookies; Objects = objects; Labels = labels; } #region Debug View internal sealed class DebugView { private readonly InstructionArray _array; public DebugView(InstructionArray array) { ContractUtils.RequiresNotNull(array, nameof(array)); _array = array; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public InstructionList.DebugView.InstructionView[]/*!*/ A0 => GetInstructionViews(includeDebugCookies: true); public InstructionList.DebugView.InstructionView[] GetInstructionViews(bool includeDebugCookies = false) { return InstructionList.DebugView.GetInstructionViews( _array.Instructions, _array.Objects, (index) => _array.Labels[index].Index, includeDebugCookies ? _array.DebugCookies : null ); } } #endregion } [DebuggerTypeProxy(typeof(InstructionList.DebugView))] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal sealed class InstructionList { private readonly List<Instruction> _instructions = new List<Instruction>(); private List<object> _objects; private int _currentStackDepth; private int _maxStackDepth; private int _currentContinuationsDepth; private int _maxContinuationDepth; private int _runtimeLabelCount; private List<BranchLabel> _labels; // list of (instruction index, cookie) sorted by instruction index: private List<KeyValuePair<int, object>> _debugCookies = null; #region Debug View internal sealed class DebugView { private readonly InstructionList _list; public DebugView(InstructionList list) { ContractUtils.RequiresNotNull(list, nameof(list)); _list = list; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public InstructionView[]/*!*/ A0 => GetInstructionViews(includeDebugCookies: true); public InstructionView[] GetInstructionViews(bool includeDebugCookies = false) { return GetInstructionViews( _list._instructions, _list._objects, (index) => _list._labels[index].TargetIndex, includeDebugCookies ? _list._debugCookies : null ); } internal static InstructionView[] GetInstructionViews(IReadOnlyList<Instruction> instructions, IReadOnlyList<object> objects, Func<int, int> labelIndexer, IReadOnlyList<KeyValuePair<int, object>> debugCookies) { var result = new List<InstructionView>(); int index = 0; int stackDepth = 0; int continuationsDepth = 0; IEnumerator<KeyValuePair<int, object>> cookieEnumerator = (debugCookies ?? Array.Empty<KeyValuePair<int, object>>()).GetEnumerator(); bool hasCookie = cookieEnumerator.MoveNext(); for (int i = 0, n = instructions.Count; i < n; i++) { Instruction instruction = instructions[i]; object cookie = null; while (hasCookie && cookieEnumerator.Current.Key == i) { cookie = cookieEnumerator.Current.Value; hasCookie = cookieEnumerator.MoveNext(); } int stackDiff = instruction.StackBalance; int contDiff = instruction.ContinuationsBalance; string name = instruction.ToDebugString(i, cookie, labelIndexer, objects); result.Add(new InstructionView(instruction, name, i, stackDepth, continuationsDepth)); index++; stackDepth += stackDiff; continuationsDepth += contDiff; } return result.ToArray(); } [DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")] internal struct InstructionView { private readonly int _index; private readonly int _stackDepth; private readonly int _continuationsDepth; private readonly string _name; private readonly Instruction _instruction; internal string GetName() { return _index + (_continuationsDepth == 0 ? "" : " C(" + _continuationsDepth + ")") + (_stackDepth == 0 ? "" : " S(" + _stackDepth + ")"); } internal string GetValue() { return _name; } internal string GetDisplayType() { return _instruction.ContinuationsBalance + "/" + _instruction.StackBalance; } public InstructionView(Instruction instruction, string name, int index, int stackDepth, int continuationsDepth) { _instruction = instruction; _name = name; _index = index; _stackDepth = stackDepth; _continuationsDepth = continuationsDepth; } } } #endregion #region Core Emit Ops public void Emit(Instruction instruction) { _instructions.Add(instruction); UpdateStackDepth(instruction); } private void UpdateStackDepth(Instruction instruction) { Debug.Assert(instruction.ConsumedStack >= 0 && instruction.ProducedStack >= 0 && instruction.ConsumedContinuations >= 0 && instruction.ProducedContinuations >= 0, "bad instruction " + instruction.ToString()); _currentStackDepth -= instruction.ConsumedStack; Debug.Assert(_currentStackDepth >= 0, "negative stack depth " + instruction.ToString()); _currentStackDepth += instruction.ProducedStack; if (_currentStackDepth > _maxStackDepth) { _maxStackDepth = _currentStackDepth; } _currentContinuationsDepth -= instruction.ConsumedContinuations; Debug.Assert(_currentContinuationsDepth >= 0, "negative continuations " + instruction.ToString()); _currentContinuationsDepth += instruction.ProducedContinuations; if (_currentContinuationsDepth > _maxContinuationDepth) { _maxContinuationDepth = _currentContinuationsDepth; } } // "Un-emit" the previous instruction. // Useful if the instruction was emitted in the calling method, and covers the more usual case. // In particular, calling this after an EmitPush() or EmitDup() costs about the same as adding // an EmitPop() to undo it at compile time, and leaves a slightly leaner instruction list. public void UnEmit() { Instruction instruction = _instructions[_instructions.Count - 1]; _instructions.RemoveAt(_instructions.Count - 1); _currentContinuationsDepth -= instruction.ProducedContinuations; _currentContinuationsDepth += instruction.ConsumedContinuations; _currentStackDepth -= instruction.ProducedStack; _currentStackDepth += instruction.ConsumedStack; } /// <summary> /// Attaches a cookie to the last emitted instruction. /// </summary> [Conditional("DEBUG")] public void SetDebugCookie(object cookie) { #if DEBUG if (_debugCookies == null) { _debugCookies = new List<KeyValuePair<int, object>>(); } Debug.Assert(Count > 0); _debugCookies.Add(new KeyValuePair<int, object>(Count - 1, cookie)); #endif } public int Count => _instructions.Count; public int CurrentStackDepth => _currentStackDepth; public int CurrentContinuationsDepth => _currentContinuationsDepth; public int MaxStackDepth => _maxStackDepth; internal Instruction GetInstruction(int index) => _instructions[index]; #if STATS private static Dictionary<string, int> _executedInstructions = new Dictionary<string, int>(); private static Dictionary<string, Dictionary<object, bool>> _instances = new Dictionary<string, Dictionary<object, bool>>(); static InstructionList() { AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) => { PerfTrack.DumpHistogram(_executedInstructions); Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, (sum, value) => sum + value)); Console.WriteLine("-----"); var referenced = new Dictionary<string, int>(); int total = 0; foreach (var entry in _instances) { referenced[entry.Key] = entry.Value.Count; total += entry.Value.Count; } PerfTrack.DumpHistogram(referenced); Console.WriteLine("-- Total referenced: {0}", total); Console.WriteLine("-----"); }); } #endif public InstructionArray ToArray() { #if STATS lock (_executedInstructions) { _instructions.ForEach((instr) => { int value = 0; var name = instr.GetType().Name; _executedInstructions.TryGetValue(name, out value); _executedInstructions[name] = value + 1; Dictionary<object, bool> dict; if (!_instances.TryGetValue(name, out dict)) { _instances[name] = dict = new Dictionary<object, bool>(); } dict[instr] = true; }); } #endif return new InstructionArray( _maxStackDepth, _maxContinuationDepth, _instructions.ToArray(), _objects?.ToArray(), BuildRuntimeLabels(), _debugCookies ); } #endregion #region Stack Operations private const int PushIntMinCachedValue = -100; private const int PushIntMaxCachedValue = 100; private const int CachedObjectCount = 256; private static Instruction s_null; private static Instruction s_true; private static Instruction s_false; private static Instruction[] s_Ints; private static Instruction[] s_loadObjectCached; public void EmitLoad(object value) { EmitLoad(value, type: null); } public void EmitLoad(bool value) { if (value) { Emit(s_true ?? (s_true = new LoadObjectInstruction(Utils.BoxedTrue))); } else { Emit(s_false ?? (s_false = new LoadObjectInstruction(Utils.BoxedFalse))); } } public void EmitLoad(object value, Type type) { if (value == null) { Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); return; } if (type == null || type.IsValueType) { if (value is bool) { EmitLoad((bool)value); return; } if (value is int) { int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { if (s_Ints == null) { s_Ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; } i -= PushIntMinCachedValue; Emit(s_Ints[i] ?? (s_Ints[i] = new LoadObjectInstruction(value))); return; } } } if (_objects == null) { _objects = new List<object>(); if (s_loadObjectCached == null) { s_loadObjectCached = new Instruction[CachedObjectCount]; } } if (_objects.Count < s_loadObjectCached.Length) { uint index = (uint)_objects.Count; _objects.Add(value); Emit(s_loadObjectCached[index] ?? (s_loadObjectCached[index] = new LoadCachedObjectInstruction(index))); } else { Emit(new LoadObjectInstruction(value)); } } public void EmitDup() { Emit(DupInstruction.Instance); } public void EmitPop() { Emit(PopInstruction.Instance); } #endregion #region Locals internal void SwitchToBoxed(int index, int instructionIndex) { var instruction = _instructions[instructionIndex] as IBoxableInstruction; if (instruction != null) { Instruction newInstruction = instruction.BoxIfIndexMatches(index); if (newInstruction != null) { _instructions[instructionIndex] = newInstruction; } } } private const int LocalInstrCacheSize = 64; private static Instruction[] s_loadLocal; private static Instruction[] s_loadLocalBoxed; private static Instruction[] s_loadLocalFromClosure; private static Instruction[] s_loadLocalFromClosureBoxed; private static Instruction[] s_assignLocal; private static Instruction[] s_storeLocal; private static Instruction[] s_assignLocalBoxed; private static Instruction[] s_storeLocalBoxed; private static Instruction[] s_assignLocalToClosure; public void EmitLoadLocal(int index) { if (s_loadLocal == null) { s_loadLocal = new Instruction[LocalInstrCacheSize]; } if (index < s_loadLocal.Length) { Emit(s_loadLocal[index] ?? (s_loadLocal[index] = new LoadLocalInstruction(index))); } else { Emit(new LoadLocalInstruction(index)); } } public void EmitLoadLocalBoxed(int index) { Emit(LoadLocalBoxed(index)); } internal static Instruction LoadLocalBoxed(int index) { if (s_loadLocalBoxed == null) { s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; } if (index < s_loadLocalBoxed.Length) { return s_loadLocalBoxed[index] ?? (s_loadLocalBoxed[index] = new LoadLocalBoxedInstruction(index)); } else { return new LoadLocalBoxedInstruction(index); } } public void EmitLoadLocalFromClosure(int index) { if (s_loadLocalFromClosure == null) { s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; } if (index < s_loadLocalFromClosure.Length) { Emit(s_loadLocalFromClosure[index] ?? (s_loadLocalFromClosure[index] = new LoadLocalFromClosureInstruction(index))); } else { Emit(new LoadLocalFromClosureInstruction(index)); } } public void EmitLoadLocalFromClosureBoxed(int index) { if (s_loadLocalFromClosureBoxed == null) { s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; } if (index < s_loadLocalFromClosureBoxed.Length) { Emit(s_loadLocalFromClosureBoxed[index] ?? (s_loadLocalFromClosureBoxed[index] = new LoadLocalFromClosureBoxedInstruction(index))); } else { Emit(new LoadLocalFromClosureBoxedInstruction(index)); } } public void EmitAssignLocal(int index) { if (s_assignLocal == null) { s_assignLocal = new Instruction[LocalInstrCacheSize]; } if (index < s_assignLocal.Length) { Emit(s_assignLocal[index] ?? (s_assignLocal[index] = new AssignLocalInstruction(index))); } else { Emit(new AssignLocalInstruction(index)); } } public void EmitStoreLocal(int index) { if (s_storeLocal == null) { s_storeLocal = new Instruction[LocalInstrCacheSize]; } if (index < s_storeLocal.Length) { Emit(s_storeLocal[index] ?? (s_storeLocal[index] = new StoreLocalInstruction(index))); } else { Emit(new StoreLocalInstruction(index)); } } public void EmitAssignLocalBoxed(int index) { Emit(AssignLocalBoxed(index)); } internal static Instruction AssignLocalBoxed(int index) { if (s_assignLocalBoxed == null) { s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; } if (index < s_assignLocalBoxed.Length) { return s_assignLocalBoxed[index] ?? (s_assignLocalBoxed[index] = new AssignLocalBoxedInstruction(index)); } else { return new AssignLocalBoxedInstruction(index); } } public void EmitStoreLocalBoxed(int index) { Emit(StoreLocalBoxed(index)); } internal static Instruction StoreLocalBoxed(int index) { if (s_storeLocalBoxed == null) { s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; } if (index < s_storeLocalBoxed.Length) { return s_storeLocalBoxed[index] ?? (s_storeLocalBoxed[index] = new StoreLocalBoxedInstruction(index)); } else { return new StoreLocalBoxedInstruction(index); } } public void EmitAssignLocalToClosure(int index) { if (s_assignLocalToClosure == null) { s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; } if (index < s_assignLocalToClosure.Length) { Emit(s_assignLocalToClosure[index] ?? (s_assignLocalToClosure[index] = new AssignLocalToClosureInstruction(index))); } else { Emit(new AssignLocalToClosureInstruction(index)); } } public void EmitStoreLocalToClosure(int index) { EmitAssignLocalToClosure(index); EmitPop(); } public void EmitInitializeLocal(int index, Type type) { object value = ScriptingRuntimeHelpers.GetPrimitiveDefaultValue(type); if (value != null) { Emit(new InitializeLocalInstruction.ImmutableValue(index, value)); } else if (type.IsValueType) { Emit(new InitializeLocalInstruction.MutableValue(index, type)); } else { Emit(InitReference(index)); } } internal void EmitInitializeParameter(int index) { Emit(Parameter(index)); } internal static Instruction Parameter(int index) { return new InitializeLocalInstruction.Parameter(index); } internal static Instruction ParameterBox(int index) { return new InitializeLocalInstruction.ParameterBox(index); } internal static Instruction InitReference(int index) { return new InitializeLocalInstruction.Reference(index); } internal static Instruction InitImmutableRefBox(int index) { return new InitializeLocalInstruction.ImmutableRefBox(index); } public void EmitNewRuntimeVariables(int count) { Emit(new RuntimeVariablesInstruction(count)); } #endregion #region Array Operations public void EmitGetArrayItem() { Emit(GetArrayItemInstruction.Instance); } public void EmitSetArrayItem() { Emit(SetArrayItemInstruction.Instance); } public void EmitNewArray(Type elementType) { Emit(new NewArrayInstruction(elementType)); } public void EmitNewArrayBounds(Type elementType, int rank) { Emit(new NewArrayBoundsInstruction(elementType, rank)); } public void EmitNewArrayInit(Type elementType, int elementCount) { Emit(new NewArrayInitInstruction(elementType, elementCount)); } #endregion #region Arithmetic Operations public void EmitAdd(Type type, bool @checked) { Emit(@checked ? AddOvfInstruction.Create(type) : AddInstruction.Create(type)); } public void EmitSub(Type type, bool @checked) { Emit(@checked ? SubOvfInstruction.Create(type) : SubInstruction.Create(type)); } public void EmitMul(Type type, bool @checked) { Emit(@checked ? MulOvfInstruction.Create(type) : MulInstruction.Create(type)); } public void EmitDiv(Type type) { Emit(DivInstruction.Create(type)); } public void EmitModulo(Type type) { Emit(ModuloInstruction.Create(type)); } #endregion #region Comparisons public void EmitExclusiveOr(Type type) { Emit(ExclusiveOrInstruction.Create(type)); } public void EmitAnd(Type type) { Emit(AndInstruction.Create(type)); } public void EmitOr(Type type) { Emit(OrInstruction.Create(type)); } public void EmitLeftShift(Type type) { Emit(LeftShiftInstruction.Create(type)); } public void EmitRightShift(Type type) { Emit(RightShiftInstruction.Create(type)); } public void EmitEqual(Type type, bool liftedToNull = false) { Emit(EqualInstruction.Create(type, liftedToNull)); } public void EmitNotEqual(Type type, bool liftedToNull = false) { Emit(NotEqualInstruction.Create(type, liftedToNull)); } public void EmitLessThan(Type type, bool liftedToNull) { Emit(LessThanInstruction.Create(type, liftedToNull)); } public void EmitLessThanOrEqual(Type type, bool liftedToNull) { Emit(LessThanOrEqualInstruction.Create(type, liftedToNull)); } public void EmitGreaterThan(Type type, bool liftedToNull) { Emit(GreaterThanInstruction.Create(type, liftedToNull)); } public void EmitGreaterThanOrEqual(Type type, bool liftedToNull) { Emit(GreaterThanOrEqualInstruction.Create(type, liftedToNull)); } #endregion #region Conversions public void EmitNumericConvertChecked(TypeCode from, TypeCode to, bool isLiftedToNull) { Emit(new NumericConvertInstruction.Checked(from, to, isLiftedToNull)); } public void EmitNumericConvertUnchecked(TypeCode from, TypeCode to, bool isLiftedToNull) { Emit(new NumericConvertInstruction.Unchecked(from, to, isLiftedToNull)); } public void EmitConvertToUnderlying(TypeCode to, bool isLiftedToNull) { Emit(new NumericConvertInstruction.ToUnderlying(to, isLiftedToNull)); } public void EmitCast(Type toType) { Emit(CastInstruction.Create(toType)); } public void EmitCastToEnum(Type toType) { Emit(new CastToEnumInstruction(toType)); } public void EmitCastReferenceToEnum(Type toType) { Debug.Assert(_instructions[_instructions.Count - 1] == NullCheckInstruction.Instance); Emit(new CastReferenceToEnumInstruction(toType)); } #endregion #region Boolean Operators public void EmitNot(Type type) { Emit(NotInstruction.Create(type)); } #endregion #region Types public void EmitDefaultValue(Type type) { Emit(new DefaultValueInstruction(type)); } public void EmitNew(ConstructorInfo constructorInfo) { EmitNew(constructorInfo, constructorInfo.GetParametersCached()); } public void EmitNew(ConstructorInfo constructorInfo, ParameterInfo[] parameters) { Emit(new NewInstruction(constructorInfo, parameters.Length)); } public void EmitByRefNew(ConstructorInfo constructorInfo, ByRefUpdater[] updaters) { EmitByRefNew(constructorInfo, constructorInfo.GetParametersCached(), updaters); } public void EmitByRefNew(ConstructorInfo constructorInfo, ParameterInfo[] parameters, ByRefUpdater[] updaters) { Emit(new ByRefNewInstruction(constructorInfo, parameters.Length, updaters)); } internal void EmitCreateDelegate(LightDelegateCreator creator) { Emit(new CreateDelegateInstruction(creator)); } public void EmitTypeEquals() { Emit(TypeEqualsInstruction.Instance); } public void EmitArrayLength() { Emit(ArrayLengthInstruction.Instance); } public void EmitNegate(Type type) { Emit(NegateInstruction.Create(type)); } public void EmitNegateChecked(Type type) { Emit(NegateCheckedInstruction.Create(type)); } public void EmitIncrement(Type type) { Emit(IncrementInstruction.Create(type)); } public void EmitDecrement(Type type) { Emit(DecrementInstruction.Create(type)); } public void EmitTypeIs(Type type) { Emit(new TypeIsInstruction(type)); } public void EmitTypeAs(Type type) { Emit(new TypeAsInstruction(type)); } #endregion #region Fields and Methods private static readonly Dictionary<FieldInfo, Instruction> s_loadFields = new Dictionary<FieldInfo, Instruction>(); public void EmitLoadField(FieldInfo field) { Emit(GetLoadField(field)); } private Instruction GetLoadField(FieldInfo field) { lock (s_loadFields) { Instruction instruction; if (!s_loadFields.TryGetValue(field, out instruction)) { if (field.IsStatic) { instruction = new LoadStaticFieldInstruction(field); } else { instruction = new LoadFieldInstruction(field); } s_loadFields.Add(field, instruction); } return instruction; } } public void EmitStoreField(FieldInfo field) { if (field.IsStatic) { Emit(new StoreStaticFieldInstruction(field)); } else { Emit(new StoreFieldInstruction(field)); } } public void EmitCall(MethodInfo method) { EmitCall(method, method.GetParametersCached()); } public void EmitCall(MethodInfo method, ParameterInfo[] parameters) { Emit(CallInstruction.Create(method, parameters)); } public void EmitByRefCall(MethodInfo method, ParameterInfo[] parameters, ByRefUpdater[] byrefArgs) { Emit(new ByRefMethodInfoCallInstruction(method, method.IsStatic ? parameters.Length : parameters.Length + 1, byrefArgs)); } public void EmitNullableCall(MethodInfo method, ParameterInfo[] parameters) { Emit(NullableMethodCallInstruction.Create(method.Name, parameters.Length, method)); } #endregion #region Control Flow private static readonly RuntimeLabel[] s_emptyRuntimeLabels = new RuntimeLabel[] { new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0) }; private RuntimeLabel[] BuildRuntimeLabels() { if (_runtimeLabelCount == 0) { return s_emptyRuntimeLabels; } var result = new RuntimeLabel[_runtimeLabelCount + 1]; foreach (BranchLabel label in _labels) { if (label.HasRuntimeLabel) { result[label.LabelIndex] = label.ToRuntimeLabel(); } } // "return and rethrow" label: result[result.Length - 1] = new RuntimeLabel(Interpreter.RethrowOnReturn, 0, 0); return result; } public BranchLabel MakeLabel() { if (_labels == null) { _labels = new List<BranchLabel>(); } var label = new BranchLabel(); _labels.Add(label); return label; } internal void FixupBranch(int branchIndex, int offset) { _instructions[branchIndex] = ((OffsetInstruction)_instructions[branchIndex]).Fixup(offset); } private int EnsureLabelIndex(BranchLabel label) { if (label.HasRuntimeLabel) { return label.LabelIndex; } label.LabelIndex = _runtimeLabelCount; _runtimeLabelCount++; return label.LabelIndex; } public int MarkRuntimeLabel() { BranchLabel handlerLabel = MakeLabel(); MarkLabel(handlerLabel); return EnsureLabelIndex(handlerLabel); } public void MarkLabel(BranchLabel label) { label.Mark(this); } public void EmitGoto(BranchLabel label, bool hasResult, bool hasValue, bool labelTargetGetsValue) { Emit(GotoInstruction.Create(EnsureLabelIndex(label), hasResult, hasValue, labelTargetGetsValue)); } private void EmitBranch(OffsetInstruction instruction, BranchLabel label) { Emit(instruction); label.AddBranch(this, Count - 1); } public void EmitBranch(BranchLabel label) { EmitBranch(new BranchInstruction(), label); } public void EmitBranch(BranchLabel label, bool hasResult, bool hasValue) { EmitBranch(new BranchInstruction(hasResult, hasValue), label); } public void EmitCoalescingBranch(BranchLabel leftNotNull) { EmitBranch(new CoalescingBranchInstruction(), leftNotNull); } public void EmitBranchTrue(BranchLabel elseLabel) { EmitBranch(new BranchTrueInstruction(), elseLabel); } public void EmitBranchFalse(BranchLabel elseLabel) { EmitBranch(new BranchFalseInstruction(), elseLabel); } public void EmitThrow() { Emit(ThrowInstruction.Throw); } public void EmitThrowVoid() { Emit(ThrowInstruction.VoidThrow); } public void EmitRethrow() { Emit(ThrowInstruction.Rethrow); } public void EmitRethrowVoid() { Emit(ThrowInstruction.VoidRethrow); } public void EmitEnterTryFinally(BranchLabel finallyStartLabel) { Emit(EnterTryCatchFinallyInstruction.CreateTryFinally(EnsureLabelIndex(finallyStartLabel))); } public void EmitEnterTryCatch() { Emit(EnterTryCatchFinallyInstruction.CreateTryCatch()); } public EnterTryFaultInstruction EmitEnterTryFault(BranchLabel tryEnd) { var instruction = new EnterTryFaultInstruction(EnsureLabelIndex(tryEnd)); Emit(instruction); return instruction; } public void EmitEnterFinally(BranchLabel finallyStartLabel) { Emit(EnterFinallyInstruction.Create(EnsureLabelIndex(finallyStartLabel))); } public void EmitLeaveFinally() { Emit(LeaveFinallyInstruction.Instance); } public void EmitEnterFault(BranchLabel faultStartLabel) { Emit(EnterFaultInstruction.Create(EnsureLabelIndex(faultStartLabel))); } public void EmitLeaveFault() { Emit(LeaveFaultInstruction.Instance); } public void EmitEnterExceptionFilter() { Emit(EnterExceptionFilterInstruction.Instance); } public void EmitLeaveExceptionFilter() { Emit(LeaveExceptionFilterInstruction.Instance); } public void EmitEnterExceptionHandlerNonVoid() { Emit(EnterExceptionHandlerInstruction.NonVoid); } public void EmitEnterExceptionHandlerVoid() { Emit(EnterExceptionHandlerInstruction.Void); } public void EmitLeaveExceptionHandler(bool hasValue, BranchLabel tryExpressionEndLabel) { Emit(LeaveExceptionHandlerInstruction.Create(EnsureLabelIndex(tryExpressionEndLabel), hasValue)); } public void EmitIntSwitch<T>(Dictionary<T, int> cases) { Emit(new IntSwitchInstruction<T>(cases)); } public void EmitStringSwitch(Dictionary<string, int> cases, StrongBox<int> nullCase) { Emit(new StringSwitchInstruction(cases, nullCase)); } #endregion } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C02_Continent (editable root object).<br/> /// This is a generated base class of <see cref="C02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="C03_SubContinentObjects"/> of type <see cref="C03_SubContinentColl"/> (1:M relation to <see cref="C04_SubContinent"/>) /// </remarks> [Serializable] public partial class C02_Continent : BusinessBase<C02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID"); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets or sets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_Child> C03_Continent_SingleObjectProperty = RegisterProperty<C03_Continent_Child>(p => p.C03_Continent_SingleObject, "C03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the C03 Continent Single Object ("self load" child property). /// </summary> /// <value>The C03 Continent Single Object.</value> public C03_Continent_Child C03_Continent_SingleObject { get { return GetProperty(C03_Continent_SingleObjectProperty); } private set { LoadProperty(C03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_ReChild> C03_Continent_ASingleObjectProperty = RegisterProperty<C03_Continent_ReChild>(p => p.C03_Continent_ASingleObject, "C03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the C03 Continent ASingle Object ("self load" child property). /// </summary> /// <value>The C03 Continent ASingle Object.</value> public C03_Continent_ReChild C03_Continent_ASingleObject { get { return GetProperty(C03_Continent_ASingleObjectProperty); } private set { LoadProperty(C03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<C03_SubContinentColl> C03_SubContinentObjectsProperty = RegisterProperty<C03_SubContinentColl>(p => p.C03_SubContinentObjects, "C03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the C03 Sub Continent Objects ("self load" child property). /// </summary> /// <value>The C03 Sub Continent Objects.</value> public C03_SubContinentColl C03_SubContinentObjects { get { return GetProperty(C03_SubContinentObjectsProperty); } private set { LoadProperty(C03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="C02_Continent"/> object.</returns> public static C02_Continent NewC02_Continent() { return DataPortal.Create<C02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="C02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID parameter of the C02_Continent to fetch.</param> /// <returns>A reference to the fetched <see cref="C02_Continent"/> object.</returns> public static C02_Continent GetC02_Continent(int continent_ID) { return DataPortal.Fetch<C02_Continent>(continent_ID); } /// <summary> /// Factory method. Deletes a <see cref="C02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID of the C02_Continent to delete.</param> public static void DeleteC02_Continent(int continent_ID) { DataPortal.Delete<C02_Continent>(continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void DataPortal_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(C03_Continent_SingleObjectProperty, DataPortal.CreateChild<C03_Continent_Child>()); LoadProperty(C03_Continent_ASingleObjectProperty, DataPortal.CreateChild<C03_Continent_ReChild>()); LoadProperty(C03_SubContinentObjectsProperty, DataPortal.CreateChild<C03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="C02_Continent"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID">The Continent ID.</param> protected void DataPortal_Fetch(int continent_ID) { var args = new DataPortalHookArgs(continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC02_ContinentDal>(); var data = dal.Fetch(continent_ID); Fetch(data); } OnFetchPost(args); FetchChildren(); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> private void FetchChildren() { LoadProperty(C03_Continent_SingleObjectProperty, C03_Continent_Child.GetC03_Continent_Child(Continent_ID)); LoadProperty(C03_Continent_ASingleObjectProperty, C03_Continent_ReChild.GetC03_Continent_ReChild(Continent_ID)); LoadProperty(C03_SubContinentObjectsProperty, C03_SubContinentColl.GetC03_SubContinentColl(Continent_ID)); } /// <summary> /// Inserts a new <see cref="C02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IC02_ContinentDal>(); using (BypassPropertyChecks) { int continent_ID = -1; dal.Insert( out continent_ID, Continent_Name ); LoadProperty(Continent_IDProperty, continent_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="C02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IC02_ContinentDal>(); using (BypassPropertyChecks) { dal.Update( Continent_ID, Continent_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="C02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_DeleteSelf() { DataPortal_Delete(Continent_ID); } /// <summary> /// Deletes the <see cref="C02_Continent"/> object from database. /// </summary> /// <param name="continent_ID">The Continent ID.</param> [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(int continent_ID) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<IC02_ContinentDal>(); using (BypassPropertyChecks) { dal.Delete(continent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
namespace FakeItEasy.Tests.Creation { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using FakeItEasy.Core; using FakeItEasy.Creation; using NUnit.Framework; using Guard = FakeItEasy.Guard; [TestFixture] public class DummyValueCreationSessionTests { private IFakeObjectContainer container; private IFakeObjectCreator fakeObjectCreator; private DummyValueCreationSession session; [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Used reflectively.")] private object[] dummiesInContainer = new object[] { "dummy value", new Task<int>(() => 7), new Task(delegate { }) }; [SetUp] public void Setup() { this.container = A.Fake<IFakeObjectContainer>(); this.fakeObjectCreator = A.Fake<IFakeObjectCreator>(); this.session = new DummyValueCreationSession(this.container, this.fakeObjectCreator); } [TestCaseSource("dummiesInContainer")] public void Should_return_dummy_from_container_when_available(object dummyInContainer) { Guard.AgainstNull(dummyInContainer, "dummyInContainer"); // Arrange this.StubContainerWithValue(dummyInContainer); // Act object dummy; var result = this.session.TryResolveDummyValue(dummyInContainer.GetType(), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.SameAs(dummyInContainer)); } [Test] public void Should_return_false_when_type_cannot_be_created() { // Arrange // Act object dummy = null; var result = this.session.TryResolveDummyValue(typeof(TypeThatCanNotBeInstantiated), out dummy); // Assert Assert.That(result, Is.False); Assert.That(dummy, Is.Null); } [Test] public void Should_return_fake_when_it_can_be_created() { // Arrange var fake = A.Fake<IFoo>(); this.StubFakeObjectCreatorWithValue<IFoo>(fake); // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(IFoo), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.SameAs(fake)); } [Test] public void Should_return_default_value_when_type_is_value_type() { // Arrange // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(int), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.EqualTo(0)); } [Test] public void Should_be_able_to_create_class_with_default_constructor() { // Arrange // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(ClassWithDefaultConstructor), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.InstanceOf<ClassWithDefaultConstructor>()); } [Test] public void Should_be_able_to_create_class_with_resolvable_constructor_arguments() { // Arrange this.StubContainerWithValue("dummy string"); this.StubFakeObjectCreatorWithValue(A.Fake<IFoo>()); // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(TypeWithResolvableConstructorArguments<string, IFoo>), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.InstanceOf<TypeWithResolvableConstructorArguments<string, IFoo>>()); } [Test] public void Should_not_be_able_to_create_class_with_circular_dependencies() { // Arrange // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(TypeWithCircularDependency), out dummy); // Assert Assert.That(result, Is.False); } [Test] public void Should_be_able_to_resolve_same_type_twice_when_successful() { // Arrange this.StubContainerWithValue("dummy value"); object dummy; this.session.TryResolveDummyValue(typeof(string), out dummy); dummy = null; // Act var result = this.session.TryResolveDummyValue(typeof(string), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.EqualTo("dummy value")); } [Test] public void Should_return_false_when_default_constructor_throws() { // Arrange // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(TypeWithDefaultConstructorThatThrows), out dummy); // Assert Assert.That(result, Is.False); } [Test] public void Should_favor_the_widest_constructor_when_activating() { // Arrange this.StubContainerWithValue("dummy value"); // Act object dummy; this.session.TryResolveDummyValue(typeof(TypeWithMultipleConstructorsOfDifferentWidth), out dummy); var typedDummy = (TypeWithMultipleConstructorsOfDifferentWidth)dummy; // Assert Assert.That(typedDummy.WidestConstructorWasCalled, Is.True); } [TestCase(typeof(void))] [TestCase(typeof(Func<int>))] [TestCase(typeof(Action))] public void Should_return_false_for_restricted_types(Type restrictedType) { // Arrange // Act object dummy; var result = this.session.TryResolveDummyValue(restrictedType, out dummy); // Assert Assert.That(result, Is.False); } [Test] public void Should_be_able_to_create_lazy_wrapper() { // Arrange var fake = A.Fake<IFoo>(); this.StubFakeObjectCreatorWithValue<IFoo>(fake); // Act object dummy; var result = this.session.TryResolveDummyValue(typeof(Lazy<IFoo>), out dummy); // Assert Assert.That(result, Is.True); Assert.That(dummy, Is.InstanceOf<Lazy<IFoo>>()); Assert.That(((Lazy<IFoo>)dummy).Value, Is.SameAs(fake)); } private void StubFakeObjectCreatorWithValue<T>(T value) { object output; A.CallTo(() => this.fakeObjectCreator.TryCreateFakeObject(typeof(T), this.session, out output)) .Returns(true) .AssignsOutAndRefParameters(value); } private void StubContainerWithValue(object value) { object output; A.CallTo(() => this.container.TryCreateDummyObject(value.GetType(), out output)) .Returns(true) .AssignsOutAndRefParameters(value); } public class ClassWithDefaultConstructor { } public class TypeWithResolvableConstructorArguments<T1, T2> { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")] public TypeWithResolvableConstructorArguments(T1 argument1, T2 argument2) { } } public class TypeWithCircularDependency { [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "circular", Justification = "Required for testing.")] public TypeWithCircularDependency(TypeWithCircularDependency circular) { } } public class TypeWithMultipleConstructorsOfDifferentWidth { public TypeWithMultipleConstructorsOfDifferentWidth() { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")] public TypeWithMultipleConstructorsOfDifferentWidth(string argument1) { } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")] public TypeWithMultipleConstructorsOfDifferentWidth(string argument1, string argument2) { this.WidestConstructorWasCalled = true; } public bool WidestConstructorWasCalled { get; set; } } private static class TypeThatCanNotBeInstantiated { } private class TypeWithDefaultConstructorThatThrows { public TypeWithDefaultConstructorThatThrows() { throw new InvalidOperationException(); } } } }
//! \file KiriKiriCx.cs //! \date Sun Sep 07 06:50:11 2014 //! \brief KiriKiri Cx encryption scheme implementation. // // Copyright (C) 2014-2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Text; namespace GameRes.Formats.KiriKiri { public class CxProgramException : ApplicationException { public CxProgramException (string message) : base (message) { } } [Serializable] public class CxScheme { public uint Mask; public uint Offset; public byte[] PrologOrder; public byte[] OddBranchOrder; public byte[] EvenBranchOrder; public uint[] ControlBlock; public string TpmFileName; } [Serializable] public class CxEncryption : ICrypt { private uint m_mask; private uint m_offset; protected byte[] PrologOrder; protected byte[] OddBranchOrder; protected byte[] EvenBranchOrder; protected uint[] ControlBlock; protected string TpmFileName; [NonSerialized] CxProgram[] m_program_list = new CxProgram[0x80]; [OnDeserialized()] void PostDeserialization (StreamingContext context) { m_program_list = new CxProgram[0x80]; } public CxEncryption (CxScheme scheme) { m_mask = scheme.Mask; m_offset = scheme.Offset; PrologOrder = scheme.PrologOrder; OddBranchOrder = scheme.OddBranchOrder; EvenBranchOrder = scheme.EvenBranchOrder; ControlBlock = scheme.ControlBlock; TpmFileName = scheme.TpmFileName; } public override string ToString () { return string.Format ("{0}(0x{1:X}, 0x{2:X})", base.ToString(), m_mask, m_offset); } static readonly byte[] s_ctl_block_signature = Encoding.ASCII.GetBytes (" Encryption control block"); /// <summary> /// Look for control block within specified TPM plugin file. /// </summary> public override void Init (ArcFile arc) { if (ControlBlock != null) return; if (string.IsNullOrEmpty (TpmFileName)) throw new InvalidEncryptionScheme(); var dir_name = VFS.GetDirectoryName (arc.File.Name); var tpm_name = VFS.CombinePath (dir_name, TpmFileName); using (var tpm = VFS.OpenView (tpm_name)) { if (tpm.MaxOffset < 0x1000 || tpm.MaxOffset > uint.MaxValue) throw new InvalidEncryptionScheme ("Invalid KiriKiri TPM plugin"); using (var view = tpm.CreateViewAccessor (0, (uint)tpm.MaxOffset)) unsafe { byte* begin = view.GetPointer (0); byte* end = begin + (((uint)tpm.MaxOffset - 0x1000u) & ~0x3u); try { while (begin < end) { int i; for (i = 0; i < s_ctl_block_signature.Length; ++i) { if (begin[i] != s_ctl_block_signature[i]) break; } if (s_ctl_block_signature.Length == i) { ControlBlock = new uint[0x400]; uint* src = (uint*)begin; for (i = 0; i < ControlBlock.Length; ++i) ControlBlock[i] = ~src[i]; return; } begin += 4; // control block expected to be on a dword boundary } throw new InvalidEncryptionScheme ("No control block found inside TPM plugin"); } finally { view.SafeMemoryMappedViewHandle.ReleasePointer(); } } } } uint GetBaseOffset (uint hash) { return (hash & m_mask) + m_offset; } public override byte Decrypt (Xp3Entry entry, long offset, byte value) { uint key = entry.Hash; uint base_offset = GetBaseOffset (key); if (offset >= base_offset) { key = (key >> 16) ^ key; } var buffer = new byte[1] { value }; Decode (key, offset, buffer, 0, 1); return buffer[0]; } public override void Decrypt (Xp3Entry entry, long offset, byte[] buffer, int pos, int count) { uint key = entry.Hash; uint base_offset = GetBaseOffset (key); if (offset < base_offset) { int base_length = Math.Min ((int)(base_offset - offset), count); Decode (key, offset, buffer, pos, base_length); offset += base_length; pos += base_length; count -= base_length; } if (count > 0) { key = (key >> 16) ^ key; Decode (key, offset, buffer, pos, count); } } void Decode (uint key, long offset, byte[] buffer, int pos, int count) { Tuple<uint, uint> ret = ExecuteXCode (key); uint key1 = ret.Item2 >> 16; uint key2 = ret.Item2 & 0xffff; byte key3 = (byte)(ret.Item1); if (key1 == key2) key2 += 1; if (0 == key3) key3 = 1; if ((key2 >= offset) && (key2 < offset + count)) buffer[pos + key2 - offset] ^= (byte)(ret.Item1 >> 16); if ((key1 >= offset) && (key1 < offset + count)) buffer[pos + key1 - offset] ^= (byte)(ret.Item1 >> 8); for (int i = 0; i < count; ++i) buffer[pos + i] ^= key3; } public override void Encrypt (Xp3Entry entry, long offset, byte[] values, int pos, int count) { Decrypt (entry, offset, values, pos, count); } Tuple<uint, uint> ExecuteXCode (uint hash) { uint seed = hash & 0x7f; if (null == m_program_list[seed]) { m_program_list[seed] = GenerateProgram (seed); } hash >>= 7; uint ret1 = m_program_list[seed].Execute (hash); uint ret2 = m_program_list[seed].Execute (~hash); return new Tuple<uint, uint> (ret1, ret2); } CxProgram GenerateProgram (uint seed) { var program = NewProgram (seed); for (int stage = 5; stage > 0; --stage) { if (EmitCode (program, stage)) return program; // Trace.WriteLine (string.Format ("stage {0} failed for seed {1}", stage, seed), "GenerateProgram"); program.Clear(); } throw new CxProgramException ("Overly large CxEncryption bytecode"); } internal virtual CxProgram NewProgram (uint seed) { return new CxProgram (seed, ControlBlock); } bool EmitCode (CxProgram program, int stage) { return program.EmitNop (5) // 0x57 0x56 0x53 0x51 0x52 && program.Emit (CxByteCode.MOV_EDI_ARG, 4) // 0x8b 0x7c 0x24 0x18 && EmitBody (program, stage) && program.EmitNop (5) // 0x5a 0x59 0x5b 0x5e 0x5f && program.Emit (CxByteCode.RETN); // 0xc3 } bool EmitBody (CxProgram program, int stage) { if (1 == stage) return EmitProlog (program); if (!program.Emit (CxByteCode.PUSH_EBX)) // 0x53 return false; if (0 != (program.GetRandom() & 1)) { if (!EmitBody (program, stage - 1)) return false; } else if (!EmitBody2 (program, stage - 1)) return false; if (!program.Emit (CxByteCode.MOV_EBX_EAX, 2)) // 0x89 0xc3 return false; if (0 != (program.GetRandom() & 1)) { if (!EmitBody (program, stage - 1)) return false; } else if (!EmitBody2 (program, stage - 1)) return false; return EmitOddBranch (program) && program.Emit (CxByteCode.POP_EBX); // 0x5b } bool EmitBody2 (CxProgram program, int stage) { if (1 == stage) return EmitProlog (program); bool rc = true; if (0 != (program.GetRandom() & 1)) rc = EmitBody (program, stage - 1); else rc = EmitBody2 (program, stage - 1); return rc && EmitEvenBranch (program); } bool EmitProlog (CxProgram program) { bool rc = true; switch (PrologOrder[program.GetRandom() % 3]) { case 2: // MOV EAX, (Random() & 0x3ff) // MOV EAX, EncryptionControlBlock[EAX] rc = program.EmitNop (5) // 0xbe && program.Emit (CxByteCode.MOV_EAX_IMMED, 2) // 0x8b 0x86 && program.EmitUInt32 (program.GetRandom() & 0x3ff) && program.Emit (CxByteCode.MOV_EAX_INDIRECT, 0); break; case 1: rc = program.Emit (CxByteCode.MOV_EAX_EDI, 2); // 0x8b 0xc7 break; case 0: // MOV EAX, Random() rc = program.Emit (CxByteCode.MOV_EAX_IMMED) // 0xb8 && program.EmitRandom(); break; } return rc; } bool EmitEvenBranch (CxProgram program) { bool rc = true; switch (EvenBranchOrder[program.GetRandom() & 7]) { case 0: rc = program.Emit (CxByteCode.NOT_EAX, 2); // 0xf7 0xd0 break; case 1: rc = program.Emit (CxByteCode.DEC_EAX); // 0x48 break; case 2: rc = program.Emit (CxByteCode.NEG_EAX, 2); // 0xf7 0xd8 break; case 3: rc = program.Emit (CxByteCode.INC_EAX); // 0x40 break; case 4: rc = program.EmitNop (5) // 0xbe && program.Emit (CxByteCode.AND_EAX_IMMED) // 0x25 && program.EmitUInt32 (0x3ff) && program.Emit (CxByteCode.MOV_EAX_INDIRECT, 3); // 0x8b 0x04 0x86 break; case 5: rc = program.Emit (CxByteCode.PUSH_EBX) // 0x53 && program.Emit (CxByteCode.MOV_EBX_EAX, 2) // 0x89 0xc3 && program.Emit (CxByteCode.AND_EBX_IMMED, 2) // 0x81 0xe3 && program.EmitUInt32 (0xaaaaaaaa) && program.Emit (CxByteCode.AND_EAX_IMMED) // 0x25 && program.EmitUInt32 (0x55555555) && program.Emit (CxByteCode.SHR_EBX_1, 2) // 0xd1 0xeb && program.Emit (CxByteCode.SHL_EAX_1, 2) // 0xd1 0xe0 && program.Emit (CxByteCode.OR_EAX_EBX, 2) // 0x09 0xd8 && program.Emit (CxByteCode.POP_EBX); // 0x5b break; case 6: rc = program.Emit (CxByteCode.XOR_EAX_IMMED) // 0x35 && program.EmitRandom(); break; case 7: if (0 != (program.GetRandom() & 1)) rc = program.Emit (CxByteCode.ADD_EAX_IMMED); // 0x05 else rc = program.Emit (CxByteCode.SUB_EAX_IMMED); // 0x2d rc = rc && program.EmitRandom(); break; } return rc; } bool EmitOddBranch (CxProgram program) { bool rc = true; switch (OddBranchOrder[program.GetRandom() % 6]) { case 0: rc = program.Emit (CxByteCode.PUSH_ECX) // 0x51 && program.Emit (CxByteCode.MOV_ECX_EBX, 2) // 0x89 0xd9 && program.Emit (CxByteCode.AND_ECX_0F, 3) // 0x83 0xe1 0x0f && program.Emit (CxByteCode.SHR_EAX_CL, 2) // 0xd3 0xe8 && program.Emit (CxByteCode.POP_ECX); // 0x59 break; case 1: rc = program.Emit (CxByteCode.PUSH_ECX) // 0x51 && program.Emit (CxByteCode.MOV_ECX_EBX, 2) // 0x89 0xd9 && program.Emit (CxByteCode.AND_ECX_0F, 3) // 0x83 0xe1 0x0f && program.Emit (CxByteCode.SHL_EAX_CL, 2) // 0xd3 0xe0 && program.Emit (CxByteCode.POP_ECX); // 0x59 break; case 2: rc = program.Emit (CxByteCode.ADD_EAX_EBX, 2); // 0x01 0xd8 break; case 3: rc = program.Emit (CxByteCode.NEG_EAX, 2) // 0xf7 0xd8 && program.Emit (CxByteCode.ADD_EAX_EBX, 2); // 0x01 0xd8 break; case 4: rc = program.Emit (CxByteCode.IMUL_EAX_EBX, 3); // 0x0f 0xaf 0xc3 break; case 5: rc = program.Emit (CxByteCode.SUB_EAX_EBX, 2); // 0x29 0xd8 break; } return rc; } } enum CxByteCode { NOP, RETN, MOV_EDI_ARG, PUSH_EBX, POP_EBX, PUSH_ECX, POP_ECX, MOV_EAX_EBX, MOV_EBX_EAX, MOV_ECX_EBX, MOV_EAX_CONTROL_BLOCK, MOV_EAX_EDI, MOV_EAX_INDIRECT, ADD_EAX_EBX, SUB_EAX_EBX, IMUL_EAX_EBX, AND_ECX_0F, SHR_EBX_1, SHL_EAX_1, SHR_EAX_CL, SHL_EAX_CL, OR_EAX_EBX, NOT_EAX, NEG_EAX, DEC_EAX, INC_EAX, IMMED = 0x100, MOV_EAX_IMMED, AND_EBX_IMMED, AND_EAX_IMMED, XOR_EAX_IMMED, ADD_EAX_IMMED, SUB_EAX_IMMED, } internal class CxProgram { public const int LengthLimit = 0x80; private List<uint> m_code = new List<uint> (LengthLimit); private uint[] m_ControlBlock; private int m_length; protected uint m_seed; class Context { public uint eax; public uint ebx; public uint ecx; public uint edi; public Stack<uint> stack = new Stack<uint>(); } public CxProgram (uint seed, uint[] control_block) { m_seed = seed; m_length = 0; m_ControlBlock = control_block; } public uint Execute (uint hash) { var context = new Context(); using (var iterator = m_code.GetEnumerator()) { uint immed = 0; while (iterator.MoveNext()) { var bytecode = (CxByteCode)iterator.Current; if (CxByteCode.IMMED == (bytecode & CxByteCode.IMMED)) { if (!iterator.MoveNext()) throw new CxProgramException ("Incomplete IMMED bytecode in CxEncryption program"); immed = iterator.Current; } switch (bytecode) { case CxByteCode.NOP: break; case CxByteCode.IMMED: break; case CxByteCode.MOV_EDI_ARG: context.edi = hash; break; case CxByteCode.PUSH_EBX: context.stack.Push (context.ebx); break; case CxByteCode.POP_EBX: context.ebx = context.stack.Pop(); break; case CxByteCode.PUSH_ECX: context.stack.Push (context.ecx); break; case CxByteCode.POP_ECX: context.ecx = context.stack.Pop(); break; case CxByteCode.MOV_EBX_EAX: context.ebx = context.eax; break; case CxByteCode.MOV_EAX_EDI: context.eax = context.edi; break; case CxByteCode.MOV_ECX_EBX: context.ecx = context.ebx; break; case CxByteCode.MOV_EAX_EBX: context.eax = context.ebx; break; case CxByteCode.AND_ECX_0F: context.ecx &= 0x0f; break; case CxByteCode.SHR_EBX_1: context.ebx >>= 1; break; case CxByteCode.SHL_EAX_1: context.eax <<= 1; break; case CxByteCode.SHR_EAX_CL: context.eax >>= (int)context.ecx; break; case CxByteCode.SHL_EAX_CL: context.eax <<= (int)context.ecx; break; case CxByteCode.OR_EAX_EBX: context.eax |= context.ebx; break; case CxByteCode.NOT_EAX: context.eax = ~context.eax; break; case CxByteCode.NEG_EAX: context.eax = (uint)-context.eax; break; case CxByteCode.DEC_EAX: context.eax--; break; case CxByteCode.INC_EAX: context.eax++; break; case CxByteCode.ADD_EAX_EBX: context.eax += context.ebx; break; case CxByteCode.SUB_EAX_EBX: context.eax -= context.ebx; break; case CxByteCode.IMUL_EAX_EBX: context.eax *= context.ebx; break; case CxByteCode.ADD_EAX_IMMED: context.eax += immed; break; case CxByteCode.SUB_EAX_IMMED: context.eax -= immed; break; case CxByteCode.AND_EBX_IMMED: context.ebx &= immed; break; case CxByteCode.AND_EAX_IMMED: context.eax &= immed; break; case CxByteCode.XOR_EAX_IMMED: context.eax ^= immed; break; case CxByteCode.MOV_EAX_IMMED: context.eax = immed; break; case CxByteCode.MOV_EAX_INDIRECT: if (context.eax >= m_ControlBlock.Length) throw new CxProgramException ("Index out of bounds in CxEncryption program"); context.eax = ~m_ControlBlock[context.eax]; break; case CxByteCode.RETN: if (context.stack.Count > 0) throw new CxProgramException ("Imbalanced stack in CxEncryption program"); return context.eax; default: throw new CxProgramException ("Invalid bytecode in CxEncryption program"); } } } throw new CxProgramException ("CxEncryption program without RETN bytecode"); } public void Clear () { m_length = 0; m_code.Clear(); } public bool EmitNop (int count) { if (m_length + count > LengthLimit) return false; m_length += count; return true; } public bool Emit (CxByteCode code, int length = 1) { if (m_length + length > LengthLimit) return false; m_length += length; m_code.Add ((uint)code); return true; } public bool EmitUInt32 (uint x) { if (m_length + 4 > LengthLimit) return false; m_length += 4; m_code.Add (x); return true; } public bool EmitRandom () { return EmitUInt32 (GetRandom()); } public virtual uint GetRandom () { uint seed = m_seed; m_seed = 1103515245 * seed + 12345; return m_seed ^ (seed << 16) ^ (seed >> 16); } } internal class CxProgramNana : CxProgram { protected uint m_random_seed; public CxProgramNana (uint seed, uint random_seed, uint[] control_block) : base (seed, control_block) { m_random_seed = random_seed; } public override uint GetRandom () { uint s = m_seed ^ (m_seed << 17); s ^= (s << 18) | (s >> 15); m_seed = ~s; uint r = m_random_seed ^ (m_random_seed << 13); r ^= r >> 17; m_random_seed = r ^ (r << 5); return m_seed ^ m_random_seed; } } /* CxEncryption base branch order OddBranchOrder { case 0: SHR_EAX_CL case 1: SHL_EAX_CL case 2: ADD_EAX_EBX case 3: NEG_EAX; ADD_EAX_EBX case 4: IMUL_EAX_EBX case 5: SUB_EAX_EBX } EvenBranchOrder { case 0: NOT_EAX case 1: DEC_EAX case 2: NEG_EAX case 3: INC_EAX case 4: MOV_EAX_INDIRECT case 5: OR_EAX_EBX case 6: XOR_EAX_IMMED case 7: ADD_EAX_IMMED } */ }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using Microsoft.AspNetCore.Mvc; using SchoolBusAPI.Models; using SchoolBusAPI.Services; using SchoolBusAPI.Authorization; using SchoolBusAPI.Helpers; using SchoolBusAPI.ViewModels; namespace SchoolBusAPI.Controllers { /// <summary> /// /// </summary> [ApiVersion("1.0")] [ApiController] public class SchoolBusOwnerController : ControllerBase { private readonly ISchoolBusOwnerService _service; /// <summary> /// Create a controller and set the service /// </summary> public SchoolBusOwnerController(ISchoolBusOwnerService service) { _service = service; } /// <summary> /// /// </summary> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersGet() { return this._service.SchoolbusownersGetAsync(); } /// <summary> /// /// </summary> /// <remarks>Returns attachments for a particular SchoolBusOwner</remarks> /// <param name="id">id of SchoolBusOwner to fetch attachments for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners/{id}/attachments")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersIdAttachmentsGet([FromRoute]int id) { return this._service.SchoolbusownersIdAttachmentsGetAsync(id); } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBusOwner to delete</param> /// <response code="200">OK</response> /// <response code="404">SchoolBusOwner not found</response> [HttpPost] [Route("/api/schoolbusowners/{id}/delete")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdDeletePost([FromRoute]int id) { return this._service.SchoolbusownersIdDeletePostAsync(id); } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBusOwner to fetch</param> /// <response code="200">OK</response> /// <response code="404">SchoolBusOwner not found</response> [HttpGet] [Route("/api/schoolbusowners/{id}")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersIdGet([FromRoute]int id) { return this._service.SchoolbusownersIdGetAsync(id); } /// <summary> /// /// </summary> /// <remarks>Returns History for a particular SchoolBusOwner</remarks> /// <param name="id">id of SchoolBusOwner to fetch History for</param> /// <param name="offset">offset for records that are returned</param> /// <param name="limit">limits the number of records returned.</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners/{id}/history")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit) { return this._service.SchoolbusownersIdHistoryGetAsync(id, offset, limit); } /// <summary> /// /// </summary> /// <remarks>Add a History record to the SchoolBus Owner</remarks> /// <param name="id">id of SchoolBusOwner to add History for</param> /// <param name="item"></param> /// <response code="201">History created</response> [HttpPost] [Route("/api/schoolbusowners/{id}/history")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdHistoryPost([FromRoute]int id, [FromBody]History item) { return this._service.SchoolbusownersIdHistoryPostAsync(id, item); } /// <summary> /// /// </summary> /// <remarks>Returns notes for a particular SchoolBusOwner</remarks> /// <param name="id">id of SchoolBusOwner to fetch notes for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners/{id}/notes")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersIdNotesGet([FromRoute]int id) { return this._service.SchoolbusownersIdNotesGetAsync(id); } [HttpPut] [Route("/api/schoolbusowners/{ownerId}/notes/{noteId}")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdNotesPut(int ownerId, int noteId, [FromBody] NoteSaveViewModel item) { var (success, error) = _service.UpdateSchoolBusOwnerNote(ownerId, noteId, item); return success ? NoContent() : error; } [HttpPost] [Route("/api/schoolbusowners/{ownerId}/notes/")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdNotesPost(int ownerId, [FromBody] NoteSaveViewModel note) { var (success, error) = _service.CreateSchoolBusOwnerNote(ownerId, note); return success ? NoContent() : error; } [HttpDelete] [Route("/api/schoolbusowners/{ownerId}/notes/{noteId}")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdNotesDelete(int ownerId, int noteId) { var (success, error) = _service.DeleteSchoolBusOwnerNote(ownerId, noteId); return success ? NoContent() : error; } /// <summary> /// /// </summary> /// <param name="id">id of SchoolBusOwner to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">SchoolBusOwner not found</response> [HttpPut] [Route("/api/schoolbusowners/{id}")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersIdPut([FromRoute]int id, [FromBody]SchoolBusOwner item) { return this._service.SchoolbusownersIdPutAsync(id, item); } /// <summary> /// /// </summary> /// <remarks>Returns SchoolBusOwner data plus additional information required for display</remarks> /// <param name="id">id of SchoolBusOwner to fetch attachments for</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners/{id}/view")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersIdViewGet([FromRoute]int id) { return this._service.SchoolbusownersIdViewGetAsync(id); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">SchoolBusOwner created</response> [HttpPost] [Route("/api/schoolbusowners")] [RequiresPermission(Permissions.OwnerWrite)] public virtual IActionResult SchoolbusownersPost([FromBody]SchoolBusOwner item) { return this._service.SchoolbusownersPostAsync(item); } /// <summary> /// Searches school bus owners /// </summary> /// <remarks>Used for the search school bus owners.</remarks> /// <param name="districts">Districts (array of id numbers)</param> /// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param> /// <param name="owner"></param> /// <param name="includeInactive">True if Inactive schoolbuses will be returned</param> /// <response code="200">OK</response> [HttpGet] [Route("/api/schoolbusowners/search")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusownersSearchGet( [ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] districts, [ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] inspectors, [FromQuery]int? owner, [FromQuery]bool? includeInactive) { return this._service.SchoolbusownersSearchGetAsync(districts, inspectors, owner, includeInactive); } /// <summary> /// /// </summary> /// <param name = "id">id of school bus owner to fetch contacts</param> /// <response code = "200">OK</response> /// <response code = "404">school bus owner not found</response> [HttpGet] [Route("/api/schoolbusowners/{id}/contacts")] [RequiresPermission(Permissions.OwnerRead)] public virtual IActionResult SchoolbusesIdInspectionsGet([FromRoute]int id) { return this._service.SchoolbuseownersIdContactsGetAsync(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Android.Animation; using Android.App; using Android.Content; using Android.Content.Res; using Android.Graphics; using Android.Graphics.Drawables; using Android.OS; using Android.Runtime; using Android.Support.V4.Content; using Android.Support.V7.Widget; using Android.Views; using Android.Widget; using com.refractored.fab; using DrHandy.DataBase; using DrHandy.Droid.Custom_Views; using DrHandy.Droid.Utils; using DrHandy.Model; using Object = Java.Lang.Object; namespace DrHandy.Droid.Adapters { /* * HealthModulesListAdapter - Adapter for displaying the list of available health modules */ class HealthModulesListAdapter : RecyclerView.Adapter { //ViewHolder For The Health Modules private class ViewHolder : RecyclerView.ViewHolder { public RelativeLayout Header { get; set; } public TextView ModuleName { get; set; } public TextView ModuleDescriptionShort { get; set; } public CustomTextView ModuleDescriptionLong { get; set; } public int ModuleDescriptionHeight { get; set; } public ImageView ModuleIcon { get; set; } public FloatingActionButton AddButton { get; set; } public View RevealView { get; set; } public View Background { get; set; } public ViewHolder(View itemView) : base(itemView) { Header = itemView.FindViewById<RelativeLayout>(Resource.Id.header); ModuleName = itemView.FindViewById<TextView>(Resource.Id.module_name); ModuleDescriptionShort = itemView.FindViewById<TextView>(Resource.Id.module_description_short); ModuleDescriptionLong = itemView.FindViewById<CustomTextView>(Resource.Id.module_description_long); ModuleIcon = itemView.FindViewById<ImageView>(Resource.Id.module_icon); AddButton = itemView.FindViewById<FloatingActionButton>(Resource.Id.module_addbutton); RevealView = itemView.FindViewById<View>(Resource.Id.reveal); Background = itemView.FindViewById<View>(Resource.Id.background); } } private Context _context; private LayoutInflater _inflater; private List<HealthModule> _modules; private List<ModuleViewCell> _viewCells = new List<ModuleViewCell>(); private bool Enabled { get; set; } = true; public HealthModulesListAdapter(Context context, List<HealthModule> healthModules) { _context = context; _inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService); _modules = healthModules; } public void AddModule(HealthModule module) { _modules.Add(module); } public void SetModules(List<HealthModule> modules) { _modules = modules; } public override int ItemCount { get { return _modules.Count; } } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { var itemView = LayoutInflater.From(parent.Context). Inflate(Resource.Layout.module_viewcell, parent, false); var viewHolder = new ViewHolder(itemView); viewHolder.AddButton.Click += delegate { OnAddButtonClick(viewHolder); }; viewHolder.ItemView.Click += delegate { if (Enabled) { if (ExpandedView != null) { if (ExpandedView != viewHolder) { OnHeaderClick(ExpandedView); //Collapse previous HealthModule ExpandedView = viewHolder; } else { ExpandedView = null; } } else { ExpandedView = viewHolder; } OnHeaderClick(viewHolder); //Expand selected HealthModule } }; return viewHolder; } public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { HealthModulesListAdapter.ViewHolder viewHolder = holder as HealthModulesListAdapter.ViewHolder; var item = _modules[position]; var moduleColor = new Color(ContextCompat.GetColor(_context, _context.Resources.GetIdentifier(item.Color, "color", _context.PackageName))); if (viewHolder != null) { var drawable = (LayerDrawable) viewHolder.Background.Background; var background = (GradientDrawable) drawable.FindDrawableByLayerId(Resource.Id.background); background.SetColor(moduleColor); } viewHolder.ModuleName.Text = item.Name; viewHolder.ModuleIcon.Background = item.GetIcon(_context, item.ShortName); viewHolder.ModuleDescriptionShort.Text = viewHolder.ModuleDescriptionLong.Text = item.Description; viewHolder.ModuleDescriptionLong.SetTextColor(moduleColor); viewHolder.RevealView.Background = item.GetHeader(_context); if (DBHelper.Instance.CheckIfExists(item) && DBHelper.Instance.CheckIfVisible(item)) { viewHolder.AddButton.SetImageDrawable(ContextCompat.GetDrawable(_context, Resource.Drawable.ic_clear)); viewHolder.AddButton.SetColorNormalResId(Resource.Color.red); viewHolder.AddButton.SetColorPressedResId(Resource.Color.red); } else { viewHolder.AddButton.SetImageDrawable(ContextCompat.GetDrawable(_context, Resource.Drawable.ic_add)); viewHolder.AddButton.SetColorNormalResId(Resource.Color.green); viewHolder.AddButton.SetColorPressedResId(Resource.Color.green); } } public bool IsEnabled(int position) { return Enabled; } private ViewHolder ExpandedView { get; set; } private void OnAddButtonClick(ViewHolder viewHolder) { var module = _modules.Find(x => x.Name == viewHolder.ModuleName.Text); if (DBHelper.Instance.CheckIfExists(module)) { if (DBHelper.Instance.CheckIfVisible(module)) { DBHelper.Instance.ChangeModuleVisibility(module, false); Toast.MakeText(_context, _context.Resources.GetString(Resource.String.module_removed), ToastLength.Short).Show(); } else { DBHelper.Instance.ChangeModuleVisibility(module, true); Toast.MakeText(_context, _context.Resources.GetString(Resource.String.module_added), ToastLength.Short).Show(); } }else { DBHelper.Instance.AddHealthModule(module); module.GetUtilsClass().InitModuleDB(); Toast.MakeText(_context, _context.Resources.GetString(Resource.String.module_added), ToastLength.Short).Show(); } NotifyDataSetChanged(); } private void OnHeaderClick(ViewHolder v) { var iconMarginLeft = ((ViewGroup.MarginLayoutParams) v.ModuleIcon.LayoutParameters).LeftMargin; var iconMarginTop = ((ViewGroup.MarginLayoutParams) v.ModuleIcon.LayoutParameters).TopMargin; var cx = (v.ModuleIcon.Left + v.ModuleIcon.Right - iconMarginLeft) / 2; var cy = (v.ModuleIcon.Top + v.ModuleIcon.Bottom - iconMarginTop) / 2; var radius = v.Header.Width; ValueAnimator headerAnimator = null; if (v.ModuleDescriptionLong.Visibility == ViewStates.Visible) { if (Enabled) { AnimationUtils.StartTranslateAnimation(v.ModuleIcon, v.ModuleIcon.Left, v.ModuleIcon.Top); AnimationUtils.StartScaleAnimation(v.ModuleIcon, 1f, 1f); AnimationUtils.HideViewCircular(v.RevealView, cx, cy, radius); AnimationUtils.RevealViewCircular(v.Background, cx, cy, v.Background.MeasuredHeight); AnimationUtils.StartTranslateAnimation(v.ModuleName, v.ModuleName.Left, v.ModuleName.Top); AnimationUtils.StartScaleAnimation(v.ModuleName, 1f, 1f); headerAnimator = AnimationUtils.ExpandView(v.Header, v.Header.MeasuredHeight - v.ModuleIcon.MeasuredHeight - v.ModuleName.MeasuredHeight * 2); AnimationUtils.FadeAnimation(v.ModuleDescriptionLong, 0f); AnimationUtils.ExpandView(v.ModuleDescriptionLong, 0).Start(); AnimationUtils.FadeAnimation(v.ModuleDescriptionShort, 1f); AnimationUtils.FadeAnimation(v.AddButton, 0f); v.ModuleName.SetTextColor(Color.DimGray); } } else { AnimationUtils.HideViewCircular(v.Background, cx, cy, v.Background.MeasuredHeight, 300); AnimationUtils.RevealViewCircular(v.RevealView, cx, cy, radius); AnimationUtils.StartTranslateAnimation(v.ModuleIcon, (v.Header.Width - v.ModuleIcon.Width) / 2, (int) (v.ModuleIcon.Height / 1.5f)); AnimationUtils.StartScaleAnimation(v.ModuleIcon, 1.5f, 1.5f); var finalX = (v.Header.Width - v.ModuleName.Width) / 2; AnimationUtils.StartTranslateAnimation(v.ModuleName, finalX, (int) (v.ModuleIcon.Height * 2.3f)); AnimationUtils.StartScaleAnimation(v.ModuleName, 1.5f, 1.5f); headerAnimator = AnimationUtils.ExpandView(v.Header, v.Header.MeasuredHeight + v.ModuleIcon.MeasuredHeight + v.ModuleName.MeasuredHeight * 2); AnimationUtils.FadeAnimation(v.ModuleDescriptionLong, 1f); AnimationUtils.ExpandView(v.ModuleDescriptionLong, v.ModuleDescriptionHeight, true).Start(); AnimationUtils.FadeAnimation(v.ModuleDescriptionShort, 0f); AnimationUtils.FadeAnimation(v.AddButton, 1f); v.ModuleName.SetTextColor(Color.White); } if (headerAnimator != null) { headerAnimator.AnimationStart += delegate { Enabled = false; }; headerAnimator.AnimationEnd += delegate { Enabled = true; }; headerAnimator.Start(); } } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Security.Principal; using Orleans.Runtime; using Orleans.Runtime.Counters; using Orleans.Runtime.Configuration; namespace Orleans.Counter.Control { /// <summary> /// Control Orleans Counters - Register or Unregister the Orleans counter set /// </summary> internal class CounterControl { public bool Unregister { get; private set; } public bool BruteForce { get; private set; } public bool NeedRunAsAdministrator { get; private set; } public bool IsRunningAsAdministrator { get; private set; } public bool PauseAtEnd { get; private set; } public CounterControl() { // Check user is Administrator and has granted UAC elevation permission to run this app var userIdent = WindowsIdentity.GetCurrent(); var userPrincipal = new WindowsPrincipal(userIdent); IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator); } public void PrintUsage() { using (var usageStr = new StringWriter()) { usageStr.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe {command}"); usageStr.WriteLine("Where commands are:"); usageStr.WriteLine(" /? or /help = Display usage info"); usageStr.WriteLine(" /r or /register = Register Windows performance counters for Orleans [default]"); usageStr.WriteLine(" /u or /unregister = Unregister Windows performance counters for Orleans"); usageStr.WriteLine(" /f or /force = Use brute force, if necessary"); usageStr.WriteLine(" /pause = Pause for user key press after operation"); ConsoleText.WriteUsage(usageStr.ToString()); } } public bool ParseArguments(string[] args) { bool ok = true; NeedRunAsAdministrator = true; Unregister = false; foreach (var arg in args) { if (arg.StartsWith("/") || arg.StartsWith("-")) { var a = arg.ToLowerInvariant().Substring(1); switch (a) { case "r": case "register": Unregister = false; break; case "u": case "unregister": Unregister = true; break; case "f": case "force": BruteForce = true; break; case "pause": PauseAtEnd = true; break; case "?": case "help": NeedRunAsAdministrator = false; ok = false; break; default: NeedRunAsAdministrator = false; ok = false; break; } } else { ConsoleText.WriteError("Unrecognised command line option: " + arg); ok = false; } } return ok; } public int Run() { if (NeedRunAsAdministrator && !IsRunningAsAdministrator) { ConsoleText.WriteError("Need to be running in Administrator role to perform the requested operations."); return 1; } InitConsoleLogging(); try { if (Unregister) { ConsoleText.WriteStatus("Unregistering Orleans performance counters with Windows"); UnregisterWindowsPerfCounters(this.BruteForce); } else { ConsoleText.WriteStatus("Registering Orleans performance counters with Windows"); RegisterWindowsPerfCounters(true); // Always reinitialize counter registrations, even if already existed } ConsoleText.WriteStatus("Operation completed successfully."); return 0; } catch (Exception exc) { ConsoleText.WriteError("Error running " + Assembly.GetExecutingAssembly().GetName().Name + ".exe", exc); if (!BruteForce) return 2; ConsoleText.WriteStatus("Ignoring error due to brute-force mode"); return 0; } } /// <summary> /// Initialize log infrastrtucture for Orleans runtime sub-components /// </summary> private static void InitConsoleLogging() { Trace.Listeners.Clear(); var cfg = new NodeConfiguration {TraceFilePattern = null, TraceToConsole = false}; TraceLogger.Initialize(cfg); var logWriter = new LogWriterToConsole(true, true); // Use compact console output & no timestamps / log message metadata TraceLogger.LogConsumers.Add(logWriter); } /// <summary> /// Create the set of Orleans counters, if they do not already exist /// </summary> /// <param name="useBruteForce">Use brute force, if necessary</param> /// <remarks>Note: Program needs to be running as Administrator to be able to register Windows perf counters.</remarks> private static void RegisterWindowsPerfCounters(bool useBruteForce) { try { if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable()) { if (!useBruteForce) { ConsoleText.WriteStatus("Orleans counters are already registered -- Use brute-force mode to re-initialize"); return; } // Delete any old perf counters UnregisterWindowsPerfCounters(true); } if (GrainTypeManager.Instance == null) { var typeManager = new GrainTypeManager(false, null); // We shouldn't need GrainFactory in this case GrainTypeManager.Instance.Start(false); } // Register perf counters OrleansPerfCounterManager.InstallCounters(); if (OrleansPerfCounterManager.AreWindowsPerfCountersAvailable()) ConsoleText.WriteStatus("Orleans counters registered successfully"); else ConsoleText.WriteError("Orleans counters are NOT registered"); } catch (Exception exc) { ConsoleText.WriteError("Error registering Orleans counters - {0}" + exc); throw; } } /// <summary> /// Remove the set of Orleans counters, if they already exist /// </summary> /// <param name="useBruteForce">Use brute force, if necessary</param> /// <remarks>Note: Program needs to be running as Administrator to be able to unregister Windows perf counters.</remarks> private static void UnregisterWindowsPerfCounters(bool useBruteForce) { if (!OrleansPerfCounterManager.AreWindowsPerfCountersAvailable()) { ConsoleText.WriteStatus("Orleans counters are already unregistered"); return; } // Delete any old perf counters try { OrleansPerfCounterManager.DeleteCounters(); } catch (Exception exc) { ConsoleText.WriteError("Error deleting old Orleans counters - {0}" + exc); if (useBruteForce) ConsoleText.WriteStatus("Ignoring error deleting Orleans counters due to brute-force mode"); else throw; } } } }
/*********************************************************************************************************************** * TorrentDotNET - A BitTorrent library based on the .NET platform * * Copyright (C) 2004, Peter Ward * * * * This library is free software; you can redistribute it and/or modify it under the terms of the * * GNU Lesser General Public License as published by the Free Software Foundation; * * either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; * * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***********************************************************************************************************************/ using System.Collections; using IO = System.IO; namespace PWLib.Platform { /// <summary> /// BEncode encapsulates the bEncode format used extensively by BitTorrent. /// </summary> public class BEncode { /// <summary> /// bEncode uses different elements to encode it's data. All element types derive from this class. /// </summary> public abstract class Element : System.ICloneable { protected int position = -1, length = -1; /// <summary></summary> /// <returns>Position in the stream at which this element begins.</returns> public int Position { get { return position; } } /// <summary></summary> /// <returns>Length of the element within the stream.</returns> public int Length { get { return length; } } /// <summary>Clones the object</summary> /// <returns>Clone</returns> object System.ICloneable.Clone() { return this.Clone(); } /// <summary>Clones the object</summary> /// <returns>Clone</returns> public Element Clone() { return (Element)this.MemberwiseClone(); } internal virtual void Write(IO.Stream ostream) { throw new System.NotImplementedException(); } } /// <summary> /// String class /// </summary> public class String : Element, System.IComparable, IEnumerable { private byte[] data; /// <summary></summary> /// <returns>Raw byte value for the string, as not all bencoded strings are actually strings</returns> public byte[] Data { get { return this.data; } } /// <summary>Constructs a string from the bEncoded stream</summary> /// <param name="istream">Stream to construct string from</param> public String(IO.Stream istream, int firstchar) { if (istream.CanSeek) this.position = (int)istream.Position - 1; string numstr = new string((char)firstchar, 1); while (true) { int c = istream.ReadByte(); if (c != ':') numstr += (char)c; else break; } int length = System.Int32.Parse(numstr); if (length < 0) throw new System.Exception("Invalid string length"); this.data = new byte[length]; istream.Read(this.data, 0, length); if (istream.CanSeek) this.length = (int)(istream.Position - this.position); // System.Diagnostics.Debugger.Log(0, "BEncode", "String: " + this.ToString() + "\n"); } //// <summary>Constructs a String from the bytes (Assumes ASCII format, as that is what bEncode uses</summary> /// <param name="bytes">Data to read from</param> /// <param name="offset">Offset to read from</param> /// <param name="length">Length to read</param> public String(byte[] bytes, int offset, int length) { this.data = new byte[length]; System.Array.Copy(bytes, offset, this.data, 0, length); } /// <summary>Constructs a String from the string passed in</summary> /// <param name="str">String to use</param> public String(string str) { this.data = System.Text.ASCIIEncoding.ASCII.GetBytes(str); } /// <summary>Compares the object passed in to see if it is the same</summary> /// <param name="obj">Object to compare to</param> /// <returns>True if the same, false otherwise</returns> public override bool Equals(object obj) { if (obj is BEncode.String) { BEncode.String str = (BEncode.String)obj; if (str.data.Length != this.data.Length) return false; for (int i=0; i<str.data.Length; ++i) { if (str.data[i] != this.data[i]) return false; } return true; } else return false; } internal override void Write(System.IO.Stream ostream) { string str = this.data.Length + ":"; ostream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(str), 0, str.Length); ostream.Write(this.data, 0, this.data.Length); } /// <summary></summary> /// <returns>Unique hashcode for the string</returns> public override int GetHashCode() { if (this.data.Length <= 0) return 0; else { int hash = this.data[0]; for (int i=1; i<this.data.Length; ++i) { hash ^= this.data[i]; } return hash; } } /// <summary></summary> /// <returns>String representation of the ASCII bencode string</returns> public override string ToString() { return System.Text.ASCIIEncoding.ASCII.GetString(data); } /// <summary>Implicitly converts a .NET string to a bencoded one</summary> /// <param name="str">.NET string</param> /// <returns>bencoded string</returns> public static implicit operator BEncode.String(string str) { return new BEncode.String(str); } /// <summary>Implicitly converts a bencoded string to a .NET one</summary> /// <param name="str">bencoded string</param> /// <returns>.NET string</returns> public static implicit operator string(BEncode.String str) { return str.ToString(); } /// <summary>Indexer, returns the byte at the specified index</summary> /// <param name="index">Index to get/set</param> /// <returns>Byte at index</returns> public byte this[int index] { get { return this.data[index]; } set { this.data[index] = value; } } #region IComparable Members /// <summary>Compares the two objects</summary> /// <param name="obj">Object to compare to</param> /// <returns>Zero if they are the same</returns> int System.IComparable.CompareTo(object obj) { return this.CompareTo((BEncode.String)obj); } /// <summary>Compares the two objects</summary> /// <param name="str">String to compare to</param> /// <returns>Zero if they are the same</returns> public int CompareTo(BEncode.String str) { return this.ToString().CompareTo(str); } #endregion #region IEnumerable Members /// <summary>Gets the enumerator</summary> /// <returns>Enumerator</returns> public IEnumerator GetEnumerator() { return this.data.GetEnumerator(); } #endregion } /// <summary> /// Integer class /// </summary> public class Integer : Element { private int integer; /// <summary></summary> /// <returns>Integer element</returns> public int Data { get { return integer; } } /// <summary>Constructs an integer from the bEncoded stream</summary> /// <param name="istream">Stream to construct integer from</param> internal Integer(IO.Stream istream) { if (istream.CanSeek) this.position = (int)istream.Position - 1; string numstr = ""; char c; while ((c = (char)istream.ReadByte()) != 'e') { numstr += c; } this.integer = System.Int32.Parse(numstr); if (istream.CanSeek) this.length = (int)istream.Position - this.position; } internal override void Write(System.IO.Stream ostream) { string str = "i" + this.ToString() + "e"; ostream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(str), 0, str.Length); } /// <summary>Constructs an integer</summary> /// <param name="i">Integer value</param> public Integer(int i) { this.integer = i; } /// <summary>Implicitly converts from an integer to a bencoded integer</summary> /// <param name="i">Integer</param> /// <returns>bencoded integer</returns> public static implicit operator Integer(int i) { return new BEncode.Integer(i); } /// <summary>Implicitly converts from an integer to a bencoded integer</summary> /// <param name="i">bencoded integer</param> /// <returns>Integer</returns> public static implicit operator int(BEncode.Integer i) { return i.Data; } /// <summary>Converts the integer to it's string equivalent</summary> /// <returns>string</returns> public override string ToString() { return this.integer.ToString(); } /// <summary>Converts the integer to it's string equivalent</summary> /// <param name="format">Format to use</param> /// <returns>string</returns> public string ToString(string format) { return this.integer.ToString(format); } } /// <summary> /// List class /// </summary> public class List : Element, ICollection, IList, IEnumerable { private ArrayList list = new ArrayList(); /// <summary>Constructs an integer from the bEncoded stream</summary> /// <param name="istream">Stream to construct integer from</param> public List(IO.Stream istream) { if (istream.CanSeek) this.position = (int)istream.Position - 1; int c; while ((c = istream.ReadByte()) != 'e') { BEncode.Element element = BEncode.NextElement(istream, c); string el = element.ToString(); this.list.Add(element); } if (istream.CanSeek) this.length = (int)istream.Position - this.position; } internal override void Write(IO.Stream ostream) { ostream.WriteByte((int)'l'); foreach (BEncode.Element element in this.list) { element.Write(ostream); } ostream.WriteByte((int)'e'); } /// <summary>Constructs an empty list</summary> public List() { } #region ICollection members /// <summary></summary> /// <returns>Number of items in the collection</returns> public int Count { get { return this.list.Count; } } /// <summary></summary> /// <returns>Whether the collection is synchronized</returns> public bool IsSynchronized { get { return this.list.IsSynchronized; } } /// <summary></summary> /// <returns>Synchronization root</returns> public object SyncRoot { get { return this.list.SyncRoot; } } /// <summary>Copies the contents of the collection to any array</summary> /// <param name="array">Destination array</param> /// <param name="index">Destination index to start copying</param> public void CopyTo(System.Array array, int index) { this.list.CopyTo(array, index); } #endregion #region IList members /// <summary></summary> /// <returns>True if the list is of fixed size</returns> public bool IsFixedSize { get { return this.list.IsFixedSize; } } /// <summary></summary> /// <returns>True if the list is read only</returns> public bool IsReadOnly { get { return this.list.IsReadOnly; } } /// <summary></summary> /// <param name="index">Index to get/set</param> /// <returns>Object at specified index</returns> object IList.this[int index] { get { return this.list[index]; } set { this.list[index] = value; } } /// <summary></summary> /// <param name="index">Index to get/set</param> /// <returns>Element at specified index</returns> public BEncode.Element this[int index] { get { return (BEncode.Element)this.list[index]; } set { this.list[index] = value; } } /// <summary></summary> /// <param name="obj">Object to add to list</param> /// <returns>Index of object added</returns> int IList.Add(object obj) { return this.Add((BEncode.Element)obj); } /// <summary></summary> /// <param name="element">Object to add to list</param> /// <returns>Index of object added</returns> public int Add(BEncode.Element element) { return this.list.Add(element); } /// <summary>Clears all elements from the list</summary> public void Clear() { this.list.Clear(); } /// <summary></summary> /// <param name="obj">Object to check if it exists in the list</param> /// <returns>True if object is in the list, false otherwise</returns> bool IList.Contains(object obj) { return this.Contains((BEncode.Element)obj); } /// <summary></summary> /// <param name="element">Object to check if it exists in the list</param> /// <returns>True if object is in the list, false otherwise</returns> public bool Contains(BEncode.Element element) { return this.list.Contains(element); } /// <summary>Finds the index at which the object resides</summary> /// <param name="obj">Object to check</param> /// <returns>Index of object, -1 if it does not exist</returns> int IList.IndexOf(object obj) { return this.IndexOf((BEncode.Element)obj); } /// <summary>Finds the index at which the element resides</summary> /// <param name="obj">Element to check</param> /// <returns>Index of element, -1 if it does not exist</returns> public int IndexOf(BEncode.Element element) { return this.list.IndexOf(element); } /// <summary>Inserts an object into the list at the specified index</summary> /// <param name="index">Index to insert object at</param> /// <param name="obj">Object to insert</param> void IList.Insert(int index, object obj) { this.Insert(index, (BEncode.Element)obj); } /// <summary>Inserts an element into the list at the specified index</summary> /// <param name="index">Index to insert element at</param> /// <param name="obj">Element to insert</param> public void Insert(int index, BEncode.Element element) { this.list.Insert(index, element); } /// <summary>Removes an object from the list</summary> /// <param name="obj">Object to remove</param> void IList.Remove(object obj) { this.Remove((BEncode.Element)obj); } /// <summary>Removes an element from the list</summary> /// <param name="obj">Element to remove</param> public void Remove(BEncode.Element element) { this.list.Remove(element); } /// <summary>Removes an element at the specified index</summary> /// <param name="index">Index to remove element from</param> public void RemoveAt(int index) { this.list.RemoveAt(index); } #endregion #region IEnumerable Members /// <summary>Gets the the enumerator for the list</summary> /// <returns>Enumerator</returns> public IEnumerator GetEnumerator() { return this.list.GetEnumerator(); } #endregion } /// <summary> /// Dictionary class /// </summary> public class Dictionary : Element, IDictionary, ICollection, IEnumerable { private Hashtable map = new Hashtable(); /// <summary> /// Constructs a dictionary /// </summary> /// <param name="istream">Stream to construct dictionary from</param> public Dictionary(IO.Stream istream) { if (istream.CanSeek) this.position = (int)istream.Position - 1; int c; while ((c = istream.ReadByte()) != 'e') { BEncode.String key = new BEncode.String(istream, c); // keys are always strings string strkey = key; Element element = BEncode.NextElement(istream); if (!this.map.Contains(key)) this.map.Add(key, element); } if (istream.CanSeek) this.length = (int)istream.Position - this.position; } internal override void Write(IO.Stream ostream) { ostream.WriteByte((int)'d'); foreach (BEncode.String key in this.map.Keys) { key.Write(ostream); ((BEncode.Element)this.map[key]).Write(ostream); } ostream.WriteByte((int)'e'); } /// <summary> /// Gets the dictionary with the specified key. Same as GetElement(), except performs the casting automatically. /// </summary> /// <param name="key">Key name</param> /// <returns>Dictionary element</returns> public Dictionary GetDictionary(BEncode.String key) { return (BEncode.Dictionary)this[key]; } /// <summary> /// Gets the list with the specified key. Same as GetElement(), except performs the casting automatically. /// </summary> /// <param name="key">Key name</param> /// <returns>List element</returns> public List GetList(BEncode.String key) { return (BEncode.List)this[key]; } /// <summary> /// Gets the string with the specified key. Same as GetElement(), except performs the casting automatically. /// </summary> /// <param name="key">Key name</param> /// <returns>String element</returns> public string GetString(BEncode.String key) { return (BEncode.String)this[key]; } /// <summary> /// Gets the bytes with the specified key. Same as GetElement(), except performs the casting automatically. /// </summary> /// <param name="key">Key name</param> /// <returns>Bytes element</returns> public byte[] GetBytes(BEncode.String key) { return ((BEncode.String)this[key]).Data; } /// <summary> /// Gets the integer with the specified key. Same as GetElement(), except performs the casting automatically. /// </summary> /// <param name="key">Key name</param> /// <returns>Integer element</returns> public int GetInteger(BEncode.String key) { return (BEncode.Integer)this[key]; } #region IDictionary Members /// <summary></summary> /// <returns>True if the dictionary is read only</returns> public bool IsReadOnly { get { return this.map.IsReadOnly; } } /// <summary>Gets the enumerator for the dictionary</summary> /// <returns>Dictionary enumerator</returns> public IDictionaryEnumerator GetEnumerator() { return this.map.GetEnumerator(); } /// <summary>Retrieves the value associated with the specified key</summary> /// <param name="key">Key</param> /// <returns>Value</returns> object IDictionary.this[object key] { get { return this[(BEncode.String)key]; } set { this[(BEncode.String)key] = (BEncode.Element)value; } } /// <summary>Retrieves the value associated with the specified key</summary> /// <param name="key">Key</param> /// <returns>Value</returns> public BEncode.Element this[BEncode.String key] { get { return (BEncode.Element)this.map[key]; } set { this.map[key] = value; } } /// <summary>Removes a key-value pair from the dictionary</summary> /// <param name="key">Key to remove</param> void IDictionary.Remove(object key) { this.Remove((BEncode.String)key); } /// <summary>Removes a key-value pair from the dictionary</summary> /// <param name="key">Key to remove</param> public void Remove(BEncode.String key) { this.map.Remove(key); } /// <summary>Checks if the key exists in the dictionary</summary> /// <param name="key">Key to check</param> /// <returns>True if the key exists</returns> bool IDictionary.Contains(object key) { return this.Contains((BEncode.String)key); } /// <summary>Checks if the key exists in the dictionary</summary> /// <param name="key">Key to check</param> /// <returns>True if the key exists</returns> public bool Contains(BEncode.String key) { return this.map.Contains(key); } /// <summary>Clears the dictionary of all key-value pairs</summary> public void Clear() { this.map.Clear(); } /// <summary></summary> /// <returns>Values held in the dictionary</returns> public ICollection Values { get { return this.map.Values; } } /// <summary>Adds a key-value pair to the dictionary</summary> /// <param name="key">Key</param> /// <param name="val">Value</param> void IDictionary.Add(object key, object val) { this.Add((BEncode.String)key, (BEncode.Element)val); } /// <summary>Adds a key-value pair to the dictionary</summary> /// <param name="key">Key</param> /// <param name="val">Value</param> public void Add(BEncode.String key, BEncode.Element val) { this.map.Add(key, val); } /// <summary></summary> /// <returns>Keys held in the dictionary</returns> public ICollection Keys { get { return this.map.Keys; } } /// <summary></summary> /// <returns>True if the dictionary is of fixed size</returns> public bool IsFixedSize { get { return this.map.IsFixedSize; } } #endregion #region ICollection Members /// <summary></summary> /// <returns>True if the dictionary is synchronized</returns> public bool IsSynchronized { get { return this.map.IsSynchronized; } } /// <summary></summary> /// <returns>Number of key-value pairs in the dictionary</returns> public int Count { get { return this.map.Count; } } /// <summary>Copies the contents of the dictionary to the array</summary> /// <param name="array">Destination array</param> /// <param name="index">Index of destination array to copy to</param> public void CopyTo(System.Array array, int index) { this.map.CopyTo(array, index); } /// <summary></summary> /// <returns>The synchronization root of the dictionary</returns> public object SyncRoot { get { return this.map.SyncRoot; } } #endregion #region IEnumerable Members /// <summary>Gets the enumerator for the dictionary</summary> /// <returns>Enumerator</returns> IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.map.GetEnumerator(); } #endregion } #region Reading methods /// <summary> /// Returns the next element in the stream. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>bEncode element</returns> public static Element NextElement(IO.Stream istream) { return NextElement(istream, istream.ReadByte()); } public static Element NextElement(IO.Stream istream, int type) { switch (type) { case 'd': // dictionary return new Dictionary(istream); case 'l': // list return new List(istream); case 'i': // integer return new Integer(istream); case '0': // string, // case zero should never happen, but file may have bugged bencode implementation case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return new String(istream, type); default: throw new IO.IOException("Corrupt bEncode stream"); } } /// <summary> /// Returns the next dictionary in the stream, if you are expecting one. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>bEncoded dictionary</returns> public static Dictionary NextDictionary(IO.Stream istream) { return (Dictionary)NextElement(istream); } /// <summary> /// Returns the next list in the stream, if you are expecting one. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>bEncoded list</returns> public static List NextList(IO.Stream istream) { return (List)NextElement(istream); } /// <summary> /// Returns the next string in the stream, if you are expecting one. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>string</returns> public static string NextString(IO.Stream istream) { return ((String)NextElement(istream)); } /// <summary> /// Returns the next byte stream in the stream, if you are expecting one. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>bytes</returns> public static byte[] NextBytes(IO.Stream istream) { return ((String)NextElement(istream)).Data; } /// <summary> /// Returns the next integer in the stream, if you are expecting one. /// </summary> /// <param name="istream">bEncoded stream to extract element from</param> /// <returns>integer</returns> public static int NextInteger(IO.Stream istream) { return ((Integer)NextElement(istream)); } #endregion #region Writing methods public static void WriteElement(IO.Stream ostream, Element element) { element.Write(ostream); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.WindowsAzure.WebSitesExtensions.Models; namespace Microsoft.WindowsAzure.WebSitesExtensions.Models { /// <summary> /// Describes a deployment. /// </summary> public partial class Deployment { private bool _active; /// <summary> /// Optional. Indicates if the deployment is active. /// </summary> public bool Active { get { return this._active; } set { this._active = value; } } private string _author; /// <summary> /// Optional. The author. /// </summary> public string Author { get { return this._author; } set { this._author = value; } } private string _authorEmail; /// <summary> /// Optional. The author's email. /// </summary> public string AuthorEmail { get { return this._authorEmail; } set { this._authorEmail = value; } } private bool _complete; /// <summary> /// Optional. Indicates if the deployment is complete. /// </summary> public bool Complete { get { return this._complete; } set { this._complete = value; } } private string _deployer; /// <summary> /// Optional. The deployer. /// </summary> public string Deployer { get { return this._deployer; } set { this._deployer = value; } } private DateTime _endTime; /// <summary> /// Optional. The end time. /// </summary> public DateTime EndTime { get { return this._endTime; } set { this._endTime = value; } } private string _id; /// <summary> /// Optional. The identifier. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } private bool _isReadOnly; /// <summary> /// Optional. Indicates if the deployment is read only. /// </summary> public bool IsReadOnly { get { return this._isReadOnly; } set { this._isReadOnly = value; } } private bool _isTemp; /// <summary> /// Optional. Indicates if the deployment is temporary. /// </summary> public bool IsTemp { get { return this._isTemp; } set { this._isTemp = value; } } private DateTime _lastSuccessEndTime; /// <summary> /// Optional. The last success end time. /// </summary> public DateTime LastSuccessEndTime { get { return this._lastSuccessEndTime; } set { this._lastSuccessEndTime = value; } } private Uri _logUrl; /// <summary> /// Optional. The deployment log URL. /// </summary> public Uri LogUrl { get { return this._logUrl; } set { this._logUrl = value; } } private string _message; /// <summary> /// Optional. The message. /// </summary> public string Message { get { return this._message; } set { this._message = value; } } private string _progress; /// <summary> /// Optional. The progress. /// </summary> public string Progress { get { return this._progress; } set { this._progress = value; } } private DateTime _receivedTime; /// <summary> /// Optional. The received time. /// </summary> public DateTime ReceivedTime { get { return this._receivedTime; } set { this._receivedTime = value; } } private string _siteName; /// <summary> /// Optional. The deployment site name. /// </summary> public string SiteName { get { return this._siteName; } set { this._siteName = value; } } private DateTime _startTime; /// <summary> /// Optional. The start time. /// </summary> public DateTime StartTime { get { return this._startTime; } set { this._startTime = value; } } private DeployStatus _status; /// <summary> /// Optional. The status. /// </summary> public DeployStatus Status { get { return this._status; } set { this._status = value; } } private string _statusText; /// <summary> /// Optional. The status text. /// </summary> public string StatusText { get { return this._statusText; } set { this._statusText = value; } } private Uri _url; /// <summary> /// Optional. The deployment URL. /// </summary> public Uri Url { get { return this._url; } set { this._url = value; } } /// <summary> /// Initializes a new instance of the Deployment class. /// </summary> public Deployment() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Twoclass.overload.errorverifier.errorverifier { public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Twoclass.overload.overload023.overload023 { // <Title>Overloaded methods in 2 classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base { public void Method(string x) { Test.Status = 2; } } public class Derived : Base { public void Method(int x) { Test.Status = 4; } } public class FurtherDerived : Derived { public void Method(dynamic x) { Test.Status = 3; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new FurtherDerived(); dynamic d = int.MaxValue; try { b.Method(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Twoclass.overload.overload037.overload037 { // <Title>Overloaded methods in 2 classes</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Base { public void Method(string x) { Test.Status = 2; } } public class Derived : Base { public void Method(int x) { Test.Status = 4; } } public class FurtherDerived : Derived { public void Method(object x) { Test.Status = 3; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new FurtherDerived(); dynamic d = int.MaxValue; try { b.Method(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> }
using System; using System.IO; using System.Linq; namespace Serialization { public class BinarySerializer : IStorage { public byte[] Data { get; private set; } private MemoryStream _myStream; /// <summary> /// Used when serializing /// </summary> public BinarySerializer() { } /// <summary> /// Used when deserializaing /// </summary> /// <param name="data"></param> public BinarySerializer(byte[] data) { Data = data; } #region writing private BinaryWriter _writer; private void EncodeType(object item, Type storedType) { if (item == null) { WriteSimpleValue((ushort)0xFFFE); return; } var itemType = item.GetType(); //If this isn't a simple type, then this might be a subclass so we need to //store the type if (storedType == null || storedType != item.GetType() || UnitySerializer.Verbose) { //Write the type identifier var tpId = UnitySerializer.GetTypeId(itemType); WriteSimpleValue(tpId); } else //Write a dummy identifier WriteSimpleValue((ushort)0xFFFF); } public bool StartSerializing(Entry entry, int id) { if (entry.MustHaveName) { ushort nameID = UnitySerializer.GetPropertyDefinitionId(entry.Name); WriteSimpleValue(nameID); } var item = entry.Value ?? new UnitySerializer.Nuller(); EncodeType(item, entry.StoredType); return false; } public void StartSerializing() { _myStream = new MemoryStream(); _writer = new BinaryWriter(_myStream); UnitySerializer.PushKnownTypes(); UnitySerializer.PushPropertyNames(); } public void FinishedSerializing() { _writer.Flush(); _writer.Close(); _myStream.Flush(); var data = _myStream.ToArray(); _myStream.Close(); _myStream = null; var stream = new MemoryStream(); var outputWr = new BinaryWriter(stream); outputWr.Write("SerV10"); //New, store the verbose property outputWr.Write(UnitySerializer.Verbose); if(UnitySerializer.SerializationScope.IsPrimaryScope) { outputWr.Write(UnitySerializer._knownTypesLookup.Count); foreach (var kt in UnitySerializer._knownTypesLookup.Keys) { outputWr.Write(kt.FullName); } outputWr.Write(UnitySerializer._propertyLookup.Count); foreach (var pi in UnitySerializer._propertyLookup.Keys) { outputWr.Write(pi); } } else { outputWr.Write(0); outputWr.Write(0); } outputWr.Write(data.Length); outputWr.Write(data); outputWr.Flush(); outputWr.Close(); stream.Flush(); Data = stream.ToArray(); stream.Close(); _writer = null; _reader = null; UnitySerializer.PopKnownTypes(); UnitySerializer.PopPropertyNames(); } public bool SupportsOnDemand { get { return false; } } public void BeginOnDemand(int id) { } public void EndOnDemand() { } public void BeginWriteObject(int id, Type objectType, bool wasSeen) { if(objectType == null) { WriteSimpleValue('X'); } else if (wasSeen) { WriteSimpleValue('S'); WriteSimpleValue(id); } else { WriteSimpleValue('O'); } } public void BeginWriteProperties(int count) { if(count > 250) { WriteSimpleValue((byte)255); WriteSimpleValue(count); } else { WriteSimpleValue((byte)count); } } public void BeginWriteFields(int count) { if(count > 250) { WriteSimpleValue((byte)255); WriteSimpleValue(count); } else { WriteSimpleValue((byte)count); } } public void WriteSimpleValue(object value) { UnitySerializer.WriteValue(_writer, value); } public void BeginWriteList(int count, Type listType) { WriteSimpleValue(count); } public void BeginWriteDictionary(int count, Type dictionaryType) { WriteSimpleValue(count); } public void WriteSimpleArray(int count, Array array) { WriteSimpleValue(count); var elementType = array.GetType().GetElementType(); if (elementType == typeof(byte)) { UnitySerializer.WriteValue(_writer, array); } else if (elementType.IsPrimitive) { var ba = new byte[Buffer.ByteLength(array)]; Buffer.BlockCopy(array, 0, ba, 0, ba.Length); UnitySerializer.WriteValue(_writer, ba); } else { for (int i = 0; i < count; i++) { var v = array.GetValue(i); if(v==null) { UnitySerializer.WriteValue(_writer, (byte)0); } else { UnitySerializer.WriteValue(_writer, (byte)1); UnitySerializer.WriteValue(_writer, v); } } } } public void BeginMultiDimensionArray(Type arrayType, int dimensions, int count) { WriteSimpleValue(-1); WriteSimpleValue(dimensions); WriteSimpleValue(count); } public void WriteArrayDimension(int dimension, int count) { WriteSimpleValue(count); } public void BeginWriteObjectArray(int count, Type arrayType) { WriteSimpleValue(count); } public Entry[] ShouldWriteFields(Entry[] fields) { return fields; } public Entry[] ShouldWriteProperties(Entry[] properties) { return properties; } #endregion writing #region reading private BinaryReader _reader; private Type DecodeType(Type storedType) { try { var tid = ReadSimpleValue<ushort>(); if(tid == 0xffff) return storedType; if (tid == 0xFFFE) { return null; } if(tid >= 60000) { try { return UnitySerializer.PrewarmLookup[tid-60000]; } catch { throw new Exception("Data stream appears corrupt, found a TYPE ID of " + tid.ToString()); } } storedType = UnitySerializer._knownTypesList[tid]; return storedType; } catch { return null; } } public void FinishedDeserializing() { _reader.Close(); _myStream.Close(); _reader = null; _myStream = null; _writer = null; UnitySerializer.PopKnownTypes(); UnitySerializer.PopPropertyNames(); } //Gets the name from the stream public void DeserializeGetName(Entry entry) { if (!entry.MustHaveName) { return; } var id = ReadSimpleValue<ushort>(); try { entry.Name = id >= 50000 ? PreWarm.PrewarmNames[id-50000] : UnitySerializer._propertyList[id]; } catch { throw new Exception("Data stream may be corrupt, found an id of " + id + " when looking a property name id"); } } /// <summary> /// Starts to deserialize the object /// </summary> /// <param name="entry"></param> /// <returns></returns> public object StartDeserializing(Entry entry) { var itemType = DecodeType(entry.StoredType); entry.StoredType = itemType; return null; } public Entry BeginReadProperty(Entry entry) { return entry; } public void EndReadProperty() { } public Entry BeginReadField(Entry entry) { return entry; } public void EndReadField() { } public void StartDeserializing() { UnitySerializer.PushKnownTypes(); UnitySerializer.PushPropertyNames(); var stream = new MemoryStream(Data); var reader = new BinaryReader(stream); var version = reader.ReadString(); UnitySerializer.currentVersion = int.Parse(version.Substring(4)); if (UnitySerializer.currentVersion >= 3) { UnitySerializer.Verbose = reader.ReadBoolean(); } var count = reader.ReadInt32(); for (var i = 0; i < count; i++) { var typeName = reader.ReadString(); var tp = UnitySerializer.GetTypeEx(typeName); if (tp == null) { var map = new UnitySerializer.TypeMappingEventArgs { TypeName = typeName }; UnitySerializer.InvokeMapMissingType(map); tp = map.UseType; } if (tp == null) throw new ArgumentException(string.Format("Cannot reference type {0} in this context", typeName)); UnitySerializer._knownTypesList.Add(tp); } count = reader.ReadInt32(); for (var i = 0; i < count; i++) { UnitySerializer._propertyList.Add(reader.ReadString()); } var data = reader.ReadBytes(reader.ReadInt32()); _myStream = new MemoryStream(data); _reader = new BinaryReader(_myStream); reader.Close(); stream.Close(); } public void FinishDeserializing(Entry entry) { } public Array ReadSimpleArray(Type elementType, int count) { if (count == -1) { count = ReadSimpleValue<int>(); } if (elementType == typeof(byte)) { return ReadSimpleValue<byte[]>(); } if (elementType.IsPrimitive && UnitySerializer.currentVersion >= 6) { var ba = ReadSimpleValue<byte[]>(); var a = Array.CreateInstance(elementType, count); Buffer.BlockCopy(ba, 0, a, 0, ba.Length); return a; } var result = Array.CreateInstance(elementType, count); if(UnitySerializer.currentVersion >= 8) { for (var l = 0; l < count; l++) { var go = (byte)ReadSimpleValue(typeof(byte)); result.SetValue(go != 0 ? ReadSimpleValue(elementType) : null, l); } } else { for (var l = 0; l < count; l++) { result.SetValue(ReadSimpleValue(elementType), l); } } return result; } public int BeginReadProperties() { var count = ReadSimpleValue<byte>(); return count==255 ? ReadSimpleValue<int>() : count; } public int BeginReadFields() { var count = ReadSimpleValue<byte>(); return count==255 ? ReadSimpleValue<int>() : count; } public T ReadSimpleValue<T>() { return (T)ReadSimpleValue(typeof(T)); } public object ReadSimpleValue(Type type) { UnitySerializer.ReadAValue read; if (!UnitySerializer.Readers.TryGetValue(type, out read)) { return _reader.ReadInt32(); } return read(_reader); } public bool IsMultiDimensionalArray(out int length) { var count = ReadSimpleValue<int>(); if (count == -1) { length = -1; return true; } length = count; return false; } public int BeginReadDictionary(Type keyType, Type valueType) { return ReadSimpleValue<int>(); } public void EndReadDictionary() { } public int BeginReadObjectArray(Type valueType) { return ReadSimpleValue<int>(); } public void EndReadObjectArray() { } public void BeginReadMultiDimensionalArray(out int dimension, out int count) { // //var dimensions = storage.ReadValue<int>("dimensions"); //var totalLength = storage.ReadValue<int>("length"); dimension = ReadSimpleValue<int>(); count = ReadSimpleValue<int>(); } public void EndReadMultiDimensionalArray() { } public int ReadArrayDimension(int index) { // //.ReadValue<int>("dim_len" + item); return ReadSimpleValue<int>(); } public int BeginReadList(Type valueType) { return ReadSimpleValue<int>(); } public void EndReadList() { } public int BeginReadObject(out bool isReference) { int result; var knownType = ReadSimpleValue<char>(); if(knownType == 'X') { isReference = false; return -1; } if (knownType == 'O') { result = -1; isReference = false; } else { result = ReadSimpleValue<int>(); isReference = true; } return result; } #endregion reading #region do nothing methods public void EndWriteObjectArray() { } public void EndWriteList() { } public void EndWriteDictionary() { } public bool BeginWriteDictionaryKey(int id, object value) { return false; } public void EndWriteDictionaryKey() { } public bool BeginWriteDictionaryValue(int id, object value) { return false; } public void EndWriteDictionaryValue() { } public void EndMultiDimensionArray() { } public void EndReadObject() { } public bool BeginWriteListItem(int index, object value) { return false; } public void EndWriteListItem() { } public bool BeginWriteObjectArrayItem(int index, object value) { return false; } public void EndWriteObjectArrayItem() { } public void EndReadProperties() { } public void EndReadFields() { } public object BeginReadListItem(int index, Entry entry) { return null; } public void EndReadListItem() { } public object BeginReadDictionaryKeyItem(int index, Entry entry) { return null; } public void EndReadDictionaryKeyItem() { } public object BeginReadDictionaryValueItem(int index, Entry entry) { return null; } public void EndReadDictionaryValueItem() { } public object BeginReadObjectArrayItem(int index, Entry entry) { return null; } public void EndReadObjectArrayItem() { } public void EndWriteObject() { } public void BeginWriteProperty(string name, Type type) { } public void EndWriteProperty() { } public void BeginWriteField(string name, Type type) { } public void EndWriteField() { } public void EndWriteProperties() { } public void EndWriteFields() { } public void FinishSerializing(Entry entry) { } public void BeginReadDictionaryKeys () { } public void EndReadDictionaryKeys () { } public void BeginReadDictionaryValues () { } public void EndReadDictionaryValues () { } public void BeginWriteDictionaryKeys () { } public void EndWriteDictionaryKeys () { } public void BeginWriteDictionaryValues () { } public void EndWriteDictionaryValues () { } public bool HasMore () { throw new NotImplementedException (); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics; using Microsoft.Xna.Framework; using FlatRedBall.Input; using Vector3 = Microsoft.Xna.Framework.Vector3; using FlatRedBall.Utilities; namespace FlatRedBall.Math.Geometry { public class ShapeCollection : ICollidable, IEquatable<ShapeCollection> ,IMouseOver, INameable { #region Fields private delegate bool CollisionDelegate(); private delegate void SetLastMovePositionDelegate(Vector2 lastMovePosition); internal PositionedObjectList<AxisAlignedRectangle> mAxisAlignedRectangles = new PositionedObjectList<AxisAlignedRectangle>(); internal PositionedObjectList<Circle> mCircles = new PositionedObjectList<Circle>(); internal PositionedObjectList<Polygon> mPolygons = new PositionedObjectList<Polygon>(); internal PositionedObjectList<Line> mLines = new PositionedObjectList<Line>(); internal PositionedObjectList<Sphere> mSpheres = new PositionedObjectList<Sphere>(); internal PositionedObjectList<AxisAlignedCube> mAxisAlignedCubes = new PositionedObjectList<AxisAlignedCube>(); internal PositionedObjectList<Capsule2D> mCapsule2Ds = new PositionedObjectList<Capsule2D>(); // if you add here, add below too! internal protected float mMaxAxisAlignedRectanglesRadius; internal protected float mMaxCirclesRadius; internal protected float mMaxPolygonsRadius; internal protected float mMaxLinesRadius; internal protected float mMaxSpheresRadius; internal protected float mMaxAxisAlignedCubesRadius; internal protected float mMaxCapsule2DsRadius; internal bool mSuppressLastCollisionClear; internal List<AxisAlignedRectangle> mLastCollisionAxisAlignedRectangles = new List<AxisAlignedRectangle>(); internal List<Circle> mLastCollisionCircles = new List<Circle>(); internal List<Polygon> mLastCollisionPolygons = new List<Polygon>(); internal List<Line> mLastCollisionLines = new List<Line>(); internal List<Sphere> mLastCollisionSpheres = new List<Sphere>(); internal List<AxisAlignedCube> mLastCollisionAxisAlignedCubes = new List<AxisAlignedCube>(); internal List<Capsule2D> mLastCollisionCapsule2Ds = new List<Capsule2D>(); #endregion #region Properties ShapeCollection ICollidable.Collision { get { return this; } } public PositionedObjectList<AxisAlignedRectangle> AxisAlignedRectangles { get { return mAxisAlignedRectangles; } } public PositionedObjectList<AxisAlignedCube> AxisAlignedCubes { get { return mAxisAlignedCubes; } } public PositionedObjectList<Capsule2D> Capsule2Ds { get { return mCapsule2Ds; } } public PositionedObjectList<Circle> Circles { get { return mCircles; } } public PositionedObjectList<Polygon> Polygons { get { return mPolygons; } } public List<AxisAlignedRectangle> LastCollisionAxisAlignedRectangles { get { return mLastCollisionAxisAlignedRectangles; } } public List<Circle> LastCollisionCircles { get { return mLastCollisionCircles; } } public List<Polygon> LastCollisionPolygons { get { return mLastCollisionPolygons; } } public List<Line> LastCollisionLines { get { return mLastCollisionLines; } } public List<Sphere> LastCollisionSpheres { get { return mLastCollisionSpheres; } } public List<AxisAlignedCube> LastCollisionAxisAlignedCubes { get { return mLastCollisionAxisAlignedCubes; } } public List<Capsule2D> LastCollisionCapsule2Ds { get { return mLastCollisionCapsule2Ds; } } public PositionedObjectList<Line> Lines { get { return mLines; } } public PositionedObjectList<Sphere> Spheres { get { return mSpheres; } } public bool IsEmpty { get { return mAxisAlignedCubes.Count == 0 && mAxisAlignedRectangles.Count == 0 && mCapsule2Ds.Count == 0 && mCircles.Count == 0 && mPolygons.Count == 0 && mLines.Count == 0 && mSpheres.Count == 0; } } public string Name { get; set; } public bool Visible { set { foreach (AxisAlignedRectangle aar in mAxisAlignedRectangles) { aar.Visible = value; } foreach (AxisAlignedCube aac in mAxisAlignedCubes) { aac.Visible = value; } foreach (Circle circle in mCircles) { circle.Visible = value; } foreach (Polygon polygon in mPolygons) { polygon.Visible = value; } foreach (Line line in mLines) { line.Visible = value; } foreach (Sphere sphere in mSpheres) { sphere.Visible = value; } foreach (Capsule2D capsule2D in mCapsule2Ds) { capsule2D.Visible = value; } } } public float MaxAxisAlignedRectanglesScale { get { return mMaxAxisAlignedRectanglesRadius; } set { mMaxAxisAlignedRectanglesRadius = value; } } public float MaxPolygonRadius { get => mMaxPolygonsRadius; set => mMaxPolygonsRadius = value; } #endregion #region Methods #region Public Methods public void AddToThis(ShapeCollection shapeCollection) { mAxisAlignedRectangles.AddRange(shapeCollection.AxisAlignedRectangles); mCircles.AddRange(shapeCollection.Circles); mPolygons.AddRange(shapeCollection.Polygons); mLines.AddRange(shapeCollection.Lines); mSpheres.AddRange(shapeCollection.Spheres); mAxisAlignedCubes.AddRange(shapeCollection.mAxisAlignedCubes); mCapsule2Ds.AddRange(shapeCollection.mCapsule2Ds); } public void Add(Circle circle) { mCircles.Add(circle); } public void Add(AxisAlignedRectangle rectangle) { mAxisAlignedRectangles.Add(rectangle); } public void Add(Polygon polygon) { mPolygons.Add(polygon); } public void AddToManagers() { AddToManagers(null); } public void AddToManagers(Layer layer, bool makeAutomaticallyUpdated = true) { for (int i = 0; i < mAxisAlignedRectangles.Count; i++) { AxisAlignedRectangle rectangle = mAxisAlignedRectangles[i]; ShapeManager.AddToLayer(rectangle, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mAxisAlignedCubes.Count; i++) { AxisAlignedCube cube = mAxisAlignedCubes[i]; ShapeManager.AddToLayer(cube, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mCapsule2Ds.Count; i++) { Capsule2D capsule = mCapsule2Ds[i]; ShapeManager.AddToLayer(capsule, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mCircles.Count; i++) { Circle circle = mCircles[i]; ShapeManager.AddToLayer(circle, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mSpheres.Count; i++) { Sphere sphere = mSpheres[i]; ShapeManager.AddToLayer(sphere, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mPolygons.Count; i++) { Polygon polygon = mPolygons[i]; ShapeManager.AddToLayer(polygon, layer, makeAutomaticallyUpdated); } for (int i = 0; i < mLines.Count; i++) { Line line = mLines[i]; ShapeManager.AddToLayer(line, layer, makeAutomaticallyUpdated); } } public void AttachAllDetachedTo(PositionedObject newParent, bool changeRelative) { mAxisAlignedRectangles.AttachAllDetachedTo(newParent, changeRelative); mCircles.AttachAllDetachedTo(newParent, changeRelative); mPolygons.AttachAllDetachedTo(newParent, changeRelative); mLines.AttachAllDetachedTo(newParent, changeRelative); mSpheres.AttachAllDetachedTo(newParent, changeRelative); mAxisAlignedCubes.AttachAllDetachedTo(newParent, changeRelative); mCapsule2Ds.AttachAllDetachedTo(newParent, changeRelative); } public void AttachTo(PositionedObject newParent, bool changeRelative) { mAxisAlignedRectangles.AttachTo(newParent, changeRelative); mCircles.AttachTo(newParent, changeRelative); mPolygons.AttachTo(newParent, changeRelative); mLines.AttachTo(newParent, changeRelative); mSpheres.AttachTo(newParent, changeRelative); mAxisAlignedCubes.AttachTo(newParent, changeRelative); mCapsule2Ds.AttachTo(newParent, changeRelative); } public void CalculateAllMaxRadii() { mMaxAxisAlignedRectanglesRadius = 0; mMaxCirclesRadius = 0; mMaxPolygonsRadius = 0; mMaxLinesRadius = 0; mMaxSpheresRadius = 0; mMaxAxisAlignedCubesRadius = 0; mMaxCapsule2DsRadius = 0; for(int i = 0; i < mAxisAlignedRectangles.Count; i++) { mMaxAxisAlignedRectanglesRadius = System.Math.Max(mMaxAxisAlignedRectanglesRadius, mAxisAlignedRectangles[i].BoundingRadius); } for(int i = 0; i < mCircles.Count; i++) { mMaxCirclesRadius = System.Math.Max(mMaxCirclesRadius, mCircles[i].Radius); } for(int i = 0; i < mPolygons.Count; i++) { mMaxPolygonsRadius = System.Math.Max(mMaxPolygonsRadius, mPolygons[i].BoundingRadius); } for(int i = 0; i < mLines.Count; i++) { // mega inefficient!!!!! float boundingRadius = (float)System.Math.Max( mLines[i].RelativePoint1.Length(), mLines[i].RelativePoint2.Length()); mMaxLinesRadius = System.Math.Max(mMaxLinesRadius, boundingRadius); } for(int i = 0; i < mSpheres.Count; i++) { mMaxSpheresRadius = System.Math.Max(mMaxSpheresRadius, mSpheres[i].Radius); } for(int i = 0; i < mAxisAlignedCubes.Count; i++) { mMaxAxisAlignedCubesRadius = System.Math.Max(mMaxAxisAlignedCubesRadius, mAxisAlignedCubes[i].BoundingRadius); } for (int i = 0; i < mCapsule2Ds.Count; i++) { mMaxCapsule2DsRadius = System.Math.Max(mMaxCapsule2DsRadius, mCapsule2Ds[i].BoundingRadius); } } public void Clear() { mAxisAlignedRectangles.Clear(); mAxisAlignedCubes.Clear(); mCircles.Clear(); mPolygons.Clear(); mLines.Clear(); mSpheres.Clear(); mCapsule2Ds.Clear(); } public ShapeCollection Clone() { ShapeCollection shapeCollection = new ShapeCollection(); for (int i = 0; i < mAxisAlignedRectangles.Count; i++) { shapeCollection.mAxisAlignedRectangles.Add(mAxisAlignedRectangles[i].Clone()); } for (int i = 0; i < mCircles.Count; i++) { shapeCollection.mCircles.Add(mCircles[i].Clone()); } for (int i = 0; i < mPolygons.Count; i++) { shapeCollection.mPolygons.Add(mPolygons[i].Clone()); } for (int i = 0; i < mLines.Count; i++) { shapeCollection.mLines.Add(mLines[i].Clone()); } for (int i = 0; i < mSpheres.Count; i++) { shapeCollection.mSpheres.Add(mSpheres[i].Clone()); } for (int i = 0; i < mAxisAlignedCubes.Count; i++) { shapeCollection.mAxisAlignedCubes.Add(mAxisAlignedCubes[i].Clone()); } for (int i = 0; i < mCapsule2Ds.Count; i++) { shapeCollection.mCapsule2Ds.Add(mCapsule2Ds[i].Clone()); } return shapeCollection; } public void CopyAbsoluteToRelative() { CopyAbsoluteToRelative(true); } public void CopyAbsoluteToRelative(bool includeItemsWithParent) { mAxisAlignedRectangles.CopyAbsoluteToRelative(includeItemsWithParent); mCircles.CopyAbsoluteToRelative(includeItemsWithParent); mPolygons.CopyAbsoluteToRelative(includeItemsWithParent); mLines.CopyAbsoluteToRelative(includeItemsWithParent); mSpheres.CopyAbsoluteToRelative(includeItemsWithParent); mAxisAlignedCubes.CopyAbsoluteToRelative(includeItemsWithParent); mCapsule2Ds.CopyAbsoluteToRelative(includeItemsWithParent); } public PositionedObject FindByName(string nameToSearchFor) { AxisAlignedRectangle aar = mAxisAlignedRectangles.FindByName(nameToSearchFor); if (aar != null) { return aar; } Circle circle = mCircles.FindByName(nameToSearchFor); if (circle != null) { return circle; } Polygon polygon = mPolygons.FindByName(nameToSearchFor); if (polygon != null) { return polygon; } Line line = mLines.FindByName(nameToSearchFor); if(line != null) { return line; } Sphere sphere = mSpheres.FindByName(nameToSearchFor); if(sphere != null) { return sphere; } AxisAlignedCube aac = mAxisAlignedCubes.FindByName(nameToSearchFor); if(aac != null) { return aac; } Capsule2D capsule = mCapsule2Ds.FindByName(nameToSearchFor); if (capsule != null) { return capsule; } // If we got here then there's no object in the ShapeCollection by this name. return null; } /// <summary> /// Removes all contained shapes from the ShapeManager and clears this ShapeCollection. /// </summary> public void RemoveFromManagers() { RemoveFromManagers(true); } /// <summary> /// Removes all contained shapes from the ShapeManager and optionally clears this ShapeCollection. /// </summary> /// <remarks> /// Removal of shapes removes shapes from every-frame management and visibility. /// </remarks> /// <param name="clearThis">Whether to clear this ShapeCollection.</param> public void RemoveFromManagers(bool clearThis) { if (!clearThis) { MakeOneWay(); } #region Remove the AxisAlignedRectangles for (int i = mAxisAlignedRectangles.Count - 1; i > -1; i--) { AxisAlignedRectangle shape = mAxisAlignedRectangles[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the AxisAlignedCubes for (int i = mAxisAlignedCubes.Count - 1; i > -1; i--) { AxisAlignedCube shape = mAxisAlignedCubes[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the Capsules for (int i = mCapsule2Ds.Count - 1; i > -1; i--) { Capsule2D shape = mCapsule2Ds[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the Spheres for (int i = mSpheres.Count - 1; i > -1; i--) { Sphere shape = mSpheres[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the Circles for (int i = mCircles.Count - 1; i > -1; i--) { Circle shape = mCircles[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the Polygons for (int i = mPolygons.Count - 1; i > -1; i--) { Polygon shape = mPolygons[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion #region Remove the Lines for (int i = mLines.Count - 1; i > -1; i--) { Line shape = mLines[i]; PositionedObject oldParent = shape.Parent; ShapeManager.Remove(shape); if (!clearThis && oldParent != null) { shape.AttachTo(oldParent, false); } } #endregion if (!clearThis) { MakeTwoWay(); } else { // just in case its oneway already Clear(); } } /// <summary> /// Makes all contained lists (such as for AxisAlignedRectangles and Circles) two-way. /// </summary> public void MakeTwoWay() { mAxisAlignedCubes.MakeTwoWay(); mAxisAlignedRectangles.MakeTwoWay(); mCapsule2Ds.MakeTwoWay(); mCircles.MakeTwoWay(); mSpheres.MakeTwoWay(); mPolygons.MakeTwoWay(); mLines.MakeTwoWay(); } /// <summary> /// Makes all contained lists (such as for AxisAlignedRectangles and Circles) one-way. /// </summary> public void MakeOneWay() { mAxisAlignedCubes.MakeOneWay(); mAxisAlignedRectangles.MakeOneWay(); mCapsule2Ds.MakeOneWay(); mCircles.MakeOneWay(); mSpheres.MakeOneWay(); mPolygons.MakeOneWay(); mLines.MakeOneWay(); } /// <summary> /// Moves all contained objects by the argument shiftVector; /// </summary> /// <param name="shiftVector">The amount to shift by.</param> public void Shift(Vector3 shiftVector) { int i; for (i = 0; i < mAxisAlignedRectangles.Count; i++) { mAxisAlignedRectangles[i].Position += shiftVector; } for (i = 0; i < mCircles.Count; i++) { mCircles[i].Position += shiftVector; } for (i = 0; i < mPolygons.Count; i++) { mPolygons[i].Position += shiftVector; } for (i = 0; i < mLines.Count; i++) { mLines[i].Position += shiftVector; } for (i = 0; i < mSpheres.Count; i++) { mSpheres[i].Position += shiftVector; } for (i = 0; i < mAxisAlignedCubes.Count; i++) { mAxisAlignedCubes[i].Position += shiftVector; } for (i = 0; i < mCapsule2Ds.Count; i++) { mCapsule2Ds[i].Position += shiftVector; } } public void ShiftRelative(float x, float y, float z) { Vector3 shiftVector = new Vector3(x, y, z); mAxisAlignedRectangles.ShiftRelative(shiftVector); mCircles.ShiftRelative(shiftVector); mPolygons.ShiftRelative(shiftVector); mLines.ShiftRelative(shiftVector); mSpheres.ShiftRelative(shiftVector); mAxisAlignedCubes.ShiftRelative(shiftVector); mCapsule2Ds.ShiftRelative(shiftVector); } public void SortAscending(Axis axisToSortOn) { switch (axisToSortOn) { case Axis.X: mAxisAlignedRectangles.SortXInsertionAscending(); mCircles.SortXInsertionAscending(); mPolygons.SortXInsertionAscending(); mLines.SortXInsertionAscending(); mSpheres.SortXInsertionAscending(); mAxisAlignedCubes.SortXInsertionAscending(); mCapsule2Ds.SortXInsertionAscending(); break; case Axis.Y: mAxisAlignedRectangles.SortYInsertionAscending(); mCircles.SortYInsertionAscending(); mPolygons.SortYInsertionAscending(); mLines.SortYInsertionAscending(); mSpheres.SortYInsertionAscending(); mAxisAlignedCubes.SortYInsertionAscending(); mCapsule2Ds.SortYInsertionAscending(); break; default: throw new NotImplementedException(); // break; } } public override string ToString() { return "ShapeCollection: " + Name; } public void UpdateDependencies(double currentTime) { for (int i = 0; i < mAxisAlignedRectangles.Count; i++) { mAxisAlignedRectangles[i].UpdateDependencies(currentTime); } for (int i = 0; i < mCircles.Count; i++) { mCircles[i].UpdateDependencies(currentTime); } for (int i = 0; i < mPolygons.Count; i++) { mPolygons[i].UpdateDependencies(currentTime); } for (int i = 0; i < mLines.Count; i++) { mLines[i].UpdateDependencies(currentTime); } for (int i = 0; i < mSpheres.Count; i++) { mSpheres[i].UpdateDependencies(currentTime); } for (int i = 0; i < mAxisAlignedCubes.Count; i++) { mAxisAlignedCubes[i].UpdateDependencies(currentTime); } for (int i = 0; i < mCapsule2Ds.Count; i++) { mCapsule2Ds[i].UpdateDependencies(currentTime); } } public void FlipHorizontally() { #region Flip the AxisAlignedRectangles for (int i = mAxisAlignedRectangles.Count - 1; i > -1; i--) { AxisAlignedRectangle shape = mAxisAlignedRectangles[i]; shape.RelativePosition.X = -shape.RelativePosition.X; } #endregion #region Flip the AxisAlignedCubes for (int i = mAxisAlignedCubes.Count - 1; i > -1; i--) { AxisAlignedCube shape = mAxisAlignedCubes[i]; shape.RelativePosition.X = -shape.RelativePosition.X; } #endregion #region Flip the Capsules for (int i = mCapsule2Ds.Count - 1; i > -1; i--) { Capsule2D shape = mCapsule2Ds[i]; shape.RelativePosition.X = -shape.RelativePosition.X; shape.RotationZ = -shape.RotationZ; shape.RelativeRotationZ = -shape.RelativeRotationZ; } #endregion #region Flip the Spheres for (int i = mSpheres.Count - 1; i > -1; i--) { Sphere shape = mSpheres[i]; shape.RelativePosition.X = -shape.RelativePosition.X; } #endregion #region Flip the Circles for (int i = mCircles.Count - 1; i > -1; i--) { Circle shape = mCircles[i]; shape.RelativePosition.X = -shape.RelativePosition.X; } #endregion #region Flip the Polygons for (int i = mPolygons.Count - 1; i > -1; i--) { Polygon shape = mPolygons[i]; shape.FlipRelativePointsHorizontally(); shape.RelativePosition.X = -shape.RelativePosition.X; shape.RotationZ = -shape.RotationZ; shape.RelativeRotationZ = -shape.RelativeRotationZ; } #endregion #region Flip the Lines for (int i = mLines.Count - 1; i > -1; i--) { Line shape = mLines[i]; shape.FlipRelativePointsHorizontally(); shape.RelativePosition.X = -shape.RelativePosition.X; shape.RotationZ = -shape.RotationZ; shape.RelativeRotationZ = -shape.RelativeRotationZ; } #endregion } /// <summary> /// Checks if the designated 2D point is in the 2D shapes of the shape collection /// </summary> public bool IsPointInside(float x, float y) { int count; count = AxisAlignedRectangles.Count; for (int i = 0; i < count; i++) { if (AxisAlignedRectangles[i].IsPointInside(x, y)) return true; } count = Circles.Count; for (int i = 0; i < count; i++) { if (Circles[i].IsPointInside(x, y)) return true; } count = Polygons.Count; for (int i = 0; i < count; i++) { if (Polygons[i].IsPointInside(x, y)) return true; } return false; } #endregion #region Internal Methods internal void ClearLastCollisionLists() { if (!mSuppressLastCollisionClear) { mLastCollisionAxisAlignedRectangles.Clear(); mLastCollisionCircles.Clear(); mLastCollisionPolygons.Clear(); mLastCollisionLines.Clear(); mLastCollisionSpheres.Clear(); mLastCollisionAxisAlignedCubes.Clear(); mLastCollisionCapsule2Ds.Clear(); } } internal void ResetLastUpdateTimes() { foreach (var shape in mAxisAlignedRectangles) { shape.LastDependencyUpdate = -1; } foreach (var shape in mCircles) { shape.LastDependencyUpdate = -1; } foreach (var shape in mPolygons) { shape.LastDependencyUpdate = -1; } foreach (var shape in mLines) { shape.LastDependencyUpdate = -1; } foreach (var shape in mSpheres) { shape.LastDependencyUpdate = -1; } foreach (var shape in mAxisAlignedCubes) { shape.LastDependencyUpdate = -1; } foreach (var shape in mCapsule2Ds) { shape.LastDependencyUpdate = -1; } } #endregion #region Private Methods private bool CollideWithoutSnag2D(CollisionDelegate collisionMethod, SetLastMovePositionDelegate lastMovePosition, PositionedObject collidingShape) { Vector2 originalPosition; Vector2 originalVelocity; Vector2 originalParentPosition; UpdateDependencies(TimeManager.CurrentTime); collidingShape.UpdateDependencies(TimeManager.CurrentTime); originalPosition.X = collidingShape.X; originalPosition.Y = collidingShape.Y; originalVelocity.X = collidingShape.TopParent.XVelocity; originalVelocity.Y = collidingShape.TopParent.YVelocity; originalParentPosition.X = collidingShape.TopParent.X; originalParentPosition.Y = collidingShape.TopParent.Y; if (collisionMethod()) { if (originalPosition.X != collidingShape.X && originalPosition.Y != collidingShape.Y) { Vector2 finalPosition; Vector2 finalVelocity; Vector2 newPosition; Vector2 newVelocity; Vector2 newTopParentPosition; List<AxisAlignedCube> finalLastCollisionAxisAlignedCubes = new List<AxisAlignedCube>(); List<AxisAlignedRectangle> finalLastCollisionAxisAlignedRectangles = new List<AxisAlignedRectangle>(); List<Capsule2D> finalLastCollisionCapsule2Ds = new List<Capsule2D>(); List<Circle> finalLastCollisionCircles = new List<Circle>(); List<Line> finalLastCollisionLines = new List<Line>(); List<Polygon> finalLastCollisionPolygons = new List<Polygon>(); List<Sphere> finalLastCollisionSpheres = new List<Sphere>(); newPosition.X = collidingShape.X; newPosition.Y = collidingShape.Y; newVelocity.X = collidingShape.TopParent.XVelocity; newVelocity.Y = collidingShape.TopParent.YVelocity; newTopParentPosition.X = collidingShape.TopParent.X; newTopParentPosition.Y = collidingShape.TopParent.Y; /////////////// /////Fix X///// /////////////// //Move back to original X position collidingShape.X = originalPosition.X; collidingShape.TopParent.XVelocity = originalVelocity.X; collidingShape.TopParent.X = originalParentPosition.X; collidingShape.ForceUpdateDependencies(); //Collide collisionMethod(); //Save new position finalPosition.X = collidingShape.X; finalVelocity.X = collidingShape.TopParent.XVelocity; //Move back to new position collidingShape.X = newPosition.X; collidingShape.TopParent.XVelocity = newVelocity.X; collidingShape.TopParent.X = newTopParentPosition.X; collidingShape.Y = newPosition.Y; collidingShape.TopParent.YVelocity = newVelocity.Y; collidingShape.TopParent.Y = newTopParentPosition.Y; collidingShape.ForceUpdateDependencies(); //Save LastMove Shapes finalLastCollisionAxisAlignedCubes.AddRange(mLastCollisionAxisAlignedCubes); finalLastCollisionAxisAlignedRectangles.AddRange(mLastCollisionAxisAlignedRectangles); finalLastCollisionCapsule2Ds.AddRange(mLastCollisionCapsule2Ds); finalLastCollisionCircles.AddRange(mLastCollisionCircles); finalLastCollisionLines.AddRange(mLastCollisionLines); finalLastCollisionPolygons.AddRange(mLastCollisionPolygons); finalLastCollisionSpheres.AddRange(mLastCollisionSpheres); /////////////// /////Fix Y///// /////////////// //Move back to original Y position collidingShape.Y = originalPosition.Y; collidingShape.TopParent.YVelocity = originalVelocity.Y; collidingShape.TopParent.Y = originalParentPosition.Y; collidingShape.ForceUpdateDependencies(); //Collide collisionMethod(); //Save new position finalPosition.Y = collidingShape.Y; finalVelocity.Y = collidingShape.TopParent.YVelocity; //Update to final position collidingShape.X = finalPosition.X; collidingShape.TopParent.XVelocity = finalVelocity.X; collidingShape.TopParent.X = originalParentPosition.X + (finalPosition.X - originalPosition.X); collidingShape.Y = finalPosition.Y; collidingShape.TopParent.YVelocity = finalVelocity.Y; collidingShape.TopParent.Y = originalParentPosition.Y + (finalPosition.Y - originalPosition.Y); lastMovePosition(new Vector2(finalPosition.X - originalPosition.X, finalPosition.Y - originalPosition.Y)); collidingShape.ForceUpdateDependencies(); //Add missing LastMove Shapes // todo - change this from a foreach because foreach generates memory foreach (AxisAlignedCube cube in finalLastCollisionAxisAlignedCubes) { if (!LastCollisionAxisAlignedCubes.Contains(cube)) LastCollisionAxisAlignedCubes.Add(cube); } foreach (AxisAlignedRectangle rect in finalLastCollisionAxisAlignedRectangles) { if (!finalLastCollisionAxisAlignedRectangles.Contains(rect)) finalLastCollisionAxisAlignedRectangles.Add(rect); } foreach (Capsule2D cap2D in finalLastCollisionCapsule2Ds) { if (!finalLastCollisionCapsule2Ds.Contains(cap2D)) finalLastCollisionCapsule2Ds.Add(cap2D); } foreach (Circle circle in finalLastCollisionCircles) { if (!finalLastCollisionCircles.Contains(circle)) finalLastCollisionCircles.Add(circle); } foreach (Line line in finalLastCollisionLines) { if (!finalLastCollisionLines.Contains(line)) finalLastCollisionLines.Add(line); } foreach (Polygon polygon in finalLastCollisionPolygons) { if (!finalLastCollisionPolygons.Contains(polygon)) finalLastCollisionPolygons.Add(polygon); } foreach (Sphere sphere in finalLastCollisionSpheres) { if (!finalLastCollisionSpheres.Contains(sphere)) finalLastCollisionSpheres.Add(sphere); } } return true; } return false; } #endregion #endregion #region IEquatable<ShapeCollection> Members public bool Equals(ShapeCollection other) { return this == other; } #endregion #region Generated collision calling code public bool CollideAgainst(AxisAlignedRectangle axisAlignedRectangle) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, axisAlignedRectangle, false, Axis.X); } public bool CollideAgainst(AxisAlignedRectangle axisAlignedRectangle, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, axisAlignedRectangle, considerPartitioning, axisToUse); } public bool CollideAgainst(Circle circle) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, circle, false, Axis.X); } public bool CollideAgainst(Circle circle, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, circle, considerPartitioning, axisToUse); } public bool CollideAgainst(Polygon polygon) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, polygon, false, Axis.X); } public bool CollideAgainst(Polygon polygon, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, polygon, considerPartitioning, axisToUse); } public bool CollideAgainst(Line line) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, line, false, Axis.X); } public bool CollideAgainst(Line line, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, line, considerPartitioning, axisToUse); } public bool CollideAgainst(Capsule2D capsule2D) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, capsule2D, false, Axis.X); } public bool CollideAgainst(Capsule2D capsule2D, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, capsule2D, considerPartitioning, axisToUse); } public bool CollideAgainst(Sphere sphere) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, sphere, false, Axis.X); } public bool CollideAgainst(Sphere sphere, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, sphere, considerPartitioning, axisToUse); } public bool CollideAgainst(AxisAlignedCube axisAlignedCube) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, axisAlignedCube, false, Axis.X); } public bool CollideAgainst(AxisAlignedCube axisAlignedCube, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, axisAlignedCube, considerPartitioning, axisToUse); } public bool CollideAgainstMove(AxisAlignedRectangle axisAlignedRectangle, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedRectangle, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(AxisAlignedRectangle axisAlignedRectangle, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedRectangle, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(Circle circle, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, circle, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(Circle circle, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, circle, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(Polygon polygon, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, polygon, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(Polygon polygon, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, polygon, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(Line line, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, line, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(Line line, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, line, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(Capsule2D capsule2D, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, capsule2D, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(Capsule2D capsule2D, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, capsule2D, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(Sphere sphere, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, sphere, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(Sphere sphere, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, sphere, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstMove(AxisAlignedCube axisAlignedCube, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedCube, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(AxisAlignedCube axisAlignedCube, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedCube, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstBounce(AxisAlignedRectangle axisAlignedRectangle, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedRectangle, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(AxisAlignedRectangle axisAlignedRectangle, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedRectangle, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Circle circle, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, circle, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Circle circle, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, circle, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Polygon polygon, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, polygon, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Polygon polygon, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, polygon, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Line line, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, line, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Line line, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, line, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Capsule2D capsule2D, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, capsule2D, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Capsule2D capsule2D, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, capsule2D, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Sphere sphere, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, sphere, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Sphere sphere, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, sphere, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(AxisAlignedCube axisAlignedCube, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedCube, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(AxisAlignedCube axisAlignedCube, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedCube, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainst(ShapeCollection shapeCollection) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, shapeCollection, false, Axis.X); } public bool CollideAgainst(ShapeCollection shapeCollection, bool considerPartitioning, Axis axisToUse) { return ShapeCollectionCollision.CollideShapeAgainstThis(this, shapeCollection, considerPartitioning, axisToUse); } public bool CollideAgainstMove(ShapeCollection shapeCollection, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, shapeCollection, false, Axis.X, otherMass, thisMass); } public bool CollideAgainstMove(ShapeCollection shapeCollection, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass) { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, shapeCollection, considerPartitioning, axisToUse, otherMass, thisMass); } public bool CollideAgainstBounce(ShapeCollection shapeCollection, float thisMass, float otherMass, float elasticity) { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, shapeCollection, false, Axis.X, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(ShapeCollection shapeCollection, bool considerPartitioning, Axis axisToUse, float thisMass, float otherMass, float elasticity) { this.ClearLastCollisionLists(); return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, shapeCollection, considerPartitioning, axisToUse, otherMass, thisMass, elasticity); } public bool CollideAgainstMoveWithoutSnag(AxisAlignedRectangle axisAlignedRectangle) { return CollideWithoutSnag2D(delegate() {return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedRectangle, false, Axis.X, 0, 1);} , delegate(Vector2 lastMovePosition) { axisAlignedRectangle.mLastMoveCollisionReposition.X = lastMovePosition.X; axisAlignedRectangle.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , axisAlignedRectangle); } public bool CollideAgainstMoveWithoutSnag(AxisAlignedRectangle axisAlignedRectangle, bool considerPartitioning, Axis axisToUse) { return CollideWithoutSnag2D(delegate() {return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, axisAlignedRectangle, considerPartitioning, axisToUse, 0, 1);} , delegate(Vector2 lastMovePosition) { axisAlignedRectangle.mLastMoveCollisionReposition.X = lastMovePosition.X; axisAlignedRectangle.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , axisAlignedRectangle); } public bool CollideAgainstMoveWithoutSnag(Circle circle) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, circle, false, Axis.X, 0, 1); } , delegate(Vector2 lastMovePosition) { circle.LastMoveCollisionReposition.X = lastMovePosition.X; circle.LastMoveCollisionReposition.Y = lastMovePosition.Y; } , circle); } public bool CollideAgainstMoveWithoutSnag(Circle circle, bool considerPartitioning, Axis axisToUse) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, circle, considerPartitioning, axisToUse, 0, 1); } , delegate(Vector2 lastMovePosition) { circle.LastMoveCollisionReposition.X = lastMovePosition.X; circle.LastMoveCollisionReposition.Y = lastMovePosition.Y; } , circle); } public bool CollideAgainstMoveWithoutSnag(Polygon polygon) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, polygon, false, Axis.X, 0, 1); } , delegate(Vector2 lastMovePosition) { polygon.mLastMoveCollisionReposition.X = lastMovePosition.X; polygon.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , polygon); } public bool CollideAgainstMoveWithoutSnag(Polygon polygon, bool considerPartitioning, Axis axisToUse) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisMove(this, polygon, considerPartitioning, axisToUse, 0, 1); } , delegate(Vector2 lastMovePosition) { polygon.mLastMoveCollisionReposition.X = lastMovePosition.X; polygon.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , polygon); } public bool CollideAgainstBounceWithoutSnag(AxisAlignedRectangle axisAlignedRectangle, float elasticity) { return CollideWithoutSnag2D(delegate() {return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedRectangle, false, Axis.X, 0, 1, elasticity);} , delegate(Vector2 lastMovePosition) { axisAlignedRectangle.mLastMoveCollisionReposition.X = lastMovePosition.X; axisAlignedRectangle.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , axisAlignedRectangle); } public bool CollideAgainstBounceWithoutSnag(AxisAlignedRectangle axisAlignedRectangle, bool considerPartitioning, Axis axisToUse, float elasticity) { return CollideWithoutSnag2D(delegate() {return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, axisAlignedRectangle, considerPartitioning, axisToUse, 0, 1, elasticity);} , delegate(Vector2 lastMovePosition) { axisAlignedRectangle.mLastMoveCollisionReposition.X = lastMovePosition.X; axisAlignedRectangle.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , axisAlignedRectangle); } public bool CollideAgainstBounceWithoutSnag(Circle circle, float elasticity) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, circle, false, Axis.X, 0, 1, elasticity); } , delegate(Vector2 lastMovePosition) { circle.LastMoveCollisionReposition.X = lastMovePosition.X; circle.LastMoveCollisionReposition.Y = lastMovePosition.Y; } , circle); } public bool CollideAgainstBounceWithoutSnag(Circle circle, bool considerPartitioning, Axis axisToUse, float elasticity) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, circle, considerPartitioning, axisToUse, 0, 1, elasticity); } , delegate(Vector2 lastMovePosition) { circle.LastMoveCollisionReposition.X = lastMovePosition.X; circle.LastMoveCollisionReposition.Y = lastMovePosition.Y; } , circle); } public bool CollideAgainstBounceWithoutSnag(Polygon polygon, float elasticity) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, polygon, false, Axis.X, 0, 1, elasticity); } , delegate(Vector2 lastMovePosition) { polygon.mLastMoveCollisionReposition.X = lastMovePosition.X; polygon.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , polygon); } /// <summary> /// Performs a "snagless" collision between this and the argument Polygon. /// </summary> /// <param name="polygon">The Polygon to perform collision against.</param> /// <param name="considerPartitioning">Whether to consider spacial partitioning.</param> /// <param name="axisToUse">If partitioning is used, the axis that the list is already sorted along.</param> /// <param name="elasticity">The elasticity to use in the collision.</param> /// <returns>Whether collision has occurred.</returns> public bool CollideAgainstBounceWithoutSnag(Polygon polygon, bool considerPartitioning, Axis axisToUse, float elasticity) { return CollideWithoutSnag2D(delegate() { return ShapeCollectionCollision.CollideShapeAgainstThisBounce(this, polygon, considerPartitioning, axisToUse, 0, 1, elasticity); } , delegate(Vector2 lastMovePosition) { polygon.mLastMoveCollisionReposition.X = lastMovePosition.X; polygon.mLastMoveCollisionReposition.Y = lastMovePosition.Y; } , polygon); } public bool CollideAgainstMoveSoft(ShapeCollection shapeCollection, float thisMass, float otherMass, float separationVelocity) { mSuppressLastCollisionClear = true; bool returnValue = false; // currently we only support aarect vs aarect and // circle vs circle for (int i = 0; i < shapeCollection.AxisAlignedRectangles.Count; i++) { AxisAlignedRectangle shape = shapeCollection.AxisAlignedRectangles[i]; for(int j = 0; j < this.AxisAlignedRectangles.Count; j++) { returnValue |= shape.CollideAgainstMoveSoft(AxisAlignedRectangles[j], otherMass, thisMass, separationVelocity); } } for(int i = 0; i < shapeCollection.Circles.Count; i++) { var shape = shapeCollection.Circles[i]; for(int j = 0; j < Circles.Count; j++) { returnValue |= shape.CollideAgainstMoveSoft(Circles[j], otherMass, thisMass, separationVelocity); } } mSuppressLastCollisionClear = false; return returnValue; } #endregion public bool IsMouseOver(Gui.Cursor cursor) { return IsMouseOver(cursor, null); } public bool IsMouseOver(Gui.Cursor cursor, Layer layer) { return cursor.IsOn3D(this, layer); } } }
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 Finance.Server.Areas.HelpPage.ModelDescriptions; using Finance.Server.Areas.HelpPage.Models; namespace Finance.Server.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); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// ModelBuildResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Preview.Understand.Assistant { public class ModelBuildResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Enqueued = new StatusEnum("enqueued"); public static readonly StatusEnum Building = new StatusEnum("building"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Failed = new StatusEnum("failed"); public static readonly StatusEnum Canceled = new StatusEnum("canceled"); } private static Request BuildFetchRequest(FetchModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Fetch(FetchModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> FetchAsync(FetchModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Fetch(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchModelBuildOptions(pathAssistantSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> FetchAsync(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchModelBuildOptions(pathAssistantSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/ModelBuilds", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ResourceSet<ModelBuildResource> Read(ReadModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<ModelBuildResource>.FromJson("model_builds", response.Content); return new ResourceSet<ModelBuildResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ResourceSet<ModelBuildResource>> ReadAsync(ReadModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<ModelBuildResource>.FromJson("model_builds", response.Content); return new ResourceSet<ModelBuildResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ResourceSet<ModelBuildResource> Read(string pathAssistantSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadModelBuildOptions(pathAssistantSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ResourceSet<ModelBuildResource>> ReadAsync(string pathAssistantSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadModelBuildOptions(pathAssistantSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<ModelBuildResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<ModelBuildResource> NextPage(Page<ModelBuildResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<ModelBuildResource> PreviousPage(Page<ModelBuildResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<ModelBuildResource>.FromJson("model_builds", response.Content); } private static Request BuildCreateRequest(CreateModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/ModelBuilds", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Create(CreateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> CreateAsync(CreateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="statusCallback"> The status_callback </param> /// <param name="uniqueName"> A user-provided string that uniquely identifies this resource as an alternative to the /// sid. Unique up to 64 characters long. For example: v0.1 </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Create(string pathAssistantSid, Uri statusCallback = null, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateModelBuildOptions(pathAssistantSid){StatusCallback = statusCallback, UniqueName = uniqueName}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="statusCallback"> The status_callback </param> /// <param name="uniqueName"> A user-provided string that uniquely identifies this resource as an alternative to the /// sid. Unique up to 64 characters long. For example: v0.1 </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> CreateAsync(string pathAssistantSid, Uri statusCallback = null, string uniqueName = null, ITwilioRestClient client = null) { var options = new CreateModelBuildOptions(pathAssistantSid){StatusCallback = statusCallback, UniqueName = uniqueName}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Update(UpdateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> UpdateAsync(UpdateModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="uniqueName"> A user-provided string that uniquely identifies this resource as an alternative to the /// sid. Unique up to 64 characters long. For example: v0.1 </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static ModelBuildResource Update(string pathAssistantSid, string pathSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new UpdateModelBuildOptions(pathAssistantSid, pathSid){UniqueName = uniqueName}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="uniqueName"> A user-provided string that uniquely identifies this resource as an alternative to the /// sid. Unique up to 64 characters long. For example: v0.1 </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<ModelBuildResource> UpdateAsync(string pathAssistantSid, string pathSid, string uniqueName = null, ITwilioRestClient client = null) { var options = new UpdateModelBuildOptions(pathAssistantSid, pathSid){UniqueName = uniqueName}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteModelBuildOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/ModelBuilds/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static bool Delete(DeleteModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete ModelBuild parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteModelBuildOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of ModelBuild </returns> public static bool Delete(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteModelBuildOptions(pathAssistantSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The assistant_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of ModelBuild </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteModelBuildOptions(pathAssistantSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ModelBuildResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ModelBuildResource object represented by the provided JSON </returns> public static ModelBuildResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ModelBuildResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique ID of the Account that created this Model Build. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The date that this resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date that this resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The unique ID of the parent Assistant. /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// A string that described the model build status. The values can be: enqueued, building, completed, failed /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public ModelBuildResource.StatusEnum Status { get; private set; } /// <summary> /// A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. /// </summary> [JsonProperty("unique_name")] public string UniqueName { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The time in seconds it took to build the model. /// </summary> [JsonProperty("build_duration")] public int? BuildDuration { get; private set; } /// <summary> /// The error_code /// </summary> [JsonProperty("error_code")] public int? ErrorCode { get; private set; } private ModelBuildResource() { } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Diagnostics { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Security; using System.Security.Permissions; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Configuration; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; static class PerformanceCounters { static PerformanceCounterScope scope; static object perfCounterDictionarySyncObject = new object(); internal const int MaxInstanceNameLength = 127; static bool serviceOOM = false; static bool endpointOOM = false; static bool operationOOM = false; //we need a couple of ways of accessing the same performance counters. Normally, we know which endpoint //for which we need to update a perf counter. In some cases (e.g. RM), we only have a base uri. In those //cases, we update all the perf counters associated with the base uri. These two dictionaries point to //the same underlying perf counters, but in different ways. static Dictionary<string, ServiceModelPerformanceCounters> performanceCounters = null; static Dictionary<string, ServiceModelPerformanceCountersEntry> performanceCountersBaseUri = null; static List<ServiceModelPerformanceCounters> performanceCountersList = null; static internal PerformanceCounterScope Scope { get { return PerformanceCounters.scope; } set { PerformanceCounters.scope = value; } } static internal bool PerformanceCountersEnabled { get { return (PerformanceCounters.scope != PerformanceCounterScope.Off) && (PerformanceCounters.scope != PerformanceCounterScope.Default); } } static internal bool MinimalPerformanceCountersEnabled { get { return (PerformanceCounters.scope == PerformanceCounterScope.Default); } } static PerformanceCounters() { PerformanceCounterScope scope = GetPerformanceCountersFromConfig(); if (PerformanceCounterScope.Off != scope) { try { if (scope == PerformanceCounterScope.Default) { scope = OSEnvironmentHelper.IsVistaOrGreater ? PerformanceCounterScope.ServiceOnly : PerformanceCounterScope.Off; } PerformanceCounters.scope = scope; } catch (SecurityException securityException) { //switch off the counters - not supported in PT PerformanceCounters.scope = PerformanceCounterScope.Off; // not re-throwing on purpose DiagnosticUtility.TraceHandledException(securityException, TraceEventType.Warning); if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(System.Diagnostics.TraceEventType.Warning, TraceCode.PerformanceCounterFailedToLoad, SR.GetString(SR.PartialTrustPerformanceCountersNotEnabled)); } } } else { PerformanceCounters.scope = PerformanceCounterScope.Off; } } [Fx.Tag.SecurityNote(Critical = "Calls SecurityCritical method UnsafeGetSection which elevates in order to load config.", Safe = "Does not leak any config objects.")] [SecuritySafeCritical] static PerformanceCounterScope GetPerformanceCountersFromConfig() { return DiagnosticSection.UnsafeGetSection().PerformanceCounters; } static internal PerformanceCounter GetOperationPerformanceCounter(string perfCounterName, string instanceName) { return PerformanceCounters.GetPerformanceCounter( PerformanceCounterStrings.SERVICEMODELOPERATION.OperationPerfCounters, perfCounterName, instanceName, PerformanceCounterInstanceLifetime.Process); } static internal PerformanceCounter GetEndpointPerformanceCounter(string perfCounterName, string instanceName) { return PerformanceCounters.GetPerformanceCounter( PerformanceCounterStrings.SERVICEMODELENDPOINT.EndpointPerfCounters, perfCounterName, instanceName, PerformanceCounterInstanceLifetime.Process); } static internal PerformanceCounter GetServicePerformanceCounter(string perfCounterName, string instanceName) { return PerformanceCounters.GetPerformanceCounter( PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters, perfCounterName, instanceName, PerformanceCounterInstanceLifetime.Process); } static internal PerformanceCounter GetDefaultPerformanceCounter(string perfCounterName, string instanceName) { return PerformanceCounters.GetPerformanceCounter( PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters, perfCounterName, instanceName, PerformanceCounterInstanceLifetime.Global); } static internal PerformanceCounter GetPerformanceCounter(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime) { PerformanceCounter counter = null; if (PerformanceCounters.PerformanceCountersEnabled || PerformanceCounters.MinimalPerformanceCountersEnabled) { counter = PerformanceCounters.GetPerformanceCounterInternal(categoryName, perfCounterName, instanceName, instanceLifetime); } return counter; } static internal PerformanceCounter GetPerformanceCounterInternal(string categoryName, string perfCounterName, string instanceName, PerformanceCounterInstanceLifetime instanceLifetime) { PerformanceCounter counter = null; try { counter = new PerformanceCounter(); counter.CategoryName = categoryName; counter.CounterName = perfCounterName; counter.InstanceName = instanceName; counter.ReadOnly = false; counter.InstanceLifetime = instanceLifetime; // We now need to access the counter raw data to // force the counter object to be initialized. This // will force any exceptions due to mis-installation // of counters to occur here and be traced appropriately. try { long rawValue = counter.RawValue; } catch (InvalidOperationException) { counter = null; throw; } catch (SecurityException securityException) { // Cannot access performance counter due to partial trust scenarios // Disable the default performance counters' access otherwise // in PT the service will be broken PerformanceCounters.scope = PerformanceCounterScope.Off; DiagnosticUtility.TraceHandledException(new SecurityException(SR.GetString( SR.PartialTrustPerformanceCountersNotEnabled), securityException), TraceEventType.Warning); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.GetString( SR.PartialTrustPerformanceCountersNotEnabled))); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (null != counter) { if (!counter.ReadOnly) { try { counter.RemoveInstance(); } // Already inside a catch block for a failure case // ok to ---- any exceptions here and trace the // original failure. #pragma warning suppress 56500 // covered by FxCOP catch (Exception e1) { if (Fx.IsFatal(e1)) { throw; } } } counter = null; } bool logEvent = true; if (categoryName == PerformanceCounterStrings.SERVICEMODELSERVICE.ServicePerfCounters) { if (serviceOOM == false) { serviceOOM = true; } else { logEvent = false; } } else if (categoryName == PerformanceCounterStrings.SERVICEMODELOPERATION.OperationPerfCounters) { if (operationOOM == false) { operationOOM = true; } else { logEvent = false; } } else if (categoryName == PerformanceCounterStrings.SERVICEMODELENDPOINT.EndpointPerfCounters) { if (endpointOOM == false) { endpointOOM = true; } else { logEvent = false; } } if (logEvent) { DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, (ushort)System.Runtime.Diagnostics.EventLogCategory.PerformanceCounter, (uint)System.Runtime.Diagnostics.EventLogEventId.FailedToLoadPerformanceCounter, categoryName, perfCounterName, e.ToString()); } } return counter; } internal static Dictionary<string, ServiceModelPerformanceCounters> PerformanceCountersForEndpoint { get { if (PerformanceCounters.performanceCounters == null) { lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (PerformanceCounters.performanceCounters == null) { PerformanceCounters.performanceCounters = new Dictionary<string, ServiceModelPerformanceCounters>(); } } } return PerformanceCounters.performanceCounters; } } internal static List<ServiceModelPerformanceCounters> PerformanceCountersForEndpointList { get { if (PerformanceCounters.performanceCountersList == null) { lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (PerformanceCounters.performanceCountersList == null) { PerformanceCounters.performanceCountersList = new List<ServiceModelPerformanceCounters>(); } } } return PerformanceCounters.performanceCountersList; } } internal static Dictionary<string, ServiceModelPerformanceCountersEntry> PerformanceCountersForBaseUri { get { if (PerformanceCounters.performanceCountersBaseUri == null) { lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (PerformanceCounters.performanceCountersBaseUri == null) { PerformanceCounters.performanceCountersBaseUri = new Dictionary<string, ServiceModelPerformanceCountersEntry>(); } } } return PerformanceCounters.performanceCountersBaseUri; } } internal static void AddPerformanceCountersForEndpoint( ServiceHostBase serviceHost, ContractDescription contractDescription, EndpointDispatcher endpointDispatcher) { Fx.Assert(serviceHost != null, "The 'serviceHost' argument must not be null."); Fx.Assert(contractDescription != null, "The 'contractDescription' argument must not be null."); Fx.Assert(endpointDispatcher != null, "The 'endpointDispatcher' argument must not be null."); bool performanceCountersEnabled = PerformanceCounters.PerformanceCountersEnabled; bool minimalPerformanceCountersEnabled = PerformanceCounters.MinimalPerformanceCountersEnabled; if (performanceCountersEnabled || minimalPerformanceCountersEnabled) { if (endpointDispatcher.SetPerfCounterId()) { ServiceModelPerformanceCounters counters; lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (!PerformanceCounters.PerformanceCountersForEndpoint.TryGetValue(endpointDispatcher.PerfCounterId, out counters)) { counters = new ServiceModelPerformanceCounters(serviceHost, contractDescription, endpointDispatcher); if (counters.Initialized) { PerformanceCounters.PerformanceCountersForEndpoint.Add(endpointDispatcher.PerfCounterId, counters); int index = PerformanceCounters.PerformanceCountersForEndpointList.FindIndex(c => c == null); if (index >= 0) { PerformanceCounters.PerformanceCountersForEndpointList[index] = counters; } else { PerformanceCounters.PerformanceCountersForEndpointList.Add(counters); index = PerformanceCounters.PerformanceCountersForEndpointList.Count - 1; } endpointDispatcher.PerfCounterInstanceId = index; } else { return; } } } ServiceModelPerformanceCountersEntry countersEntry; lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (!PerformanceCounters.PerformanceCountersForBaseUri.TryGetValue(endpointDispatcher.PerfCounterBaseId, out countersEntry)) { if (performanceCountersEnabled) { countersEntry = new ServiceModelPerformanceCountersEntry(serviceHost.Counters); } else if (minimalPerformanceCountersEnabled) { countersEntry = new ServiceModelPerformanceCountersEntry(serviceHost.DefaultCounters); } PerformanceCounters.PerformanceCountersForBaseUri.Add(endpointDispatcher.PerfCounterBaseId, countersEntry); } countersEntry.Add(counters); } } } } internal static void ReleasePerformanceCountersForEndpoint(string id, string baseId) { if (PerformanceCounters.PerformanceCountersEnabled) { lock (PerformanceCounters.perfCounterDictionarySyncObject) { if (!String.IsNullOrEmpty(id)) { ServiceModelPerformanceCounters counters; if (PerformanceCounters.PerformanceCountersForEndpoint.TryGetValue(id, out counters)) { PerformanceCounters.PerformanceCountersForEndpoint.Remove(id); int index = PerformanceCounters.PerformanceCountersForEndpointList.IndexOf(counters); PerformanceCounters.PerformanceCountersForEndpointList[index] = null; } } if (!String.IsNullOrEmpty(baseId)) { PerformanceCounters.PerformanceCountersForBaseUri.Remove(baseId); } } } } internal static void ReleasePerformanceCounter(ref PerformanceCounter counter) { if (counter != null) { try { counter.RemoveInstance(); counter = null; } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } } } internal static void TxFlowed(EndpointDispatcher el, string operation) { if (null != el) { ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.TxFlowed(); } if (PerformanceCounters.Scope == PerformanceCounterScope.All) { OperationPerformanceCountersBase oCounters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operation); if (null != oCounters) { oCounters.TxFlowed(); } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { eCounters.TxFlowed(); } } } } internal static void TxAborted(EndpointDispatcher el, long count) { if (PerformanceCounters.PerformanceCountersEnabled) { if (null != el) { ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.TxAborted(count); } } } } internal static void TxCommitted(EndpointDispatcher el, long count) { if (PerformanceCounters.PerformanceCountersEnabled) { if (null != el) { ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.TxCommitted(count); } } } } internal static void TxInDoubt(EndpointDispatcher el, long count) { if (PerformanceCounters.PerformanceCountersEnabled) { if (null != el) { ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.TxInDoubt(count); } } } } internal static void MethodCalled(string operationName) { EndpointDispatcher el = GetEndpointDispatcher(); if (null != el) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { string uri = el.PerfCounterId; OperationPerformanceCountersBase opCounters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operationName); if (null != opCounters) { opCounters.MethodCalled(); } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != eCounters) { eCounters.MethodCalled(); } } ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.MethodCalled(); } } } internal static void MethodReturnedSuccess(string operationName) { PerformanceCounters.MethodReturnedSuccess(operationName, -1); } internal static void MethodReturnedSuccess(string operationName, long time) { EndpointDispatcher el = GetEndpointDispatcher(); if (null != el) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { string uri = el.PerfCounterId; OperationPerformanceCountersBase counters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operationName); if (null != counters) { counters.MethodReturnedSuccess(); if (time > 0) { counters.SaveCallDuration(time); } } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != eCounters) { eCounters.MethodReturnedSuccess(); if (time > 0) { eCounters.SaveCallDuration(time); } } } ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.MethodReturnedSuccess(); if (time > 0) { sCounters.SaveCallDuration(time); } } } } internal static void MethodReturnedFault(string operationName) { PerformanceCounters.MethodReturnedFault(operationName, -1); } internal static void MethodReturnedFault(string operationName, long time) { EndpointDispatcher el = GetEndpointDispatcher(); if (null != el) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { string uri = el.PerfCounterId; OperationPerformanceCountersBase counters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operationName); if (null != counters) { counters.MethodReturnedFault(); if (time > 0) { counters.SaveCallDuration(time); } } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != eCounters) { eCounters.MethodReturnedFault(); if (time > 0) { eCounters.SaveCallDuration(time); } } } ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.MethodReturnedFault(); if (time > 0) { sCounters.SaveCallDuration(time); } } } } internal static void MethodReturnedError(string operationName) { PerformanceCounters.MethodReturnedError(operationName, -1); } internal static void MethodReturnedError(string operationName, long time) { EndpointDispatcher el = GetEndpointDispatcher(); if (null != el) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { string uri = el.PerfCounterId; OperationPerformanceCountersBase counters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operationName); if (null != counters) { counters.MethodReturnedError(); if (time > 0) { counters.SaveCallDuration(time); } } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != eCounters) { eCounters.MethodReturnedError(); if (time > 0) { eCounters.SaveCallDuration(time); } } } ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.MethodReturnedError(); if (time > 0) { sCounters.SaveCallDuration(time); } } } } static void InvokeMethod(object o, string methodName) { Fx.Assert(null != o, "object must not be null"); MethodInfo method = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); Fx.Assert(null != method, o.GetType().ToString() + " must have method " + methodName); method.Invoke(o, null); } static void CallOnAllCounters(string methodName, Message message, Uri listenUri, bool includeOperations) { Fx.Assert(null != message, "message must not be null"); Fx.Assert(null != listenUri, "listenUri must not be null"); if (null != message && null != message.Headers && null != message.Headers.To && null != listenUri) { string uri = listenUri.AbsoluteUri.ToUpperInvariant(); ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { Fx.Assert(null != counters.ServicePerformanceCounters, "counters.ServicePerformanceCounters must not be null"); PerformanceCounters.InvokeMethod(counters.ServicePerformanceCounters, methodName); if (PerformanceCounters.Scope == PerformanceCounterScope.All) { List<ServiceModelPerformanceCounters> counters2 = counters.CounterList; foreach (ServiceModelPerformanceCounters sCounters in counters2) { if (sCounters.EndpointPerformanceCounters != null) { PerformanceCounters.InvokeMethod(sCounters.EndpointPerformanceCounters, methodName); } if (includeOperations) { OperationPerformanceCountersBase oCounters = sCounters.GetOperationPerformanceCountersFromMessage(message); if (oCounters != null) { PerformanceCounters.InvokeMethod(oCounters, methodName); } } } } } } } static internal void AuthenticationFailed(Message message, Uri listenUri) { PerformanceCounters.CallOnAllCounters("AuthenticationFailed", message, listenUri, true); } static internal void AuthorizationFailed(string operationName) { EndpointDispatcher el = GetEndpointDispatcher(); if (null != el) { string uri = el.PerfCounterId; if (PerformanceCounters.Scope == PerformanceCounterScope.All) { OperationPerformanceCountersBase counters = PerformanceCounters.GetOperationPerformanceCounters(el.PerfCounterInstanceId, operationName); if (null != counters) { counters.AuthorizationFailed(); } EndpointPerformanceCountersBase eCounters = PerformanceCounters.GetEndpointPerformanceCounters(el.PerfCounterInstanceId); if (null != eCounters) { eCounters.AuthorizationFailed(); } } ServicePerformanceCountersBase sCounters = PerformanceCounters.GetServicePerformanceCounters(el.PerfCounterInstanceId); if (null != sCounters) { sCounters.AuthorizationFailed(); } } } internal static void SessionFaulted(string uri) { ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { counters.ServicePerformanceCounters.SessionFaulted(); if (PerformanceCounters.Scope == PerformanceCounterScope.All) { List<ServiceModelPerformanceCounters> counters2 = counters.CounterList; foreach (ServiceModelPerformanceCounters sCounters in counters2) { if (sCounters.EndpointPerformanceCounters != null) { sCounters.EndpointPerformanceCounters.SessionFaulted(); } } } } } internal static void MessageDropped(string uri) { ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { counters.ServicePerformanceCounters.MessageDropped(); if (PerformanceCounters.Scope == PerformanceCounterScope.All) { List<ServiceModelPerformanceCounters> counters2 = counters.CounterList; foreach (ServiceModelPerformanceCounters sCounters in counters2) { if (sCounters.EndpointPerformanceCounters != null) { sCounters.EndpointPerformanceCounters.MessageDropped(); } } } } } internal static void MsmqDroppedMessage(string uri) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { counters.ServicePerformanceCounters.MsmqDroppedMessage(); } } } internal static void MsmqPoisonMessage(string uri) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { counters.ServicePerformanceCounters.MsmqPoisonMessage(); } } } internal static void MsmqRejectedMessage(string uri) { if (PerformanceCounters.Scope == PerformanceCounterScope.All) { ServiceModelPerformanceCountersEntry counters = PerformanceCounters.GetServiceModelPerformanceCountersBaseUri(uri); if (null != counters) { counters.ServicePerformanceCounters.MsmqRejectedMessage(); } } } static internal EndpointDispatcher GetEndpointDispatcher() { EndpointDispatcher endpointDispatcher = null; OperationContext currentContext = OperationContext.Current; if (null != currentContext && currentContext.InternalServiceChannel != null) { endpointDispatcher = currentContext.EndpointDispatcher; } return endpointDispatcher; } static ServiceModelPerformanceCounters GetServiceModelPerformanceCounters(int perfCounterInstanceId) { if (PerformanceCounters.PerformanceCountersForEndpointList.Count == 0) { return null; } return PerformanceCounters.PerformanceCountersForEndpointList[perfCounterInstanceId]; } static ServiceModelPerformanceCountersEntry GetServiceModelPerformanceCountersBaseUri(string uri) { ServiceModelPerformanceCountersEntry counters = null; if (!String.IsNullOrEmpty(uri)) { PerformanceCounters.PerformanceCountersForBaseUri.TryGetValue(uri, out counters); } return counters; } static OperationPerformanceCountersBase GetOperationPerformanceCounters(int perfCounterInstanceId, string operation) { ServiceModelPerformanceCounters counters = PerformanceCounters.GetServiceModelPerformanceCounters(perfCounterInstanceId); if (counters != null) { return counters.GetOperationPerformanceCounters(operation); } return null; } static EndpointPerformanceCountersBase GetEndpointPerformanceCounters(int perfCounterInstanceId) { ServiceModelPerformanceCounters counters = PerformanceCounters.GetServiceModelPerformanceCounters(perfCounterInstanceId); if (counters != null) { return counters.EndpointPerformanceCounters; } return null; } static ServicePerformanceCountersBase GetServicePerformanceCounters(int perfCounterInstanceId) { ServiceModelPerformanceCounters counters = PerformanceCounters.GetServiceModelPerformanceCounters(perfCounterInstanceId); if (counters != null) { return counters.ServicePerformanceCounters; } return null; } static internal void TracePerformanceCounterUpdateFailure(string instanceName, string perfCounterName) { if (DiagnosticUtility.ShouldTraceError) { TraceUtility.TraceEvent( System.Diagnostics.TraceEventType.Error, TraceCode.PerformanceCountersFailedDuringUpdate, SR.GetString(SR.TraceCodePerformanceCountersFailedDuringUpdate, perfCounterName + "::" + instanceName)); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using System; using System.Runtime.CompilerServices; using UnityEngine; [assembly: InternalsVisibleTo("Microsoft.MixedReality.Toolkit.Editor.Inspectors")] namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Used to define a controller or other input device's physical buttons, and other attributes. /// </summary> [Serializable] public struct MixedRealityControllerMapping { /// <summary> /// Constructor. /// </summary> /// <param name="controllerType">Controller Type to instantiate at runtime.</param> /// <param name="handedness">The designated hand that the device is managing.</param> public MixedRealityControllerMapping(Type controllerType, Handedness handedness = Handedness.None) : this() { this.controllerType = new SystemType(controllerType); this.handedness = handedness; interactions = null; } /// <summary> /// Description of the Device. /// </summary> public string Description { get { string controllerName = "Unknown"; if (controllerType.Type != null) { var attr = MixedRealityControllerAttribute.Find(controllerType); if (attr != null) { controllerName = attr.SupportedControllerType.ToString().ToProperCase(); } } string handednessText = string.Empty; switch (handedness) { case Handedness.Left: case Handedness.Right: handednessText = $"{handedness} Hand "; // Avoid multiple occurrences of "Hand": controllerName = controllerName.Replace("Hand", "").Trim(); break; } return $"{controllerName} {handednessText}Controller"; } } [SerializeField] [Tooltip("Controller type to instantiate at runtime.")] [Implements(typeof(IMixedRealityController), TypeGrouping.ByNamespaceFlat)] private SystemType controllerType; /// <summary> /// Controller Type to instantiate at runtime. /// </summary> public SystemType ControllerType => controllerType; public SupportedControllerType SupportedControllerType { get { if (controllerType.Type != null) { var attr = MixedRealityControllerAttribute.Find(controllerType); if (attr != null) { return attr.SupportedControllerType; } } return 0; } } [SerializeField] [Tooltip("The designated hand that the device is managing.")] private Handedness handedness; /// <summary> /// The designated hand that the device is managing. /// </summary> public Handedness Handedness => handedness; /// <summary> /// Is this controller mapping using custom interactions? /// </summary> public bool HasCustomInteractionMappings { get { if (controllerType.Type != null) { var attr = MixedRealityControllerAttribute.Find(controllerType); if (attr != null) { return attr.Flags.HasFlag(MixedRealityControllerConfigurationFlags.UseCustomInteractionMappings); } } return false; } } [SerializeField] [Tooltip("Details the list of available buttons / interactions available from the device.")] private MixedRealityInteractionMapping[] interactions; /// <summary> /// Details the list of available buttons / interactions available from the device. /// </summary> public MixedRealityInteractionMapping[] Interactions => interactions; /// <summary> /// Sets the default interaction mapping based on the current controller type. /// </summary> internal void SetDefaultInteractionMapping(bool overwrite = false) { if (interactions == null || interactions.Length == 0 || overwrite) { MixedRealityInteractionMapping[] defaultMappings = GetDefaultInteractionMappings(); if (defaultMappings != null) { interactions = defaultMappings; } } } internal bool UpdateInteractionSettingsFromDefault() { if (interactions == null || interactions.Length == 0) { return false; } MixedRealityInteractionMapping[] newDefaultInteractions = GetDefaultInteractionMappings(); if (newDefaultInteractions == null) { return false; } if (interactions.Length != newDefaultInteractions.Length) { interactions = CreateNewMatchedMapping(interactions, newDefaultInteractions); return true; } bool updatedMappings = false; for (int i = 0; i < newDefaultInteractions.Length; i++) { MixedRealityInteractionMapping currentMapping = interactions[i]; MixedRealityInteractionMapping currentDefaultMapping = newDefaultInteractions[i]; if (!Equals(currentMapping, currentDefaultMapping)) { interactions[i] = new MixedRealityInteractionMapping(currentDefaultMapping) { MixedRealityInputAction = currentMapping.MixedRealityInputAction }; updatedMappings = true; } } return updatedMappings; } private MixedRealityInteractionMapping[] CreateNewMatchedMapping(MixedRealityInteractionMapping[] interactions, MixedRealityInteractionMapping[] newDefaultInteractions) { MixedRealityInteractionMapping[] newDefaultMapping = new MixedRealityInteractionMapping[newDefaultInteractions.Length]; for (int i = 0; i < newDefaultInteractions.Length; i++) { for (int j = 0; j < interactions.Length; j++) { if (Equals(interactions[j], newDefaultInteractions[i])) { newDefaultMapping[i] = new MixedRealityInteractionMapping(newDefaultInteractions[i]) { MixedRealityInputAction = interactions[j].MixedRealityInputAction }; break; } } if (newDefaultMapping[i] == null) { newDefaultMapping[i] = new MixedRealityInteractionMapping(newDefaultInteractions[i]); } } return newDefaultMapping; } private bool Equals(MixedRealityInteractionMapping a, MixedRealityInteractionMapping b) { return !(a.Description != b.Description || a.AxisType != b.AxisType || a.InputType != b.InputType || a.KeyCode != b.KeyCode || a.AxisCodeX != b.AxisCodeX || a.AxisCodeY != b.AxisCodeY || a.InvertXAxis != b.InvertXAxis || a.InvertYAxis != b.InvertYAxis); } private MixedRealityInteractionMapping[] GetDefaultInteractionMappings() { if (Activator.CreateInstance(controllerType, TrackingState.NotTracked, handedness, null, null) is BaseController detectedController) { switch (handedness) { case Handedness.Left: return detectedController.DefaultLeftHandedInteractions; case Handedness.Right: return detectedController.DefaultRightHandedInteractions; default: return detectedController.DefaultInteractions; } } return null; } /// <summary> /// Synchronizes the input actions of the same physical controller of a different concrete type. /// </summary> internal void SynchronizeInputActions(MixedRealityInteractionMapping[] otherControllerMapping) { if (otherControllerMapping.Length != interactions.Length) { throw new ArgumentException($"otherControllerMapping length {otherControllerMapping.Length} does not match this length {interactions.Length}."); } for (int i = 0; i < interactions.Length; i++) { interactions[i].MixedRealityInputAction = otherControllerMapping[i].MixedRealityInputAction; } } } }
/* * 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. */ /* This file borrows heavily from MXPServer.cs - the reference MXPServer * See http://www.bubblecloud.org for a copy of the original file and * implementation details. */ using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using log4net; using MXP; using MXP.Messages; using OpenMetaverse; using OpenSim.Client.MXP.ClientStack; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Communications; using System.Security.Cryptography; namespace OpenSim.Client.MXP.PacketHandler { public class MXPPacketServer { internal static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Fields private readonly List<MXPClientView> m_clients = new List<MXPClientView>(); private readonly Dictionary<UUID, Scene> m_scenes; private readonly Transmitter m_transmitter; // private readonly Thread m_clientThread; private readonly IList<Session> m_sessions = new List<Session>(); private readonly IList<Session> m_sessionsToClient = new List<Session>(); private readonly IList<MXPClientView> m_sessionsToRemove = new List<MXPClientView>(); private readonly int m_port; private readonly bool m_accountsAuthenticate; private readonly String m_programName; private readonly byte m_programMajorVersion; private readonly byte m_programMinorVersion; #endregion #region Constructors public MXPPacketServer(int port, Dictionary<UUID, Scene> scenes, bool accountsAuthenticate) { m_port = port; m_accountsAuthenticate = accountsAuthenticate; m_scenes = scenes; m_programMinorVersion = 63; m_programMajorVersion = 0; m_programName = "OpenSimulator"; m_transmitter = new Transmitter(port); StartListener(); } public void StartListener() { m_log.Info("[MXP ClientStack] Transmitter starting on UDP server port: " + m_port); m_transmitter.Startup(); m_log.Info("[MXP ClientStack] Transmitter started. MXP version: "+MxpConstants.ProtocolMajorVersion+"."+MxpConstants.ProtocolMinorVersion+" Source Revision: "+MxpConstants.ProtocolSourceRevision); } #endregion #region Properties /// <summary> /// Number of sessions pending. (Process() accepts pending sessions). /// </summary> public int PendingSessionCount { get { return m_transmitter.PendingSessionCount; } } /// <summary> /// Number of connected sessions. /// </summary> public int SessionCount { get { return m_sessions.Count; } } /// <summary> /// Property reflecting whether client transmitter threads are alive. /// </summary> public bool IsTransmitterAlive { get { return m_transmitter != null && m_transmitter.IsAlive; } } /// <summary> /// Number of packets sent. /// </summary> public ulong PacketsSent { get { return m_transmitter != null ? m_transmitter.PacketsSent : 0; } } /// <summary> /// Number of packets received. /// </summary> public ulong PacketsReceived { get { return m_transmitter != null ? m_transmitter.PacketsReceived : 0; } } /// <summary> /// Bytes client has received so far. /// </summary> public ulong BytesReceived { get { return m_transmitter != null ? m_transmitter.BytesReceived : 0; } } /// <summary> /// Bytes client has sent so far. /// </summary> public ulong BytesSent { get { return m_transmitter != null ? m_transmitter.BytesSent : 0; } } /// <summary> /// Number of bytes received (bytes per second) during past second. /// </summary> public double ReceiveRate { get { return m_transmitter != null ? m_transmitter.ReceiveRate : 0; } } /// <summary> /// Number of bytes sent (bytes per second) during past second. /// </summary> public double SendRate { get { return m_transmitter != null ? m_transmitter.SendRate : 0; } } #endregion #region Session Management public void Disconnect(Session session) { if (session.IsConnected) { Message message = MessageFactory.Current.ReserveMessage(typeof(LeaveRequestMessage)); session.Send(message); MessageFactory.Current.ReleaseMessage(message); } else { throw new Exception("Not connected."); } } #endregion #region Processing public void Process() { ProcessMessages(); Clean(); } public void Clean() { foreach (MXPClientView clientView in m_clients) { if (clientView.Session.SessionState == SessionState.Disconnected) { m_sessionsToRemove.Add(clientView); } } foreach (MXPClientView clientView in m_sessionsToRemove) { clientView.Scene.RemoveClient(clientView.AgentId); clientView.OnClean(); m_clients.Remove(clientView); m_sessions.Remove(clientView.Session); } m_sessionsToRemove.Clear(); } public void ProcessMessages() { if (m_transmitter.PendingSessionCount > 0) { Session tmp = m_transmitter.AcceptPendingSession(); m_sessions.Add(tmp); m_sessionsToClient.Add(tmp); } List<Session> tmpRemove = new List<Session>(); foreach (Session session in m_sessionsToClient) { while (session.AvailableMessages > 0) { Message message = session.Receive(); if (message.GetType() == typeof (JoinRequestMessage)) { JoinRequestMessage joinRequestMessage = (JoinRequestMessage) message; m_log.Info("[MXP ClientStack]: Session join request: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")"); try { if (joinRequestMessage.BubbleId == Guid.Empty) { foreach (Scene scene in m_scenes.Values) { if (scene.RegionInfo.RegionName == joinRequestMessage.BubbleName) { m_log.Info("[MXP ClientStack]: Resolved region by name: " + joinRequestMessage.BubbleName + " (" + scene.RegionInfo.RegionID + ")"); joinRequestMessage.BubbleId = scene.RegionInfo.RegionID.Guid; } } } if (joinRequestMessage.BubbleId == Guid.Empty) { m_log.Warn("[MXP ClientStack]: Failed to resolve region by name: " + joinRequestMessage.BubbleName); } UUID sceneId = new UUID(joinRequestMessage.BubbleId); bool regionExists = true; if (!m_scenes.ContainsKey(sceneId)) { m_log.Info("[MXP ClientStack]: No such region: " + sceneId); regionExists = false; } UserProfileData user = null; UUID userId = UUID.Zero; string firstName = null; string lastName = null; bool authorized = regionExists ? AuthoriseUser(joinRequestMessage.ParticipantName, joinRequestMessage.ParticipantPassphrase, new UUID(joinRequestMessage.BubbleId), out userId, out firstName, out lastName, out user) : false; if (authorized) { Scene scene = m_scenes[sceneId]; UUID mxpSessionID = UUID.Random(); string reason; m_log.Debug("[MXP ClientStack]: Session join request success: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")"); m_log.Debug("[MXP ClientStack]: Attaching UserAgent to UserProfile..."); AttachUserAgentToUserProfile(session, mxpSessionID, sceneId, user); m_log.Debug("[MXP ClientStack]: Attached UserAgent to UserProfile."); m_log.Debug("[MXP ClientStack]: Preparing Scene to Connection..."); if (!PrepareSceneForConnection(mxpSessionID, sceneId, user, out reason)) { m_log.DebugFormat("[MXP ClientStack]: Scene refused connection: {0}", reason); DeclineConnection(session, joinRequestMessage); tmpRemove.Add(session); continue; } m_log.Debug("[MXP ClientStack]: Prepared Scene to Connection."); m_log.Debug("[MXP ClientStack]: Accepting connection..."); AcceptConnection(session, joinRequestMessage, mxpSessionID, userId); m_log.Info("[MXP ClientStack]: Accepted connection."); m_log.Debug("[MXP ClientStack]: Creating ClientView...."); MXPClientView client = new MXPClientView(session, mxpSessionID, userId, scene, firstName, lastName); m_clients.Add(client); m_log.Debug("[MXP ClientStack]: Created ClientView."); client.MXPSendSynchronizationBegin(m_scenes[new UUID(joinRequestMessage.BubbleId)].SceneContents.GetTotalObjectsCount()); m_log.Debug("[MXP ClientStack]: Starting ClientView..."); try { client.Start(); m_log.Debug("[MXP ClientStack]: Started ClientView."); } catch (Exception e) { m_log.Error(e); } m_log.Debug("[MXP ClientStack]: Connected"); } else { m_log.Info("[MXP ClientStack]: Session join request failure: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")"); DeclineConnection(session, joinRequestMessage); } } catch (Exception e) { m_log.Error("[MXP ClientStack]: Session join request failure: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + "): "+e.ToString()+" :"+e.StackTrace.ToString()); } tmpRemove.Add(session); } } } foreach (Session session in tmpRemove) { m_sessionsToClient.Remove(session); } foreach (MXPClientView clientView in m_clients) { int messagesProcessedCount = 0; Session session = clientView.Session; while (session.AvailableMessages > 0) { Message message = session.Receive(); if (message.GetType() == typeof(LeaveRequestMessage)) { LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)MessageFactory.Current.ReserveMessage( typeof(LeaveResponseMessage)); m_log.Debug("[MXP ClientStack]: Session leave request: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")"); leaveResponseMessage.RequestMessageId = message.MessageId; leaveResponseMessage.FailureCode = 0; session.Send(leaveResponseMessage); if (session.SessionState != SessionState.Disconnected) { session.SetStateDisconnected(); } m_log.Debug("[MXP ClientStack]: Removing Client from Scene"); //clientView.Scene.RemoveClient(clientView.AgentId); } if (message.GetType() == typeof(LeaveResponseMessage)) { LeaveResponseMessage leaveResponseMessage = (LeaveResponseMessage)message; m_log.Debug("[MXP ClientStack]: Session leave response: " + session.SessionId + " (" + (session.IsIncoming ? "from" : "to") + " " + session.RemoteEndPoint.Address + ":" + session.RemoteEndPoint.Port + ")"); if (leaveResponseMessage.FailureCode == 0) { session.SetStateDisconnected(); } m_log.Debug("[MXP ClientStack]: Removing Client from Scene"); //clientView.Scene.RemoveClient(clientView.AgentId); } else { clientView.MXPPRocessMessage(message); } MessageFactory.Current.ReleaseMessage(message); messagesProcessedCount++; if (messagesProcessedCount > 1000) { break; } } } } private void AcceptConnection(Session session, JoinRequestMessage joinRequestMessage, UUID mxpSessionID, UUID userId) { JoinResponseMessage joinResponseMessage = (JoinResponseMessage)MessageFactory.Current.ReserveMessage( typeof(JoinResponseMessage)); joinResponseMessage.RequestMessageId = joinRequestMessage.MessageId; joinResponseMessage.FailureCode = MxpResponseCodes.SUCCESS; joinResponseMessage.BubbleId = joinRequestMessage.BubbleId; joinResponseMessage.ParticipantId = userId.Guid; joinResponseMessage.AvatarId = userId.Guid; joinResponseMessage.BubbleAssetCacheUrl = "http://" + NetworkUtil.GetHostFor(session.RemoteEndPoint.Address, m_scenes[ new UUID(joinRequestMessage.BubbleId)]. RegionInfo. ExternalHostName) + ":" + m_scenes[new UUID(joinRequestMessage.BubbleId)].RegionInfo. HttpPort + "/assets/"; joinResponseMessage.BubbleName = m_scenes[new UUID(joinRequestMessage.BubbleId)].RegionInfo.RegionName; joinResponseMessage.BubbleRange = 128; joinResponseMessage.BubblePerceptionRange = 128 + 256; joinResponseMessage.BubbleRealTime = 0; joinResponseMessage.ProgramName = m_programName; joinResponseMessage.ProgramMajorVersion = m_programMajorVersion; joinResponseMessage.ProgramMinorVersion = m_programMinorVersion; joinResponseMessage.ProtocolMajorVersion = MxpConstants.ProtocolMajorVersion; joinResponseMessage.ProtocolMinorVersion = MxpConstants.ProtocolMinorVersion; joinResponseMessage.ProtocolSourceRevision = MxpConstants.ProtocolSourceRevision; session.Send(joinResponseMessage); session.SetStateConnected(); } private void DeclineConnection(Session session, Message joinRequestMessage) { JoinResponseMessage joinResponseMessage = (JoinResponseMessage)MessageFactory.Current.ReserveMessage(typeof(JoinResponseMessage)); joinResponseMessage.RequestMessageId = joinRequestMessage.MessageId; joinResponseMessage.FailureCode = MxpResponseCodes.UNAUTHORIZED_OPERATION; joinResponseMessage.ProgramName = m_programName; joinResponseMessage.ProgramMajorVersion = m_programMajorVersion; joinResponseMessage.ProgramMinorVersion = m_programMinorVersion; joinResponseMessage.ProtocolMajorVersion = MxpConstants.ProtocolMajorVersion; joinResponseMessage.ProtocolMinorVersion = MxpConstants.ProtocolMinorVersion; joinResponseMessage.ProtocolSourceRevision = MxpConstants.ProtocolSourceRevision; session.Send(joinResponseMessage); session.SetStateDisconnected(); } public bool AuthoriseUser(string participantName, string password, UUID sceneId, out UUID userId, out string firstName, out string lastName, out UserProfileData userProfile) { userId = UUID.Zero; firstName = ""; lastName = ""; userProfile = null; string[] nameParts = participantName.Split(' '); if (nameParts.Length != 2) { m_log.Error("[MXP ClientStack]: Login failed as user name is not formed of first and last name separated by space: " + participantName); return false; } firstName = nameParts[0]; lastName = nameParts[1]; userProfile = m_scenes[sceneId].CommsManager.UserService.GetUserProfile(firstName, lastName); if (userProfile == null && !m_accountsAuthenticate) { userId = ((UserManagerBase)m_scenes[sceneId].CommsManager.UserService).AddUser(firstName, lastName, "test", "", 1000, 1000); } else { if (userProfile == null) { m_log.Error("[MXP ClientStack]: Login failed as user was not found: " + participantName); return false; } userId = userProfile.ID; } if (m_accountsAuthenticate) { if (!password.StartsWith("$1$")) { password = "$1$" + Util.Md5Hash(password); } password = password.Remove(0, 3); //remove $1$ string s = Util.Md5Hash(password + ":" + userProfile.PasswordSalt); return (userProfile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) || userProfile.PasswordHash.Equals(password, StringComparison.InvariantCulture)); } else { return true; } } private void AttachUserAgentToUserProfile(Session session, UUID sessionId, UUID sceneId, UserProfileData userProfile) { //Scene scene = m_scenes[sceneId]; CommunicationsManager commsManager = m_scenes[sceneId].CommsManager; IUserService userService = (IUserService)commsManager.UserService; UserAgentData agent = new UserAgentData(); // User connection agent.AgentOnline = true; agent.AgentIP = session.RemoteEndPoint.Address.ToString(); agent.AgentPort = (uint)session.RemoteEndPoint.Port; agent.SecureSessionID = UUID.Random(); agent.SessionID = sessionId; // Profile UUID agent.ProfileID = userProfile.ID; // Current location/position/alignment if (userProfile.CurrentAgent != null) { agent.Region = userProfile.CurrentAgent.Region; agent.Handle = userProfile.CurrentAgent.Handle; agent.Position = userProfile.CurrentAgent.Position; agent.LookAt = userProfile.CurrentAgent.LookAt; } else { agent.Region = userProfile.HomeRegionID; agent.Handle = userProfile.HomeRegion; agent.Position = userProfile.HomeLocation; agent.LookAt = userProfile.HomeLookAt; } // What time did the user login? agent.LoginTime = Util.UnixTimeSinceEpoch(); agent.LogoutTime = 0; userProfile.CurrentAgent = agent; userService.UpdateUserProfile(userProfile); //userService.CommitAgent(ref userProfile); } private bool PrepareSceneForConnection(UUID sessionId, UUID sceneId, UserProfileData userProfile, out string reason) { Scene scene = m_scenes[sceneId]; CommunicationsManager commsManager = m_scenes[sceneId].CommsManager; UserManagerBase userService = (UserManagerBase)commsManager.UserService; AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = userProfile.ID; agent.firstname = userProfile.FirstName; agent.lastname = userProfile.SurName; agent.SessionID = sessionId; agent.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; agent.circuitcode = sessionId.CRC(); agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = new Vector3(0, 0, 0); // TODO Fill in region start position agent.CapsPath = "http://localhost/"; agent.Appearance = userService.GetUserAppearance(userProfile.ID); if (agent.Appearance == null) { m_log.WarnFormat("[INTER]: Appearance not found for {0} {1}. Creating default.", agent.firstname, agent.lastname); agent.Appearance = new AvatarAppearance(); } return scene.NewUserConnection(agent, 0, out reason); } public void PrintDebugInformation() { m_log.Info("[MXP ClientStack]: Statistics report"); m_log.Info("Pending Sessions: " + PendingSessionCount); m_log.Info("Sessions: " + SessionCount + " (Clients: " + m_clients.Count + " )"); m_log.Info("Transmitter Alive?: " + IsTransmitterAlive); m_log.Info("Packets Sent/Received: " + PacketsSent + " / " + PacketsReceived); m_log.Info("Bytes Sent/Received: " + BytesSent + " / " + BytesReceived); m_log.Info("Send/Receive Rate (bps): " + SendRate + " / " + ReceiveRate); } #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 Microsoft.Win32.SafeHandles; using System; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography.X509Certificates; using Internal.Cryptography.Pal.Native; namespace Internal.Cryptography.Pal { internal sealed partial class CertificatePal : IDisposable, ICertificatePal { public static ICertificatePal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(rawData, null, password, keyStorageFlags); } public static ICertificatePal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return FromBlobOrFile(null, fileName, password, keyStorageFlags); } private static ICertificatePal FromBlobOrFile(byte[] rawData, string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { Debug.Assert(rawData != null || fileName != null); Debug.Assert(password != null); bool loadFromFile = (fileName != null); PfxCertStoreFlags pfxCertStoreFlags = MapKeyStorageFlags(keyStorageFlags); bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet)); CertEncodingType msgAndCertEncodingType; ContentType contentType; FormatType formatType; SafeCertStoreHandle hCertStore = null; SafeCryptMsgHandle hCryptMsg = null; SafeCertContextHandle pCertContext = null; try { unsafe { fixed (byte* pRawData = rawData) { fixed (char* pFileName = fileName) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(loadFromFile ? 0 : rawData.Length, pRawData); CertQueryObjectType objectType = loadFromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB; void* pvObject = loadFromFile ? (void*)pFileName : (void*)&certBlob; bool success = Interop.crypt32.CryptQueryObject( objectType, pvObject, X509ExpectedContentTypeFlags, X509ExpectedFormatTypeFlags, 0, out msgAndCertEncodingType, out contentType, out formatType, out hCertStore, out hCryptMsg, out pCertContext ); if (!success) { int hr = Marshal.GetHRForLastWin32Error(); throw hr.ToCryptographicException(); } } } if (contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED || contentType == ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED) { pCertContext = GetSignerInPKCS7Store(hCertStore, hCryptMsg); } else if (contentType == ContentType.CERT_QUERY_CONTENT_PFX) { if (loadFromFile) rawData = File.ReadAllBytes(fileName); pCertContext = FilterPFXStore(rawData, password, pfxCertStoreFlags); } CertificatePal pal = new CertificatePal(pCertContext, deleteKeyContainer: !persistKeySet); pCertContext = null; return pal; } } finally { if (hCertStore != null) hCertStore.Dispose(); if (hCryptMsg != null) hCryptMsg.Dispose(); if (pCertContext != null) pCertContext.Dispose(); } } private static SafeCertContextHandle GetSignerInPKCS7Store(SafeCertStoreHandle hCertStore, SafeCryptMsgHandle hCryptMsg) { // make sure that there is at least one signer of the certificate store int dwSigners; int cbSigners = sizeof(int); if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_COUNT_PARAM, 0, out dwSigners, ref cbSigners)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; if (dwSigners == 0) throw ErrorCode.CRYPT_E_SIGNER_NOT_FOUND.ToCryptographicException(); // get the first signer from the store, and use that as the loaded certificate int cbData = 0; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, null, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; byte[] cmsgSignerBytes = new byte[cbData]; if (!Interop.crypt32.CryptMsgGetParam(hCryptMsg, CryptMessageParameterType.CMSG_SIGNER_INFO_PARAM, 0, cmsgSignerBytes, ref cbData)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; CERT_INFO certInfo = default(CERT_INFO); unsafe { fixed (byte* pCmsgSignerBytes = cmsgSignerBytes) { CMSG_SIGNER_INFO_Partial* pCmsgSignerInfo = (CMSG_SIGNER_INFO_Partial*)pCmsgSignerBytes; certInfo.Issuer.cbData = pCmsgSignerInfo->Issuer.cbData; certInfo.Issuer.pbData = pCmsgSignerInfo->Issuer.pbData; certInfo.SerialNumber.cbData = pCmsgSignerInfo->SerialNumber.cbData; certInfo.SerialNumber.pbData = pCmsgSignerInfo->SerialNumber.pbData; } SafeCertContextHandle pCertContext = null; if (!Interop.crypt32.CertFindCertificateInStore(hCertStore, CertFindType.CERT_FIND_SUBJECT_CERT, &certInfo, ref pCertContext)) throw Marshal.GetHRForLastWin32Error().ToCryptographicException();; return pCertContext; } } private static SafeCertContextHandle FilterPFXStore(byte[] rawData, SafePasswordHandle password, PfxCertStoreFlags pfxCertStoreFlags) { SafeCertStoreHandle hStore; unsafe { fixed (byte* pbRawData = rawData) { CRYPTOAPI_BLOB certBlob = new CRYPTOAPI_BLOB(rawData.Length, pbRawData); hStore = Interop.crypt32.PFXImportCertStore(ref certBlob, password, pfxCertStoreFlags); if (hStore.IsInvalid) throw Marshal.GetHRForLastWin32Error().ToCryptographicException(); } } try { // Find the first cert with private key. If none, then simply take the very first cert. Along the way, delete the keycontainers // of any cert we don't accept. SafeCertContextHandle pCertContext = SafeCertContextHandle.InvalidHandle; SafeCertContextHandle pEnumContext = null; while (Interop.crypt32.CertEnumCertificatesInStore(hStore, ref pEnumContext)) { if (pEnumContext.ContainsPrivateKey) { if ((!pCertContext.IsInvalid) && pCertContext.ContainsPrivateKey) { // We already found our chosen one. Free up this one's key and move on. // If this one has a persisted private key, clean up the key file. // If it was an ephemeral private key no action is required. if (pEnumContext.HasPersistedPrivateKey) { SafeCertContextHandleWithKeyContainerDeletion.DeleteKeyContainer(pEnumContext); } } else { // Found our first cert that has a private key. Set him up as our chosen one but keep iterating // as we need to free up the keys of any remaining certs. pCertContext.Dispose(); pCertContext = pEnumContext.Duplicate(); } } else { if (pCertContext.IsInvalid) pCertContext = pEnumContext.Duplicate(); // Doesn't have a private key but hang on to it anyway in case we don't find any certs with a private key. } } if (pCertContext.IsInvalid) { // For compat, setting "hr" to ERROR_INVALID_PARAMETER even though ERROR_INVALID_PARAMETER is not actually an HRESULT. throw ErrorCode.ERROR_INVALID_PARAMETER.ToCryptographicException(); } return pCertContext; } finally { hStore.Dispose(); } } private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & X509Certificate.KeyStorageFlagsAll) != keyStorageFlags) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); PfxCertStoreFlags pfxCertStoreFlags = 0; if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET; else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET; if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE; if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected) pfxCertStoreFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED; // If a user is asking for an Ephemeral key they should be willing to test their code to find out // that it will no longer import into CAPI. This solves problems of legacy CSPs being // difficult to do SHA-2 RSA signatures with, simplifies the story for UWP, and reduces the // complexity of pointer interpretation. if ((keyStorageFlags & X509KeyStorageFlags.EphemeralKeySet) == X509KeyStorageFlags.EphemeralKeySet) pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_NO_PERSIST_KEY | PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP; // In the full .NET Framework loading a PFX then adding the key to the Windows Certificate Store would // enable a native application compiled against CAPI to find that private key and interoperate with it. // // For CoreFX this behavior is being retained. // // For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not // allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the // CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too. #if NETNATIVE pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP; #endif return pfxCertStoreFlags; } private const ExpectedContentTypeFlags X509ExpectedContentTypeFlags = ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX; private const ExpectedFormatTypeFlags X509ExpectedFormatTypeFlags = ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL; } }
// Either EFCORE or NHIBERNATE should be defined in the project properties using Breeze.AspNetCore; using Breeze.Persistence; #if EFCORE using Breeze.Persistence.EFCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Models.NorthwindIB.CF; using Foo; #elif NHIBERNATE using Breeze.Persistence.NH; using Models.NorthwindIB.NH; #endif using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using BreezeEntityState = Breeze.Persistence.EntityState; using Microsoft.Data.SqlClient; using System.Threading.Tasks; namespace Test.AspNetCore.Controllers { [Route("breeze/[controller]/[action]")] [BreezeQueryFilter] public class NorthwindIBModelController : Controller { private NorthwindPersistenceManager PersistenceManager; // called via DI #if EFCORE public NorthwindIBModelController(NorthwindIBContext_CF context) { PersistenceManager = new NorthwindPersistenceManager(context); } #elif NHIBERNATE public NorthwindIBModelController(NHSessionProvider<NorthwindPersistenceManager> provider) { PersistenceManager = new NorthwindPersistenceManager(provider); } #endif [HttpGet] public IActionResult Metadata() { return Ok(PersistenceManager.Metadata()); } [HttpPost] public Task<SaveResult> SaveChanges([FromBody] JObject saveBundle) { return PersistenceManager.SaveChangesAsync(saveBundle); } #region Save interceptors [HttpPost] public Task<SaveResult> SaveWithTransactionScope([FromBody]JObject saveBundle) { var txSettings = new TransactionSettings() { TransactionType = TransactionType.TransactionScope }; return PersistenceManager.SaveChangesAsync(saveBundle, txSettings); } [HttpPost] public Task<SaveResult> SaveWithDbTransaction([FromBody]JObject saveBundle) { var txSettings = new TransactionSettings() { TransactionType = TransactionType.DbTransaction }; return PersistenceManager.SaveChangesAsync(saveBundle, txSettings); } [HttpPost] public Task<SaveResult> SaveWithNoTransaction([FromBody]JObject saveBundle) { var txSettings = new TransactionSettings() { TransactionType = TransactionType.None }; return PersistenceManager.SaveChangesAsync(saveBundle, txSettings); } [HttpPost] public Task<SaveResult> SaveWithComment([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntitiesDelegate = AddComment; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveWithExit([FromBody]JObject saveBundle) { // set break points here to see how these two approaches give you a SaveMap w/o saving. var saveMap = PersistenceManager.GetSaveMapFromSaveBundle(saveBundle); #if EFCORE saveMap = new NorthwindIBDoNotSaveContext().GetSaveMapFromSaveBundle(saveBundle); #endif return Task.FromResult(new SaveResult() { Entities = new List<Object>(), KeyMappings = new List<KeyMapping>() }); } [HttpPost] public Task<SaveResult> SaveAndThrow([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntitiesDelegate = ThrowError; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveWithEntityErrorsException([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntitiesDelegate = ThrowEntityErrorsException; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveWithAuditFields([FromBody] JObject saveBundle) { PersistenceManager.BeforeSaveEntityDelegate = SetAuditFields; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveWithFreight([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntityDelegate = CheckFreight; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveWithFreight2([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntitiesDelegate = CheckFreightOnOrders; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveCheckInitializer([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntitiesDelegate = AddOrder; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveCheckUnmappedProperty([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntityDelegate = CheckUnmappedProperty; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveCheckUnmappedPropertySerialized([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntityDelegate = CheckUnmappedPropertySerialized; return PersistenceManager.SaveChangesAsync(saveBundle); } [HttpPost] public Task<SaveResult> SaveCheckUnmappedPropertySuppressed([FromBody]JObject saveBundle) { PersistenceManager.BeforeSaveEntityDelegate = CheckUnmappedPropertySuppressed; return PersistenceManager.SaveChangesAsync(saveBundle); } private Dictionary<Type, List<EntityInfo>> ThrowError(Dictionary<Type, List<EntityInfo>> saveMap) { throw new Exception("Deliberately thrown exception"); } private Dictionary<Type, List<EntityInfo>> ThrowEntityErrorsException(Dictionary<Type, List<EntityInfo>> saveMap) { List<EntityInfo> orderInfos; if (saveMap.TryGetValue(typeof(Order), out orderInfos)) { var errors = orderInfos.Select(oi => { #if NHIBERNATE return new EntityError() { EntityTypeName = typeof(Order).FullName, ErrorMessage = "Cannot save orders with this save method", ErrorName = "WrongMethod", KeyValues = new object[] { ((Order) oi.Entity).OrderID }, PropertyName = "OrderID" }; #else return new EFEntityError(oi, "WrongMethod", "Cannot save orders with this save method", "OrderID"); #endif }); var ex = new EntityErrorsException("test of custom exception message", errors); // if you want to see a different error status code use this. // ex.StatusCode = HttpStatusCode.Conflict; // Conflict = 409 ; default is Forbidden (403). throw ex; } return saveMap; } private Dictionary<Type, List<EntityInfo>> AddOrder(Dictionary<Type, List<EntityInfo>> saveMap) { var order = new Order(); order.OrderDate = DateTime.Today; var ei = PersistenceManager.CreateEntityInfo(order); List<EntityInfo> orderInfos = PersistenceManager.GetEntityInfos(saveMap, typeof(Order)); orderInfos.Add(ei); return saveMap; } private Dictionary<Type, List<EntityInfo>> CheckFreightOnOrders(Dictionary<Type, List<EntityInfo>> saveMap) { List<EntityInfo> entityInfos; if (saveMap.TryGetValue(typeof(Order), out entityInfos)) { foreach (var entityInfo in entityInfos) { CheckFreight(entityInfo); } } return saveMap; } private bool CheckFreight(EntityInfo entityInfo) { if ((PersistenceManager.SaveOptions.Tag as String) == "freight update") { var order = entityInfo.Entity as Order; order.Freight = order.Freight + 1; } else if ((PersistenceManager.SaveOptions.Tag as String) == "freight update-ov") { var order = entityInfo.Entity as Order; order.Freight = order.Freight + 1; entityInfo.OriginalValuesMap["Freight"] = null; } else if ((PersistenceManager.SaveOptions.Tag as String) == "freight update-force") { var order = entityInfo.Entity as Order; order.Freight = order.Freight + 1; entityInfo.ForceUpdate = true; } return true; } private bool SetAuditFields(EntityInfo entityInfo) { var entity = entityInfo.Entity as User; if (entity == null) return true; var userId = 12345; if (entityInfo.EntityState == Breeze.Persistence.EntityState.Added) { entityInfo.OriginalValuesMap["CreatedBy"] = entity.CreatedBy; entityInfo.OriginalValuesMap["CreatedByUserId"] = entity.CreatedByUserId; entityInfo.OriginalValuesMap["CreatedDate"] = entity.CreatedDate; //entityInfo.ForceUpdate = true; entity.CreatedBy = "test"; entity.CreatedByUserId = userId; entity.CreatedDate = DateTime.Now; entity.ModifiedBy = "test"; entity.ModifiedByUserId = userId; entity.ModifiedDate = DateTime.Now; } else if (entityInfo.EntityState == Breeze.Persistence.EntityState.Modified) { entityInfo.OriginalValuesMap["ModifiedBy"] = entity.ModifiedBy; entityInfo.OriginalValuesMap["ModifiedByUserId"] = entity.ModifiedByUserId; entityInfo.OriginalValuesMap["ModifiedDate"] = entity.ModifiedDate; //entityInfo.ForceUpdate = true; entity.ModifiedBy = "test"; entity.ModifiedByUserId = userId; entity.ModifiedDate = DateTime.Now; } return true; } private Dictionary<Type, List<EntityInfo>> AddComment(Dictionary<Type, List<EntityInfo>> saveMap) { var comment = new Comment(); var tag = PersistenceManager.SaveOptions.Tag; comment.Comment1 = (tag == null) ? "Generic comment" : tag.ToString(); comment.CreatedOn = DateTime.Now; comment.SeqNum = 1; var ei = PersistenceManager.CreateEntityInfo(comment); List<EntityInfo> commentInfos = PersistenceManager.GetEntityInfos(saveMap, typeof(Comment)); commentInfos.Add(ei); return saveMap; } private bool CheckUnmappedProperty(EntityInfo entityInfo) { var unmappedValue = entityInfo.UnmappedValuesMap["MyUnmappedProperty"]; // fixed in v 1.4.18 // var unmappedValue = entityInfo.UnmappedValuesMap["myUnmappedProperty"]; if ((String)unmappedValue != "anything22") { throw new Exception("wrong value for unmapped property: " + unmappedValue); } Customer cust = entityInfo.Entity as Customer; return false; } private bool CheckUnmappedPropertySuppressed(EntityInfo entityInfo) { if (entityInfo.UnmappedValuesMap != null) { throw new Exception("unmapped properties should have been suppressed"); } return false; } private bool CheckUnmappedPropertySerialized(EntityInfo entityInfo) { var unmappedValue = entityInfo.UnmappedValuesMap["MyUnmappedProperty"]; if ((String)unmappedValue != "ANYTHING22") { throw new Exception("wrong value for unmapped property: " + unmappedValue); } var anotherOne = entityInfo.UnmappedValuesMap["AnotherOne"]; if (((dynamic)anotherOne).z[5].foo.Value != 4) { throw new Exception("wrong value for 'anotherOne.z[5].foo'"); } if (((dynamic)anotherOne).extra.Value != 666) { throw new Exception("wrong value for 'anotherOne.extra'"); } Customer cust = entityInfo.Entity as Customer; if (cust.CompanyName.ToUpper() != cust.CompanyName) { throw new Exception("Uppercasing of company name did not occur"); } return false; } #endregion #region standard queries [HttpGet] // [EnableBreezeQuery(MaxAnyAllExpressionDepth = 3)] public IQueryable<Customer> Customers() { var q = PersistenceManager.Context.Customers; // For testing expression trees // var expr = (q.Where(c => c.Orders.Any(o => o.Freight > 950)) as IQueryable).Expression; return q; } [HttpGet] // [EnableBreezeQuery(MaxExpansionDepth = 3)] public IQueryable<Order> Orders() { return PersistenceManager.Context.Orders; } [HttpGet] public IQueryable<Employee> Employees() { return PersistenceManager.Context.Employees; } [HttpGet] public IQueryable<OrderDetail> OrderDetails() { return PersistenceManager.Context.OrderDetails; } [HttpGet] public IQueryable<Product> Products() { return PersistenceManager.Context.Products; } [HttpGet] public IQueryable<Supplier> Suppliers() { return PersistenceManager.Context.Suppliers; } [HttpGet] public IQueryable<Region> Regions() { return PersistenceManager.Context.Regions; } [HttpGet] public IQueryable<Territory> Territories() { return PersistenceManager.Context.Territories; } [HttpGet] public IQueryable<Category> Categories() { return PersistenceManager.Context.Categories; } [HttpGet] public IQueryable<Role> Roles() { return PersistenceManager.Context.Roles; } [HttpGet] public IQueryable<User> Users() { return PersistenceManager.Context.Users; } [HttpGet] public IQueryable<TimeLimit> TimeLimits() { return PersistenceManager.Context.TimeLimits; } [HttpGet] public IQueryable<TimeGroup> TimeGroups() { return PersistenceManager.Context.TimeGroups; } [HttpGet] public IQueryable<Comment> Comments() { return PersistenceManager.Context.Comments; } [HttpGet] public IQueryable<UnusualDate> UnusualDates() { return PersistenceManager.Context.UnusualDates; } //[HttpGet] //public IQueryable<Geospatial> Geospatials() { // return PersistenceManager.TypedContext.Geospatials; //} #endregion #region named queries [HttpGet] public IQueryable<Customer> CustomersStartingWith(string companyName) { if (companyName == "null") { throw new Exception("nulls should not be passed as 'null'"); } if (String.IsNullOrEmpty(companyName)) { companyName = ""; } var custs = PersistenceManager.Context.Customers.Where(c => c.CompanyName.StartsWith(companyName)); return custs; } [HttpGet] public Object CustomerCountsByCountry() { return PersistenceManager.Context.Customers.GroupBy(c => c.Country).Select(g => new { g.Key, Count = g.Count() }); } [HttpGet] public Customer CustomerWithScalarResult() { return PersistenceManager.Context.Customers.First(); } [HttpGet] public IActionResult CustomersWithHttpError() { //var responseMsg = new HttpResponseMessage(HttpStatusCode.NotFound); //responseMsg.Content = new StringContent("Custom error message"); //responseMsg.ReasonPhrase = "Custom Reason"; //throw new HttpResponseException(responseMsg); return StatusCode(StatusCodes.Status404NotFound, "Custom error message"); } [HttpGet] // [EnableBreezeQuery] public IEnumerable<Employee> EnumerableEmployees() { return PersistenceManager.Context.Employees.ToList(); } [HttpGet] public IQueryable<Employee> EmployeesFilteredByCountryAndBirthdate(DateTime birthDate, string country) { return PersistenceManager.Context.Employees.Where(emp => emp.BirthDate >= birthDate && emp.Country == country); } #if NHIBERNATE [HttpGet] public List<Employee> QueryInvolvingMultipleEntities() { var pm = PersistenceManager; var query = (from t1 in pm.Employees where (from t2 in pm.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID) select t1); var result = query.ToList(); return result; } #else [HttpGet] public List<Employee> QueryInvolvingMultipleEntities() { var dc0 = new NorthwindIBContext_CF(PersistenceManager.Context.Options); var pm = new EFPersistenceManager<NorthwindIBContext_CF>(dc0); //the query executes using pure EF var query0 = (from t1 in dc0.Employees where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID) select t1); var result0 = query0.ToList(); //the same query fails if using EFContextProvider dc0 = pm.Context; var query = (from t1 in dc0.Employees where (from t2 in dc0.Orders select t2.EmployeeID).Distinct().Contains(t1.EmployeeID) select t1); var result = query.ToList(); return result; } #endif [HttpGet] public List<Customer> CustomerFirstOrDefault() { var customer = PersistenceManager.Context.Customers.Where(c => c.CompanyName.StartsWith("blah")).FirstOrDefault(); if (customer == null) { return new List<Customer>(); } else { return new List<Customer>() { customer }; } // return Ok(customer); } [HttpGet] public Int32 OrdersCountForCustomer(string companyName) { var customer = PersistenceManager.Context.Customers.Include("Orders").Where(c => c.CompanyName.StartsWith(companyName)).First(); return customer.Orders.Count; } [HttpGet] // AltCustomers will not be in the resourceName/entityType map; public IQueryable<Customer> AltCustomers() { return PersistenceManager.Context.Customers; } [HttpGet] // public IQueryable<Employee> SearchEmployees([FromUri] int[] employeeIds) { // // may need to use FromRoute... as opposed to FromQuery public IQueryable<Employee> SearchEmployees([FromQuery] int[] employeeIds) { var query = PersistenceManager.Context.Employees.AsQueryable(); if (employeeIds.Length > 0) { query = query.Where(emp => employeeIds.Contains(emp.EmployeeID)); var result = query.ToList(); } return query; } [HttpGet] public IQueryable<Customer> SearchCustomers([FromQuery] CustomerQBE qbe) { // var query = ContextProvider.Context.Customers.Where(c => // c.CompanyName.StartsWith(qbe.CompanyName)); var ok = qbe != null && qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1; if (!ok) { throw new Exception("qbe error"); } // just testing that qbe actually made it in not attempted to write qbe logic here // so just return first 3 customers. return PersistenceManager.Context.Customers.Take(3); } [HttpGet] public IQueryable<Customer> SearchCustomers2([FromQuery] CustomerQBE[] qbeList) { if (qbeList.Length < 2) { throw new Exception("all least two items must be passed in"); } var ok = qbeList.All(qbe => { return qbe.CompanyName != null & qbe.ContactNames.Length > 0 && qbe.City.Length > 1; }); if (!ok) { throw new Exception("qbeList error"); } // just testing that qbe actually made it in not attempted to write qbe logic here // so just return first 3 customers. return PersistenceManager.Context.Customers.Take(3); } public class CustomerQBE { public String CompanyName { get; set; } public String[] ContactNames { get; set; } public String City { get; set; } } [HttpGet] public IQueryable<Customer> CustomersOrderedStartingWith(string companyName) { var customers = PersistenceManager.Context.Customers.Where(c => c.CompanyName.StartsWith(companyName)).OrderBy(cust => cust.CompanyName); var list = customers.ToList(); return customers; } [HttpGet] public IQueryable<Employee> EmployeesMultipleParams(int employeeID, string city) { // HACK: if (city == "null") { city = null; } var emps = PersistenceManager.Context.Employees.Where(emp => emp.EmployeeID == employeeID || emp.City.Equals(city)); return emps; } [HttpGet] public IEnumerable<Object> Lookup1Array() { var regions = PersistenceManager.Context.Regions; var lookups = new List<Object>(); lookups.Add(new { regions = regions }); return lookups; } [HttpGet] public object Lookups() { var regions = PersistenceManager.Context.Regions; var territories = PersistenceManager.Context.Territories; var categories = PersistenceManager.Context.Categories; var lookups = new { regions, territories, categories }; return lookups; } [HttpGet] public IEnumerable<Object> LookupsEnumerableAnon() { var regions = PersistenceManager.Context.Regions; var territories = PersistenceManager.Context.Territories; var categories = PersistenceManager.Context.Categories; var lookups = new List<Object>(); lookups.Add(new { regions = regions, territories = territories, categories = categories }); return lookups; } [HttpGet] public IQueryable<Object> CompanyNames() { var stuff = PersistenceManager.Context.Customers.Select(c => c.CompanyName); return stuff; } [HttpGet] public IQueryable<Object> CompanyNamesAndIds() { var stuff = PersistenceManager.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID }); return stuff; } [HttpGet] public IQueryable<CustomerDTO> CompanyNamesAndIdsAsDTO() { var stuff = PersistenceManager.Context.Customers.Select(c => new CustomerDTO() { CompanyName = c.CompanyName, CustomerID = c.CustomerID }); return stuff; } public class CustomerDTO { public CustomerDTO() { } public CustomerDTO(String companyName, Guid customerID) { CompanyName = companyName; CustomerID = customerID; } public Guid CustomerID { get; set; } public String CompanyName { get; set; } public AnotherType AnotherItem { get; set; } } public class AnotherType { } [HttpGet] public IQueryable<Object> CustomersWithBigOrders() { var stuff = PersistenceManager.Context.Customers.Where(c => c.Orders.Any(o => o.Freight > 100)).Select(c => new { Customer = c, BigOrders = c.Orders.Where(o => o.Freight > 100) }); return stuff; } [HttpGet] #if NHIBERNATE public IQueryable<Object> CompanyInfoAndOrders() { // Need to handle this specially for NH, to prevent $top being applied to Orders var q = PersistenceManager.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID, c.Orders }); var stuff = q.ToList().AsQueryable(); #else public IQueryable<Object> CompanyInfoAndOrders() { var stuff = PersistenceManager.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID, c.Orders }); #endif return stuff; } [HttpGet] public Object CustomersAndProducts() { var stuff = new { Customers = PersistenceManager.Context.Customers.ToList(), Products = PersistenceManager.Context.Products.ToList() }; return stuff; } [HttpGet] public IQueryable<Object> TypeEnvelopes() { var stuff = this.GetType().Assembly.GetTypes() .Select(t => new { t.Assembly.FullName, t.Name, t.Namespace }) .AsQueryable(); return stuff; } [HttpGet] public IQueryable<Customer> CustomersAndOrders() { var custs = PersistenceManager.Context.Customers.Include("Orders"); return custs; } [HttpGet] public IQueryable<Order> OrdersAndCustomers() { var orders = PersistenceManager.Context.Orders.Include("Customer"); return orders; } [HttpGet] public IQueryable<Customer> CustomersStartingWithA() { var custs = PersistenceManager.Context.Customers.Where(c => c.CompanyName.StartsWith("A")); return custs; } [HttpGet] // [EnableBreezeQuery] // public HttpResponseMessage CustomersAsHRM() { public IActionResult CustomersAsHRM() { var customers = PersistenceManager.Context.Customers.Cast<Customer>(); return Ok(customers); } [HttpGet] public IQueryable<OrderDetail> OrderDetailsMultiple(int multiple, string expands) { var query = PersistenceManager.Context.OrderDetails.OfType<OrderDetail>(); if (!string.IsNullOrWhiteSpace(expands)) { var segs = expands.Split(',').ToList(); segs.ForEach(s => { query = ((dynamic)query).Include(s); }); } var orig = query.ToList() as IList<OrderDetail>; var list = new List<OrderDetail>(orig.Count * multiple); for (var i = 0; i < multiple; i++) { for (var j = 0; j < orig.Count; j++) { var od = orig[j]; var newProductID = i * j + 1; var clone = new OrderDetail(); clone.Order = od.Order; clone.OrderID = od.OrderID; clone.RowVersion = od.RowVersion; clone.UnitPrice = od.UnitPrice; clone.Quantity = (short)multiple; clone.Discount = i; clone.ProductID = newProductID; if (od.Product != null) { var p = new Product(); var op = od.Product; p.ProductID = newProductID; p.Category = op.Category; p.CategoryID = op.CategoryID; p.Discontinued = op.Discontinued; p.DiscontinuedDate = op.DiscontinuedDate; p.ProductName = op.ProductName; p.QuantityPerUnit = op.QuantityPerUnit; p.ReorderLevel = op.ReorderLevel; p.RowVersion = op.RowVersion; p.Supplier = op.Supplier; p.SupplierID = op.SupplierID; p.UnitPrice = op.UnitPrice; p.UnitsInStock = op.UnitsInStock; p.UnitsOnOrder = op.UnitsOnOrder; clone.Product = p; } list.Add(clone); } } return list.AsQueryable(); } #endregion } #if EFCORE public class NorthwindPersistenceManager : EFPersistenceManager<NorthwindIBContext_CF> { public const string CONFIG_VERSION = "EFCORE"; public NorthwindPersistenceManager(NorthwindIBContext_CF dbContext) : base(dbContext) { } #elif NHIBERNATE public class NorthwindPersistenceManager : NorthwindNHPersistenceManager { public const string CONFIG_VERSION = "NHIBERNATE"; public NorthwindPersistenceManager(NHSessionProvider<NorthwindPersistenceManager> provider) : base(provider.OpenSession()) { } #endif protected override void AfterSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap, List<KeyMapping> keyMappings) { var tag = (string)SaveOptions.Tag; if (tag == "CommentKeyMappings.After") { foreach (var km in keyMappings) { var realint = Convert.ToInt32(km.RealValue); byte seq = (byte)(realint % 512); AddComment(km.EntityTypeName + ':' + km.RealValue, seq); } } else if (tag == "UpdateProduceKeyMapping.After") { if (!keyMappings.Any()) throw new Exception("UpdateProduce.After: No key mappings available"); var km = keyMappings[0]; UpdateProduceDescription(km.EntityTypeName + ':' + km.RealValue); } else if (tag == "LookupEmployeeInSeparateContext.After") { LookupEmployeeInSeparateContext(false); } else if (tag == "LookupEmployeeInSeparateContext.SameConnection.After") { LookupEmployeeInSeparateContext(true); } else if (tag == "deleteProductOnServer") { var t = typeof(Product); var prodinfo = saveMap[t].First(); prodinfo.EntityState = BreezeEntityState.Deleted; } else if (tag != null && tag.StartsWith("deleteProductOnServer:")) { // create new EntityInfo for entity that we want to delete that was not in the save bundle var id = tag.Substring(tag.IndexOf(':') + 1); var product = new Product(); product.ProductID = int.Parse(id); var infos = GetEntityInfos(saveMap, typeof(Product)); var info = CreateEntityInfo(product, BreezeEntityState.Deleted); infos.Add(info); } else if (tag == "deleteSupplierAndProductOnServer") { // mark deleted entities that are in the save bundle var t = typeof(Product); var infos = GetEntityInfos(saveMap, typeof(Product)); var prodinfo = infos.FirstOrDefault(); if (prodinfo != null) prodinfo.EntityState = BreezeEntityState.Deleted; infos = GetEntityInfos(saveMap, typeof(Supplier)); var supinfo = infos.FirstOrDefault(); if (supinfo != null) supinfo.EntityState = BreezeEntityState.Deleted; } base.AfterSaveEntities(saveMap, keyMappings); } public List<EntityInfo> GetEntityInfos(Dictionary<Type, List<EntityInfo>> saveMap, Type t) { List<EntityInfo> entityInfos; if (!saveMap.TryGetValue(t, out entityInfos)) { entityInfos = new List<EntityInfo>(); saveMap.Add(t, entityInfos); } return entityInfos; } public Dictionary<Type, List<EntityInfo>> GetSaveMapFromSaveBundle(JObject saveBundle) { InitializeSaveState(saveBundle); // Sets initial EntityInfos SaveWorkState.BeforeSave(); // Creates the SaveMap as byproduct of BeforeSave logic return SaveWorkState.SaveMap; } #if (EFCORE || DATABASEFIRST_NEW || DATABASEFIRST_OLD) /* hack to set the current DbTransaction onto the DbCommand. Transaction comes from EF private properties. */ public void SetCurrentTransaction(System.Data.Common.DbCommand command) { if (EntityTransaction != null) { // get private member via reflection //var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; //var etype = EntityTransaction.GetType(); //var stProp = etype.GetProperty("StoreTransaction", bindingFlags); //var transaction = stProp.GetValue(EntityTransaction, null); //var dbTransaction = transaction as System.Data.Common.DbTransaction; //if (dbTransaction != null) { // command.Transaction = dbTransaction; //} if (this.DbContext.Database.CurrentTransaction != null) { command.Transaction = this.DbContext.Database.CurrentTransaction.GetDbTransaction(); } } } #endif // Test performing a raw db insert to NorthwindIB using the base connection private int AddComment(string comment, byte seqnum) { #if ORACLE_EDMX var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var text = String.Format("insert into COMMENT_ (CreatedOn, Comment1, SeqNum) values (TO_DATE('{0}','YYYY-MM-DD HH24:MI:SS'), '{1}', {2})", time, comment, seqnum); #else var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); var text = String.Format("insert into Comment (CreatedOn, Comment1, SeqNum) values ('{0}', '{1}', {2})", time, comment, seqnum); #endif #if NHIBERNATE var cmd = Session.CreateSQLQuery(text); var result = cmd.ExecuteUpdate(); #else var conn = EntityConnection; var cmd = conn.CreateCommand(); #if !ORACLE_EDMX SetCurrentTransaction(cmd); #endif cmd.CommandText = text; var result = cmd.ExecuteNonQuery(); #endif return result; } // Test performing a raw db update to ProduceTPH using the ProduceTPH connection. Requires DTC. private int UpdateProduceDescription(string comment) { using var conn = new SqlConnection("data source=.;initial catalog=ProduceTPH;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"); conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = String.Format("update ItemOfProduce set Description='{0}' where id='{1}'", comment, "13F1C9F5-3189-45FA-BA6E-13314FAFAA92"); var result = cmd.ExecuteNonQuery(); conn.Close(); return result; } // Use another Context to simulate lookup. Returns Margaret Peacock if employeeId is not specified. private Employee LookupEmployeeInSeparateContext(bool existingConnection, int employeeId = 4) { var context2 = existingConnection #if EFCORE ? new NorthwindIBContext_CF(this.Context.Options) : new NorthwindIBContext_CF(this.Context.Options); #elif NHIBERNATE ? new NorthwindNHPersistenceManager(this) : new NorthwindNHPersistenceManager(this.Session.SessionFactory.OpenSession()); #endif var query = context2.Employees.Where(e => e.EmployeeID == employeeId); var employee = query.FirstOrDefault(); return employee; } protected override bool BeforeSaveEntity(EntityInfo entityInfo) { if ((string)SaveOptions.Tag == "addProdOnServer") { Supplier supplier = entityInfo.Entity as Supplier; Product product = new Product() { ProductName = "Product added on server" }; #if EFCORE if (supplier.Products == null) supplier.Products = new List<Product>(); #endif supplier.Products.Add(product); return true; } // prohibit any additions of entities of type 'Region' if (entityInfo.Entity.GetType() == typeof(Region) && entityInfo.EntityState == BreezeEntityState.Added) { var region = entityInfo.Entity as Region; if (region.RegionDescription.ToLowerInvariant().StartsWith("error")) return false; } #if ORACLE_EDMX // Convert GUIDs in Customer and Order to be compatible with Oracle if (entityInfo.Entity.GetType() == typeof(Customer)) { var cust = entityInfo.Entity as Customer; if (cust.CustomerID != null) { cust.CustomerID = cust.CustomerID.ToUpperInvariant(); } } else if (entityInfo.Entity.GetType() == typeof(Order)) { var order = entityInfo.Entity as Order; if (order.CustomerID != null) { order.CustomerID = order.CustomerID.ToUpperInvariant(); } } #endif return base.BeforeSaveEntity(entityInfo); } protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap) { var tag = (string)SaveOptions.Tag; if (tag == "CommentOrderShipAddress.Before") { var orderInfos = saveMap[typeof(Order)]; byte seq = 1; foreach (var info in orderInfos) { var order = (Order)info.Entity; AddComment(order.ShipAddress, seq++); } } else if (tag == "UpdateProduceShipAddress.Before") { var orderInfos = saveMap[typeof(Order)]; var order = (Order)orderInfos[0].Entity; UpdateProduceDescription(order.ShipAddress); } else if (tag == "LookupEmployeeInSeparateContext.Before") { LookupEmployeeInSeparateContext(false); } else if (tag == "LookupEmployeeInSeparateContext.SameConnection.Before") { LookupEmployeeInSeparateContext(true); } else if (tag == "ValidationError.Before") { foreach (var type in saveMap.Keys) { var list = saveMap[type]; foreach (var entityInfo in list) { var entity = entityInfo.Entity; var entityError = new EntityError() { EntityTypeName = type.Name, ErrorMessage = "Error message for " + type.Name, ErrorName = "Server-Side Validation", }; if (entity is Order) { var order = (Order)entity; entityError.KeyValues = new object[] { order.OrderID }; entityError.PropertyName = "OrderDate"; } } } } else if (tag == "increaseProductPrice") { Dictionary<Type, List<EntityInfo>> saveMapAdditions = new Dictionary<Type, List<EntityInfo>>(); foreach (var type in saveMap.Keys) { if (type == typeof(Category)) { foreach (var entityInfo in saveMap[type]) { if (entityInfo.EntityState == BreezeEntityState.Modified) { Category category = (entityInfo.Entity as Category); var products = this.Context.Products.Where(p => p.CategoryID == category.CategoryID); foreach (var product in products) { if (!saveMapAdditions.ContainsKey(typeof(Product))) saveMapAdditions[typeof(Product)] = new List<EntityInfo>(); var ei = this.CreateEntityInfo(product, BreezeEntityState.Modified); ei.ForceUpdate = true; var incr = (Convert.ToInt64(product.UnitPrice) % 2) == 0 ? 1 : -1; product.UnitPrice += incr; saveMapAdditions[typeof(Product)].Add(ei); } } } } } foreach (var type in saveMapAdditions.Keys) { if (!saveMap.ContainsKey(type)) { saveMap[type] = new List<EntityInfo>(); } foreach (var enInfo in saveMapAdditions[type]) { saveMap[type].Add(enInfo); } } } else if (tag == "deleteProductOnServer.Before") { var prodinfo = saveMap[typeof(Product)].First(); if (prodinfo.EntityState == BreezeEntityState.Added) { // because Deleted throws error when trying delete non-existent row from database prodinfo.EntityState = BreezeEntityState.Detached; } else { prodinfo.EntityState = BreezeEntityState.Deleted; } } else if (tag == "deleteSupplierOnServer.Before") { var product = (Product)saveMap[typeof(Product)].First().Entity; var infos = GetEntityInfos(saveMap, typeof(Supplier)); var supinfo = infos.FirstOrDefault(); if (supinfo != null) { supinfo.EntityState = BreezeEntityState.Deleted; } else { // create new EntityInfo for entity that we want to delete that was not in the save bundle var supplier = new Supplier(); supplier.Location = new Location(); supplier.SupplierID = product.SupplierID.GetValueOrDefault(); supplier.CompanyName = "delete me"; supplier.RowVersion = 1; supinfo = CreateEntityInfo(supplier, BreezeEntityState.Deleted); infos.Add(supinfo); } } DataAnnotationsValidator.AddDescriptor(typeof(Customer), typeof(Customer)); var validator = new DataAnnotationsValidator(this); validator.ValidateEntities(saveMap, true); return base.BeforeSaveEntities(saveMap); } } }
// Copyright (c) The Mapsui authors. // The Mapsui authors licensed this file under the MIT license. // See the LICENSE file in the project root for full license information. // This file was originally created by Paul den Dulk (Geodan) as part of SharpMap using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Mapsui.Extensions; using Mapsui.Utilities; using Mapsui.ViewportAnimations; namespace Mapsui { /// <summary> /// Viewport holds all information about the visible part of the map. /// </summary> /// <remarks> /// Viewport is the connection between Map and MapControl. It tells MapControl, /// which part of Map should be displayed on screen. /// </remarks> public class Viewport : IViewport { public event PropertyChangedEventHandler? ViewportChanged; // State private double _centerX; private double _centerY; private double _resolution = Constants.DefaultResolution; private double _rotation; private double _width; private double _height; // Derived from state private readonly MRect _extent; private List<AnimationEntry<Viewport>> _animations = new(); /// <summary> /// Create a new viewport /// </summary> public Viewport() { _extent = new MRect(0, 0, 0, 0); } /// <summary> /// Create a new viewport from another viewport /// </summary> /// <param name="viewport">Viewport from which to copy all values</param> public Viewport(IReadOnlyViewport viewport) : this() { _centerX = viewport.Center.X; _centerY = viewport.Center.Y; _resolution = viewport.Resolution; _width = viewport.Width; _height = viewport.Height; _rotation = viewport.Rotation; IsRotated = viewport.IsRotated; if (viewport.Extent != null) _extent = new MRect(viewport.Extent); UpdateExtent(); } public bool HasSize => !_width.IsNanOrInfOrZero() && !_height.IsNanOrInfOrZero(); /// <inheritdoc /> public MReadOnlyPoint Center => new MReadOnlyPoint(_centerX, _centerY); /// <inheritdoc /> public double CenterX { get => _centerX; set { _centerX = value; UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public double CenterY { get => _centerY; set { _centerY = value; UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public double Resolution { get => _resolution; set { _resolution = value; UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public double Width { get => _width; set { _width = value; UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public double Height { get => _height; set { _height = value; UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public double Rotation { get => _rotation; set { // normalize the value to be [0, 360) _rotation = value % 360.0; if (_rotation < 0) _rotation += 360.0; IsRotated = !double.IsNaN(_rotation) && _rotation > Constants.Epsilon && _rotation < 360 - Constants.Epsilon; if (!IsRotated) _rotation = 0; // If not rotated set _rotation explicitly to exactly 0 UpdateExtent(); OnViewportChanged(); } } /// <inheritdoc /> public bool IsRotated { get; private set; } /// <inheritdoc /> public MRect Extent => _extent; /// <inheritdoc /> public MPoint WorldToScreen(MPoint worldPosition) { return WorldToScreen(worldPosition.X, worldPosition.Y); } /// <inheritdoc /> public MPoint ScreenToWorld(MPoint position) { return ScreenToWorld(position.X, position.Y); } /// <inheritdoc /> public MPoint ScreenToWorld(double positionX, double positionY) { var (x, y) = ScreenToWorldXY(positionX, positionY); return new MPoint(x, y); } /// <inheritdoc /> public MPoint WorldToScreen(double worldX, double worldY) { var (x, y) = WorldToScreenXY(worldX, worldY); return new MPoint(x, y); } /// <inheritdoc /> public (double screenX, double screenY) WorldToScreenXY(double worldX, double worldY) { var (screenX, screenY) = WorldToScreenUnrotated(worldX, worldY); if (IsRotated) { var screenCenterX = Width / 2.0; var screenCenterY = Height / 2.0; return Rotate(-_rotation, screenX, screenY, screenCenterX, screenCenterY); } return (screenX, screenY); } public (double x, double y) Rotate(double degrees, double x, double y, double centerX, double centerY) { // translate this point back to the center var newX = x - centerX; var newY = y - centerY; // rotate the values var p = Algorithms.RotateClockwiseDegrees(newX, newY, degrees); // translate back to original reference frame newX = p.X + centerX; newY = p.Y + centerY; return (newX, newY); } /// <inheritdoc /> public (double screenX, double screenY) WorldToScreenUnrotated(double worldX, double worldY) { var screenCenterX = Width / 2.0; var screenCenterY = Height / 2.0; var screenX = (worldX - Center.X) / _resolution + screenCenterX; var screenY = (Center.Y - worldY) / _resolution + screenCenterY; return (screenX, screenY); } /// <inheritdoc /> public (double worldX, double worldY) ScreenToWorldXY(double screenX, double screenY) { var screenCenterX = Width / 2.0; var screenCenterY = Height / 2.0; if (IsRotated) { var screen = new MPoint(screenX, screenY).Rotate(_rotation, screenCenterX, screenCenterY); screenX = screen.X; screenY = screen.Y; } var worldX = Center.X + (screenX - screenCenterX) * _resolution; var worldY = Center.Y - (screenY - screenCenterY) * _resolution; return (worldX, worldY); } /// <inheritdoc /> public void Transform(MPoint positionScreen, MPoint previousPositionScreen, double deltaResolution = 1, double deltaRotation = 0) { _animations = new(); var previous = ScreenToWorld(previousPositionScreen.X, previousPositionScreen.Y); var current = ScreenToWorld(positionScreen.X, positionScreen.Y); var newX = _centerX + previous.X - current.X; var newY = _centerY + previous.Y - current.Y; if (deltaResolution != 1) { Resolution = Resolution / deltaResolution; // Calculate current position again with adjusted resolution // Zooming should be centered on the place where the map is touched. // This is done with the scale correction. var scaleCorrectionX = (1 - deltaResolution) * (current.X - Center.X); var scaleCorrectionY = (1 - deltaResolution) * (current.Y - Center.Y); newX -= scaleCorrectionX; newY -= scaleCorrectionY; } CenterX = newX; CenterY = newY; if (deltaRotation != 0) { current = ScreenToWorld(positionScreen.X, positionScreen.Y); // calculate current position again with adjusted resolution Rotation += deltaRotation; var postRotation = ScreenToWorld(positionScreen.X, positionScreen.Y); // calculate current position again with adjusted resolution CenterX = _centerX - (postRotation.X - current.X); CenterY = _centerY - (postRotation.Y - current.Y); } } /// <summary> /// Recalculates extent for viewport /// </summary> private void UpdateExtent() { // calculate the window extent which is not rotate var halfSpanX = _width * _resolution * 0.5; var halfSpanY = _height * _resolution * 0.5; var left = Center.X - halfSpanX; var bottom = Center.Y - halfSpanY; var right = Center.X + halfSpanX; var top = Center.Y + halfSpanY; var windowExtent = new MQuad { BottomLeft = new MPoint(left, bottom), TopLeft = new MPoint(left, top), TopRight = new MPoint(right, top), BottomRight = new MPoint(right, bottom) }; if (!IsRotated) { _extent.Min.X = left; _extent.Min.Y = bottom; _extent.Max.X = right; _extent.Max.Y = top; } else { // Calculate the extent that will encompass a rotated viewport (slightly larger - used for tiles). // Perform rotations on corner offsets and then add them to the Center point. windowExtent = windowExtent.Rotate(-_rotation, Center.X, Center.Y); var rotatedBoundingBox = windowExtent.ToBoundingBox(); _extent.Min.X = rotatedBoundingBox.MinX; _extent.Min.Y = rotatedBoundingBox.MinY; _extent.Max.X = rotatedBoundingBox.MaxX; _extent.Max.Y = rotatedBoundingBox.MaxY; } } public void SetSize(double width, double height) { _animations = new(); _width = width; _height = height; UpdateExtent(); OnViewportChanged(); } public void SetCenter(double x, double y, long duration = 0, Easing? easing = default) { _animations = new(); _centerX = x; _centerY = y; UpdateExtent(); OnViewportChanged(); } public void SetCenterAndResolution(double x, double y, double resolution, long duration = 0, Easing? easing = default) { _animations = new(); if (duration == 0) { _centerX = x; _centerY = y; _resolution = resolution; } else { _animations = ZoomOnCenterAnimation.Create(this, x, y, resolution, duration); } UpdateExtent(); OnViewportChanged(); } public void SetCenter(MReadOnlyPoint center, long duration = 0, Easing? easing = default) { _animations = new(); if (center.Equals(Center)) return; if (duration == 0) { _centerX = center.X; _centerY = center.Y; } else { _animations = CenterAnimation.Create(this, center.X, center.Y, duration, easing); } UpdateExtent(); OnViewportChanged(); } public void SetResolution(double resolution, long duration = 0, Easing? easing = default) { _animations = new(); if (Resolution == resolution) return; if (duration == 0) Resolution = resolution; else { _animations = ZoomAnimation.Create(this, resolution, duration, easing); } UpdateExtent(); OnViewportChanged(); } public void SetRotation(double rotation, long duration = 0, Easing? easing = default) { _animations = new(); if (Rotation == rotation) return; if (duration == 0) Rotation = rotation; else { _animations = RotateAnimation.Create(this, rotation, duration, easing); } UpdateExtent(); OnViewportChanged(); } /// <summary> /// Property change event /// </summary> /// <param name="propertyName">Name of property that changed</param> private void OnViewportChanged([CallerMemberName] string? propertyName = null) { ViewportChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public static Viewport Create(MRect extent, double resolution) { return new Viewport { Resolution = resolution, _centerX = extent.Centroid.X, _centerY = extent.Centroid.Y, Width = extent.Width / resolution, Height = extent.Height / resolution }; } public bool UpdateAnimations() { if (_animations.All(a => a.Done)) _animations = new List<AnimationEntry<Viewport>>(); return Animation.UpdateAnimations(this, _animations); } public void SetAnimations(List<AnimationEntry<Viewport>> animations) { _animations = animations; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Cli.CommandParsing; using Microsoft.TemplateEngine.Edge; using Microsoft.TemplateEngine.Edge.Settings; using Microsoft.TemplateEngine.Edge.Template; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Cli { public static class TemplateListResolver { private static readonly IReadOnlyCollection<MatchLocation> NameFields = new HashSet<MatchLocation> { MatchLocation.Name, MatchLocation.ShortName, MatchLocation.Alias }; private static void ParseTemplateArgs(ITemplateInfo templateInfo, IHostSpecificDataLoader hostDataLoader, INewCommandInput commandInput) { HostSpecificTemplateData hostData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo); commandInput.ReparseForTemplate(templateInfo, hostData); } private static bool AreAllTemplatesSameGroupIdentity(IEnumerable<IFilteredTemplateInfo> templateList) { return templateList.AllAreTheSame((x) => x.Info.GroupIdentity, StringComparer.OrdinalIgnoreCase); } private static bool IsTemplateHiddenByHostFile(ITemplateInfo templateInfo, IHostSpecificDataLoader hostDataLoader) { HostSpecificTemplateData hostData = hostDataLoader.ReadHostSpecificTemplateData(templateInfo); return hostData.IsHidden; } public static bool ValidateRemainingParameters(INewCommandInput commandInput, out IReadOnlyList<string> invalidParams) { List<string> badParams = new List<string>(); if (AnyRemainingParameters(commandInput)) { foreach (string flag in commandInput.RemainingParameters.Keys) { badParams.Add(flag); } } invalidParams = badParams; return !invalidParams.Any(); } public static bool AnyRemainingParameters(INewCommandInput commandInput) { return commandInput.RemainingParameters.Any(); } public static IFilteredTemplateInfo FindHighestPrecedenceTemplateIfAllSameGroupIdentity(IReadOnlyList<IFilteredTemplateInfo> templateList) { if (!AreAllTemplatesSameGroupIdentity(templateList)) { return null; } IFilteredTemplateInfo highestPrecedenceTemplate = null; foreach (IFilteredTemplateInfo template in templateList) { if (highestPrecedenceTemplate == null) { highestPrecedenceTemplate = template; } else if (template.Info.Precedence > highestPrecedenceTemplate.Info.Precedence) { highestPrecedenceTemplate = template; } } return highestPrecedenceTemplate; } // Lists all the templates, unfiltered - except the ones hidden by their host file. public static IReadOnlyCollection<IFilteredTemplateInfo> PerformAllTemplatesQuery(IReadOnlyList<ITemplateInfo> templateInfo, IHostSpecificDataLoader hostDataLoader) { IReadOnlyCollection<IFilteredTemplateInfo> templates = TemplateListFilter.FilterTemplates ( templateInfo, false, WellKnownSearchFilters.NameFilter(string.Empty) ) .Where(x => !IsTemplateHiddenByHostFile(x.Info, hostDataLoader)).ToList(); return templates; } // Lists all the templates, filtered only by the context (item, project, etc) - and the host file. public static IReadOnlyCollection<IFilteredTemplateInfo> PerformAllTemplatesInContextQuery(IReadOnlyList<ITemplateInfo> templateInfo, IHostSpecificDataLoader hostDataLoader, string context) { IReadOnlyCollection<IFilteredTemplateInfo> templates = TemplateListFilter.FilterTemplates ( templateInfo, false, WellKnownSearchFilters.ContextFilter(context), WellKnownSearchFilters.NameFilter(string.Empty) ) .Where(x => !IsTemplateHiddenByHostFile(x.Info, hostDataLoader)).ToList(); return templates; } // Query for template matches, filtered by everything available: name, language, context, parameters, and the host file. public static TemplateListResolutionResult PerformCoreTemplateQuery(IReadOnlyList<ITemplateInfo> templateInfo, IHostSpecificDataLoader hostDataLoader, INewCommandInput commandInput, string defaultLanguage) { IReadOnlyCollection<IFilteredTemplateInfo> templates = TemplateListFilter.FilterTemplates ( templateInfo, false, WellKnownSearchFilters.NameFilter(commandInput.TemplateName), WellKnownSearchFilters.ClassificationsFilter(commandInput.TemplateName), WellKnownSearchFilters.LanguageFilter(commandInput.Language), WellKnownSearchFilters.ContextFilter(commandInput.TypeFilter?.ToLowerInvariant()), WellKnownSearchFilters.BaselineFilter(commandInput.BaselineName) ) .Where(x => !IsTemplateHiddenByHostFile(x.Info, hostDataLoader)).ToList(); IReadOnlyList<IFilteredTemplateInfo> coreMatchedTemplates = templates.Where(x => x.IsMatch).ToList(); bool anyExactCoreMatches; if (coreMatchedTemplates.Count == 0) { coreMatchedTemplates = templates.Where(x => x.IsPartialMatch).ToList(); anyExactCoreMatches = false; } else { anyExactCoreMatches = true; IReadOnlyList<IFilteredTemplateInfo> matchesWithExactDispositionsInNameFields = coreMatchedTemplates.Where(x => x.MatchDisposition.Any(y => NameFields.Contains(y.Location) && y.Kind == MatchKind.Exact)).ToList(); if (matchesWithExactDispositionsInNameFields.Count > 0) { coreMatchedTemplates = matchesWithExactDispositionsInNameFields; } } TemplateListResolutionResult matchResults = new TemplateListResolutionResult() { CoreMatchedTemplates = coreMatchedTemplates }; QueryForUnambiguousTemplateGroup(templateInfo, hostDataLoader, commandInput, matchResults, defaultLanguage, anyExactCoreMatches); return matchResults; } private static void QueryForUnambiguousTemplateGroup(IReadOnlyList<ITemplateInfo> templateInfo, IHostSpecificDataLoader hostDataLoader, INewCommandInput commandInput, TemplateListResolutionResult matchResults, string defaultLanguage, bool anyExactCoreMatches) { if (!anyExactCoreMatches || matchResults.CoreMatchedTemplates == null || matchResults.CoreMatchedTemplates.Count == 0) { return; } if (matchResults.CoreMatchedTemplates.Count == 1) { matchResults.UnambiguousTemplateGroupToUse = matchResults.CoreMatchedTemplates; return; } if (string.IsNullOrEmpty(commandInput.Language) && !string.IsNullOrEmpty(defaultLanguage)) { IReadOnlyList<IFilteredTemplateInfo> languageMatchedTemplates = FindTemplatesExplicitlyMatchingLanguage(matchResults.CoreMatchedTemplates, defaultLanguage); if (languageMatchedTemplates.Count == 1) { matchResults.UnambiguousTemplateGroupToUse = languageMatchedTemplates; return; } } UseSecondaryCriteriaToDisambiguateTemplateMatches(hostDataLoader, matchResults, commandInput, defaultLanguage); } // Returns the templates from the input list whose language is the input language. private static IReadOnlyList<IFilteredTemplateInfo> FindTemplatesExplicitlyMatchingLanguage(IEnumerable<IFilteredTemplateInfo> listToFilter, string language) { List<IFilteredTemplateInfo> languageMatches = new List<IFilteredTemplateInfo>(); if (string.IsNullOrEmpty(language)) { return languageMatches; } foreach (IFilteredTemplateInfo info in listToFilter) { // ChoicesAndDescriptions is invoked as case insensitive if (info.Info.Tags == null || info.Info.Tags.TryGetValue("language", out ICacheTag languageTag) && languageTag.ChoicesAndDescriptions.ContainsKey(language)) { languageMatches.Add(info); } } return languageMatches; } // coordinates filtering templates based on the parameters & language private static void UseSecondaryCriteriaToDisambiguateTemplateMatches(IHostSpecificDataLoader hostDataLoader, TemplateListResolutionResult matchResults, INewCommandInput commandInput, string defaultLanguage) { if (string.IsNullOrEmpty(commandInput.TemplateName)) { return; } matchResults.MatchedTemplatesWithSecondaryMatchInfo = FilterTemplatesOnParameters(matchResults.CoreMatchedTemplates, hostDataLoader, commandInput).Where(x => x.IsMatch).ToList(); IReadOnlyList<IFilteredTemplateInfo> matchesAfterParameterChecks = matchResults.MatchedTemplatesWithSecondaryMatchInfo.Where(x => x.IsParameterMatch).ToList(); if (matchResults.MatchedTemplatesWithSecondaryMatchInfo.Any(x => x.HasAmbiguousParameterMatch)) { matchesAfterParameterChecks = matchResults.MatchedTemplatesWithSecondaryMatchInfo; } if (matchesAfterParameterChecks.Count == 0) { // no param matches, continue additional matching with the list from before param checking (but with the param match dispositions) matchesAfterParameterChecks = matchResults.MatchedTemplatesWithSecondaryMatchInfo; } if (matchesAfterParameterChecks.Count == 1) { matchResults.UnambiguousTemplateGroupToUse = matchesAfterParameterChecks; return; } else if (string.IsNullOrEmpty(commandInput.Language) && !string.IsNullOrEmpty(defaultLanguage)) { IReadOnlyList<IFilteredTemplateInfo> languageFiltered = FindTemplatesExplicitlyMatchingLanguage(matchesAfterParameterChecks, defaultLanguage); if (languageFiltered.Count == 1) { matchResults.UnambiguousTemplateGroupToUse = languageFiltered; return; } else if (AreAllTemplatesSameGroupIdentity(languageFiltered)) { IReadOnlyList<IFilteredTemplateInfo> languageFilteredMatchesAfterParameterChecks = languageFiltered.Where(x => x.IsParameterMatch).ToList(); if (languageFilteredMatchesAfterParameterChecks.Count > 0 && !languageFiltered.Any(x => x.HasAmbiguousParameterMatch)) { matchResults.UnambiguousTemplateGroupToUse = languageFilteredMatchesAfterParameterChecks; return; } matchResults.UnambiguousTemplateGroupToUse = languageFiltered; return; } } else if (AreAllTemplatesSameGroupIdentity(matchesAfterParameterChecks)) { matchResults.UnambiguousTemplateGroupToUse = matchesAfterParameterChecks; return; } } // filters templates based on matches between the input parameters & the template parameters. private static IReadOnlyList<IFilteredTemplateInfo> FilterTemplatesOnParameters(IReadOnlyList<IFilteredTemplateInfo> templatesToFilter, IHostSpecificDataLoader hostDataLoader, INewCommandInput commandInput) { List<IFilteredTemplateInfo> filterResults = new List<IFilteredTemplateInfo>(); foreach (IFilteredTemplateInfo templateWithFilterInfo in templatesToFilter) { List<MatchInfo> dispositionForTemplate = templateWithFilterInfo.MatchDisposition.ToList(); try { ParseTemplateArgs(templateWithFilterInfo.Info, hostDataLoader, commandInput); // params are already parsed. But choice values aren't checked foreach (KeyValuePair<string, string> matchedParamInfo in commandInput.AllTemplateParams) { string paramName = matchedParamInfo.Key; string paramValue = matchedParamInfo.Value; if (templateWithFilterInfo.Info.Tags.TryGetValue(paramName, out ICacheTag paramDetails)) { // key is the value user should provide, value is description if (paramDetails.ChoicesAndDescriptions.ContainsKey(paramValue)) { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.Exact, ChoiceIfLocationIsOtherChoice = paramName }); } else { int startsWithCount = paramDetails.ChoicesAndDescriptions.Count(x => x.Key.StartsWith(paramValue, StringComparison.OrdinalIgnoreCase)); if (startsWithCount == 1) { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.Exact, ChoiceIfLocationIsOtherChoice = paramName }); } else if (startsWithCount > 1) { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.AmbiguousParameterValue, ChoiceIfLocationIsOtherChoice = paramName }); } else { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.InvalidParameterValue, ChoiceIfLocationIsOtherChoice = paramName }); } } } else if (templateWithFilterInfo.Info.CacheParameters.ContainsKey(paramName)) { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.Exact, ChoiceIfLocationIsOtherChoice = paramName }); } else { dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.InvalidParameterValue, ChoiceIfLocationIsOtherChoice = paramName }); } } foreach (string unmatchedParamName in commandInput.RemainingParameters.Keys.Where(x => !x.Contains(':'))) // filter debugging params { if (commandInput.TryGetCanonicalNameForVariant(unmatchedParamName, out string canonical)) { // the name is a known template param, it must have not parsed due to an invalid value // // Note (scp 2017-02-27): This probably can't happen, the param parsing doesn't check the choice values. dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.InvalidParameterValue, ChoiceIfLocationIsOtherChoice = unmatchedParamName }); } else { // the name is not known dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.OtherParameter, Kind = MatchKind.InvalidParameterName, ChoiceIfLocationIsOtherChoice = unmatchedParamName }); } } } catch { // if we do actually throw, add a non-match dispositionForTemplate.Add(new MatchInfo { Location = MatchLocation.Unspecified, Kind = MatchKind.Unspecified }); } filterResults.Add(new FilteredTemplateInfo(templateWithFilterInfo.Info, dispositionForTemplate)); } return filterResults; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Management.Automation; using EnvDTE; using NuGet.VisualStudio; namespace NuGet.PowerShell.Commands { /// <summary> /// This command lists the available packages which are either from a package source or installed in the current solution. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.PowerShell", "PS1101:AllCmdletsShouldAcceptPipelineInput", Justification = "Will investiage this one.")] [Cmdlet(VerbsCommon.Get, "Package", DefaultParameterSetName = ParameterAttribute.AllParameterSets)] [OutputType(typeof(IPackage))] public class GetPackageCommand : NuGetBaseCommand { private readonly IPackageRepositoryFactory _repositoryFactory; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IPackageRepository _recentPackagesRepository; private readonly IProductUpdateService _productUpdateService; private int _firstValue; private bool _firstValueSpecified; private bool _hasConnectedToHttpSource; public GetPackageCommand() : this(ServiceLocator.GetInstance<IPackageRepositoryFactory>(), ServiceLocator.GetInstance<IVsPackageSourceProvider>(), ServiceLocator.GetInstance<ISolutionManager>(), ServiceLocator.GetInstance<IVsPackageManagerFactory>(), ServiceLocator.GetInstance<IRecentPackageRepository>(), ServiceLocator.GetInstance<IHttpClientEvents>(), ServiceLocator.GetInstance<IProductUpdateService>()) { } public GetPackageCommand(IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, ISolutionManager solutionManager, IVsPackageManagerFactory packageManagerFactory, IPackageRepository recentPackagesRepository, IHttpClientEvents httpClientEvents, IProductUpdateService productUpdateService) : base(solutionManager, packageManagerFactory, httpClientEvents) { if (repositoryFactory == null) { throw new ArgumentNullException("repositoryFactory"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } if (recentPackagesRepository == null) { throw new ArgumentNullException("recentPackagesRepository"); } _repositoryFactory = repositoryFactory; _packageSourceProvider = packageSourceProvider; _recentPackagesRepository = recentPackagesRepository; _productUpdateService = productUpdateService; } [Parameter(Position = 0)] [ValidateNotNullOrEmpty] public string Filter { get; set; } [Parameter(Position = 1, ParameterSetName = "Remote")] [Parameter(Position = 1, ParameterSetName = "Updates")] [ValidateNotNullOrEmpty] public string Source { get; set; } [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Project")] [ValidateNotNullOrEmpty] public string ProjectName { get; set; } [Parameter(Mandatory = true, ParameterSetName = "Remote")] [Alias("Online", "Remote")] public SwitchParameter ListAvailable { get; set; } [Parameter(Mandatory = true, ParameterSetName = "Updates")] public SwitchParameter Updates { get; set; } [Parameter(Mandatory = true, ParameterSetName = "Recent")] public SwitchParameter Recent { get; set; } [Parameter(ParameterSetName = "Remote")] [Parameter(ParameterSetName = "Recent")] [Parameter(ParameterSetName = "Updates")] public SwitchParameter AllVersions { get; set; } [Parameter(ParameterSetName = "Remote")] [Parameter(ParameterSetName = "Updates")] [Alias("Prerelease")] public SwitchParameter IncludePrerelease { get; set; } [Parameter] [ValidateRange(0, Int32.MaxValue)] public int First { get { return _firstValue; } set { _firstValue = value; _firstValueSpecified = true; } } [Parameter] [ValidateRange(0, Int32.MaxValue)] public int Skip { get; set; } /// <summary> /// Determines if local repository are not needed to process this command /// </summary> private bool UseRemoteSourceOnly { get { return ListAvailable.IsPresent || (!String.IsNullOrEmpty(Source) && !Updates.IsPresent) || Recent.IsPresent; } } /// <summary> /// Determines if a remote repository will be used to process this command. /// </summary> private bool UseRemoteSource { get { return ListAvailable.IsPresent || Updates.IsPresent || !String.IsNullOrEmpty(Source) || Recent.IsPresent; } } protected virtual bool CollapseVersions { get { return !AllVersions.IsPresent && (ListAvailable || Recent); } } private IProjectManager GetProjectManager(string projectName) { Project project = SolutionManager.GetProject(projectName); if (project == null) { ErrorHandler.ThrowNoCompatibleProjectsTerminatingError(); } IProjectManager projectManager = PackageManager.GetProjectManager(project); Debug.Assert(projectManager != null); return projectManager; } protected override void ProcessRecordCore() { if (!UseRemoteSourceOnly && !SolutionManager.IsSolutionOpen) { ErrorHandler.ThrowSolutionNotOpenTerminatingError(); } IPackageRepository repository; if (UseRemoteSource) { repository = GetRemoteRepository(); } else if (!String.IsNullOrEmpty(ProjectName)) { // use project repository when ProjectName is specified repository = GetProjectManager(ProjectName).LocalRepository; } else { repository = PackageManager.LocalRepository; } IQueryable<IPackage> packages; if (Updates.IsPresent) { packages = GetPackagesForUpdate(repository); } else { packages = GetPackages(repository); } // Apply VersionCollapsing, Skip and Take, in that order. var packagesToDisplay = FilterPackages(repository, packages); WritePackages(packagesToDisplay); } protected virtual IEnumerable<IPackage> FilterPackages(IPackageRepository sourceRepository, IQueryable<IPackage> packages) { if (CollapseVersions) { // In the event the client is going up against a v1 feed, do not try to fetch pre release packages since this flag does not exist. if (Recent || (IncludePrerelease && sourceRepository.SupportsPrereleasePackages)) { // For Recent packages, we want to show the highest package even if it is a recent. // Review: We should change this to show both the absolute latest and the latest versions but that requires changes to our collapsing behavior. packages = packages.Where(p => p.IsAbsoluteLatestVersion); } else { packages = packages.Where(p => p.IsLatestVersion); } } if (UseRemoteSourceOnly && _firstValueSpecified) { // Optimization: If First parameter is specified, we'll wrap the IQueryable in a BufferedEnumerable to prevent consuming the entire result set. packages = packages.AsBufferedEnumerable(First * 3).AsQueryable(); } IEnumerable<IPackage> packagesToDisplay = packages.AsEnumerable() .Where(PackageExtensions.IsListed); // When querying a remote source, collapse versions unless AllVersions is specified. // We need to do this as the last step of the Queryable as the filtering occurs on the client. if (CollapseVersions) { // Review: We should perform the Listed check over OData for better perf packagesToDisplay = packagesToDisplay.AsCollapsed(); } if (ListAvailable && !IncludePrerelease) { // If we aren't collapsing versions, and the pre-release flag is not set, only display release versions when displaying from a remote source. // We don't need to filter packages when showing recent packages or installed packages. packagesToDisplay = packagesToDisplay.Where(p => p.IsReleaseVersion()); } packagesToDisplay = packagesToDisplay.Skip(Skip); if (_firstValueSpecified) { packagesToDisplay = packagesToDisplay.Take(First); } return packagesToDisplay; } /// <summary> /// Determines the remote repository to be used based on the state of the solution and the Source parameter /// </summary> private IPackageRepository GetRemoteRepository() { if (!String.IsNullOrEmpty(Source)) { _hasConnectedToHttpSource |= UriHelper.IsHttpSource(Source); // If a Source parameter is explicitly specified, use it return CreateRepositoryFromSource(_repositoryFactory, _packageSourceProvider, Source); } else if (Recent.IsPresent) { return _recentPackagesRepository; } else if (SolutionManager.IsSolutionOpen) { _hasConnectedToHttpSource |= UriHelper.IsHttpSource(_packageSourceProvider); // If the solution is open, retrieve the cached repository instance return PackageManager.SourceRepository; } else if (_packageSourceProvider.ActivePackageSource != null) { _hasConnectedToHttpSource |= UriHelper.IsHttpSource(_packageSourceProvider); // No solution available. Use the repository Url to create a new repository return _repositoryFactory.CreateRepository(_packageSourceProvider.ActivePackageSource.Source); } else { // No active source has been specified. throw new InvalidOperationException(Resources.Cmdlet_NoActivePackageSource); } } protected virtual IQueryable<IPackage> GetPackages(IPackageRepository sourceRepository) { IQueryable<IPackage> packages = null; if (String.IsNullOrEmpty(Filter)) { packages = sourceRepository.GetPackages(); } else { packages = sourceRepository.Search(Filter, IncludePrerelease); } // for recent packages, we want to order by last installed first instead of Id if (!Recent.IsPresent) { packages = packages.OrderBy(p => p.Id); } return packages; } protected virtual IQueryable<IPackage> GetPackagesForUpdate(IPackageRepository sourceRepository) { IPackageRepository localRepository = PackageManager.LocalRepository; var packagesToUpdate = localRepository.GetPackages(); if (!String.IsNullOrEmpty(Filter)) { packagesToUpdate = packagesToUpdate.Find(Filter); } return sourceRepository.GetUpdates(packagesToUpdate, IncludePrerelease, AllVersions).AsQueryable(); } private void WritePackages(IEnumerable<IPackage> packages) { bool hasPackage = false; foreach (var package in packages) { // exit early if ctrl+c pressed if (Stopping) { break; } hasPackage = true; var pso = new PSObject(package); if (!pso.Properties.Any(p => p.Name == "IsUpdate")) { pso.Properties.Add(new PSNoteProperty("IsUpdate", Updates.IsPresent)); } WriteObject(pso); } if (!hasPackage) { if (!UseRemoteSource) { Log(MessageLevel.Info, Resources.Cmdlet_NoPackagesInstalled); } else if (Updates.IsPresent) { Log(MessageLevel.Info, Resources.Cmdlet_NoPackageUpdates); } else if (Recent.IsPresent) { Log(MessageLevel.Info, Resources.Cmdlet_NoRecentPackages); } } } protected override void EndProcessing() { base.EndProcessing(); CheckForNuGetUpdate(); } private void CheckForNuGetUpdate() { if (_productUpdateService != null && _hasConnectedToHttpSource) { _productUpdateService.CheckForAvailableUpdateAsync(); } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.IO; using System.Text; namespace Ctrip.DateFormatter { /// <summary> /// Formats a <see cref="DateTime"/> as <c>"HH:mm:ss,fff"</c>. /// </summary> /// <remarks> /// <para> /// Formats a <see cref="DateTime"/> in the format <c>"HH:mm:ss,fff"</c> for example, <c>"15:49:37,459"</c>. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class AbsoluteTimeDateFormatter : IDateFormatter { #region Protected Instance Methods /// <summary> /// Renders the date into a string. Format is <c>"HH:mm:ss"</c>. /// </summary> /// <param name="dateToFormat">The date to render into a string.</param> /// <param name="buffer">The string builder to write to.</param> /// <remarks> /// <para> /// Subclasses should override this method to render the date /// into a string using a precision up to the second. This method /// will be called at most once per second and the result will be /// reused if it is needed again during the same second. /// </para> /// </remarks> virtual protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) { int hour = dateToFormat.Hour; if (hour < 10) { buffer.Append('0'); } buffer.Append(hour); buffer.Append(':'); int mins = dateToFormat.Minute; if (mins < 10) { buffer.Append('0'); } buffer.Append(mins); buffer.Append(':'); int secs = dateToFormat.Second; if (secs < 10) { buffer.Append('0'); } buffer.Append(secs); } #endregion Protected Instance Methods #region Implementation of IDateFormatter /// <summary> /// Renders the date into a string. Format is "HH:mm:ss,fff". /// </summary> /// <param name="dateToFormat">The date to render into a string.</param> /// <param name="writer">The writer to write to.</param> /// <remarks> /// <para> /// Uses the <see cref="FormatDateWithoutMillis"/> method to generate the /// time string up to the seconds and then appends the current /// milliseconds. The results from <see cref="FormatDateWithoutMillis"/> are /// cached and <see cref="FormatDateWithoutMillis"/> is called at most once /// per second. /// </para> /// <para> /// Sub classes should override <see cref="FormatDateWithoutMillis"/> /// rather than <see cref="FormatDate"/>. /// </para> /// </remarks> virtual public void FormatDate(DateTime dateToFormat, TextWriter writer) { // Calculate the current time precise only to the second long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond)); string timeString = null; // Compare this time with the stored last time // If we are in the same second then append // the previously calculated time string if (s_lastTimeToTheSecond != currentTimeToTheSecond) { s_lastTimeStrings.Clear(); } else { timeString = (string) s_lastTimeStrings[GetType()]; } if (timeString == null) { // lock so that only one thread can use the buffer and // update the s_lastTimeToTheSecond and s_lastTimeStrings // PERF: Try removing this lock and using a new StringBuilder each time lock(s_lastTimeBuf) { timeString = (string) s_lastTimeStrings[GetType()]; if (timeString == null) { // We are in a new second. s_lastTimeBuf.Length = 0; // Calculate the new string for this second FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); // Render the string buffer to a string timeString = s_lastTimeBuf.ToString(); #if NET_1_1 // Ensure that the above string is written into the variable NOW on all threads. // This is only required on multiprocessor machines with weak memeory models System.Threading.Thread.MemoryBarrier(); #endif // Store the time as a string (we only have to do this once per second) s_lastTimeStrings[GetType()] = timeString; s_lastTimeToTheSecond = currentTimeToTheSecond; } } } writer.Write(timeString); // Append the current millisecond info writer.Write(','); int millis = dateToFormat.Millisecond; if (millis < 100) { writer.Write('0'); } if (millis < 10) { writer.Write('0'); } writer.Write(millis); } #endregion Implementation of IDateFormatter #region Public Static Fields /// <summary> /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is <b>ABSOLUTE</b>. /// </summary> public const string AbsoluteTimeDateFormat = "ABSOLUTE"; /// <summary> /// String constant used to specify DateTimeDateFormat in layouts. Current value is <b>DATE</b>. /// </summary> public const string DateAndTimeDateFormat = "DATE"; /// <summary> /// String constant used to specify ISO8601DateFormat in layouts. Current value is <b>ISO8601</b>. /// </summary> public const string Iso8601TimeDateFormat = "ISO8601"; #endregion Public Static Fields #region Private Static Fields /// <summary> /// Last stored time with precision up to the second. /// </summary> private static long s_lastTimeToTheSecond = 0; /// <summary> /// Last stored time with precision up to the second, formatted /// as a string. /// </summary> private static StringBuilder s_lastTimeBuf = new StringBuilder(); /// <summary> /// Last stored time with precision up to the second, formatted /// as a string. /// </summary> private static Hashtable s_lastTimeStrings = new Hashtable(); #endregion Private Static Fields } }
/* Copyright (c) 2006 Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Xml; using System.Xml.Schema; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using PHP.Core; namespace PHP.Library.Xml { /// <summary> /// DOM entity. /// </summary> [ImplementsType] public partial class DOMEntity : DOMNode { #region Fields and Properties protected internal XmlEntity XmlEntity { get { return (XmlEntity)XmlNode; } set { XmlNode = value; } } /// <summary> /// Returns the type of the node (<see cref="NodeType.Entity"/>). /// </summary> [PhpVisible] public override object nodeType { get { return (int)NodeType.Entity; } } /// <summary> /// Returns the public identifier of this entity. /// </summary> [PhpVisible] public string publicId { get { return XmlEntity.PublicId; } } /// <summary> /// Returns the system identifier of this entity. /// </summary> [PhpVisible] public string systemId { get { return XmlEntity.SystemId; } } /// <summary> /// Returns the name of the optional NDATA attribute. /// </summary> [PhpVisible] public string notationName { get { return XmlEntity.NotationName; } } /// <summary> /// Always returns <B>null</B> as in PHP 5.1.6. /// </summary> [PhpVisible] public string actualEncoding { get { return null; } set { } } /// <summary> /// Always returns <B>null</B> as in PHP 5.1.6. /// </summary> [PhpVisible] public string encoding { get { return null; } set { } } /// <summary> /// Always returns <B>null</B> as in PHP 5.1.6. /// </summary> [PhpVisible] public string version { get { return null; } set { } } #endregion #region Construction public DOMEntity() : base(ScriptContext.CurrentContext, true) { } internal DOMEntity(XmlEntity/*!*/ xmlEntity) : base(ScriptContext.CurrentContext, true) { this.XmlEntity = xmlEntity; } protected override PHP.Core.Reflection.DObject CloneObjectInternal(PHP.Core.Reflection.DTypeDesc caller, ScriptContext context, bool deepCopyFields) { if (IsAssociated) return new DOMEntity(XmlEntity); else return new DOMEntity(); } #endregion } /// <summary> /// DOM entity reference. /// </summary> [ImplementsType] public partial class DOMEntityReference : DOMNode { #region Fields and Properties protected internal XmlEntityReference XmlEntityReference { get { return (XmlEntityReference)XmlNode; } set { XmlNode = value; } } private string _name; /// <summary> /// Returns the name of the entity reference. /// </summary> [PhpVisible] public override string nodeName { get { return (IsAssociated ? base.nodeName : _name); } } /// <summary> /// Returns <B>null</B>. /// </summary> [PhpVisible] public override object nodeValue { get { return null; } set { } } /// <summary> /// Returns <B>null</B>. /// </summary> [PhpVisible] public override string namespaceURI { get { return null; } } /// <summary> /// Returns the type of the node (<see cref="NodeType.EntityReference"/>). /// </summary> [PhpVisible] public override object nodeType { get { return (int)NodeType.EntityReference; } } #endregion #region Construction public DOMEntityReference() : base(ScriptContext.CurrentContext, true) { } internal DOMEntityReference(XmlEntityReference/*!*/ xmlEntityReference) : base(ScriptContext.CurrentContext, true) { this.XmlEntityReference = xmlEntityReference; } protected override PHP.Core.Reflection.DObject CloneObjectInternal(PHP.Core.Reflection.DTypeDesc caller, ScriptContext context, bool deepCopyFields) { if (IsAssociated) return new DOMEntityReference(XmlEntityReference); else { DOMEntityReference copy = new DOMEntityReference(); copy.__construct(this._name); return copy; } } [PhpVisible] public void __construct(string name) { this._name = name; } #endregion #region Hierarchy protected internal override void Associate(XmlDocument/*!*/ document) { if (!IsAssociated) { XmlEntityReference = document.CreateEntityReference(_name); } } #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.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class FusionAssemblyIdentity { [Flags] internal enum ASM_DISPLAYF { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PUBLIC_KEY = 0x08, CUSTOM = 0x10, PROCESSORARCHITECTURE = 0x20, LANGUAGEID = 0x40, RETARGET = 0x80, CONFIG_MASK = 0x100, MVID = 0x200, CONTENT_TYPE = 0x400, FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE } internal enum PropertyId { PUBLIC_KEY = 0, // 0 PUBLIC_KEY_TOKEN, // 1 HASH_VALUE, // 2 NAME, // 3 MAJOR_VERSION, // 4 MINOR_VERSION, // 5 BUILD_NUMBER, // 6 REVISION_NUMBER, // 7 CULTURE, // 8 PROCESSOR_ID_ARRAY, // 9 OSINFO_ARRAY, // 10 HASH_ALGID, // 11 ALIAS, // 12 CODEBASE_URL, // 13 CODEBASE_LASTMOD, // 14 NULL_PUBLIC_KEY, // 15 NULL_PUBLIC_KEY_TOKEN, // 16 CUSTOM, // 17 NULL_CUSTOM, // 18 MVID, // 19 FILE_MAJOR_VERSION, // 20 FILE_MINOR_VERSION, // 21 FILE_BUILD_NUMBER, // 22 FILE_REVISION_NUMBER, // 23 RETARGET, // 24 SIGNATURE_BLOB, // 25 CONFIG_MASK, // 26 ARCHITECTURE, // 27 CONTENT_TYPE, // 28 MAX_PARAMS // 29 } private static class CANOF { public const uint PARSE_DISPLAY_NAME = 0x1; public const uint SET_DEFAULT_VALUES = 0x2; } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal unsafe interface IAssemblyName { void SetProperty(PropertyId id, void* data, uint size); [PreserveSig] int GetProperty(PropertyId id, void* data, ref uint size); [PreserveSig] int Finalize(); [PreserveSig] int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); [PreserveSig] int __BindToObject(/*...*/); [PreserveSig] int __GetName(/*...*/); [PreserveSig] int GetVersion(out uint versionHi, out uint versionLow); [PreserveSig] int IsEqual(IAssemblyName pName, uint dwCmpFlags); [PreserveSig] int Clone(out IAssemblyName pName); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] internal interface IApplicationContext { } // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. // Wrap all calls to this with a lock. private static readonly object s_assemblyIdentityGate = new object(); private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) { lock (s_assemblyIdentityGate) { return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); } } [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)]string szAssemblyName, uint dwFlags, IntPtr pvReserved); private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) { int hr; uint characterCountIncludingTerminator = 0; hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); if (hr == 0) { return String.Empty; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; fixed (byte* p = data) { hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); } } internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) { int hr; uint size = 0; hr = nameObject.GetProperty(propertyId, null, ref size); if (hr == 0) { return null; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)size]; fixed (byte* p = data) { hr = nameObject.GetProperty(propertyId, p, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } } return data; } internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) { byte[] data = GetPropertyBytes(nameObject, propertyId); if (data == null) { return null; } fixed (byte* p = data) { return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); } } internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId) { Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY); uint size = 0; int hr = nameObject.GetProperty(propertyId, null, ref size); return hr == 0; } internal static unsafe Version GetVersion(IAssemblyName nameObject) { uint hi, lo; int hr = nameObject.GetVersion(out hi, out lo); if (hr != 0) { Debug.Assert(hr == FUSION_E_INVALID_NAME); return null; } return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); } internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts) { uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION); uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION); uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER); uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER); parts = 0; if (major != null) { parts |= AssemblyIdentityParts.VersionMajor; } if (minor != null) { parts |= AssemblyIdentityParts.VersionMinor; } if (build != null) { parts |= AssemblyIdentityParts.VersionBuild; } if (revision != null) { parts |= AssemblyIdentityParts.VersionRevision; } return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0)); } internal static byte[] GetPublicKeyToken(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN)) { return Array.Empty<byte>(); } return null; } internal static byte[] GetPublicKey(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY)) { return Array.Empty<byte>(); } return null; } internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) { uint result; uint size = sizeof(uint); int hr = nameObject.GetProperty(propertyId, &result, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } if (size == 0) { return null; } return result; } internal static string GetName(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.NAME); } internal static string GetCulture(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.CULTURE); } internal static AssemblyContentType GetContentType(IAssemblyName nameObject) { return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0); } internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) { return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); } internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject) { AssemblyNameFlags result = 0; uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0; if (retarget != 0) { result |= AssemblyNameFlags.Retargetable; } return result; } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { Debug.Assert(data.IndexOf('\0') == -1); fixed (char* p = data) { Debug.Assert(p[data.Length] == '\0'); // size is in bytes, include trailing \0 character: nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { fixed (byte* p = data) { nameObject.SetProperty(propertyId, p, (uint)data.Length); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data) { nameObject.SetProperty(propertyId, &data, sizeof(ushort)); } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data) { nameObject.SetProperty(propertyId, &data, sizeof(uint)); } private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value) { // An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property. if (value != null && value.Length == 0) { nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0); } else { SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value); } } /// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled. /// </summary> /// <returns> /// Assembly name with Version, Culture and PublicKeyToken components filled in: /// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX". /// In addition Retargetable flag and ContentType are set. /// </returns> internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject) { if (nameObject == null) { return null; } AssemblyNameFlags flags = GetFlags(nameObject); byte[] publicKey = GetPublicKey(nameObject); bool hasPublicKey = publicKey != null && publicKey.Length != 0; AssemblyIdentityParts versionParts; return new AssemblyIdentity( GetName(nameObject), GetVersion(nameObject, out versionParts), GetCulture(nameObject) ?? "", (hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(), hasPublicKey: hasPublicKey, isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0, contentType: GetContentType(nameObject)); } /// <summary> /// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>. /// </summary> internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) { if (name == null) { return null; } IAssemblyName result; Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero)); string assemblyName = name.Name; if (assemblyName != null) { if (assemblyName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif WORKSPACE_DESKTOP throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.NAME, assemblyName); } if (name.Version != null) { SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major)); SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor)); SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build)); SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision)); } string cultureName = name.CultureName; if (cultureName != null) { if (cultureName.IndexOf('\0') >= 0) { #if SCRIPTING throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidCharactersInAssemblyName, nameof(name)); #elif WORKSPACE_DESKTOP throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_characters_in_assembly_name, nameof(name)); #else throw new ArgumentException(Microsoft.CodeAnalysis.CodeAnalysisResources.InvalidCharactersInAssemblyName, nameof(name)); #endif } SetProperty(result, PropertyId.CULTURE, cultureName); } if (name.Flags == AssemblyNameFlags.Retargetable) { SetProperty(result, PropertyId.RETARGET, 1U); } if (name.ContentType != AssemblyContentType.Default) { SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType); } byte[] token = name.GetPublicKeyToken(); SetPublicKeyToken(result, token); return result; } /// <summary> /// Creates <see cref="IAssemblyName"/> object by parsing given display name. /// </summary> internal static IAssemblyName ToAssemblyNameObject(string displayName) { // CLR doesn't handle \0 in the display name well: if (displayName.IndexOf('\0') >= 0) { return null; } Debug.Assert(displayName != null); IAssemblyName result; int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); if (hr != 0) { return null; } Debug.Assert(result != null); return result; } /// <summary> /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. /// All candidates are assumed to have the same name and must include versions and cultures. /// </summary> internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt) { IAssemblyName bestCandidate = null; Version bestVersion = null; string bestCulture = null; foreach (var candidate in candidates) { if (bestCandidate != null) { Version candidateVersion = GetVersion(candidate); Debug.Assert(candidateVersion != null); if (bestVersion == null) { bestVersion = GetVersion(bestCandidate); Debug.Assert(bestVersion != null); } int cmp = bestVersion.CompareTo(candidateVersion); if (cmp == 0) { if (preferredCultureOpt != null) { string candidateCulture = GetCulture(candidate); Debug.Assert(candidateCulture != null); if (bestCulture == null) { bestCulture = GetCulture(candidate); Debug.Assert(bestCulture != null); } // we have exactly the preferred culture or // we have neutral culture and the best candidate's culture isn't the preferred one: if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) { bestCandidate = candidate; bestVersion = candidateVersion; bestCulture = candidateCulture; } } } else if (cmp < 0) { bestCandidate = candidate; bestVersion = candidateVersion; } } else { bestCandidate = candidate; } } return bestCandidate; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Serilog.Sinks.Amazon.Kinesis.Logging; namespace Serilog.Sinks.Amazon.Kinesis { internal abstract class HttpLogShipperBase<TRecord, TResponse> : IDisposable { const long ERROR_SHARING_VIOLATION = 0x20; const long ERROR_LOCK_VIOLATION = 0x21; ILog _logger; protected ILog Logger => _logger ?? (_logger = LogProvider.GetLogger(GetType())); protected readonly int _batchPostingLimit; protected readonly string _bookmarkFilename; protected readonly string _candidateSearchPath; protected readonly string _logFolder; readonly TimeSpan _period; protected readonly object _stateLock = new object(); protected readonly string _streamName; readonly Timer _timer; protected volatile bool _unloading; protected HttpLogShipperBase(KinesisSinkStateBase state) { _period = state.SinkOptions.Period; _timer = new Timer(s => OnTick()); _batchPostingLimit = state.SinkOptions.BatchPostingLimit; _streamName = state.SinkOptions.StreamName; _bookmarkFilename = Path.GetFullPath(state.SinkOptions.BufferBaseFilename + ".bookmark"); _logFolder = Path.GetDirectoryName(_bookmarkFilename); _candidateSearchPath = Path.GetFileName(state.SinkOptions.BufferBaseFilename) + "*.json"; Logger.InfoFormat("Candidate search path is {0}", _candidateSearchPath); Logger.InfoFormat("Log folder is {0}", _logFolder); AppDomain.CurrentDomain.DomainUnload += OnAppDomainUnloading; AppDomain.CurrentDomain.ProcessExit += OnAppDomainUnloading; SetTimer(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { Dispose(true); } protected abstract TRecord PrepareRecord(byte[] bytes); protected abstract TResponse SendRecords(List<TRecord> records, out bool successful); protected abstract void HandleError(TResponse response, int originalRecordCount); public event EventHandler<LogSendErrorEventArgs> LogSendError; void OnAppDomainUnloading(object sender, EventArgs e) { CloseAndFlush(); } protected void OnLogSendError(LogSendErrorEventArgs e) { var handler = LogSendError; if (handler != null) { handler(this, e); } } void CloseAndFlush() { lock (_stateLock) { if (_unloading) return; _unloading = true; } AppDomain.CurrentDomain.DomainUnload -= OnAppDomainUnloading; AppDomain.CurrentDomain.ProcessExit -= OnAppDomainUnloading; var wh = new ManualResetEvent(false); if (_timer.Dispose(wh)) wh.WaitOne(); OnTick(); } /// <summary> /// Free resources held by the sink. /// </summary> /// <param name="disposing"> /// If true, called because the object is being disposed; if false, /// the object is being disposed from the finalizer. /// </param> protected virtual void Dispose(bool disposing) { if (!disposing) return; CloseAndFlush(); } protected void SetTimer() { // Note, called under _stateLock #if NET40 _timer.Change(_period, TimeSpan.FromDays(30)); #else _timer.Change(_period, Timeout.InfiniteTimeSpan); #endif } void OnTick() { try { int count; do { count = 0; // Locking the bookmark ensures that though there may be multiple instances of this // class running, only one will ship logs at a time. using (var bookmark = File.Open(_bookmarkFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { long nextLineBeginsAtOffset; string currentFilePath; TryReadBookmark(bookmark, out nextLineBeginsAtOffset, out currentFilePath); Logger.TraceFormat("Bookmark is currently at offset {0} in '{1}'", nextLineBeginsAtOffset, currentFilePath); var fileSet = GetFileSet(); if (currentFilePath == null || !File.Exists(currentFilePath)) { nextLineBeginsAtOffset = 0; currentFilePath = fileSet.FirstOrDefault(); Logger.InfoFormat("Current log file is {0}", currentFilePath); if (currentFilePath == null) continue; } var records = new List<TRecord>(); long startingOffset; using (var current = File.Open(currentFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { startingOffset = current.Position = nextLineBeginsAtOffset; string nextLine; while (count < _batchPostingLimit && TryReadLine(current, ref nextLineBeginsAtOffset, out nextLine)) { ++count; var bytes = Encoding.UTF8.GetBytes(nextLine); var record = PrepareRecord(bytes); records.Add(record); } } if (count > 0) { bool successful; var response = SendRecords(records, out successful); if (!successful) { HandleError(response, records.Count); } else { // Advance the bookmark only if we successfully wrote Logger.TraceFormat("Advancing bookmark from '{0}' to '{1}'", startingOffset, nextLineBeginsAtOffset); WriteBookmark(bookmark, nextLineBeginsAtOffset, currentFilePath); } } else { Logger.TraceFormat("Found no records to process"); // Only advance the bookmark if no other process has the // current file locked, and its length is as we found it. var bufferedFilesCount = fileSet.Length; var isProcessingFirstFile = fileSet.First().Equals(currentFilePath, StringComparison.InvariantCultureIgnoreCase); var weAreAtEndOfTheFile = WeAreAtEndOfTheFile(currentFilePath, nextLineBeginsAtOffset); Logger.TraceFormat("BufferedFilesCount: {0}; IsProcessingFirstFile: {1}; WeAreAtEndOfTheFile: {2}", bufferedFilesCount, isProcessingFirstFile, weAreAtEndOfTheFile); if (bufferedFilesCount == 2 && isProcessingFirstFile && weAreAtEndOfTheFile) { Logger.TraceFormat("Advancing bookmark from '{0}' to '{1}'", currentFilePath, fileSet[1]); WriteBookmark(bookmark, 0, fileSet[1]); } if (bufferedFilesCount > 2) { // Once there's a third file waiting to ship, we do our // best to move on, though a lock on the current file // will delay this. Logger.InfoFormat("Deleting '{0}'", fileSet[0]); File.Delete(fileSet[0]); } } } } while (count == _batchPostingLimit); } catch (IOException ex) { long win32ErrorCode = GetWin32ErrorCode(ex); if (win32ErrorCode == ERROR_SHARING_VIOLATION || win32ErrorCode == ERROR_LOCK_VIOLATION) { Logger.TraceException("Swallowed I/O exception", ex); } else { Logger.ErrorException("Unexpected I/O exception", ex); } } catch (Exception ex) { Logger.ErrorException("Exception while emitting periodic batch", ex); OnLogSendError(new LogSendErrorEventArgs(string.Format("Error in shipping logs to '{0}' stream)", _streamName), ex)); } finally { lock (_stateLock) { if (!_unloading) SetTimer(); } } } private long GetWin32ErrorCode(IOException ex) { #if NET40 long win32ErrorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex) & 0xFFFF; #else long win32ErrorCode = ex.HResult & 0xFFFF; #endif return win32ErrorCode; } protected bool WeAreAtEndOfTheFile(string file, long nextLineBeginsAtOffset) { try { using (var fileStream = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { return fileStream.Length <= nextLineBeginsAtOffset; } } catch (IOException ex) { long win32ErrorCode = GetWin32ErrorCode(ex); if (win32ErrorCode == ERROR_SHARING_VIOLATION || win32ErrorCode == ERROR_LOCK_VIOLATION) { Logger.TraceException("Swallowed I/O exception while testing locked status of {0}", ex, file); } else { Logger.ErrorException("Unexpected I/O exception while testing locked status of {0}", ex, file); } } catch (Exception ex) { Logger.ErrorException("Unexpected exception while testing locked status of {0}", ex, file); } return false; } protected static void WriteBookmark(FileStream bookmark, long nextLineBeginsAtOffset, string currentFile) { #if NET40 // Important not to dispose this StreamReader as the stream must remain open. var writer = new StreamWriter(bookmark); writer.WriteLine("{0}:::{1}", nextLineBeginsAtOffset, currentFile); writer.Flush(); #else using (var writer = new StreamWriter(bookmark)) { writer.WriteLine("{0}:::{1}", nextLineBeginsAtOffset, currentFile); } #endif } // It would be ideal to chomp whitespace here, but not required. protected static bool TryReadLine(System.IO.Stream current, ref long nextStart, out string nextLine) { var includesBom = nextStart == 0; if (current.Length <= nextStart) { nextLine = null; return false; } current.Position = nextStart; #if NET40 // Important not to dispose this StreamReader as the stream must remain open. var reader = new StreamReader(current, Encoding.UTF8, false, 128); nextLine = reader.ReadLine(); #else using (var reader = new StreamReader(current, Encoding.UTF8, false, 128, true)) { nextLine = reader.ReadLine(); } #endif if (nextLine == null) return false; nextStart += Encoding.UTF8.GetByteCount(nextLine) + Encoding.UTF8.GetByteCount(Environment.NewLine); if (includesBom) nextStart += 3; return true; } protected static void TryReadBookmark(System.IO.Stream bookmark, out long nextLineBeginsAtOffset, out string currentFile) { nextLineBeginsAtOffset = 0; currentFile = null; if (bookmark.Length != 0) { string current; #if NET40 // Important not to dispose this StreamReader as the stream must remain open. var reader = new StreamReader(bookmark, Encoding.UTF8, false, 128); current = reader.ReadLine(); #else using (var reader = new StreamReader(bookmark, Encoding.UTF8, false, 128, true)) { current = reader.ReadLine(); } #endif if (current != null) { bookmark.Position = 0; var parts = current.Split(new[] {":::"}, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 2) { nextLineBeginsAtOffset = long.Parse(parts[0]); currentFile = parts[1]; } } } } protected string[] GetFileSet() { var fileSet = Directory.GetFiles(_logFolder, _candidateSearchPath) .OrderBy(n => n) .ToArray(); var fileSetDesc = string.Join(";", fileSet); Logger.InfoFormat("FileSet contains: {0}", fileSetDesc); return fileSet; } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Globalization; using System.Linq; using NLog.Layouts; namespace NLog.Config { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using JetBrains.Annotations; using NLog.Common; using NLog.Internal; using NLog.Targets; /// <summary> /// Keeps logging configuration and provides simple API /// to modify it. /// </summary> public class LoggingConfiguration { private readonly IDictionary<string, Target> targets = new Dictionary<string, Target>(StringComparer.OrdinalIgnoreCase); private object[] configItems; /// <summary> /// Variables defined in xml or in API. name is case case insensitive. /// </summary> private readonly Dictionary<string, SimpleLayout> variables = new Dictionary<string, SimpleLayout>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Initializes a new instance of the <see cref="LoggingConfiguration" /> class. /// </summary> public LoggingConfiguration() { this.LoggingRules = new List<LoggingRule>(); } /// <summary> /// Use the old exception log handling of NLog 3.0? /// </summary> [Obsolete("This option will be removed in NLog 5")] public bool ExceptionLoggingOldStyle { get; set; } /// <summary> /// Gets the variables defined in the configuration. /// </summary> public IDictionary<string, SimpleLayout> Variables { get { return variables; } } /// <summary> /// Gets a collection of named targets specified in the configuration. /// </summary> /// <returns> /// A list of named targets. /// </returns> /// <remarks> /// Unnamed targets (such as those wrapped by other targets) are not returned. /// </remarks> public ReadOnlyCollection<Target> ConfiguredNamedTargets { get { return new List<Target>(this.targets.Values).AsReadOnly(); } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// </summary> public virtual IEnumerable<string> FileNamesToWatch { get { return new string[0]; } } /// <summary> /// Gets the collection of logging rules. /// </summary> public IList<LoggingRule> LoggingRules { get; private set; } /// <summary> /// Gets or sets the default culture info to use as <see cref="LogEventInfo.FormatProvider"/>. /// </summary> /// <value> /// Specific culture info or null to use <see cref="CultureInfo.CurrentCulture"/> /// </value> [CanBeNull] public CultureInfo DefaultCultureInfo { get; set; } /// <summary> /// Gets all targets. /// </summary> public ReadOnlyCollection<Target> AllTargets { get { return this.configItems.OfType<Target>().ToList().AsReadOnly(); } } /// <summary> /// Registers the specified target object. The name of the target is read from <see cref="Target.Name"/>. /// </summary> /// <param name="target"> /// The target object with a non <see langword="null"/> <see cref="Target.Name"/> /// </param> /// <exception cref="ArgumentNullException">when <paramref name="target"/> is <see langword="null"/></exception> public void AddTarget([NotNull] Target target) { if (target == null) throw new ArgumentNullException("target"); AddTarget(target.Name, target); } /// <summary> /// Registers the specified target object under a given name. /// </summary> /// <param name="name"> /// Name of the target. /// </param> /// <param name="target"> /// The target object. /// </param> public void AddTarget(string name, Target target) { if (name == null) { throw new ArgumentException("Target name cannot be null", "name"); } InternalLogger.Debug("Registering target {0}: {1}", name, target.GetType().FullName); this.targets[name] = target; } /// <summary> /// Finds the target with the specified name. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <returns> /// Found target or <see langword="null"/> when the target is not found. /// </returns> public Target FindTargetByName(string name) { Target value; if (!this.targets.TryGetValue(name, out value)) { return null; } return value; } /// <summary> /// Finds the target with the specified name and specified type. /// </summary> /// <param name="name"> /// The name of the target to be found. /// </param> /// <typeparam name="TTarget">Type of the target</typeparam> /// <returns> /// Found target or <see langword="null"/> when the target is not found of not of type <typeparamref name="TTarget"/> /// </returns> public TTarget FindTargetByName<TTarget>(string name) where TTarget : Target { return FindTargetByName(name) as TTarget; } /// <summary> /// Called by LogManager when one of the log configuration files changes. /// </summary> /// <returns> /// A new instance of <see cref="LoggingConfiguration"/> that represents the updated configuration. /// </returns> public virtual LoggingConfiguration Reload() { return this; } /// <summary> /// Removes the specified named target. /// </summary> /// <param name="name"> /// Name of the target. /// </param> public void RemoveTarget(string name) { this.targets.Remove(name); } /// <summary> /// Installs target-specific objects on current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Installation typically runs with administrative permissions. /// </remarks> public void Install(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in this.configItems.OfType<IInstallable>()) { installationContext.Info("Installing '{0}'", installable); try { installable.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("'{0}' installation failed: {1}.", installable, exception); } } } /// <summary> /// Uninstalls target-specific objects from current system. /// </summary> /// <param name="installationContext">The installation context.</param> /// <remarks> /// Uninstallation typically runs with administrative permissions. /// </remarks> public void Uninstall(InstallationContext installationContext) { if (installationContext == null) { throw new ArgumentNullException("installationContext"); } this.InitializeAll(); foreach (IInstallable installable in this.configItems.OfType<IInstallable>()) { installationContext.Info("Uninstalling '{0}'", installable); try { installable.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installable); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } installationContext.Error("Uninstallation of '{0}' failed: {1}.", installable, exception); } } } /// <summary> /// Closes all targets and releases any unmanaged resources. /// </summary> internal void Close() { InternalLogger.Debug("Closing logging configuration..."); foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>()) { InternalLogger.Trace("Closing {0}", initialize); try { initialize.Close(); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Warn("Exception while closing {0}", exception); } } InternalLogger.Debug("Finished closing logging configuration."); } /// <summary> /// Log to the internal (NLog) logger the information about the <see cref="Target"/> and <see /// cref="LoggingRule"/> associated with this <see cref="LoggingConfiguration"/> instance. /// </summary> /// <remarks> /// The information are only recorded in the internal logger if Debug level is enabled, otherwise nothing is /// recorded. /// </remarks> internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); foreach (Target target in this.targets.Values) { InternalLogger.Debug("{0}", target); } InternalLogger.Debug("Rules:"); foreach (LoggingRule rule in this.LoggingRules) { InternalLogger.Debug("{0}", rule); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } /// <summary> /// Flushes any pending log messages on all appenders. /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> internal void FlushAllTargets(AsyncContinuation asyncContinuation) { var uniqueTargets = new List<Target>(); foreach (var rule in this.LoggingRules) { foreach (var t in rule.Targets) { if (!uniqueTargets.Contains(t)) { uniqueTargets.Add(t); } } } AsyncHelpers.ForEachItemInParallel(uniqueTargets, asyncContinuation, (target, cont) => target.Flush(cont)); } /// <summary> /// Validates the configuration. /// </summary> internal void ValidateConfig() { var roots = new List<object>(); foreach (LoggingRule r in this.LoggingRules) { roots.Add(r); } foreach (Target target in this.targets.Values) { roots.Add(target); } this.configItems = ObjectGraphScanner.FindReachableObjects<object>(roots.ToArray()); // initialize all config items starting from most nested first // so that whenever the container is initialized its children have already been InternalLogger.Info("Found {0} configuration items", this.configItems.Length); foreach (object o in this.configItems) { PropertyHelper.CheckRequiredParameters(o); } } internal void InitializeAll() { this.ValidateConfig(); foreach (ISupportsInitialize initialize in this.configItems.OfType<ISupportsInitialize>().Reverse()) { InternalLogger.Trace("Initializing {0}", initialize); try { initialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error during initialization of " + initialize, exception); } } } } internal void EnsureInitialized() { this.InitializeAll(); } } }
using System; using System.IO; using NUnit.Framework; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Asn1.Tests { [TestFixture] public class Asn1SequenceParserTest { private static readonly byte[] seqData = Hex.Decode("3006020100060129"); private static readonly byte[] nestedSeqData = Hex.Decode("300b0201000601293003020101"); private static readonly byte[] expTagSeqData = Hex.Decode("a1083006020100060129"); private static readonly byte[] implTagSeqData = Hex.Decode("a106020100060129"); private static readonly byte[] nestedSeqExpTagData = Hex.Decode("300d020100060129a1053003020101"); private static readonly byte[] nestedSeqImpTagData = Hex.Decode("300b020100060129a103020101"); private static readonly byte[] berSeqData = Hex.Decode("30800201000601290000"); private static readonly byte[] berDerNestedSeqData = Hex.Decode("308002010006012930030201010000"); private static readonly byte[] berNestedSeqData = Hex.Decode("3080020100060129308002010100000000"); private static readonly byte[] berExpTagSeqData = Hex.Decode("a180308002010006012900000000"); private static readonly byte[] berSeqWithDERNullData = Hex.Decode("308005000201000601290000"); [Test] public void TestDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(seqData, bOut.ToArray()), "basic DER writing test failed."); } [Test] public void TestNestedDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.One)); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqData, bOut.ToArray()), "nested DER writing test failed."); } [Test] public void TestDerExplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, true); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(expTagSeqData, bOut.ToArray()), "explicit tag writing test failed."); } [Test] public void TestDerImplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, false); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(implTagSeqData, bOut.ToArray()), "implicit tag writing test failed."); } [Test] public void TestNestedExplicitTagDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream(), 1, true); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqExpTagData, bOut.ToArray()), "nested explicit tagged DER writing test failed."); } [Test] public void TestNestedImplicitTagDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream(), 1, false); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqImpTagData, bOut.ToArray()), "nested implicit tagged DER writing test failed."); } [Test] public void TestBerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen = new BerSequenceGenerator(bOut); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(berSeqData, bOut.ToArray()), "basic BER writing test failed."); } [Test] public void TestNestedBerDerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen1 = new BerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(berDerNestedSeqData, bOut.ToArray()), "nested BER/DER writing test failed."); } [Test] public void TestNestedBerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen1 = new BerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); BerSequenceGenerator seqGen2 = new BerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(berNestedSeqData, bOut.ToArray()), "nested BER writing test failed."); } [Test] public void TestDerReading() { Asn1StreamParser aIn = new Asn1StreamParser(seqData); Asn1SequenceParser seq = (Asn1SequenceParser)aIn.ReadObject(); int count = 0; Assert.IsNotNull(seq, "null sequence returned"); object o; while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(2, count, "wrong number of objects in sequence"); } private void doTestNestedReading( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o = null; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; case 2: Assert.IsTrue(o is Asn1SequenceParser); Asn1SequenceParser s = (Asn1SequenceParser)o; // NB: Must exhaust the nested parser while (s.ReadObject() != null) { // Ignore } break; } count++; } Assert.AreEqual(3, count, "wrong number of objects in sequence"); } [Test] public void TestNestedDerReading() { doTestNestedReading(nestedSeqData); } [Test] public void TestBerReading() { Asn1StreamParser aIn = new Asn1StreamParser(berSeqData); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o = null; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(2, count, "wrong number of objects in sequence"); } [Test] public void TestNestedBerDerReading() { doTestNestedReading(berDerNestedSeqData); } [Test] public void TestNestedBerReading() { doTestNestedReading(berNestedSeqData); } [Test] public void TestBerExplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen = new BerSequenceGenerator(bOut, 1, true); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(berExpTagSeqData, bOut.ToArray()), "explicit BER tag writing test failed."); } [Test] public void TestSequenceWithDerNullReading() { doTestParseWithNull(berSeqWithDERNullData); } private void doTestParseWithNull( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is Asn1Null); break; case 1: Assert.IsTrue(o is DerInteger); break; case 2: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(3, count, "wrong number of objects in sequence"); } } }
// ---------------------------------------------------------------------------------- // // 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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Net; using System.Net.Cache; using System.Reflection; using System.Text; using System.Threading; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.Service.Gateway; using Microsoft.WindowsAzure.Management.ServiceManagement.Model; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; using Microsoft.WindowsAzure.Management.Utilities.Common; using Microsoft.WindowsAzure.ServiceManagement; [TestClass] public class ScenarioTest : ServiceManagementTest { private string serviceName; string perfFile; [TestInitialize] public void Initialize() { SetTestSettings(); serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); pass = false; testStartTime = DateTime.Now; } /// <summary> /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureQuickVM,Get-AzureVMImage,Get-AzureVM,Get-AzureLocation,Import-AzurePublishSettingsFile,Get-AzureSubscription,Set-AzureSubscription)")] public void NewWindowsAzureQuickVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if(string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureLocation,Test-AzureName ,Get-AzureVMImage,New-AzureQuickVM,Get-AzureVM ,Restart-AzureVM,Stop-AzureVM , Start-AzureVM)")] public void ProvisionLinuxVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSLinuxVM"); string linuxImageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickLinuxVM(OS.Linux, newAzureQuickVMName, serviceName, linuxImageName, "user", password, locationName); // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // TODO: Disabling Stop / start / restart tests for now due to timing isues /* // Stop & start the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.StartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); // Restart the VM vmPowershellCmdlets.StopAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Stopped); vmPowershellCmdlets.RestartAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, newAzureQuickVMSvcName); Assert.AreEqual(vmRoleCtxt.PowerState, VMPowerState.Started.ToString()); * */ // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); //TODO: Need to do proper cleanup of the service // vmPowershellCmdlets.RemoveAzureService(newAzureQuickVMSvcName); // Assert.AreEqual(null, vmPowershellCmdlets.GetAzureService(newAzureQuickVMSvcName)); pass = true; } /// <summary> /// Verify Advanced Provisioning /// </summary> [TestMethod(), TestCategory("BVT"), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureService,New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void AdvancedProvisioning() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureVM1Name = Utilities.GetUniqueShortName(vmNamePrefix); string newAzureVM2Name = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); AzureVMConfigInfo azureVMConfigInfo1 = new AzureVMConfigInfo(newAzureVM1Name, InstanceSize.ExtraSmall, imageName); AzureVMConfigInfo azureVMConfigInfo2 = new AzureVMConfigInfo(newAzureVM2Name, InstanceSize.ExtraSmall, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); AddAzureDataDiskConfig azureDataDiskConfigInfo = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(ProtocolInfo.tcp, 80, 80, "web", "lbweb", 80, ProtocolInfo.http, @"/", null, null); PersistentVMConfigInfo persistentVMConfigInfo1 = new PersistentVMConfigInfo(azureVMConfigInfo1, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVMConfigInfo persistentVMConfigInfo2 = new PersistentVMConfigInfo(azureVMConfigInfo2, azureProvisioningConfig, azureDataDiskConfigInfo, azureEndPointConfigInfo); PersistentVM persistentVM1 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo1); PersistentVM persistentVM2 = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo2); PersistentVM[] VMs = { persistentVM1, persistentVM2 }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureVM1Name, serviceName); vmPowershellCmdlets.RemoveAzureVM(newAzureVM2Name, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM1Name, serviceName)); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureVM2Name, serviceName)); pass = true; } /// <summary> /// Modifying Existing Virtual Machines /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig ,Add-AzureDataDisk ,Add-AzureEndpoint,New-AzureVM)")] public void ModifyingVM() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AzureEndPointConfigInfo azureEndPointConfigInfo = new AzureEndPointConfigInfo(ProtocolInfo.tcp, 1433, 2000, "sql"); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisksAndEndPoint(newAzureQuickVMName, serviceName, dataDiskConfig, azureEndPointConfigInfo); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadWrite, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); vmPowershellCmdlets.GetAzureDataDisk(newAzureQuickVMName, serviceName); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Changes that Require a Reboot /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("priya"), Description("Test the cmdlets (Get-AzureVM,Set-AzureDataDisk ,Update-AzureVM,Set-AzureVMSize)")] public void UpdateAndReboot() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk1", 0); AddAzureDataDiskConfig azureDataDiskConfigInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, 50, "datadisk2", 1); AddAzureDataDiskConfig[] dataDiskConfig = { azureDataDiskConfigInfo1, azureDataDiskConfigInfo2 }; vmPowershellCmdlets.AddVMDataDisks(newAzureQuickVMName, serviceName, dataDiskConfig); SetAzureDataDiskConfig setAzureDataDiskConfig1 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig setAzureDataDiskConfig2 = new SetAzureDataDiskConfig(HostCaching.ReadOnly, 0); SetAzureDataDiskConfig[] diskConfig = { setAzureDataDiskConfig1, setAzureDataDiskConfig2 }; vmPowershellCmdlets.SetVMDataDisks(newAzureQuickVMName, serviceName, diskConfig); SetAzureVMSizeConfig vmSizeConfig = new SetAzureVMSizeConfig(InstanceSize.Medium); vmPowershellCmdlets.SetVMSize(newAzureQuickVMName, serviceName, vmSizeConfig); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureDisk,Remove-AzureVM,Remove-AzureDisk,Get-AzureVMImage)")] public void ManagingDiskImages() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name and Service Name string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. Collection<DiskContext> vmDisks = vmPowershellCmdlets.GetAzureDiskAttachedToRoleName(new[] { newAzureQuickVMName }); // Get-AzureDisk | Where {$_.AttachedTo.RoleName -eq $vmname } foreach (var disk in vmDisks) Console.WriteLine("The disk, {0}, is created", disk.DiskName); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM, {0}, is successfully removed.", newAzureQuickVMName); foreach (var disk in vmDisks) { for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.RemoveAzureDisk(disk.DiskName, true); // Remove-AzureDisk break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The vhd, {0}, is still in the state of being used by the deleted VM", disk.DiskName); Thread.Sleep(120000); continue; } else { Assert.Fail("error during Remove-AzureDisk: {0}", e.ToString()); } } } try { vmPowershellCmdlets.GetAzureDisk(disk.DiskName); // Get-AzureDisk -DiskName (try to get the removed disk.) Console.WriteLine("Disk is not removed: {0}", disk.DiskName); pass = false; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The disk, {0}, is successfully removed.", disk.DiskName); continue; } else { Assert.Fail("Exception: {0}", e.ToString()); } } } pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (New-AzureVMConfig,Add-AzureProvisioningConfig,New-AzureVM,Save-AzureVMImage)")] public void CaptureImagingExportingImportingVMConfig() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a unique VM name string newAzureVMName = Utilities.GetUniqueShortName("PSTestVM"); Console.WriteLine("VM Name: {0}", newAzureVMName); // Create a unique Service Name vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("Service Name: {0}", serviceName); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); // starting the test. AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(newAzureVMName, InstanceSize.Small, imageName); // parameters for New-AzureVMConfig (-Name -InstanceSize -ImageName) AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); // parameters for Add-AzureProvisioningConfig (-Windows -Password) PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM persistentVM = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); // New-AzureVMConfig & Add-AzureProvisioningConfig PersistentVM[] VMs = { persistentVM }; vmPowershellCmdlets.NewAzureVM(serviceName, VMs); // New-AzureVM Console.WriteLine("The VM is successfully created: {0}", persistentVM.RoleName); PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); Assert.AreEqual(vmRoleCtxt.Name, persistentVM.RoleName, true); vmPowershellCmdlets.StopAzureVM(newAzureVMName, serviceName); // Stop-AzureVM for (int i = 0; i < 3; i++) { vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName); if (vmRoleCtxt.InstanceStatus == "StoppedVM") break; else { Console.WriteLine("The status of the VM {0} : {1}", persistentVM.RoleName, vmRoleCtxt.InstanceStatus); Thread.Sleep(120000); } } Assert.AreEqual(vmRoleCtxt.InstanceStatus, "StoppedVM", true); //TODO // RDP //TODO: // Run sysprep and shutdown // Check the status of VM //PersistentVMRoleContext vmRoleCtxt2 = vmPowershellCmdlets.GetAzureVM(newAzureVMName, newAzureSvcName); // Get-AzureVM -Name //Assert.AreEqual(newAzureVMName, vmRoleCtxt2.Name, true); // // Save-AzureVMImage //string newImageName = "newImage"; //string newImageLabel = "newImageLabel"; //string postAction = "Delete"; // Save-AzureVMImage -ServiceName -Name -NewImageName -NewImageLabel -PostCaptureAction //vmPowershellCmdlets.SaveAzureVMImage(newAzureSvcName, newAzureVMName, newImageName, newImageLabel, postAction); // Cleanup vmPowershellCmdlets.RemoveAzureVM(persistentVM.RoleName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(persistentVM.RoleName, serviceName)); } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Export-AzureVM,Remove-AzureVM,Import-AzureVM,New-AzureVM)")] public void ExportingImportingVMConfigAsTemplateforRepeatableUsage() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. string path = ".\\mytestvmconfig1.xml"; PersistentVMRoleContext vmRole = vmPowershellCmdlets.ExportAzureVM(newAzureQuickVMName, serviceName, path); // Export-AzureVM Console.WriteLine("Exporting VM is successfully done: path - {0} Name - {1}", path, vmRole.Name); vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); // Remove-AzureVM Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); Console.WriteLine("The VM is successfully removed: {0}", newAzureQuickVMName); List<PersistentVM> VMs = new List<PersistentVM>(); foreach (var pervm in vmPowershellCmdlets.ImportAzureVM(path)) // Import-AzureVM { VMs.Add(pervm); Console.WriteLine("The VM, {0}, is imported.", pervm.RoleName); } for (int i = 0; i < 3; i++) { try { vmPowershellCmdlets.NewAzureVM(serviceName, VMs.ToArray()); // New-AzureVM Console.WriteLine("All VMs are successfully created."); foreach (var vm in VMs) { Console.WriteLine("created VM: {0}", vm.RoleName); } break; } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("currently in use") && i != 2) { Console.WriteLine("The removed VM is still using the vhd"); Thread.Sleep(120000); continue; } else { Assert.Fail("error during New-AzureVM: {0}", e.ToString()); } } } // Verify PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(newAzureQuickVMName, vmRoleCtxt.Name, true); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "IaaS"), Priority(1), Owner("hylee"), Description("Test the cmdlets (Get-AzureVM,Get-AzureEndpoint,Get-AzureRemoteDesktopFile)")] public void ManagingRDPSSHConnectivity() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Create a new Azure quick VM string newAzureQuickVMName = Utilities.GetUniqueShortName("PSTestVM"); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); // starting the test. PersistentVMRoleContext vmRoleCtxt = vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName); // Get-AzureVM InputEndpointContext inputEndpointCtxt = vmPowershellCmdlets.GetAzureEndPoint(vmRoleCtxt)[0]; // Get-AzureEndpoint Console.WriteLine("InputEndpointContext Name: {0}", inputEndpointCtxt.Name); Console.WriteLine("InputEndpointContext port: {0}", inputEndpointCtxt.Port); Console.WriteLine("InputEndpointContext protocol: {0}", inputEndpointCtxt.Protocol); Assert.AreEqual(inputEndpointCtxt.Name, "RemoteDesktop", true); string path = ".\\myvmconnection.rdp"; vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, serviceName, path, false); // Get-AzureRemoteDesktopFile Console.WriteLine("RDP file is successfully created at: {0}", path); // ToDo: Automate RDP. //vmPowershellCmdlets.GetAzureRemoteDesktopFile(newAzureQuickVMName, newAzureQuickVMSvcName, path, true); // Get-AzureRemoteDesktopFile -Launch Console.WriteLine("Test passed"); // Cleanup vmPowershellCmdlets.RemoveAzureVM(newAzureQuickVMName, serviceName); Assert.AreEqual(null, vmPowershellCmdlets.GetAzureVM(newAzureQuickVMName, serviceName)); pass = true; } /// <summary> /// Basic Provisioning a Virtual Machine /// </summary> [TestMethod(), TestCategory("Scenario"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\packageScenario.csv", "packageScenario#csv", DataAccessMethod.Sequential)] [Ignore] public void DeploymentUpgrade() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); perfFile = @"..\deploymentUpgradeResult.csv"; // Choose the package and config files from local machine string path = Convert.ToString(TestContext.DataRow["path"]); string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); string upgradeConfigName2 = Convert.ToString(TestContext.DataRow["upgradeConfig2"]); var packagePath1 = new FileInfo(@path + packageName); // package with two roles var packagePath2 = new FileInfo(@path + upgradePackageName); // package with one role var configPath1 = new FileInfo(@path + configName); // config with 2 roles, 4 instances each var configPath2 = new FileInfo(@path + upgradeConfigName); // config with 1 role, 2 instances var configPath3 = new FileInfo(@path + upgradeConfigName2); // config with 1 role, 4 instances Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; try { vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); // New deployment to Production DateTime start = DateTime.Now; vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Production, deploymentLabel, deploymentName, false, false); TimeSpan duration = DateTime.Now - start; Uri site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 1000); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Deployment, {0}, {1}", duration, DateTime.Now - start) }); Console.WriteLine("site: {0}", site.ToString()); Console.WriteLine("Time for all instances to become in ready state: {0}", DateTime.Now - start); // Auto-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Auto, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Auto upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Auto Upgrade, {0}, {1}", duration, DateTime.Now - start) }); // Manual-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Manual, packagePath1.FullName, configPath1.FullName); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 0); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 1); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 2); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 3); vmPowershellCmdlets.SetAzureWalkUpgradeDomain(serviceName, DeploymentSlotType.Production, 4); duration = DateTime.Now - start; Console.WriteLine("Manual upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Manual Upgrade, {0}, {1}", duration, DateTime.Now - start) }); // Simulatenous-Upgrade the deployment start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath1.FullName, configPath1.FullName); duration = DateTime.Now - start; Console.WriteLine("Simulatenous upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 8); Console.WriteLine("successfully updated the deployment"); site = Utilities.GetDeploymentAndWaitForReady(serviceName, DeploymentSlotType.Production, 10, 600); System.IO.File.AppendAllLines(perfFile, new string[] { String.Format("Simulatenous Upgrade, {0}, {1}", duration, DateTime.Now - start) }); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } /// <summary> /// AzureVNetGatewayTest() /// </summary> /// Note: Create a VNet, a LocalNet from the portal without creating a gateway. [TestMethod(), TestCategory("LongRunningTest"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Set,Remove)-AzureVNetConfig, Get-AzureVNetSite, (New,Get,Set,Remove)-AzureVNetGateway, Get-AzureVNetConnection)")] [Ignore] public void VNetTest() { StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix); if (string.IsNullOrEmpty(imageName)) imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows", "testvmimage" }, false); // Read the vnetconfig file and get the names of local networks, virtual networks and affinity groups. XDocument vnetconfigxml = XDocument.Load(vnetConfigFilePath); List<string> localNets = new List<string>(); List<string> virtualNets = new List<string>(); HashSet<string> affinityGroups = new HashSet<string>(); foreach (XElement el in vnetconfigxml.Descendants()) { switch (el.Name.LocalName) { case "LocalNetworkSite": localNets.Add(el.FirstAttribute.Value); break; case "VirtualNetworkSite": virtualNets.Add(el.Attribute("name").Value); affinityGroups.Add(el.Attribute("AffinityGroup").Value); break; default: break; } } foreach (string aff in affinityGroups) { if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, aff)) { vmPowershellCmdlets.NewAzureAffinityGroup(aff, Resource.Location, null, null); } } string vnet1 = virtualNets[0]; string lnet1 = localNets[0]; try { vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName); vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath); foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(null)) { Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup); } foreach (string vnet in virtualNets) { Assert.AreEqual(vnet, vmPowershellCmdlets.GetAzureVNetSite(vnet)[0].Name); Assert.AreEqual(ProvisioningState.NotProvisioned, vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State); } vmPowershellCmdlets.NewAzureVNetGateway(vnet1); Assert.IsTrue(GetVNetState(vnet1, ProvisioningState.Provisioned, 12, 60)); // Set-AzureVNetGateway -Connect Test vmPowershellCmdlets.SetAzureVNetGateway("connect", vnet1, lnet1); foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); Assert.IsFalse(connection.ConnectivityState.ToLowerInvariant().Contains("notconnected")); } // Get-AzureVNetGatewayKey SharedKeyContext result = vmPowershellCmdlets.GetAzureVNetGatewayKey(vnet1, vmPowershellCmdlets.GetAzureVNetConnection(vnet1)[0].LocalNetworkSiteName); Console.WriteLine("Gateway Key: {0}", result.Value); // Set-AzureVNetGateway -Disconnect vmPowershellCmdlets.SetAzureVNetGateway("disconnect", vnet1, lnet1); foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1)) { Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName); } // Remove-AzureVnetGateway vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); foreach (string vnet in virtualNets) { VirtualNetworkGatewayContext gateway = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0]; Console.WriteLine("State: {0}, VIP: {1}", gateway.State.ToString(), gateway.VIPAddress); if (vnet.Equals(vnet1)) { Assert.AreEqual(ProvisioningState.Deprovisioning, gateway.State); } else { Assert.AreEqual(ProvisioningState.NotProvisioned, gateway.State); } } Utilities.RetryUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30); pass = true; } catch (Exception e) { pass = false; if (cleanupIfFailed) { try { vmPowershellCmdlets.RemoveAzureVNetGateway(vnet1); } catch { } Utilities.RetryUntilSuccess<ManagementOperationContext>(vmPowershellCmdlets.RemoveAzureVNetConfig, "in use", 10, 30); } Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { foreach (string aff in affinityGroups) { try { vmPowershellCmdlets.RemoveAzureAffinityGroup(aff); } catch { // Some service uses the affinity group, so it cannot be deleted. Just leave it. } } } } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); // Remove the service if ((cleanupIfPassed && pass) || (cleanupIfFailed && !pass)) { vmPowershellCmdlets.RemoveAzureService(serviceName); try { vmPowershellCmdlets.GetAzureService(serviceName); Console.WriteLine("The service, {0}, is not removed", serviceName); } catch (Exception e) { if (e.ToString().ToLowerInvariant().Contains("does not exist")) { Console.WriteLine("The service, {0}, is successfully removed", serviceName); } else { Console.WriteLine("Error occurred: {0}", e.ToString()); } } } } private string GetSiteContent(Uri uri, int maxRetryTimes, bool holdConnection) { Console.WriteLine("GetSiteContent. uri={0} maxRetryTimes={1}", uri.AbsoluteUri, maxRetryTimes); HttpWebRequest request; HttpWebResponse response = null; var noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore); HttpWebRequest.DefaultCachePolicy = noCachePolicy; int i; for (i = 1; i <= maxRetryTimes; i++) { try { request = (HttpWebRequest)WebRequest.Create(uri); request.Timeout = 10 * 60 * 1000; //set to 10 minutes, default 100 sec. default IE7/8 is 60 minutes response = (HttpWebResponse)request.GetResponse(); break; } catch (WebException e) { Console.WriteLine("Exception Message: " + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code: {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description: {0}", ((HttpWebResponse)e.Response).StatusDescription); } } Thread.Sleep(30 * 1000); } if (i > maxRetryTimes) { throw new Exception("Web Site has error and reached maxRetryTimes"); } Stream responseStream = response.GetResponseStream(); StringBuilder sb = new StringBuilder(); byte[] buf = new byte[100]; int length; while ((length = responseStream.Read(buf, 0, 100)) != 0) { if (holdConnection) { Thread.Sleep(TimeSpan.FromSeconds(10)); } sb.Append(Encoding.UTF8.GetString(buf, 0, length)); } string responseString = sb.ToString(); Console.WriteLine("Site content: (IsFromCache={0})", response.IsFromCache); Console.WriteLine(responseString); return responseString; } private bool GetVNetState(string vnet, ProvisioningState expectedState, int maxTime, int intervalTime) { ProvisioningState vnetState; int i = 0; do { vnetState = vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State; Thread.Sleep(intervalTime * 1000); i++; } while (!vnetState.Equals(expectedState) || i < maxTime); return vnetState.Equals(expectedState); } } }
// --------------------------------------------------------------------------- // <copyright file="MapiTypeConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the MapiTypeConverter class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MapiTypeConverterMap = System.Collections.Generic.Dictionary<MapiPropertyType, MapiTypeConverterMapEntry>; /// <summary> /// Utility class to convert between MAPI Property type values and strings. /// </summary> internal class MapiTypeConverter { /// <summary> /// Assume DateTime values are in UTC. /// </summary> private const DateTimeStyles UtcDataTimeStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal; /// <summary> /// Map from MAPI property type to converter entry. /// </summary> private static LazyMember<MapiTypeConverterMap> mapiTypeConverterMap = new LazyMember<MapiTypeConverterMap>( delegate() { MapiTypeConverterMap map = new MapiTypeConverterMap(); map.Add( MapiPropertyType.ApplicationTime, new MapiTypeConverterMapEntry(typeof(double))); map.Add( MapiPropertyType.ApplicationTimeArray, new MapiTypeConverterMapEntry(typeof(double)) { IsArray = true }); var byteConverter = new MapiTypeConverterMapEntry(typeof(byte[])) { Parse = (s) => string.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), ConvertToString = (o) => Convert.ToBase64String((byte[])o), }; map.Add( MapiPropertyType.Binary, byteConverter); var byteArrayConverter = new MapiTypeConverterMapEntry(typeof(byte[])) { Parse = (s) => string.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), ConvertToString = (o) => Convert.ToBase64String((byte[])o), IsArray = true }; map.Add( MapiPropertyType.BinaryArray, byteArrayConverter); var boolConverter = new MapiTypeConverterMapEntry(typeof(bool)) { Parse = (s) => Convert.ChangeType(s, typeof(bool), CultureInfo.InvariantCulture), ConvertToString = (o) => ((bool)o).ToString(CultureInfo.InvariantCulture).ToLower(), }; map.Add( MapiPropertyType.Boolean, boolConverter); var clsidConverter = new MapiTypeConverterMapEntry(typeof(Guid)) { Parse = (s) => new Guid(s), ConvertToString = (o) => ((Guid)o).ToString(), }; map.Add( MapiPropertyType.CLSID, clsidConverter); var clsidArrayConverter = new MapiTypeConverterMapEntry(typeof(Guid)) { Parse = (s) => new Guid(s), ConvertToString = (o) => ((Guid)o).ToString(), IsArray = true }; map.Add( MapiPropertyType.CLSIDArray, clsidArrayConverter); map.Add( MapiPropertyType.Currency, new MapiTypeConverterMapEntry(typeof(Int64))); map.Add( MapiPropertyType.CurrencyArray, new MapiTypeConverterMapEntry(typeof(Int64)) { IsArray = true }); map.Add( MapiPropertyType.Double, new MapiTypeConverterMapEntry(typeof(double))); map.Add( MapiPropertyType.DoubleArray, new MapiTypeConverterMapEntry(typeof(double)) { IsArray = true }); map.Add( MapiPropertyType.Error, new MapiTypeConverterMapEntry(typeof(Int32))); map.Add( MapiPropertyType.Float, new MapiTypeConverterMapEntry(typeof(float))); map.Add( MapiPropertyType.FloatArray, new MapiTypeConverterMapEntry(typeof(float)) { IsArray = true }); map.Add( MapiPropertyType.Integer, new MapiTypeConverterMapEntry(typeof(Int32)) { Parse = (s) => MapiTypeConverter.ParseMapiIntegerValue(s) }); map.Add( MapiPropertyType.IntegerArray, new MapiTypeConverterMapEntry(typeof(Int32)) { IsArray = true }); map.Add( MapiPropertyType.Long, new MapiTypeConverterMapEntry(typeof(Int64))); map.Add( MapiPropertyType.LongArray, new MapiTypeConverterMapEntry(typeof(Int64)) { IsArray = true }); var objectConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s }; map.Add( MapiPropertyType.Object, objectConverter); var objectArrayConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s, IsArray = true }; map.Add( MapiPropertyType.ObjectArray, objectArrayConverter); map.Add( MapiPropertyType.Short, new MapiTypeConverterMapEntry(typeof(Int16))); map.Add( MapiPropertyType.ShortArray, new MapiTypeConverterMapEntry(typeof(Int16)) { IsArray = true }); var stringConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s }; map.Add( MapiPropertyType.String, stringConverter); var stringArrayConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s, IsArray = true }; map.Add( MapiPropertyType.StringArray, stringArrayConverter); var sysTimeConverter = new MapiTypeConverterMapEntry(typeof(DateTime)) { Parse = (s) => DateTime.Parse(s, CultureInfo.InvariantCulture, UtcDataTimeStyles), ConvertToString = (o) => EwsUtilities.DateTimeToXSDateTime((DateTime)o) // Can't use DataTime.ToString() }; map.Add( MapiPropertyType.SystemTime, sysTimeConverter); var sysTimeArrayConverter = new MapiTypeConverterMapEntry(typeof(DateTime)) { IsArray = true, Parse = (s) => DateTime.Parse(s, CultureInfo.InvariantCulture, UtcDataTimeStyles), ConvertToString = (o) => EwsUtilities.DateTimeToXSDateTime((DateTime)o) // Can't use DataTime.ToString() }; map.Add( MapiPropertyType.SystemTimeArray, sysTimeArrayConverter); return map; }); /// <summary> /// Converts the string list to array. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="strings">Strings.</param> /// <returns>Array of objects.</returns> internal static Array ConvertToValue(MapiPropertyType mapiPropType, IEnumerable<string> strings) { EwsUtilities.ValidateParam(strings, "strings"); MapiTypeConverterMapEntry typeConverter = MapiTypeConverterMap[mapiPropType]; Array array = Array.CreateInstance(typeConverter.Type, strings.Count<string>()); int index = 0; foreach (string stringValue in strings) { object value = typeConverter.ConvertToValueOrDefault(stringValue); array.SetValue(value, index++); } return array; } /// <summary> /// Converts a string to value consistent with MAPI type. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="stringValue">String to convert to a value.</param> /// <returns></returns> internal static object ConvertToValue(MapiPropertyType mapiPropType, string stringValue) { return MapiTypeConverterMap[mapiPropType].ConvertToValue(stringValue); } /// <summary> /// Converts a value to a string. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="value">Value to convert to string.</param> /// <returns>String value.</returns> internal static string ConvertToString(MapiPropertyType mapiPropType, object value) { return (value == null) ? string.Empty : MapiTypeConverterMap[mapiPropType].ConvertToString(value); } /// <summary> /// Change value to a value of compatible type. /// </summary> /// <param name="mapiType">Type of the mapi property.</param> /// <param name="value">The value.</param> /// <returns>Compatible value.</returns> internal static object ChangeType(MapiPropertyType mapiType, object value) { EwsUtilities.ValidateParam(value, "value"); return MapiTypeConverterMap[mapiType].ChangeType(value); } /// <summary> /// Converts a MAPI Integer value. /// </summary> /// <remarks> /// Usually the value is an integer but there are cases where the value has been "schematized" to an /// Enumeration value (e.g. NoData) which we have no choice but to fallback and represent as a string. /// </remarks> /// <param name="s">The string value.</param> /// <returns>Integer value or the original string if the value could not be parsed as such.</returns> internal static object ParseMapiIntegerValue(string s) { int intValue; if (Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out intValue)) { return intValue; } else { return s; } } /// <summary> /// Determines whether MapiPropertyType is an array type. /// </summary> /// <param name="mapiType">Type of the mapi.</param> /// <returns>True if this is an array type.</returns> internal static bool IsArrayType(MapiPropertyType mapiType) { return MapiTypeConverterMap[mapiType].IsArray; } /// <summary> /// Gets the MAPI type converter map. /// </summary> /// <value>The MAPI type converter map.</value> internal static MapiTypeConverterMap MapiTypeConverterMap { get { return mapiTypeConverterMap.Member; } } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace gov.va.medora.mdo.dao.vista { [TestFixture] public class VistaDateTimeIteratorTest { [Test] [Category("unit-only")] public void TestSetIteratorLengthFromDates() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102.234556", "20080103"); Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.SECOND_ITERATION); Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.SECOND, testIterator._precision); } [Test] [Category("unit-only")] public void TestSetIteratorLengthFromEndDate() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102", "20080103.01"); Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.HOUR_ITERATION); Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.HOUR, testIterator._precision); } [Test] [Category("unit-only")] public void TestSetIteratorLengthFromEndDateZero() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102", "20080103.00"); Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.HOUR_ITERATION); Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.HOUR, testIterator._precision); } /// <summary> /// BEWARE: A DateTime string that gets padded with 0s will cause you to iterate /// in seconds. /// </summary> [Test] [Category("unit-only")] public void TestSetIteratorLengthNormalizedNumber() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator("20080102.000000", "20080103.0000"); Assert.IsTrue(testIterator._iterLength == VistaDateTimeIterator.SECOND_ITERATION); Assert.AreEqual((int)VistaDateTimeIterator.PRECISION.SECOND, testIterator._precision); } /// <summary>Dummy check...</summary> [Test] [Category("unit-only")] public void TestPrecisionPositions() { string testDate = VistaTimestamp.fromDateTime(new DateTime(2008, 01, 23, 12, 34, 56, 789)); Assert.AreEqual("308",testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.YEAR)); Assert.AreEqual("30801", testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.MONTH)); Assert.AreEqual("3080123", testDate.Substring(0,(int)VistaDateTimeIterator.PRECISION.DAY)); Assert.AreEqual("3080123.12", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.HOUR)); Assert.AreEqual("3080123.1234", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.MINUTE)); Assert.AreEqual("3080123.123456", testDate.Substring(0, (int)VistaDateTimeIterator.PRECISION.SECOND)); } /// <summary> /// Test to see that as we roll over days, that the iterator will do the right thing as well. /// </summary> [Test] [Category("unit-only")] public void TestHourRollOver() { VistaDateTimeIterator testIterator = new VistaDateTimeIterator( new DateTime(2008, 01, 01, 22, 0, 0) , new DateTime(2008, 01, 03) , new TimeSpan(1, 0, 0) ); List<string> values = new List<string>(); while (!testIterator.IsDone()) { testIterator.SetIterEndDate(); // put at start of loop values.Add(testIterator.GetDdrListerPart()); testIterator.AdvanceIterStartDate(); // put at end of loop } int result = string.Concat(values.ToArray()).GetHashCode(); //Spot Check - Count Assert.AreEqual(26, values.Count); String[] strings = values.ToArray(); //Spot Check - Validate Start Value Assert.IsTrue(strings[0].Equals("3080101.22")); //Spot Check - Validate End Value Assert.IsTrue(strings[25].Equals("3080102.23")); //Spot Check - Validate an Intermediate Value Assert.IsTrue(strings[14].Equals("3080102.12")); //Hash Code is not stable acrosss .Net Versions //Assert.AreEqual(1712919498, result); } [Test] [Category("unit-only")] public void TestIterationDays() { int result = VistaDateTimeIterator.IterationDays("1.000000"); Assert.AreEqual(1, result); } [Test] [Category("unit-only")] public void TestIterationDaysPoint() { int result = VistaDateTimeIterator.IterationDays(".000000"); Assert.AreEqual(0, result); } [Test] [Category("unit-only")] public void TestIterationDays1Hour() { int result = VistaDateTimeIterator.IterationDays(".100000"); Assert.AreEqual(0, result); } [Test] [Category("unit-only")] public void TestIterationDays1HourNoPoint() { int result = VistaDateTimeIterator.IterationDays("100000"); Assert.AreEqual(0, result); } [Test] [Category("unit-only")] public void TestIterationHours() { int result = VistaDateTimeIterator.IterationHours("1.100000"); Assert.AreEqual(10, result); } [Test] [Category("unit-only")] public void TestIterationHoursNoPoint() { int result = VistaDateTimeIterator.IterationHours("120000"); Assert.AreEqual(12, result); } [Test] [Category("unit-only")] public void TestIterationHoursPoint() { int result = VistaDateTimeIterator.IterationHours(".345000"); Assert.AreEqual(34, result); } [Test] [Category("unit-only")] public void TestIterationMinutes() { int result = VistaDateTimeIterator.IterationMinutes(".345000"); Assert.AreEqual(50, result); } [Test] [Category("unit-only")] public void TestIterationSecond() { int result = VistaDateTimeIterator.IterationSeconds(".345036"); Assert.AreEqual(36, result); } [Test] [Category("unit-only")] public void TestIterationTimeSpanFromString() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1.010230"); Assert.AreEqual(1, result.Days); Assert.AreEqual(1, result.Hours); Assert.AreEqual(2, result.Minutes); Assert.AreEqual(30, result.Seconds); } /// <summary>Values will roll over into next greater time range /// - e.g. seconds to minutes and hours to days /// </summary> [Test] [Category("unit-only")] public void TestIterationTimeSpanFromStringTooManySeconds() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1.250290"); Assert.AreEqual(2, result.Days); Assert.AreEqual(1, result.Hours); Assert.AreEqual(3, result.Minutes); Assert.AreEqual(30, result.Seconds); } /// <summary>Values will roll over into next greater time range /// - e.g. seconds to minutes and hours to days /// </summary> [Test] [Category("unit-only")] public void TestIterationTimeSpanFromStringOneDay() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1."); Assert.AreEqual(1, result.Days); Assert.AreEqual(0, result.Hours); Assert.AreEqual(0, result.Minutes); Assert.AreEqual(0, result.Seconds); } /// <summary> /// This actually gives you a zero timespan, so the default of one day is /// used instead. /// </summary> [Test] [Category("unit-only")] public void TestIterationTimeSpanFromStringOne() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("1"); Assert.AreEqual(1, result.Days); } /// <summary> /// One hour /// </summary> [Test] [Category("unit-only")] public void TestIterationTimeSpanFromStringDotOhOne() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString(".01"); Assert.AreEqual(1, result.Hours); } [Test] [Category("unit-only")] public void TestIterationTimeSpanFromStringOhOne() { TimeSpan result = VistaDateTimeIterator.IterationTimeSpanFromString("01"); Assert.AreEqual(1, result.Hours); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; namespace ZombieSmash { public class Level1Manager : Microsoft.Xna.Framework.DrawableGameComponent { private Rectangle window; private ContentManager Content; private bool goToNextScreen = false; private bool gameOver = false; private bool soldierIsInvincible = false; private bool soldierIsVisible = true; private int blinkTimer = 0; private List<Vector2> enemySpawnLocations; private MousePointer crosshair; private MouseState prevMS; private SpriteBatch spriteBatch; private UserControlledSprite soldier; private Texture2D door; private Texture2D road; private Texture2D grass; private Texture2D windows; private SpriteFont lives; private Texture2D lives_background; public Level1Manager(Game game) : base(game) { window = Game.Window.ClientBounds; Content = Game.Content; } public override void Initialize() { // TODO: Add your initialization code here base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(Game.GraphicsDevice); door = Content.Load<Texture2D>("Images/Door"); road = Content.Load<Texture2D>("Images/Road"); grass = Content.Load<Texture2D>("Images/Grass"); windows = Content.Load<Texture2D>("Images/Windows"); soldier = new UserControlledSprite(Content.Load<Texture2D>("images/soldier"), new Point(29, 81), 0, new Vector2(2.5f, 2.5f), new Vector2(window.Width / 2, window.Height / 2)); prevMS = Mouse.GetState(); crosshair = new MousePointer(Content.Load<Texture2D>("images/crosshair"), new Point(40, 40), 0, new Vector2(prevMS.X, prevMS.Y)); enemySpawnLocations = new List<Vector2>(); for (int yPosition = 0; yPosition < window.Height - 50; yPosition += 100) { enemySpawnLocations.Add(new Vector2(50, yPosition)); enemySpawnLocations.Add(new Vector2(window.Width - 100, yPosition)); } lives = Content.Load<SpriteFont>("Fonts/SpriteFont2"); lives_background = Content.Load<Texture2D>("Images/lives_background_square"); } public void initializeEnvironment() { EnvironmentManager.initializeSelf(window, spriteBatch); EnvironmentManager.initGameLevel(Content, soldier, enemySpawnLocations, 10, 1000); } public override void Update(GameTime gameTime) { // This code ends the level gameOver = EnvironmentManager.isGameOver(); soldierIsInvincible = EnvironmentManager.detectCollisions(soldier, soldierIsInvincible, gameTime); if (EnvironmentManager.allZombiesAreDead()) { goToNextScreen = true; } if (!soldierIsInvincible) { soldierIsVisible = true; } else { blinkTimer += gameTime.ElapsedGameTime.Milliseconds; if (blinkTimer > 75) { blinkTimer = 0; soldierIsVisible = !soldierIsVisible; } } crosshair.Update(gameTime, window); soldier.Update(gameTime, window); EnvironmentManager.Update(gameTime, soldier, Content); //Spawn a bullet at crosshair position upon left click MouseState ms = Mouse.GetState(); if (ms.LeftButton == ButtonState.Pressed && prevMS.LeftButton != ButtonState.Pressed) { Vector2 orientation = new Vector2(crosshair.position.X - soldier.position.X, crosshair.position.Y - soldier.position.Y); Vector2 position = new Vector2(soldier.position.X + 10, soldier.position.Y + 15); EnvironmentManager.spawnBullet(Content, orientation, position); } prevMS = ms; base.Update(gameTime); } public bool levelIsComplete() { return goToNextScreen; } public void resetLevel() { gameOver = false; goToNextScreen = false; soldier.position.X = window.Width / 2; soldier.position.Y = window.Height / 2; } public bool playerIsDead() { return gameOver; } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(windows, new Vector2(-60, -100), null, Color.White, 0, new Vector2(0, 0), 0.8f, SpriteEffects.None, 0); spriteBatch.Draw(windows, new Vector2(110, -100), null, Color.White, 0, new Vector2(0, 0), 0.8f, SpriteEffects.None, 0); spriteBatch.Draw(windows, new Vector2(440, -100), null, Color.White, 0, new Vector2(0, 0), 0.8f, SpriteEffects.None, 0); spriteBatch.Draw(windows, new Vector2(610, -100), null, Color.White, 0, new Vector2(0, 0), 0.8f, SpriteEffects.None, 0); spriteBatch.Draw(door, new Vector2(350, 0), null, Color.White, 0, new Vector2(0, 0), 0.1f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(0, 100), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(207, 100), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(414, 100), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(621, 100), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(grass, new Vector2(0, 425), null, Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0); spriteBatch.Draw(grass, new Vector2(220, 425), null, Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0); spriteBatch.Draw(grass, new Vector2(440, 425), null, Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0); spriteBatch.Draw(grass, new Vector2(660, 425), null, Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(0, 270), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(207, 270), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(414, 270), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); spriteBatch.Draw(road, new Vector2(621, 270), null, Color.White, 0, new Vector2(0, 0), 0.5f, SpriteEffects.None, 0); if (soldierIsVisible) { soldier.Draw(gameTime, spriteBatch); } EnvironmentManager.Draw(gameTime); spriteBatch.Draw(lives_background, new Vector2(630, 15), null, Color.White, 0, new Vector2(0, 0), 1f, SpriteEffects.None, 0); spriteBatch.DrawString(lives, "lives: " + EnvironmentManager.player_lives, new Vector2(640, 10), Color.Red); crosshair.Draw(gameTime, spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class WhileStatement : ConditionalStatement { protected Block _block; protected Block _orBlock; protected Block _thenBlock; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public WhileStatement CloneNode() { return (WhileStatement)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public WhileStatement CleanClone() { return (WhileStatement)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.WhileStatement; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnWhileStatement(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( WhileStatement)node; if (!Node.Matches(_modifier, other._modifier)) return NoMatch("WhileStatement._modifier"); if (!Node.Matches(_condition, other._condition)) return NoMatch("WhileStatement._condition"); if (!Node.Matches(_block, other._block)) return NoMatch("WhileStatement._block"); if (!Node.Matches(_orBlock, other._orBlock)) return NoMatch("WhileStatement._orBlock"); if (!Node.Matches(_thenBlock, other._thenBlock)) return NoMatch("WhileStatement._thenBlock"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_modifier == existing) { this.Modifier = (StatementModifier)newNode; return true; } if (_condition == existing) { this.Condition = (Expression)newNode; return true; } if (_block == existing) { this.Block = (Block)newNode; return true; } if (_orBlock == existing) { this.OrBlock = (Block)newNode; return true; } if (_thenBlock == existing) { this.ThenBlock = (Block)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { WhileStatement clone = (WhileStatement)FormatterServices.GetUninitializedObject(typeof(WhileStatement)); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); if (null != _modifier) { clone._modifier = _modifier.Clone() as StatementModifier; clone._modifier.InitializeParent(clone); } if (null != _condition) { clone._condition = _condition.Clone() as Expression; clone._condition.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as Block; clone._block.InitializeParent(clone); } if (null != _orBlock) { clone._orBlock = _orBlock.Clone() as Block; clone._orBlock.InitializeParent(clone); } if (null != _thenBlock) { clone._thenBlock = _thenBlock.Clone() as Block; clone._thenBlock.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; if (null != _modifier) { _modifier.ClearTypeSystemBindings(); } if (null != _condition) { _condition.ClearTypeSystemBindings(); } if (null != _block) { _block.ClearTypeSystemBindings(); } if (null != _orBlock) { _orBlock.ClearTypeSystemBindings(); } if (null != _thenBlock) { _thenBlock.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block Block { get { if (_block == null) { _block = new Block(); _block.InitializeParent(this); } return _block; } set { if (_block != value) { _block = value; if (null != _block) { _block.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block OrBlock { get { return _orBlock; } set { if (_orBlock != value) { _orBlock = value; if (null != _orBlock) { _orBlock.InitializeParent(this); } } } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Block ThenBlock { get { return _thenBlock; } set { if (_thenBlock != value) { _thenBlock = value; if (null != _thenBlock) { _thenBlock.InitializeParent(this); } } } } } }
// 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. using Google.Cloud.Iam.V1; using Google.Cloud.ClientTesting; using Google.Protobuf; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.PubSub.V1.Snippets { [SnippetOutputCollector] [Collection(nameof(PubsubSnippetFixture))] public class PublisherClientSnippets { private readonly PubsubSnippetFixture _fixture; public PublisherClientSnippets(PubsubSnippetFixture fixture) { _fixture = fixture; } [Fact] public void ListTopics() { string projectId = _fixture.ProjectId; // Snippet: ListTopics(*,*,*,*) PublisherClient client = PublisherClient.Create(); ProjectName projectName = new ProjectName(projectId); foreach (Topic topic in client.ListTopics(projectName)) { Console.WriteLine(topic.Name); } // End snippet } [Fact] public async Task ListTopicsAsync() { string projectId = _fixture.ProjectId; // Snippet: ListTopicsAsync(*,*,*,*) PublisherClient client = PublisherClient.Create(); ProjectName projectName = new ProjectName(projectId); IAsyncEnumerable<Topic> topics = client.ListTopicsAsync(projectName); await topics.ForEachAsync(topic => { Console.WriteLine(topic.Name); }); // End snippet } [Fact] public void CreateTopic() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); // Snippet: CreateTopic(TopicName,*) PublisherClient client = PublisherClient.Create(); TopicName topicName = new TopicName(projectId, topicId); Topic topic = client.CreateTopic(topicName); Console.WriteLine($"Created {topic.Name}"); // End snippet } [Fact] public async Task CreateTopicAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); // Snippet: CreateTopicAsync(TopicName,CallSettings) // Additional: CreateTopicAsync(TopicName,CancellationToken) PublisherClient client = PublisherClient.Create(); TopicName topicName = new TopicName(projectId, topicId); Topic topic = await client.CreateTopicAsync(topicName); Console.WriteLine($"Created {topic.Name}"); // End snippet } [Fact] public void Publish() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); // Snippet: Publish(*,*,*) PublisherClient client = PublisherClient.Create(); // Make sure we have a topic to publish to TopicName topicName = new TopicName(projectId, topicId); client.CreateTopic(topicName); PubsubMessage message = new PubsubMessage { // The data is any arbitrary ByteString. Here, we're using text. Data = ByteString.CopyFromUtf8("Hello, Pubsub"), // The attributes provide metadata in a string-to-string dictionary. Attributes = { { "description", "Simple text message" } } }; client.Publish(topicName, new[] { message }); // End snippet } [Fact] public async Task PublishAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); // Snippet: PublishAsync(*,*,CallSettings) // Additional: PublishAsync(*,*,CancellationToken) PublisherClient client = PublisherClient.Create(); // Make sure we have a topic to publish to TopicName topicName = new TopicName(projectId, topicId); await client.CreateTopicAsync(topicName); PubsubMessage message = new PubsubMessage { // The data is any arbitrary ByteString. Here, we're using text. Data = ByteString.CopyFromUtf8("Hello, Pubsub"), // The attributes provide metadata in a string-to-string dictionary. Attributes = { { "description", "Simple text message" } } }; await client.PublishAsync(topicName, new[] { message }); // End snippet } [Fact] public void DeleteTopic() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); PublisherClient.Create().CreateTopic(new TopicName(projectId, topicId)); // Snippet: DeleteTopic(TopicName,*) PublisherClient client = PublisherClient.Create(); TopicName topicName = new TopicName(projectId, topicId); client.DeleteTopic(topicName); Console.WriteLine($"Deleted {topicName}"); // End snippet } [Fact] public async Task DeleteTopicAsync() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); await PublisherClient.Create().CreateTopicAsync(new TopicName(projectId, topicId)); // Snippet: DeleteTopicAsync(TopicName,CallSettings) // Additional: DeleteTopicAsync(TopicName,CancellationToken) PublisherClient client = PublisherClient.Create(); TopicName topicName = new TopicName(projectId, topicId); await client.DeleteTopicAsync(topicName); Console.WriteLine($"Deleted {topicName}"); // End snippet } [Fact] public void GetIamPolicy() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); PublisherClient.Create().CreateTopic(new TopicName(projectId, topicId)); // Snippet: GetIamPolicy(string,*) PublisherClient client = PublisherClient.Create(); string topicName = new TopicName(projectId, topicId).ToString(); Policy policy = client.GetIamPolicy(topicName); Console.WriteLine($"Policy for {topicName}: {policy}"); // End snippet } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; namespace SIL.Windows.Forms.ClearShare { public class CreativeCommonsLicense : LicenseInfo { // This URL may be checked in code that uses the library, so make it available as a constant. public const string CC0Url = "http://creativecommons.org/publicdomain/zero/1.0/"; public enum DerivativeRules { NoDerivatives, DerivativesWithShareAndShareAlike, Derivatives } private bool _attributionRequired; public bool AttributionRequired { get { return _attributionRequired; } set { if (value != _attributionRequired) { HasChanges = true; } _attributionRequired = value; } } public override string ToString() { return Token; //by-nc-sa } private bool _commercialUseAllowed; public bool CommercialUseAllowed { get { return _commercialUseAllowed; } set { if (value != _commercialUseAllowed) { HasChanges = true; } _commercialUseAllowed = value; } } private DerivativeRules _derivativeRule; public DerivativeRules DerivativeRule { get { return _derivativeRule; } set { if (value != _derivativeRule) { HasChanges = true; } _derivativeRule = value; } } public const string kDefaultVersion = "4.0"; /// <summary> /// at the moment, we only use the license url, but in future we could add other custom provisions, like "ok to crop" (if they're allowed by cc?) /// </summary> public static LicenseInfo FromMetadata(Dictionary<string, string> metadataProperties) { if(!metadataProperties.ContainsKey("license")) throw new ApplicationException("A license property is required in order to make a Creative Commons License from metadata."); var result = FromLicenseUrl(metadataProperties["license"]); string rights; if (metadataProperties.TryGetValue("rights (en)", out rights)) result.RightsStatement = rights; return result; } /// <summary> /// Create a CCL from a string produced by the Token method of a CCL. /// It will have the current default Version. /// Other values are not guaranteed to work, though at present they will. /// Enhance: Possibly we should try to verify that the token is a valid CCL one? /// </summary> public new static LicenseInfo FromToken(string token) { var result = new CreativeCommonsLicense(); // Note (JH): Since version was set to default, as I add the qualifier, I'm going to let it be default as well. result.Url = MakeUrlFromParts(token, kDefaultVersion, null); return result; } public static CreativeCommonsLicense FromLicenseUrl(string url) { if(url==null || url.Trim()=="") { throw new ArgumentOutOfRangeException(); } var l = new CreativeCommonsLicense(); l.Url = url; return l; } private CreativeCommonsLicense() { } public CreativeCommonsLicense(bool attributionRequired, bool commercialUseAllowed, DerivativeRules derivativeRule, string version) { AttributionRequired = attributionRequired; CommercialUseAllowed = commercialUseAllowed; DerivativeRule = derivativeRule; Version = version; } public CreativeCommonsLicense(bool attributionRequired, bool commercialUseAllowed, DerivativeRules derivativeRule) :this(attributionRequired, commercialUseAllowed, derivativeRule, kDefaultVersion) { } public override string Url { get { return MakeUrlFromParts(Token, Version, _qualifier); } set { if(value!=Url) { HasChanges = true; } CommercialUseAllowed = true; DerivativeRule = DerivativeRules.Derivatives; AttributionRequired = false; if (value.Contains("by")) AttributionRequired = true; if (value.Contains("nc")) CommercialUseAllowed = false; if (value.Contains("nd")) DerivativeRule = DerivativeRules.NoDerivatives; if (value.Contains("sa")) DerivativeRule = DerivativeRules.DerivativesWithShareAndShareAlike; var urlWithoutTrailingSlash = value.TrimEnd(new char[] {'/'}); var parts = urlWithoutTrailingSlash.Split(new char[] { '/' }); string version; try { version = parts[5]; } catch (IndexOutOfRangeException) { // We had a problem with some urls getting saved without a version. // We fixed the save problem, but now we need to handle that bad data. // See http://issues.bloomlibrary.org/youtrack/issue/BL-4108. version = kDefaultVersion; } //just a sanity check on the version decimal result; if (decimal.TryParse(version, NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"), out result)) Version = version; if(parts.Length > 6) _qualifier = parts[6].ToLowerInvariant().Trim(); } } private static string MakeUrlFromParts(string token, string version, string qualifier) { if(token == "cc0") { // this one is weird in a couple ways, including that it doesn't have /licenses/ in the path return CC0Url; } var url = token + "/"; if (token.StartsWith("cc-")) url = url.Substring("cc-".Length); // don't want this as part of URL. if (!string.IsNullOrEmpty(version)) url += version + "/"; if (!string.IsNullOrWhiteSpace(qualifier)) url += qualifier + "/"; // e.g, igo as in https://creativecommons.org/licenses/by/3.0/igo/ return "http://creativecommons.org/licenses/" + url; } /// <summary> /// A string form used for serialization /// </summary> /// <remarks> /// REVIEW: (asked by Hatton Oct 2016) Serialization by whom? Why not just use the url, which is the canonical form? /// Note that this does not include any qualifier (of which at the moment the one one is "igo", but who knows /// what the future holds. ///</remarks> public override string Token { get { var token = "cc-"; if (AttributionRequired) token += "by-"; if (!CommercialUseAllowed) token += "nc-"; switch (DerivativeRule) { case DerivativeRules.NoDerivatives: token += "nd"; break; case DerivativeRules.DerivativesWithShareAndShareAlike: token += "sa"; break; case DerivativeRules.Derivatives: break; default: throw new ArgumentOutOfRangeException("derivativeRule"); } token = token.TrimEnd(new char[] {'-'}); if (token == "cc") token = "cc0"; // public domain return token; } } /// <summary> /// A compact form of of this license that doesn't introduce any new text (though the license may itself have text) /// E.g. CC BY-NC /// </summary> public override string GetMinimalFormForCredits(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { idOfLanguageUsed = "*"; string form; if (AttributionRequired) { form = "CC BY-"; if (!CommercialUseAllowed) form += "NC-"; switch (DerivativeRule) { case DerivativeRules.NoDerivatives: form += "ND"; break; case DerivativeRules.DerivativesWithShareAndShareAlike: form += "SA"; break; case DerivativeRules.Derivatives: break; default: throw new ArgumentOutOfRangeException("derivativeRule"); } form = form.TrimEnd(new char[] { '-', ' ' }); } else { form = "CC0"; } var additionalRights = (RightsStatement != null ? ". " + RightsStatement : ""); return (form + " " + (IntergovernmentalOriganizationQualifier ? "IGO " : "") + Version + additionalRights).Trim(); } /// <summary> /// Get a simple, non-legal summary of the license, using the "best" language for which we can find a translation. /// </summary> /// <param name="languagePriorityIds"></param> /// <param name="idOfLanguageUsed">The id of the language we were able to use. Unreliable if we had to use a mix of languages.</param> /// <returns>The description of the license.</returns> public override string GetDescription(IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { //Enhance labs.creativecommons.org has a lot of code, some of which might be useful, especially if we wanted a full, rather than concise, description. //Note that this isn't going to be able to convey to the caller the situation if some strings are translatable in some language, but others in some other language. //It will just end up being an amalgam in that case. //This IGO qualifier thing is new, and I'm not clear how I want to convey it on the page. //We could introduce text like "For more information, see", but the price of needing new // localizations at this point is somewhat daunting... for now, it seems enough that the "/igo/" is shown in the URL, if //it is in use in this license. string s= Url + System.Environment.NewLine; if(!AttributionRequired) { return GetComponentOfLicenseInBestLanguage("PublicDomain", "You can copy, modify, and distribute this work, even for commercial purposes, all without asking permission.", languagePriorityIds, out idOfLanguageUsed) + " "; } if (CommercialUseAllowed) s += GetComponentOfLicenseInBestLanguage("CommercialUseAllowed", "You are free to make commercial use of this work.", languagePriorityIds, out idOfLanguageUsed) + " "; else s += GetComponentOfLicenseInBestLanguage("NonCommercial", "You may not use this work for commercial purposes.", languagePriorityIds, out idOfLanguageUsed) + " "; if(DerivativeRule == DerivativeRules.Derivatives) s += GetComponentOfLicenseInBestLanguage("Derivatives", "You may adapt and add to this work.", languagePriorityIds, out idOfLanguageUsed) + " "; if (DerivativeRule == DerivativeRules.NoDerivatives) s += GetComponentOfLicenseInBestLanguage("NoDerivatives", "You may not make changes or build upon this work without permission.", languagePriorityIds, out idOfLanguageUsed) + " "; if (DerivativeRule == DerivativeRules.DerivativesWithShareAndShareAlike) s += GetComponentOfLicenseInBestLanguage("DerivativesWithShareAndShareAlike", "You may adapt and add to this work, but you may distribute the resulting work only under the same or similar license to this one.", languagePriorityIds, out idOfLanguageUsed) + " "; if (AttributionRequired) s += GetComponentOfLicenseInBestLanguage("AttributionRequired", "You must keep the copyright and credits for authors, illustrators, etc.", languagePriorityIds, out idOfLanguageUsed) + " "; return s.Trim(); } private string GetComponentOfLicenseInBestLanguage(string idSuffix, string englishText, IEnumerable<string> languagePriorityIds, out string idOfLanguageUsed) { const string comment = "See http://creativecommons.org/ to find out how this is normally translated in your language. What we're aiming for here is an easy to understand summary."; //Note: GetBestLicenseTranslation will prepend "MetadataDisplay.Licenses.", we should not include it here return GetBestLicenseTranslation("CreativeCommons." + idSuffix, englishText, comment, languagePriorityIds, out idOfLanguageUsed); } public override Image GetImage() { if (AttributionRequired && CommercialUseAllowed && DerivativeRule == DerivativeRules.Derivatives) return LicenseLogos.by; if (AttributionRequired && CommercialUseAllowed && DerivativeRule == DerivativeRules.NoDerivatives) return LicenseLogos.by_nd; if (AttributionRequired && CommercialUseAllowed && DerivativeRule == DerivativeRules.DerivativesWithShareAndShareAlike) return LicenseLogos.by_sa; if (AttributionRequired && !CommercialUseAllowed && DerivativeRule == DerivativeRules.NoDerivatives) return LicenseLogos.by_nc_nd; if (AttributionRequired && !CommercialUseAllowed && DerivativeRule == DerivativeRules.Derivatives) return LicenseLogos.by_nc; if (AttributionRequired && !CommercialUseAllowed && DerivativeRule == DerivativeRules.DerivativesWithShareAndShareAlike) return LicenseLogos.by_nc_sa; return LicenseLogos.cc0; } public override bool EditingAllowed { get { return false; } } private string _version; public string Version { get { return _version; } set { if (value != _version) { HasChanges = true; } _version = value; } } // For information on this qualifier, see https://wiki.creativecommons.org/wiki/Intergovernmental_Organizations private string _qualifier = null; public bool IntergovernmentalOriganizationQualifier { get { return _qualifier == "igo"; } set { var newValue = value ? "igo" : null; if (newValue != _qualifier) { HasChanges = true; if (!value) { _version = kDefaultVersion; // Undo the switch to 3.0 below } } _qualifier = newValue; if(value) { _version = "3.0";// as of November 2016, igo only had a 3.0 version, while normal cc licenses were up to 4.0 } } } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Controls { /// <summary> /// Summary description for LinkButton. /// </summary> [DefaultEvent("Click")] public class LinkButton : System.Windows.Forms.UserControl { private bool underlineOnHover = false; private Image grayImage; private Image normalImage; private Image mouseDownImage; private Image hoverImage; private ContentAlignment imageAlign = ContentAlignment.MiddleLeft; private Color foreColor; private System.Windows.Forms.PictureBox pbImage; private SmoothLabel lblLink; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public LinkButton() { this.SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.UserPaint, true); InitializeComponent(); this.DoubleBuffered = true; this.PerformLayout(); this.foreColor = this.foreColor; } public override Size GetPreferredSize(Size proposedSize) { Size size = lblLink.GetPreferredSize(proposedSize); if (normalImage != null) { size.Width += normalImage.Width; size.Height += normalImage.Height; } return size; } [TypeConverter(typeof(ImageConverter)), DefaultValue(typeof(Image), null), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Image MouseDownImage { get { return mouseDownImage; } set { mouseDownImage = value; } } [TypeConverter(typeof(ImageConverter)), DefaultValue(typeof(Image), null), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public Image LinkImage { get { return normalImage; } set { normalImage = value; if(normalImage == null) { pbImage.Visible = false; grayImage.Dispose(); grayImage = null; } else { grayImage = CreateGrayedImage(normalImage); pbImage.Visible = true; pbImage.Width = normalImage.Width; } if(this.Enabled) pbImage.Image = normalImage; else pbImage.Image = grayImage; } } private Image CreateGrayedImage(Image inputInput) { Bitmap grayBitmap = new Bitmap(inputInput); for(int x = 0; x < grayBitmap.Width; x++) { for(int y = 0; y < grayBitmap.Height; y++) { Color color = grayBitmap.GetPixel(x, y); int avgColor = (color.R + color.G + color.B) / 3; grayBitmap.SetPixel(x, y, Color.FromArgb((int)(color.A * 0.5), avgColor, avgColor, avgColor)); } } return (Image)grayBitmap; } public bool AntiAliasText { get { return lblLink.AntiAliasText; } set { lblLink.AntiAliasText = value; } } public ContentAlignment ImageAlign { get { return imageAlign; } set { switch (value) { case ContentAlignment.BottomCenter: pbImage.Dock = DockStyle.Bottom; break; case ContentAlignment.TopCenter: pbImage.Dock = DockStyle.Top; break; case ContentAlignment.BottomLeft: case ContentAlignment.MiddleLeft: case ContentAlignment.TopLeft: pbImage.Dock = DockStyle.Left; break; case ContentAlignment.BottomRight: case ContentAlignment.MiddleRight: case ContentAlignment.TopRight: pbImage.Dock = DockStyle.Right; break; } imageAlign = value; } } public ContentAlignment TextAlign { get { return lblLink.TextAlign; } set { lblLink.TextAlign = value; } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] public override string Text { get { return lblLink.Text; } set { lblLink.Text = value; } } public bool UnderlineOnHover { get { return underlineOnHover; } set { underlineOnHover = value; } } protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); lblLink.Font = this.Font; this.Invalidate(); } protected override void OnForeColorChanged(EventArgs e) { this.foreColor = this.ForeColor; base.OnForeColorChanged (e); UpdateTextColor(); } protected override void OnMouseEnter(EventArgs e) { if(!DesignMode && underlineOnHover) { Font underlineFont = new Font(this.Font, this.Font.Style | FontStyle.Underline); lblLink.Font = underlineFont; } } protected override void OnMouseLeave(EventArgs e) { if(!DesignMode && underlineOnHover) { lblLink.Font = this.Font; } } /// <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 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.pbImage = new System.Windows.Forms.PictureBox(); this.lblLink = new Controls.SmoothLabel(); ((System.ComponentModel.ISupportInitialize)(this.pbImage)).BeginInit(); this.SuspendLayout(); // // pbImage // this.pbImage.Dock = System.Windows.Forms.DockStyle.Left; this.pbImage.Location = new System.Drawing.Point(0, 0); this.pbImage.Name = "pbImage"; this.pbImage.Size = new System.Drawing.Size(24, 16); this.pbImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.pbImage.TabIndex = 0; this.pbImage.TabStop = false; this.pbImage.Visible = false; this.pbImage.DoubleClick += new System.EventHandler(this.pClick); this.pbImage.MouseLeave += new System.EventHandler(this.pMouseLeave); this.pbImage.Click += new System.EventHandler(this.pClick); this.pbImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.p_MouseDown); this.pbImage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.p_MouseUp); this.pbImage.MouseEnter += new System.EventHandler(this.pMouseEnter); // // lblLink // this.lblLink.AntiAliasText = true; this.lblLink.Dock = System.Windows.Forms.DockStyle.Fill; this.lblLink.Location = new System.Drawing.Point(24, 0); this.lblLink.Name = "lblLink"; this.lblLink.Size = new System.Drawing.Size(126, 16); this.lblLink.StringTrimming = System.Drawing.StringTrimming.EllipsisWord; this.lblLink.Strong = false; this.lblLink.TabIndex = 1; this.lblLink.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.lblLink.DoubleClick += new System.EventHandler(this.pClick); this.lblLink.MouseLeave += new System.EventHandler(this.pMouseLeave); this.lblLink.Click += new System.EventHandler(this.pClick); this.lblLink.MouseDown += new System.Windows.Forms.MouseEventHandler(this.p_MouseDown); this.lblLink.MouseEnter += new System.EventHandler(this.pMouseEnter); this.lblLink.MouseUp += new System.Windows.Forms.MouseEventHandler(this.p_MouseUp); // // LinkButton // this.Controls.Add(this.lblLink); this.Controls.Add(this.pbImage); this.Name = "LinkButton"; this.Size = new System.Drawing.Size(150, 16); this.EnabledChanged += new System.EventHandler(this.LinkButton_EnabledChanged); ((System.ComponentModel.ISupportInitialize)(this.pbImage)).EndInit(); this.ResumeLayout(false); } #endregion private void pClick(object sender, System.EventArgs e) { if(!DesignMode) this.OnClick(e); } private void pMouseEnter(object sender, System.EventArgs e) { if(!DesignMode) this.OnMouseEnter(e); } private void pMouseLeave(object sender, System.EventArgs e) { if(!DesignMode) this.OnMouseLeave(e); } private void UpdateTextColor() { if(this.Enabled) { lblLink.ForeColor = this.foreColor; } else { lblLink.ForeColor = SystemColors.GrayText; } } private void UpdateImage() { if(this.Enabled) { if(normalImage != null) pbImage.Image = normalImage; } else { if(grayImage != null) pbImage.Image = grayImage; } } private void LinkButton_EnabledChanged(object sender, System.EventArgs e) { UpdateImage(); UpdateTextColor(); } private void p_MouseDown(object sender, MouseEventArgs e) { if (mouseDownImage != null) { pbImage.Image = mouseDownImage; } } private void p_MouseUp(object sender, MouseEventArgs e) { UpdateImage(); } } }
using System; using System.IO; using System.Text; namespace ToolBelt { /// <summary> /// Equivalent of System.IO.BinaryReader, but with either endianness, depending on /// the EndianBitConverter it is constructed with. No data is buffered in the /// reader; the client may seek within the stream at will. /// </summary> public class EndianBinaryReader : IDisposable { #region Fields not directly related to properties /// <summary> /// Whether or not this reader has been disposed yet. /// </summary> bool disposed = false; /// <summary> /// Decoder to use for string conversions. /// </summary> Decoder decoder; /// <summary> /// Buffer used for temporary storage before conversion into primitives /// </summary> byte[] buffer = new byte[16]; /// <summary> /// Buffer used for temporary storage when reading a single character /// </summary> char[] charBuffer = new char[1]; /// <summary> /// Minimum number of bytes used to encode a character /// </summary> int minBytesPerChar; #endregion #region Constructors /// <summary> /// Equivalent of System.IO.BinaryWriter, but with either endianness, depending on /// the EndianBitConverter it is constructed with. /// </summary> /// <param name="bitConverter">Converter to use when reading data</param> /// <param name="stream">Stream to read data from</param> public EndianBinaryReader(EndianBitConverter bitConverter, Stream stream) : this(bitConverter, stream, Encoding.UTF8) { } /// <summary> /// Constructs a new binary reader with the given bit converter, reading /// to the given stream, using the given encoding. /// </summary> /// <param name="bitConverter">Converter to use when reading data</param> /// <param name="stream">Stream to read data from</param> /// <param name="encoding">Encoding to use when reading character data</param> public EndianBinaryReader(EndianBitConverter bitConverter, Stream stream, Encoding encoding) { if (bitConverter == null) { throw new ArgumentNullException("bitConverter"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (!stream.CanRead) { throw new ArgumentException("Stream isn't writable", "stream"); } this.stream = stream; this.bitConverter = bitConverter; this.encoding = encoding; this.decoder = encoding.GetDecoder(); this.minBytesPerChar = 1; if (encoding is UnicodeEncoding) { minBytesPerChar = 2; } } #endregion #region Properties EndianBitConverter bitConverter; /// <summary> /// The bit converter used to read values from the stream /// </summary> public EndianBitConverter BitConverter { get { return bitConverter; } } Encoding encoding; /// <summary> /// The encoding used to read strings /// </summary> public Encoding Encoding { get { return encoding; } } Stream stream; /// <summary> /// Gets the underlying stream of the EndianBinaryReader. /// </summary> public Stream BaseStream { get { return stream; } } #endregion #region Public methods /// <summary> /// Closes the reader, including the underlying stream.. /// </summary> public void Close() { Dispose(); } /// <summary> /// Seeks within the stream. /// </summary> /// <param name="offset">Offset to seek to.</param> /// <param name="origin">Origin of seek operation.</param> public void Seek(int offset, SeekOrigin origin) { CheckDisposed(); stream.Seek(offset, origin); } /// <summary> /// Reads a single byte from the stream. /// </summary> /// <returns>The byte read</returns> public byte ReadByte() { ReadInternal(buffer, 1); return buffer[0]; } /// <summary> /// Reads a single signed byte from the stream. /// </summary> /// <returns>The byte read</returns> public sbyte ReadSByte() { ReadInternal(buffer, 1); return unchecked((sbyte)buffer[0]); } /// <summary> /// Reads a boolean from the stream. 1 byte is read. /// </summary> /// <returns>The boolean read</returns> public bool ReadBoolean() { ReadInternal(buffer, 1); return bitConverter.ToBoolean(buffer, 0); } /// <summary> /// Reads a 16-bit signed integer from the stream, using the bit converter /// for this reader. 2 bytes are read. /// </summary> /// <returns>The 16-bit integer read</returns> public short ReadInt16() { ReadInternal(buffer, 2); return bitConverter.ToInt16(buffer, 0); } /// <summary> /// Reads a 32-bit signed integer from the stream, using the bit converter /// for this reader. 4 bytes are read. /// </summary> /// <returns>The 32-bit integer read</returns> public int ReadInt32() { ReadInternal(buffer, 4); return bitConverter.ToInt32(buffer, 0); } /// <summary> /// Reads a 64-bit signed integer from the stream, using the bit converter /// for this reader. 8 bytes are read. /// </summary> /// <returns>The 64-bit integer read</returns> public long ReadInt64() { ReadInternal(buffer, 8); return bitConverter.ToInt64(buffer, 0); } /// <summary> /// Reads a 16-bit unsigned integer from the stream, using the bit converter /// for this reader. 2 bytes are read. /// </summary> /// <returns>The 16-bit unsigned integer read</returns> public ushort ReadUInt16() { ReadInternal(buffer, 2); return bitConverter.ToUInt16(buffer, 0); } /// <summary> /// Reads a 32-bit unsigned integer from the stream, using the bit converter /// for this reader. 4 bytes are read. /// </summary> /// <returns>The 32-bit unsigned integer read</returns> public uint ReadUInt32() { ReadInternal(buffer, 4); return bitConverter.ToUInt32(buffer, 0); } /// <summary> /// Reads a 64-bit unsigned integer from the stream, using the bit converter /// for this reader. 8 bytes are read. /// </summary> /// <returns>The 64-bit unsigned integer read</returns> public ulong ReadUInt64() { ReadInternal(buffer, 8); return bitConverter.ToUInt64(buffer, 0); } /// <summary> /// Reads a single-precision floating-point value from the stream, using the bit converter /// for this reader. 4 bytes are read. /// </summary> /// <returns>The floating point value read</returns> public float ReadSingle() { ReadInternal(buffer, 4); return bitConverter.ToSingle(buffer, 0); } /// <summary> /// Reads a double-precision floating-point value from the stream, using the bit converter /// for this reader. 8 bytes are read. /// </summary> /// <returns>The floating point value read</returns> public double ReadDouble() { ReadInternal(buffer, 8); return bitConverter.ToDouble(buffer, 0); } /// <summary> /// Reads a decimal value from the stream, using the bit converter /// for this reader. 16 bytes are read. /// </summary> /// <returns>The decimal value read</returns> public decimal ReadDecimal() { ReadInternal(buffer, 16); return bitConverter.ToDecimal(buffer, 0); } /// <summary> /// Reads a single character from the stream, using the character encoding for /// this reader. If no characters have been fully read by the time the stream ends, /// -1 is returned. /// </summary> /// <returns>The character read, or -1 for end of stream.</returns> public int Read() { int charsRead = Read(charBuffer, 0, 1); if (charsRead == 0) { return -1; } else { return charBuffer[0]; } } /// <summary> /// Reads the specified number of characters into the given buffer, starting at /// the given index. /// </summary> /// <param name="data">The buffer to copy data into</param> /// <param name="index">The first index to copy data into</param> /// <param name="count">The number of characters to read</param> /// <returns>The number of characters actually read. This will only be less than /// the requested number of characters if the end of the stream is reached. /// </returns> public int Read(char[] data, int index, int count) { CheckDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("index"); } if (count + index > data.Length) { throw new ArgumentException ("Not enough space in buffer for specified number of characters starting at specified index"); } int read = 0; bool firstTime = true; // Use the normal buffer if we're only reading a small amount, otherwise // use at most 4K at a time. byte[] byteBuffer = buffer; if (byteBuffer.Length < count * minBytesPerChar) { byteBuffer = new byte[4096]; } while (read < count) { int amountToRead; // First time through we know we haven't previously read any data if (firstTime) { amountToRead = count * minBytesPerChar; firstTime = false; } // After that we can only assume we need to fully read "chars left -1" characters // and a single byte of the character we may be in the middle of else { amountToRead = ((count - read - 1) * minBytesPerChar) + 1; } if (amountToRead > byteBuffer.Length) { amountToRead = byteBuffer.Length; } int bytesRead = TryReadInternal(byteBuffer, amountToRead); if (bytesRead == 0) { return read; } int decoded = decoder.GetChars(byteBuffer, 0, bytesRead, data, index); read += decoded; index += decoded; } return read; } /// <summary> /// Reads the specified number of bytes into the given buffer, starting at /// the given index. /// </summary> /// <param name="buffer">The buffer to copy data into</param> /// <param name="index">The first index to copy data into</param> /// <param name="count">The number of bytes to read</param> /// <returns>The number of bytes actually read. This will only be less than /// the requested number of bytes if the end of the stream is reached. /// </returns> public int Read(byte[] buffer, int index, int count) { CheckDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("index"); } if (count + index > buffer.Length) { throw new ArgumentException ("Not enough space in buffer for specified number of bytes starting at specified index"); } int read = 0; while (count > 0) { int block = stream.Read(buffer, index, count); if (block == 0) { return read; } index += block; read += block; count -= block; } return read; } /// <summary> /// Reads the specified number of bytes, returning them in a new byte array. /// If not enough bytes are available before the end of the stream, this /// method will return what is available. /// </summary> /// <param name="count">The number of bytes to read</param> /// <returns>The bytes read</returns> public byte[] ReadBytes(int count) { CheckDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException("count"); } byte[] ret = new byte[count]; int index = 0; while (index < count) { int read = stream.Read(ret, index, count - index); // Stream has finished half way through. That's fine, return what we've got. if (read == 0) { byte[] copy = new byte[index]; Buffer.BlockCopy(ret, 0, copy, 0, index); return copy; } index += read; } return ret; } /// <summary> /// Reads the specified number of bytes, returning them in a new byte array. /// If not enough bytes are available before the end of the stream, this /// method will throw an IOException. /// </summary> /// <param name="count">The number of bytes to read</param> /// <returns>The bytes read</returns> public byte[] ReadBytesOrThrow(int count) { byte[] ret = new byte[count]; ReadInternal(ret, count); return ret; } /// <summary> /// Reads a 7-bit encoded integer from the stream. This is stored with the least significant /// information first, with 7 bits of information per byte of value, and the top /// bit as a continuation flag. This method is not affected by the endianness /// of the bit converter. /// </summary> /// <returns>The 7-bit encoded integer read from the stream.</returns> public int Read7BitEncodedInt() { CheckDisposed(); int ret = 0; for (int shift = 0; shift < 35; shift += 7) { int b = stream.ReadByte(); if (b == -1) { throw new EndOfStreamException(); } ret = ret | ((b & 0x7f) << shift); if ((b & 0x80) == 0) { return ret; } } // Still haven't seen a byte with the high bit unset? Dodgy data. throw new IOException("Invalid 7-bit encoded integer in stream."); } /// <summary> /// Reads a 7-bit encoded integer from the stream. This is stored with the most significant /// information first, with 7 bits of information per byte of value, and the top /// bit as a continuation flag. This method is not affected by the endianness /// of the bit converter. /// </summary> /// <returns>The 7-bit encoded integer read from the stream.</returns> public int ReadBigEndian7BitEncodedInt() { CheckDisposed(); int ret = 0; for (int i = 0; i < 5; i++) { int b = stream.ReadByte(); if (b == -1) { throw new EndOfStreamException(); } ret = (ret << 7) | (b & 0x7f); if ((b & 0x80) == 0) { return ret; } } // Still haven't seen a byte with the high bit unset? Dodgy data. throw new IOException("Invalid 7-bit encoded integer in stream."); } /// <summary> /// Reads a length-prefixed string from the stream, using the encoding for this reader. /// A 7-bit encoded integer is first read, which specifies the number of bytes /// to read from the stream. These bytes are then converted into a string with /// the encoding for this reader. /// </summary> /// <returns>The string read from the stream.</returns> public string ReadString() { int bytesToRead = Read7BitEncodedInt(); byte[] data = new byte[bytesToRead]; ReadInternal(data, bytesToRead); return encoding.GetString(data, 0, data.Length); } #endregion #region Private methods /// <summary> /// Checks whether or not the reader has been disposed, throwing an exception if so. /// </summary> void CheckDisposed() { if (disposed) { throw new ObjectDisposedException("EndianBinaryReader"); } } /// <summary> /// Reads the given number of bytes from the stream, throwing an exception /// if they can't all be read. /// </summary> /// <param name="data">Buffer to read into</param> /// <param name="size">Number of bytes to read</param> void ReadInternal(byte[] data, int size) { CheckDisposed(); int index = 0; while (index < size) { int read = stream.Read(data, index, size - index); if (read == 0) { throw new EndOfStreamException (String.Format("End of stream reached with {0} byte{1} left to read.", size - index, size - index == 1 ? "s" : "")); } index += read; } } /// <summary> /// Reads the given number of bytes from the stream if possible, returning /// the number of bytes actually read, which may be less than requested if /// (and only if) the end of the stream is reached. /// </summary> /// <param name="data">Buffer to read into</param> /// <param name="size">Number of bytes to read</param> /// <returns>Number of bytes actually read</returns> int TryReadInternal(byte[] data, int size) { CheckDisposed(); int index = 0; while (index < size) { int read = stream.Read(data, index, size - index); if (read == 0) { return index; } index += read; } return index; } #endregion #region IDisposable Members /// <summary> /// Disposes of the underlying stream. /// </summary> public void Dispose() { if (!disposed) { disposed = true; ((IDisposable)stream).Dispose(); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Drawing2D.PathGradientBrush.cs // // Authors: // Dennis Hayes (dennish@Raytek.com) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // Ravindra (rkumar@novell.com) // // Copyright (C) 2002/3 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004,2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel; using System.Runtime.InteropServices; namespace System.Drawing.Drawing2D { [MonoTODO("libgdiplus/cairo doesn't support path gradients - unless it can be mapped to a radial gradient")] public sealed class PathGradientBrush : Brush { internal PathGradientBrush(IntPtr native) { SetNativeBrush(native); } public PathGradientBrush(GraphicsPath path) { if (path == null) throw new ArgumentNullException("path"); IntPtr nativeObject; Status status = SafeNativeMethods.Gdip.GdipCreatePathGradientFromPath(path.nativePath, out nativeObject); SafeNativeMethods.Gdip.CheckStatus(status); SetNativeBrush(nativeObject); } public PathGradientBrush(Point[] points) : this(points, WrapMode.Clamp) { } public PathGradientBrush(PointF[] points) : this(points, WrapMode.Clamp) { } public PathGradientBrush(Point[] points, WrapMode wrapMode) { if (points == null) throw new ArgumentNullException("points"); if ((wrapMode < WrapMode.Tile) || (wrapMode > WrapMode.Clamp)) throw new InvalidEnumArgumentException("WrapMode"); IntPtr nativeObject; Status status = SafeNativeMethods.Gdip.GdipCreatePathGradientI(points, points.Length, wrapMode, out nativeObject); SafeNativeMethods.Gdip.CheckStatus(status); SetNativeBrush(nativeObject); } public PathGradientBrush(PointF[] points, WrapMode wrapMode) { if (points == null) throw new ArgumentNullException("points"); if ((wrapMode < WrapMode.Tile) || (wrapMode > WrapMode.Clamp)) throw new InvalidEnumArgumentException("WrapMode"); IntPtr nativeObject; Status status = SafeNativeMethods.Gdip.GdipCreatePathGradient(points, points.Length, wrapMode, out nativeObject); SafeNativeMethods.Gdip.CheckStatus(status); SetNativeBrush(nativeObject); } // Properties public Blend Blend { get { int count; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientBlendCount(NativeBrush, out count); SafeNativeMethods.Gdip.CheckStatus(status); float[] factors = new float[count]; float[] positions = new float[count]; status = SafeNativeMethods.Gdip.GdipGetPathGradientBlend(NativeBrush, factors, positions, count); SafeNativeMethods.Gdip.CheckStatus(status); Blend blend = new Blend(); blend.Factors = factors; blend.Positions = positions; return blend; } set { // no null check, MS throws a NullReferenceException here int count; float[] factors = value.Factors; float[] positions = value.Positions; count = factors.Length; if (count == 0 || positions.Length == 0) throw new ArgumentException("Invalid Blend object. It should have at least 2 elements in each of the factors and positions arrays."); if (count != positions.Length) throw new ArgumentException("Invalid Blend object. It should contain the same number of factors and positions values."); if (positions[0] != 0.0F) throw new ArgumentException("Invalid Blend object. The positions array must have 0.0 as its first element."); if (positions[count - 1] != 1.0F) throw new ArgumentException("Invalid Blend object. The positions array must have 1.0 as its last element."); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientBlend(NativeBrush, factors, positions, count); SafeNativeMethods.Gdip.CheckStatus(status); } } public Color CenterColor { get { int centerColor; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientCenterColor(NativeBrush, out centerColor); SafeNativeMethods.Gdip.CheckStatus(status); return Color.FromArgb(centerColor); } set { Status status = SafeNativeMethods.Gdip.GdipSetPathGradientCenterColor(NativeBrush, value.ToArgb()); SafeNativeMethods.Gdip.CheckStatus(status); } } public PointF CenterPoint { get { PointF center; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientCenterPoint(NativeBrush, out center); SafeNativeMethods.Gdip.CheckStatus(status); return center; } set { PointF center = value; Status status = SafeNativeMethods.Gdip.GdipSetPathGradientCenterPoint(NativeBrush, ref center); SafeNativeMethods.Gdip.CheckStatus(status); } } public PointF FocusScales { get { float xScale; float yScale; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientFocusScales(NativeBrush, out xScale, out yScale); SafeNativeMethods.Gdip.CheckStatus(status); return new PointF(xScale, yScale); } set { Status status = SafeNativeMethods.Gdip.GdipSetPathGradientFocusScales(NativeBrush, value.X, value.Y); SafeNativeMethods.Gdip.CheckStatus(status); } } public ColorBlend InterpolationColors { get { int count; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientPresetBlendCount(NativeBrush, out count); SafeNativeMethods.Gdip.CheckStatus(status); // if no failure, then the "managed" minimum is 1 if (count < 1) count = 1; int[] intcolors = new int[count]; float[] positions = new float[count]; // status would fail if we ask points or types with a < 2 count if (count > 1) { status = SafeNativeMethods.Gdip.GdipGetPathGradientPresetBlend(NativeBrush, intcolors, positions, count); SafeNativeMethods.Gdip.CheckStatus(status); } ColorBlend interpolationColors = new ColorBlend(); Color[] colors = new Color[count]; for (int i = 0; i < count; i++) colors[i] = Color.FromArgb(intcolors[i]); interpolationColors.Colors = colors; interpolationColors.Positions = positions; return interpolationColors; } set { // no null check, MS throws a NullReferenceException here int count; Color[] colors = value.Colors; float[] positions = value.Positions; count = colors.Length; if (count == 0 || positions.Length == 0) throw new ArgumentException("Invalid ColorBlend object. It should have at least 2 elements in each of the colors and positions arrays."); if (count != positions.Length) throw new ArgumentException("Invalid ColorBlend object. It should contain the same number of positions and color values."); if (positions[0] != 0.0F) throw new ArgumentException("Invalid ColorBlend object. The positions array must have 0.0 as its first element."); if (positions[count - 1] != 1.0F) throw new ArgumentException("Invalid ColorBlend object. The positions array must have 1.0 as its last element."); int[] blend = new int[colors.Length]; for (int i = 0; i < colors.Length; i++) blend[i] = colors[i].ToArgb(); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientPresetBlend(NativeBrush, blend, positions, count); SafeNativeMethods.Gdip.CheckStatus(status); } } public RectangleF Rectangle { get { RectangleF rect; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientRect(NativeBrush, out rect); SafeNativeMethods.Gdip.CheckStatus(status); return rect; } } public Color[] SurroundColors { get { int count; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientSurroundColorCount(NativeBrush, out count); SafeNativeMethods.Gdip.CheckStatus(status); int[] intcolors = new int[count]; status = SafeNativeMethods.Gdip.GdipGetPathGradientSurroundColorsWithCount(NativeBrush, intcolors, ref count); SafeNativeMethods.Gdip.CheckStatus(status); Color[] colors = new Color[count]; for (int i = 0; i < count; i++) colors[i] = Color.FromArgb(intcolors[i]); return colors; } set { // no null check, MS throws a NullReferenceException here int count = value.Length; int[] colors = new int[count]; for (int i = 0; i < count; i++) colors[i] = value[i].ToArgb(); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientSurroundColorsWithCount(NativeBrush, colors, ref count); SafeNativeMethods.Gdip.CheckStatus(status); } } public Matrix Transform { get { Matrix matrix = new Matrix(); Status status = SafeNativeMethods.Gdip.GdipGetPathGradientTransform(NativeBrush, matrix.nativeMatrix); SafeNativeMethods.Gdip.CheckStatus(status); return matrix; } set { if (value == null) throw new ArgumentNullException("Transform"); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientTransform(NativeBrush, value.nativeMatrix); SafeNativeMethods.Gdip.CheckStatus(status); } } public WrapMode WrapMode { get { WrapMode wrapMode; Status status = SafeNativeMethods.Gdip.GdipGetPathGradientWrapMode(NativeBrush, out wrapMode); SafeNativeMethods.Gdip.CheckStatus(status); return wrapMode; } set { if ((value < WrapMode.Tile) || (value > WrapMode.Clamp)) throw new InvalidEnumArgumentException("WrapMode"); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientWrapMode(NativeBrush, value); SafeNativeMethods.Gdip.CheckStatus(status); } } // Methods public void MultiplyTransform(Matrix matrix) { MultiplyTransform(matrix, MatrixOrder.Prepend); } public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix == null) throw new ArgumentNullException("matrix"); Status status = SafeNativeMethods.Gdip.GdipMultiplyPathGradientTransform(NativeBrush, matrix.nativeMatrix, order); SafeNativeMethods.Gdip.CheckStatus(status); } public void ResetTransform() { Status status = SafeNativeMethods.Gdip.GdipResetPathGradientTransform(NativeBrush); SafeNativeMethods.Gdip.CheckStatus(status); } public void RotateTransform(float angle) { RotateTransform(angle, MatrixOrder.Prepend); } public void RotateTransform(float angle, MatrixOrder order) { Status status = SafeNativeMethods.Gdip.GdipRotatePathGradientTransform(NativeBrush, angle, order); SafeNativeMethods.Gdip.CheckStatus(status); } public void ScaleTransform(float sx, float sy) { ScaleTransform(sx, sy, MatrixOrder.Prepend); } public void ScaleTransform(float sx, float sy, MatrixOrder order) { Status status = SafeNativeMethods.Gdip.GdipScalePathGradientTransform(NativeBrush, sx, sy, order); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetBlendTriangularShape(float focus) { SetBlendTriangularShape(focus, 1.0F); } public void SetBlendTriangularShape(float focus, float scale) { if (focus < 0 || focus > 1 || scale < 0 || scale > 1) throw new ArgumentException("Invalid parameter passed."); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientLinearBlend(NativeBrush, focus, scale); SafeNativeMethods.Gdip.CheckStatus(status); } public void SetSigmaBellShape(float focus) { SetSigmaBellShape(focus, 1.0F); } public void SetSigmaBellShape(float focus, float scale) { if (focus < 0 || focus > 1 || scale < 0 || scale > 1) throw new ArgumentException("Invalid parameter passed."); Status status = SafeNativeMethods.Gdip.GdipSetPathGradientSigmaBlend(NativeBrush, focus, scale); SafeNativeMethods.Gdip.CheckStatus(status); } public void TranslateTransform(float dx, float dy) { TranslateTransform(dx, dy, MatrixOrder.Prepend); } public void TranslateTransform(float dx, float dy, MatrixOrder order) { Status status = SafeNativeMethods.Gdip.GdipTranslatePathGradientTransform(NativeBrush, dx, dy, order); SafeNativeMethods.Gdip.CheckStatus(status); } public override object Clone() { IntPtr clonePtr; int status = SafeNativeMethods.Gdip.GdipCloneBrush(new HandleRef(this, NativeBrush), out clonePtr); SafeNativeMethods.Gdip.CheckStatus(status); PathGradientBrush clone = new PathGradientBrush(clonePtr); return clone; } } }
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 DotNETJumpStart.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; } } }
// 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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Http; using System.Net.Security; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class OpenSsl { private static readonly Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate; private unsafe static readonly Ssl.SslCtxSetAlpnCallback s_alpnServerCallback = AlpnServerSelectCallback; private static readonly IdnMapping s_idnMapping = new IdnMapping(); #region internal methods internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType) { Debug.Assert( bindingType != ChannelBindingKind.Endpoint, "Endpoint binding should be handled by EndpointChannelBindingToken"); SafeChannelBindingHandle bindingHandle; switch (bindingType) { case ChannelBindingKind.Unique: bindingHandle = new SafeChannelBindingHandle(bindingType); QueryUniqueChannelBinding(context, bindingHandle); break; default: // Keeping parity with windows, we should return null in this case. bindingHandle = null; break; } return bindingHandle; } internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) { SafeSslHandle context = null; // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest // mutually supported version and can thus handle any of the set protocols, and we then use // SetProtocolOptions to ensure we only allow the ones requested. using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } if (!Interop.Ssl.Tls13Supported) { if (protocols != SslProtocols.None && CipherSuitesPolicyPal.WantsTls13(protocols)) { protocols = protocols & (~SslProtocols.Tls13); } } else if (CipherSuitesPolicyPal.WantsTls13(protocols) && CipherSuitesPolicyPal.ShouldOptOutOfTls13(sslAuthenticationOptions.CipherSuitesPolicy, policy)) { if (protocols == SslProtocols.None) { // we are using default settings but cipher suites policy says that TLS 1.3 // is not compatible with our settings (i.e. we requested no encryption or disabled // all TLS 1.3 cipher suites) protocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12; } else { // user explicitly asks for TLS 1.3 but their policy is not compatible with TLS 1.3 throw new SslException( SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } } if (CipherSuitesPolicyPal.ShouldOptOutOfLowerThanTls13(sslAuthenticationOptions.CipherSuitesPolicy, policy)) { if (!CipherSuitesPolicyPal.WantsTls13(protocols)) { // We cannot provide neither TLS 1.3 or non TLS 1.3, user disabled all cipher suites throw new SslException( SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } protocols = SslProtocols.Tls13; } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just // create the handle, it's rooted by the using, no one else has a reference to it, etc. Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); // Sets policy and security level if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { throw new SslException( SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet // shutdown (we aren't negotiating for session close to enable later session // restoration). // // If you find yourself wanting to remove this line to enable bidirectional // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html Ssl.SslCtxSetQuietShutdown(innerContext); byte[] cipherList = CipherSuitesPolicyPal.GetOpenSslCipherList(sslAuthenticationOptions.CipherSuitesPolicy, protocols, policy); Debug.Assert(cipherList == null || (cipherList.Length >= 1 && cipherList[cipherList.Length - 1] == 0)); byte[] cipherSuites = CipherSuitesPolicyPal.GetOpenSslCipherSuites(sslAuthenticationOptions.CipherSuitesPolicy, protocols, policy); Debug.Assert(cipherSuites == null || (cipherSuites.Length >= 1 && cipherSuites[cipherSuites.Length - 1] == 0)); unsafe { fixed (byte* cipherListStr = cipherList) fixed (byte* cipherSuitesStr = cipherSuites) { if (!Ssl.SetCiphers(innerContext, cipherListStr, cipherSuitesStr)) { Crypto.ErrClearError(); throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } } } bool hasCertificateAndKey = certHandle != null && !certHandle.IsInvalid && certKeyHandle != null && !certKeyHandle.IsInvalid; if (hasCertificateAndKey) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) { Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); } GCHandle alpnHandle = default; try { if (sslAuthenticationOptions.ApplicationProtocols != null) { if (sslAuthenticationOptions.IsServer) { alpnHandle = GCHandle.Alloc(sslAuthenticationOptions.ApplicationProtocols); Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(alpnHandle)); } else { if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) { throw CreateSslException(SR.net_alpn_config_failed); } } } context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } if (!sslAuthenticationOptions.IsServer) { // The IdnMapping converts unicode input into the IDNA punycode sequence. string punyCode = s_idnMapping.GetAscii(sslAuthenticationOptions.TargetHost); // Similar to windows behavior, set SNI on openssl by default for client context, ignore errors. if (!Ssl.SslSetTlsExtHostName(context, punyCode)) { Crypto.ErrClearError(); } } if (hasCertificateAndKey) { bool hasCertReference = false; try { certHandle.DangerousAddRef(ref hasCertReference); using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) { X509Chain chain = null; try { chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false); if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) { throw CreateSslException(SR.net_ssl_use_cert_failed); } } finally { if (chain != null) { int elementsCount = chain.ChainElements.Count; for (int i = 0; i < elementsCount; i++) { chain.ChainElements[i].Certificate.Dispose(); } chain.Dispose(); } } } } finally { if (hasCertReference) certHandle.DangerousRelease(); } } context.AlpnHandle = alpnHandle; } catch { if (alpnHandle.IsAllocated) { alpnHandle.Free(); } throw; } } return context; } internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; if ((recvBuf != null) && (recvCount > 0)) { if (BioWrite(context.InputBio, recvBuf, recvOffset, recvCount) <= 0) { // Make sure we clear out the error that is stored in the queue throw Crypto.CreateOpenSslCryptographicException(); } } int retVal = Ssl.SslDoHandshake(context); if (retVal != 1) { Exception innerError; Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) { throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError); } } sendCount = Crypto.BioCtrlPending(context.OutputBio); if (sendCount > 0) { sendBuf = new byte[sendCount]; try { sendCount = BioRead(context.OutputBio, sendBuf, sendCount); } finally { if (sendCount <= 0) { // Make sure we clear out the error that is stored in the queue Crypto.ErrClearError(); sendBuf = null; sendCount = 0; } } } bool stateOk = Ssl.IsSslStateOK(context); if (stateOk) { context.MarkHandshakeCompleted(); } return stateOk; } internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory<byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode) { #if DEBUG ulong assertNoError = Crypto.ErrPeekError(); Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); #endif errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal; Exception innerError = null; lock (context) { unsafe { using (MemoryHandle handle = input.Pin()) { retVal = Ssl.SslWrite(context, (byte*)handle.Pointer, input.Length); } } if (retVal != input.Length) { errorCode = GetSslError(context, retVal, out innerError); } } if (retVal != input.Length) { retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: break; default: throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError); } } else { int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio); if (output == null || output.Length < capacityNeeded) { output = new byte[capacityNeeded]; } retVal = BioRead(context.OutputBio, output, capacityNeeded); if (retVal <= 0) { // Make sure we clear out the error that is stored in the queue Crypto.ErrClearError(); } } return retVal; } internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode) { #if DEBUG ulong assertNoError = Crypto.ErrPeekError(); Debug.Assert(assertNoError == 0, "OpenSsl error queue is not empty, run: 'openssl errstr " + assertNoError.ToString("X") + "' for original error."); #endif errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal = BioWrite(context.InputBio, outBuffer, offset, count); Exception innerError = null; lock (context) { if (retVal == count) { unsafe { fixed (byte* fixedBuffer = outBuffer) { retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length); } } if (retVal > 0) { count = retVal; } } if (retVal != count) { errorCode = GetSslError(context, retVal, out innerError); } } if (retVal != count) { retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: break; case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ errorCode = Ssl.IsSslRenegotiatePending(context) ? Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : Ssl.SslErrorCode.SSL_ERROR_WANT_READ; break; default: throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError); } } return retVal; } internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context) { return Ssl.SslGetPeerCertificate(context); } internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context) { return Ssl.SslGetPeerCertChain(context); } #endregion #region private methods private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle) { bool sessionReused = Ssl.SslSessionReused(context); int certHashLength = context.IsServer ^ sessionReused ? Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) : Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length); if (0 == certHashLength) { throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed); } bindingHandle.SetCertHashLength(certHashLength); } private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) { // Full validation is handled after the handshake in VerifyCertificateProperties and the // user callback. It's also up to those handlers to decide if a null certificate // is appropriate. So just return success to tell OpenSSL that the cert is acceptable, // we'll process it after the handshake finishes. const int OpenSslSuccess = 1; return OpenSslSuccess; } private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out byte* outp, out byte outlen, byte* inp, uint inlen, IntPtr arg) { outp = null; outlen = 0; GCHandle protocolHandle = GCHandle.FromIntPtr(arg); if (!(protocolHandle.Target is List<SslApplicationProtocol> protocolList)) { return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL; } try { for (int i = 0; i < protocolList.Count; i++) { var clientList = new Span<byte>(inp, (int)inlen); while (clientList.Length > 0) { byte length = clientList[0]; Span<byte> clientProto = clientList.Slice(1, length); if (clientProto.SequenceEqual(protocolList[i].Protocol.Span)) { fixed (byte* p = &MemoryMarshal.GetReference(clientProto)) outp = p; outlen = length; return Ssl.SSL_TLSEXT_ERR_OK; } clientList = clientList.Slice(1 + length); } } } catch { // No common application protocol was negotiated, set the target on the alpnHandle to null. // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. protocolHandle.Target = null; return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL; } // No common application protocol was negotiated, set the target on the alpnHandle to null. // It is ok to clear the handle value here, this results in handshake failure, so the SslStream object is disposed. protocolHandle.Target = null; return Ssl.SSL_TLSEXT_ERR_ALERT_FATAL; } private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= count); int bytes = Crypto.BioRead(bio, buffer, count); if (bytes != count) { throw CreateSslException(SR.net_ssl_read_bio_failed_error); } return bytes; } private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= offset + count); int bytes; unsafe { fixed (byte* bufPtr = buffer) { bytes = Ssl.BioWrite(bio, bufPtr + offset, count); } } if (bytes != count) { throw CreateSslException(SR.net_ssl_write_bio_failed_error); } return bytes; } private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError) { ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result); switch (retVal) { case Ssl.SslErrorCode.SSL_ERROR_SYSCALL: // Some I/O error occurred innerError = Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty result == 0 ? new EndOfStreamException() : // end of file that violates protocol result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error null; // no additional info available break; case Ssl.SslErrorCode.SSL_ERROR_SSL: // OpenSSL failure occurred. The error queue contains more details, when building the exception the queue will be cleared. innerError = Interop.Crypto.CreateOpenSslCryptographicException(); break; default: // No additional info available. innerError = null; break; } return retVal; } private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr) { Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid"); Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid"); int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_cert_failed); } retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_private_key_failed); } //check private key retVal = Ssl.SslCtxCheckPrivateKey(contextPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_check_private_key_failed); } } internal static SslException CreateSslException(string message) { // Capture last error to be consistent with CreateOpenSslCryptographicException ulong errorVal = Crypto.ErrPeekLastError(); Crypto.ErrClearError(); string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); return new SslException(msg, (int)errorVal); } #endregion #region Internal class internal sealed class SslException : Exception { public SslException(string inputMessage) : base(inputMessage) { } public SslException(string inputMessage, Exception ex) : base(inputMessage, ex) { } public SslException(string inputMessage, int error) : this(inputMessage) { HResult = error; } public SslException(int error) : this(SR.Format(SR.net_generic_operation_failed, error)) { HResult = error; } } #endregion } }
/* * NPlot - A charting library for .NET * * DateTimeAxis.cs * Copyright (C) 2003-2006 Matt Howlett and others. * 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. Neither the name of NPlot nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; // TODO: More control over how labels are displayed. // TODO: SkipWeekends property. // TODO: Make a relative (as opposed to absolute) TimeAxis. namespace NPlot { /// <summary> /// The DateTimeAxis class /// </summary> public class DateTimeAxis : Axis { #region Clone implementation /// <summary> /// Deep copy of DateTimeAxis. /// </summary> /// <returns>A copy of the DateTimeAxis Class.</returns> public override object Clone() { DateTimeAxis a = new DateTimeAxis(); // ensure that this isn't being called on a derived type. If it is, then oh no! if (this.GetType() != a.GetType()) { throw new NPlotException("Clone not defined in derived type. Help!"); } DoClone(this, a); return a; } /// <summary> /// Helper method for Clone. /// </summary> /// <param name="a">The original object to clone.</param> /// <param name="b">The cloned object.</param> protected static void DoClone(DateTimeAxis b, DateTimeAxis a) { Axis.DoClone(b, a); } #endregion private void Init() { } /// <summary> /// Constructor /// </summary> /// <param name="a">Axis to construct from</param> public DateTimeAxis(Axis a) : base(a) { this.Init(); this.NumberFormat = null; } /// <summary> /// Default Constructor /// </summary> public DateTimeAxis() : base() { this.Init(); } /// <summary> /// Constructor /// </summary> /// <param name="worldMin">World min of axis</param> /// <param name="worldMax">World max of axis</param> public DateTimeAxis(double worldMin, double worldMax) : base(worldMin, worldMax) { this.Init(); } /// <summary> /// Constructor /// </summary> /// <param name="worldMin">World min of axis</param> /// <param name="worldMax">World max of axis</param> public DateTimeAxis(long worldMin, long worldMax) : base(worldMin, worldMax) { this.Init(); } /// <summary> /// Constructor /// </summary> /// <param name="worldMin">World min of axis</param> /// <param name="worldMax">World max of axis</param> public DateTimeAxis(DateTime worldMin, DateTime worldMax) : base(worldMin.Ticks, worldMax.Ticks) { this.Init(); } /// <summary> /// Draw the ticks. /// </summary> /// <param name="g">The drawing surface on which to draw.</param> /// <param name="physicalMin">The minimum physical extent of the axis.</param> /// <param name="physicalMax">The maximum physical extent of the axis.</param> /// <param name="boundingBox">out: smallest box that completely encompasses all of the ticks and tick labels.</param> /// <param name="labelOffset">out: a suitable offset from the axis to draw the axis label.</param> protected override void DrawTicks( Graphics g, Point physicalMin, Point physicalMax, out object labelOffset, out object boundingBox) { // TODO: Look at offset and bounding box logic again here. why temp and other vars? Point tLabelOffset; Rectangle tBoundingBox; labelOffset = this.getDefaultLabelOffset(physicalMin, physicalMax); boundingBox = null; this.WorldTickPositions(physicalMin, physicalMax, out List<double> largeTicks, out List<double> smallTicks); // draw small ticks. for (int i = 0; i < smallTicks.Count; ++i) { this.DrawTick(g, (double)smallTicks[i], this.SmallTickSize, "", new Point(0, 0), physicalMin, physicalMax, out _, out _); // assume label offset and bounding box unchanged by small tick bounds. } // draw large ticks. for (int i = 0; i < largeTicks.Count; ++i) { DateTime tickDate = new DateTime((long)(double)largeTicks[i]); string label = LargeTickLabel(tickDate); this.DrawTick(g, (double)largeTicks[i], this.LargeTickSize, label, new Point(0, 0), physicalMin, physicalMax, out tLabelOffset, out tBoundingBox); UpdateOffsetAndBounds(ref labelOffset, ref boundingBox, tLabelOffset, tBoundingBox); } } /// <summary> /// Get the label corresponding to the provided date time /// </summary> /// <param name="tickDate">the date time to get the label for</param> /// <returns>label for the provided DateTime</returns> protected virtual string LargeTickLabel(DateTime tickDate) { string label = ""; if (this.NumberFormat is null || this.NumberFormat == String.Empty) { if (this.LargeTickLabelType_ == LargeTickLabelType.year) { label = tickDate.Year.ToString(); } else if (this.LargeTickLabelType_ == LargeTickLabelType.month) { label = tickDate.ToString("MMM"); label += " "; label += tickDate.Year.ToString().Substring(2, 2); } else if (this.LargeTickLabelType_ == LargeTickLabelType.day) { label = tickDate.Day.ToString(); label += " "; label += tickDate.ToString("MMM"); } else if (this.LargeTickLabelType_ == LargeTickLabelType.hourMinute) { string minutes = tickDate.Minute.ToString(); if (minutes.Length == 1) { minutes = "0" + minutes; } label = tickDate.Hour.ToString() + ":" + minutes; } else if (this.LargeTickLabelType_ == LargeTickLabelType.hourMinuteSeconds) { string minutes = tickDate.Minute.ToString(); string seconds = tickDate.Second.ToString(); if (seconds.Length == 1) { seconds = "0" + seconds; } if (minutes.Length == 1) { minutes = "0" + minutes; } label = tickDate.Hour.ToString() + ":" + minutes + "." + seconds; } } else { label = tickDate.ToString(NumberFormat); } return label; } /// <summary> /// Enumerates the different types of tick label possible. /// </summary> protected enum LargeTickLabelType { /// <summary> /// default - no tick labels. /// </summary> none = 0, /// <summary> /// tick labels should be years /// </summary> year = 1, /// <summary> /// Tick labels should be month names /// </summary> month = 2, /// <summary> /// Tick labels should be day names /// </summary> day = 3, /// <summary> /// Tick labels should be hour / minutes. /// </summary> hourMinute = 4, /// <summary> /// tick labels should be hour / minute / second. /// </summary> hourMinuteSeconds = 5 } /// <summary> /// this gets set after a get LargeTickPositions. /// </summary> protected LargeTickLabelType LargeTickLabelType_; /// <summary> /// Determines the positions, in world coordinates, of the large ticks. No /// small tick marks are currently calculated by this method. /// /// </summary> /// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param> /// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param> /// <param name="largeTickPositions">ArrayList containing the positions of the large ticks.</param> /// <param name="smallTickPositions">null</param> internal override void WorldTickPositions_FirstPass( Point physicalMin, Point physicalMax, out List<double> largeTickPositions, out List<double> smallTickPositions ) { smallTickPositions = null; largeTickPositions = new List<double>(); const int daysInMonth = 30; if (WorldMin < DateTime.MinValue.Ticks) WorldMin = DateTime.MinValue.Ticks; if (WorldMax > DateTime.MaxValue.Ticks) WorldMax = DateTime.MaxValue.Ticks; TimeSpan timeLength = new TimeSpan((long)(WorldMax - WorldMin)); DateTime worldMinDate = new DateTime((long)this.WorldMin); DateTime worldMaxDate = new DateTime((long)this.WorldMax); if (largeTickStep_ == TimeSpan.Zero) { // if less than 10 minutes, then large ticks on second spacings. if (timeLength < new TimeSpan(0, 0, 2, 0, 0)) { this.LargeTickLabelType_ = LargeTickLabelType.hourMinuteSeconds; double secondsSkip; if (timeLength < new TimeSpan(0, 0, 0, 10, 0)) secondsSkip = 1.0; else if (timeLength < new TimeSpan(0, 0, 0, 20, 0)) secondsSkip = 2.0; else if (timeLength < new TimeSpan(0, 0, 0, 50, 0)) secondsSkip = 5.0; else if (timeLength < new TimeSpan(0, 0, 2, 30, 0)) secondsSkip = 15.0; else secondsSkip = 30.0; int second = worldMinDate.Second; second -= second % (int)secondsSkip; DateTime currentTickDate = new DateTime( worldMinDate.Year, worldMinDate.Month, worldMinDate.Day, worldMinDate.Hour, worldMinDate.Minute, second, 0); while (currentTickDate < worldMaxDate) { double world = currentTickDate.Ticks; if (world >= this.WorldMin && world <= this.WorldMax) { largeTickPositions.Add(world); } currentTickDate = currentTickDate.AddSeconds(secondsSkip); } } // Less than 2 hours, then large ticks on minute spacings. else if (timeLength < new TimeSpan(0, 2, 0, 0, 0)) { this.LargeTickLabelType_ = LargeTickLabelType.hourMinute; double minuteSkip; if (timeLength < new TimeSpan(0, 0, 10, 0, 0)) minuteSkip = 1.0; else if (timeLength < new TimeSpan(0, 0, 20, 0, 0)) minuteSkip = 2.0; else if (timeLength < new TimeSpan(0, 0, 50, 0, 0)) minuteSkip = 5.0; else if (timeLength < new TimeSpan(0, 2, 30, 0, 0)) minuteSkip = 15.0; else //( timeLength < new TimeSpan( 0,5,0,0,0) ) minuteSkip = 30.0; int minute = worldMinDate.Minute; minute -= minute % (int)minuteSkip; DateTime currentTickDate = new DateTime( worldMinDate.Year, worldMinDate.Month, worldMinDate.Day, worldMinDate.Hour, minute, 0, 0); while (currentTickDate < worldMaxDate) { double world = currentTickDate.Ticks; if (world >= this.WorldMin && world <= this.WorldMax) { largeTickPositions.Add(world); } currentTickDate = currentTickDate.AddMinutes(minuteSkip); } } // Less than 2 days, then large ticks on hour spacings. else if (timeLength < new TimeSpan(2, 0, 0, 0, 0)) { this.LargeTickLabelType_ = LargeTickLabelType.hourMinute; double hourSkip; if (timeLength < new TimeSpan(0, 10, 0, 0, 0)) hourSkip = 1.0; else if (timeLength < new TimeSpan(0, 20, 0, 0, 0)) hourSkip = 2.0; else hourSkip = 6.0; int hour = worldMinDate.Hour; hour -= hour % (int)hourSkip; DateTime currentTickDate = new DateTime( worldMinDate.Year, worldMinDate.Month, worldMinDate.Day, hour, 0, 0, 0); while (currentTickDate < worldMaxDate) { double world = currentTickDate.Ticks; if (world >= this.WorldMin && world <= this.WorldMax) { largeTickPositions.Add(world); } currentTickDate = currentTickDate.AddHours(hourSkip); } } // less than 5 months, then large ticks on day spacings. else if (timeLength < new TimeSpan(daysInMonth * 4, 0, 0, 0, 0)) { this.LargeTickLabelType_ = LargeTickLabelType.day; double daySkip; if (timeLength < new TimeSpan(10, 0, 0, 0, 0)) daySkip = 1.0; else if (timeLength < new TimeSpan(20, 0, 0, 0, 0)) daySkip = 2.0; else if (timeLength < new TimeSpan(7 * 10, 0, 0, 0, 0)) daySkip = 7.0; else daySkip = 14.0; DateTime currentTickDate = new DateTime( worldMinDate.Year, worldMinDate.Month, worldMinDate.Day); if (daySkip == 2.0) { TimeSpan timeSinceBeginning = currentTickDate - DateTime.MinValue; if (timeSinceBeginning.Days % 2 == 1) currentTickDate = currentTickDate.AddDays(-1.0); } if (daySkip == 7 || daySkip == 14.0) { DayOfWeek dow = currentTickDate.DayOfWeek; switch (dow) { case DayOfWeek.Monday: break; case DayOfWeek.Tuesday: currentTickDate = currentTickDate.AddDays(-1.0); break; case DayOfWeek.Wednesday: currentTickDate = currentTickDate.AddDays(-2.0); break; case DayOfWeek.Thursday: currentTickDate = currentTickDate.AddDays(-3.0); break; case DayOfWeek.Friday: currentTickDate = currentTickDate.AddDays(-4.0); break; case DayOfWeek.Saturday: currentTickDate = currentTickDate.AddDays(-5.0); break; case DayOfWeek.Sunday: currentTickDate = currentTickDate.AddDays(-6.0); break; } } if (daySkip == 14.0f) { TimeSpan timeSinceBeginning = currentTickDate - DateTime.MinValue; if (timeSinceBeginning.Days / 7 % 2 == 1) { currentTickDate = currentTickDate.AddDays(-7.0); } } while (currentTickDate < worldMaxDate) { double world = currentTickDate.Ticks; if (world >= this.WorldMin && world <= this.WorldMax) { largeTickPositions.Add(world); } currentTickDate = currentTickDate.AddDays(daySkip); } } // else ticks on month or year spacings. else if (timeLength >= new TimeSpan(daysInMonth * 4, 0, 0, 0, 0)) { int monthSpacing = 0; if (timeLength.Days < daysInMonth * (12 * 3 + 6)) { LargeTickLabelType_ = LargeTickLabelType.month; if (timeLength.Days < daysInMonth * 10) monthSpacing = 1; else if (timeLength.Days < daysInMonth * 12 * 2) monthSpacing = 3; else // if ( timeLength.Days < daysInMonth*(12*3+6) ) monthSpacing = 6; } else { LargeTickLabelType_ = LargeTickLabelType.year; if (timeLength.Days < daysInMonth * 12 * 6) monthSpacing = 12; else if (timeLength.Days < daysInMonth * 12 * 12) monthSpacing = 24; else if (timeLength.Days < daysInMonth * 12 * 30) monthSpacing = 60; else monthSpacing = 120; //LargeTickLabelType_ = LargeTickLabelType.none; } // truncate start DateTime currentTickDate = new DateTime( worldMinDate.Year, worldMinDate.Month, 1); if (monthSpacing > 1) { currentTickDate = currentTickDate.AddMonths( -(currentTickDate.Month - 1) % monthSpacing); } // Align on 2 or 5 year boundaries if necessary. if (monthSpacing >= 24) { currentTickDate = currentTickDate.AddYears( -currentTickDate.Year % (monthSpacing / 12)); } //this.firstLargeTick_ = (double)currentTickDate.Ticks; if (LargeTickLabelType_ != LargeTickLabelType.none) { while (currentTickDate < worldMaxDate) { double world = currentTickDate.Ticks; if (world >= this.WorldMin && world <= this.WorldMax) { largeTickPositions.Add(world); } currentTickDate = currentTickDate.AddMonths(monthSpacing); } } } } else { for (DateTime date = worldMinDate; date < worldMaxDate; date += largeTickStep_) { largeTickPositions.Add(date.Ticks); } } } /// <summary> /// Compute the small tick positions for largetick size of one or more years. /// - inside the domain or the large tick positons, is take the mid-point of pairs of large ticks /// - outside the large tick range, check if a half tick is inside the world min/max /// This method works only if there are atleast 2 large ticks, /// since we don't know if its minutes, hours, month, or yearly divisor. /// </summary> /// <param name="physicalMin">The physical position corresponding to the world minimum of the axis.</param> /// <param name="physicalMax">The physical position corresponding to the world maximum of the axis.</param> /// <param name="largeTickPositions">Read in the large tick positions</param> /// <param name="smallTickPositions">Fill in the corresponding small tick positions</param> /// <remarks>Added by Rosco Hill</remarks> internal override void WorldTickPositions_SecondPass( Point physicalMin, Point physicalMax, List<double> largeTickPositions, ref List<double> smallTickPositions ) { if (largeTickPositions.Count < 2 || !LargeTickLabelType_.Equals(LargeTickLabelType.year)) { smallTickPositions = new List<double>(); ; } else { smallTickPositions = new List<double>(); double diff = 0.5 * ((double)largeTickPositions[1] - (double)largeTickPositions[0]); if ((double)largeTickPositions[0] - diff > this.WorldMin) { smallTickPositions.Add((double)largeTickPositions[0] - diff); } for (int i = 0; i < largeTickPositions.Count - 1; i++) { smallTickPositions.Add((double)largeTickPositions[i] + diff); } if ((double)largeTickPositions[largeTickPositions.Count - 1] + diff < this.WorldMax) { smallTickPositions.Add((double)largeTickPositions[largeTickPositions.Count - 1] + diff); } } } /// <summary> /// The distance between large ticks. If this is set to Zero [default], /// this distance will be calculated automatically. /// </summary> public TimeSpan LargeTickStep { set => largeTickStep_ = value; get => largeTickStep_; } private TimeSpan largeTickStep_ = TimeSpan.Zero; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace ODataValidator.RuleEngine { #region Namespaces using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Xml.Linq; using System.Xml.XPath; using ODataValidator.RuleEngine.Common; #endregion /// <summary> /// Helper class to instantiate service request context /// </summary> public static class ServiceContextFactory { /// <summary> /// Factory method to create the crawling metadata service context /// </summary> /// <param name="metaTarget">location pointing to the OData metadata document resource</param> /// <param name="serviceRoot">URI pointing to the OData service document resource</param> /// <param name="serviceDocument">Content of service document</param> /// <param name="metadataDocument">Content of metadata document</param> /// <param name="jobId">The validation job identifier</param> /// <param name="reqHeaders">Http headers sent as part of request</param> /// <returns>The constructed crawling metadata context</returns> /// <exception cref="CrawlRuntimeException">Throws exception when metadata document cannot be fetched</exception> /// <exception cref="ArgumentException">Throws exception when the metadata document content is empty or null</exception> public static ServiceContext CreateMetadataContext(Uri metaTarget, Uri serviceRoot, string serviceDocument, string metadataDocument, Guid jobId, IEnumerable<KeyValuePair<string, string>> reqHeaders, string respHeaders, string category = "core") { if (string.IsNullOrEmpty(metadataDocument)) { throw new ArgumentException(Resource.ArgumentNotNullOrEmpty, "metadataDocument"); } return new ServiceContext(metaTarget, jobId, HttpStatusCode.OK, respHeaders, metadataDocument, null, serviceRoot, serviceDocument, metadataDocument, false, reqHeaders, ODataMetadataType.MinOnly, null, category); } /// <summary> /// Factory method to create the light-weight online service context (without fetching service document and metadata document which are known already) /// </summary> /// <param name="target">The target resource to be crawled</param> /// <param name="acceptHeaderValue">The accept header value defined in the Http header</param> /// <param name="serviceRoot">The URI pointing to the service document resource</param> /// <param name="serviceDocument">The content of service document</param> /// <param name="metadataDocument">The content of metadata document</param> /// <param name="jobId">The validation job identifier</param> /// <param name="maximumPayloadSize">The maximum number of bytes allowed to retrieve from the target resource</param> /// <param name="reqHeaders">Http headers sent as part of request</param> /// <returns>The constructed service context</returns> /// <exception cref="CrawlRuntimeException">Throws exception when target resource exceeds the maximum size allowed</exception> public static ServiceContext Create(Uri target, string acceptHeaderValue, Uri serviceRoot, string serviceDocument, string metadataDocument, Guid jobId, int maximumPayloadSize, IEnumerable<KeyValuePair<string, string>> reqHeaders, string category="core") { Response response = WebHelper.Get(target, acceptHeaderValue, maximumPayloadSize, reqHeaders); ODataMetadataType odataMetadata = ServiceContextFactory.MapAcceptHeaderToMetadataType(acceptHeaderValue); var payloadFormat = response.ResponsePayload.GetFormatFromPayload(); var payloadType = response.ResponsePayload.GetTypeFromPayload(payloadFormat); string entityType = response.ResponsePayload.GetFullEntityType(payloadType, payloadFormat, metadataDocument); return new ServiceContext(target, jobId, response.StatusCode, response.ResponseHeaders, response.ResponsePayload, entityType, serviceRoot, serviceDocument, metadataDocument, false, reqHeaders, odataMetadata, null, category); } /// <summary> /// Factory method to set up the OData Interop context based on uri, desired format and job id /// </summary> /// <param name="destination">uri string pointing to a OData service endpoint</param> /// <param name="format">format preference, could be either "atom" or "json" - default and falling back to atom</param> /// <param name="jobId">unique identifier to tag this context</param> /// <param name="maximumPayloadSize">the maximum number of bytes rule engine is willing to retrieve from the Uri provided</param> /// <param name="reqHeaders">Http headers sent as part of request</param> /// <returns>context object representing the interop request session</returns> public static ServiceContext Create(string destination, string format, Guid jobId, int maximumPayloadSize, IEnumerable<KeyValuePair<string, string>> reqHeaders, string category="core") { Uri inputUri; Uri serviceBaseUri = null; string serviceDocument = null; string metadataDocument = null; string entityType = null; string jsonFullMetadataPayload = null; var serviceStatus = ServiceStatus.GetInstance(); if (string.IsNullOrEmpty(format)) { throw new ArgumentException(Resource.ArgumentNotNullOrEmpty, "format"); } try { if (destination.EndsWith(@"/")) { destination = destination.TrimEnd('/'); } inputUri = new Uri(destination); } catch (UriFormatException) { if (!destination.StartsWith(@"http://") && !destination.StartsWith(@"https://")) { inputUri = new Uri(SupportedScheme.SchemeHttp + "://" + destination); } else { inputUri = new Uri(Uri.EscapeUriString(destination)); } } if (!SupportedScheme.Instance.Contains(inputUri.Scheme)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resource.formatSchemeNotSupported, inputUri.Scheme), "destination"); } string acceptHeader = ServiceContextFactory.MapFormatToAcceptValue(format); ODataMetadataType odataMetadata = ServiceContextFactory.MapFormatToMetadataType(format); Response response = WebHelper.Get(inputUri, acceptHeader, maximumPayloadSize, reqHeaders); if (response.StatusCode == HttpStatusCode.NotFound) { return null; } var payloadFormat = response.ResponsePayload.GetFormatFromPayload(); var payloadType = ContextHelper.GetPayloadType(response.ResponsePayload, payloadFormat, response.ResponseHeaders); switch (payloadType) { case PayloadType.ServiceDoc: serviceBaseUri = inputUri; serviceDocument = response.ResponsePayload; break; case PayloadType.Metadata: if (inputUri.AbsoluteUri.EndsWith(Constants.OptionMetadata, StringComparison.Ordinal)) { if (payloadFormat == PayloadFormat.JsonLight) { serviceBaseUri = new Uri(serviceStatus.RootURL); serviceDocument = serviceStatus.ServiceDocument; } else { serviceBaseUri = new Uri(inputUri.AbsoluteUri.Substring(0, inputUri.AbsoluteUri.Length - Constants.OptionMetadata.Length)); var respSvcDoc = WebHelper.Get(serviceBaseUri, acceptHeader, maximumPayloadSize, reqHeaders); serviceDocument = respSvcDoc.ResponsePayload; } } break; default: if (payloadType.IsValidPayload()) { string fullPath = inputUri.GetLeftPart(UriPartial.Path).TrimEnd('/'); var uriPath = new Uri(fullPath); Uri baseUri; Response serviceDoc; if (ServiceContextFactory.TryGetServiceDocument(maximumPayloadSize, uriPath, acceptHeader, uriPath.AbsoluteUri == fullPath, out baseUri, out serviceDoc, reqHeaders)) { serviceBaseUri = baseUri; serviceDocument = serviceDoc.ResponsePayload; } } break; } if (payloadType == PayloadType.Metadata) { metadataDocument = response.ResponsePayload; } else { if (serviceBaseUri != null) { if (payloadFormat == PayloadFormat.JsonLight && payloadType == PayloadType.ServiceDoc) { metadataDocument = serviceStatus.MetadataDocument; } else { try { string metadataURL = serviceBaseUri.AbsoluteUri.EndsWith(@"/") ? Constants.OptionMetadata.TrimStart('/') : Constants.OptionMetadata; var responseMetadata = WebHelper.Get(new Uri(serviceBaseUri.AbsoluteUri + metadataURL), null, maximumPayloadSize, reqHeaders); if (responseMetadata != null) { metadataDocument = responseMetadata.ResponsePayload; } } catch (OversizedPayloadException) { // do nothing } } } } if (payloadFormat == PayloadFormat.JsonLight) { try { // Specify full metadata accept header string acceptHeaderOfFullMetadata = string.Empty; if (acceptHeader.Equals(Constants.V3AcceptHeaderJsonFullMetadata) || acceptHeader.Equals(Constants.V3AcceptHeaderJsonMinimalMetadata) || acceptHeader.Equals(Constants.V3AcceptHeaderJsonNoMetadata)) { acceptHeaderOfFullMetadata = Constants.V3AcceptHeaderJsonFullMetadata; } else { acceptHeaderOfFullMetadata = Constants.V4AcceptHeaderJsonFullMetadata; } // Send full metadata request and get full metadata response. var responseFullMetadata = WebHelper.Get(inputUri, acceptHeaderOfFullMetadata, maximumPayloadSize, reqHeaders); if (responseFullMetadata != null) { jsonFullMetadataPayload = responseFullMetadata.ResponsePayload; entityType = jsonFullMetadataPayload.GetFullEntityType(payloadType, payloadFormat, metadataDocument); } } catch (OversizedPayloadException) { // do nothing } } else { entityType = response.ResponsePayload.GetFullEntityType(payloadType, payloadFormat, metadataDocument); } return new ServiceContext(inputUri, jobId, response.StatusCode, response.ResponseHeaders, response.ResponsePayload, entityType, serviceBaseUri, serviceDocument, metadataDocument, false, reqHeaders, odataMetadata, jsonFullMetadataPayload, category); } /// <summary> /// Creates an offline service context with specified job id from payload context and metadata document. /// </summary> /// <param name="payload">The payload context</param> /// <param name="metadata">The metadata document</param> /// <param name="jobId">The job id</param> /// <param name="respHeaders">The optional Http response headers</param> /// <param name="reqHeaders">The request headers</param> /// <returns>Service context object which represents the offline interop validation session</returns> public static ServiceContext Create(string payload, string metadata, Guid jobId, string respHeaders, IEnumerable<KeyValuePair<string, string>> reqHeaders) { if (string.IsNullOrEmpty(payload) && string.IsNullOrEmpty(metadata)) { throw new ArgumentException("invalid parameters"); } if (string.IsNullOrEmpty(payload)) { payload = metadata; metadata = null; } Uri inputUri = new Uri(Constants.DefaultOfflineTarget); string entityType = null; Uri serviceBaseUri = null; string serviceDocument = null; string metadataDocument = null; var payloadFormat = payload.GetFormatFromPayload(); var payloadType = payload.GetTypeFromPayload(payloadFormat); ODataMetadataType metadataType = ServiceContextFactory.GetMetadataTypeFromOfflineHeader(respHeaders); if (payloadType != PayloadType.Metadata && !string.IsNullOrEmpty(metadata)) { var metaFormat = metadata.GetFormatFromPayload(); if (metaFormat == PayloadFormat.Xml) { var metaType = metadata.GetTypeFromPayload(metaFormat); if (metaType == PayloadType.Metadata) { //do sanity check to ensure a matching metadata, should payload be a feed or an entry if (IsMetadataMacthing(payload, metadata, payloadFormat, payloadType)) { metadataDocument = metadata; } } } } switch (payloadType) { case PayloadType.ServiceDoc: serviceDocument = payload; if (payloadFormat == PayloadFormat.Xml || payloadFormat == PayloadFormat.Atom) { XElement payloadXml = XElement.Parse(payload); XNamespace ns = "http://www.w3.org/XML/1998/namespace"; // xmlns:xml definition according to http://www.w3.org/TR/REC-xml-names/ var xmlBase = payloadXml.Attribute(ns + "base"); // rfc5023: it MAY have an "xml:base" attribute ... serving as the base URI if (xmlBase != null && !string.IsNullOrEmpty(xmlBase.Value)) { inputUri = new Uri(xmlBase.Value); } } break; case PayloadType.Metadata: serviceDocument = null; metadataDocument = payload; break; case PayloadType.Error: break; case PayloadType.Feed: case PayloadType.Entry: { entityType = payload.GetFullEntityType(payloadType, payloadFormat, metadataDocument); string shortEntityTypeName = entityType.GetLastSegment(); string target = payload.GetIdFromFeedOrEntry(payloadFormat); if (!string.IsNullOrEmpty(target)) { var projectedProperties = payload.GetProjectedPropertiesFromFeedOrEntry(payloadFormat, metadataDocument, shortEntityTypeName); if (projectedProperties != null && projectedProperties.Any()) { var opt = string.Join(",", projectedProperties); try { inputUri = new Uri(target + "?$select=" + opt); } catch (UriFormatException) { //do nothing } } else { try { inputUri = new Uri(target); } catch (UriFormatException) { //do nothing } } } } break; } return new ServiceContext(inputUri, jobId, null, respHeaders, payload, entityType, serviceBaseUri, serviceDocument, metadataDocument, true, reqHeaders, metadataType); } /// <summary> /// Decides whether the payload and metadata are matched /// </summary> /// <param name="payload">The payload content</param> /// <param name="metadata">The metadata document content</param> /// <param name="payloadFormat">The payload format</param> /// <param name="payloadType">The payload type</param> /// <returns>True if they are matched; false otherwise</returns> private static bool IsMetadataMacthing(string payload, string metadata, PayloadFormat payloadFormat, PayloadType payloadType) { bool matched = false; // only payloads of feed or entry can check metadata matching if (payloadType == PayloadType.Feed || payloadType == PayloadType.Entry) { XElement xmlMetadata; if (metadata.TryToXElement(out xmlMetadata)) { // try to extract domain namespace defined as attribute of edmN:Schema node in CSDL metadata var nodeSchema = xmlMetadata.XPathSelectElement("/*/*[local-name()='Schema' and @Namespace]", ODataNamespaceManager.Instance); if (nodeSchema != null) { string domainNamespace = nodeSchema.Attribute("Namespace").Value; // namespace must qualify the full entity type name string entityTypeFullName = payload.GetFullEntityTypeFromPayload(payloadType, payloadFormat); if (string.IsNullOrEmpty(entityTypeFullName)) { string entitySetName = payload.GetEntitySetFromPayload(payloadType, payloadFormat); entityTypeFullName = xmlMetadata.GetFullEntityTypeFromMetadata(entitySetName); } if (!string.IsNullOrEmpty(entityTypeFullName)) { matched = entityTypeFullName.StartsWith(domainNamespace + "."); } } } } else if (payloadType == PayloadType.Metadata) { matched = string.Equals(payload, metadata, StringComparison.Ordinal); } else { matched = true; } return matched; } /// <summary> /// Determine the accept header value according to the format hint /// </summary> /// <param name="format">The format hint</param> /// <returns>The value string to be set to Accept header field of HTTP requests</returns> public static string MapFormatToAcceptValue(this string format) { if (format.Equals(Constants.FormatJson, StringComparison.OrdinalIgnoreCase)) { return Constants.AcceptHeaderJson; } else if (format.Equals(Constants.V3FormatJsonVerbose, StringComparison.OrdinalIgnoreCase)) { return Constants.V3AcceptHeaderJsonVerbose; } else if (format.Equals(Constants.V3FormatJsonFullMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V3AcceptHeaderJsonFullMetadata; } else if (format.Equals(Constants.V3FormatJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V3AcceptHeaderJsonMinimalMetadata; } else if (format.Equals(Constants.V3FormatJsonNoMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V3AcceptHeaderJsonNoMetadata; } else if (format.Equals(Constants.V4FormatJsonFullMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V4AcceptHeaderJsonFullMetadata; } else if (format.Equals(Constants.V4FormatJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V4AcceptHeaderJsonMinimalMetadata; } else if (format.Equals(Constants.V4FormatJsonNoMetadata, StringComparison.OrdinalIgnoreCase)) { return Constants.V4AcceptHeaderJsonNoMetadata; } else { return Constants.AcceptHeaderAtom; } } /// <summary> /// Helper method to find the service document of the OData service this context refers to /// </summary> /// <param name="maximumPayloadSize">maximum payload size in byte</param> /// <param name="uri">uri hint, which is used to derive various possible uris in hope one of them is the service base endpoint</param> /// <param name="acceptHeaderValue">value of header of Accept that will be used in request getting the response</param> /// <param name="IgnoreInputUri">if true, the given uri is known other than service base</param> /// <param name="serviceBaseUri">out parameter: the service base uri if one shall be found</param> /// <param name="responseServiceDocument">out parameter: the response object including payload, headers and status code</param> /// <param name="reqHeaders">Http headers to be sent out to server</param> /// <returns>true if a valid service document is found; otherwise false</returns> private static bool TryGetServiceDocument(int maximumPayloadSize, Uri uri, string acceptHeaderValue, bool IgnoreInputUri, out Uri serviceBaseUri, out Response responseServiceDocument, IEnumerable<KeyValuePair<string, string>> reqHeaders) { if (!IgnoreInputUri) { try { var response = WebHelper.Get(uri, acceptHeaderValue, maximumPayloadSize, reqHeaders); if (response.IsServiceDocument()) { serviceBaseUri = uri; responseServiceDocument = response; return true; } } catch (OversizedPayloadException) { // does nothing } } var segments = uri.Segments; if (segments != null && segments.Length > 0) { Uri uriParent; if (Uri.TryCreate(uri.GetLeftPart(UriPartial.Authority) + string.Join("", segments.Take(segments.Length - 1).ToArray()), UriKind.Absolute, out uriParent)) { if (uri != uriParent) { return ServiceContextFactory.TryGetServiceDocument(maximumPayloadSize, uriParent, acceptHeaderValue, false, out serviceBaseUri, out responseServiceDocument, reqHeaders); } } } serviceBaseUri = null; responseServiceDocument = null; return false; } /// <summary> /// Determine the odata metadata type accrding to the format hint /// </summary> /// <param name="format">The format hint</param> /// <returns>The odata metadata type in request</returns> public static ODataMetadataType MapFormatToMetadataType(this string format) { if (format.Equals(Constants.V3FormatJsonFullMetadata, StringComparison.OrdinalIgnoreCase) || format.Equals(Constants.V4FormatJsonFullMetadata, StringComparison.OrdinalIgnoreCase)) { return ODataMetadataType.FullOnly; } else if (format.Equals(Constants.V3FormatJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase) || format.Equals(Constants.V4FormatJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase)) { return ODataMetadataType.MinOnly; } else { return ODataMetadataType.None; } } /// <summary> /// Determine the odata metadata type accrding to the accept header hint /// </summary> /// <param name="format">The accept header hint</param> /// <returns>The odata metadata type in request</returns> public static ODataMetadataType MapAcceptHeaderToMetadataType(this string acceptHeader) { if (acceptHeader.Equals(Constants.V3AcceptHeaderJsonFullMetadata, StringComparison.OrdinalIgnoreCase) || acceptHeader.Equals(Constants.V4AcceptHeaderJsonFullMetadata, StringComparison.OrdinalIgnoreCase)) { return ODataMetadataType.FullOnly; } else if (acceptHeader.Equals(Constants.V3AcceptHeaderJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase) || acceptHeader.Equals(Constants.V4AcceptHeaderJsonMinimalMetadata, StringComparison.OrdinalIgnoreCase)) { return ODataMetadataType.MinOnly; } else { return ODataMetadataType.None; } } /// <summary> /// Parse the metadata type of offline payload from header. /// </summary> /// <param name="offlineHeader">The string offline header.</param> /// <returns>The metadata type of offline payload.</returns> public static ODataMetadataType GetMetadataTypeFromOfflineHeader(this string offlineHeader) { ODataMetadataType metadata = ODataMetadataType.MinOnly; if (offlineHeader.Contains(Constants.V3AcceptHeaderJsonFullMetadata) || offlineHeader.Contains(Constants.V4AcceptHeaderJsonFullMetadata)) { metadata = ODataMetadataType.FullOnly; } return metadata; } } }
namespace Fonet.Pdf { using System; using System.Collections; using System.Drawing; using System.IO; using Fonet.DataTypes; using Fonet.Image; using Fonet.Layout; using Fonet.Pdf.Filter; using Fonet.Pdf.Security; using Fonet.Render.Pdf; internal sealed class PdfCreator { private PdfDocument doc; // list of objects to write in the trailer. private ArrayList trailerObjects = new ArrayList(); // the objects themselves // These objects are buffered and then written to the // PDF stream after each page has been rendered. Adding // an object to this array does not mean it is ready for // writing, but it does mean that there is no need to // wait until the end of the PDF stream. The trigger // to write these objects out is pulled by PdfRenderer, // at the end of it's render page method. private ArrayList objects = new ArrayList(); // The root outline object private PdfOutline outlineRoot; // the /Resources object private PdfResources resources; // the documents idReferences private IDReferences idReferences; // the XObjects Map. private Hashtable xObjectsMap = new Hashtable(); // The cross-reference table. private XRefTable xrefTable; // The PDF information dictionary. private PdfInfo info; // The PDF encryption dictionary. private PdfDictionary encrypt; // Links wiating for internal document references //private ArrayList pendingLinks; public PdfCreator(Stream stream) { // Create the underlying PDF document. doc = new PdfDocument(stream); doc.Version = PdfVersion.V13; resources = new PdfResources(doc.NextObjectId()); addTrailerObject(resources); this.xrefTable = new XRefTable(); } public void setIDReferences(IDReferences idReferences) { this.idReferences = idReferences; } public PdfDocument Doc { get { return doc; } } public void AddObject(PdfObject obj) { objects.Add(obj); } public PdfXObject AddImage(FonetImage img) { // check if already created string url = img.Uri; PdfXObject xObject = (PdfXObject)this.xObjectsMap[url]; if (xObject == null) { PdfICCStream iccStream = null; ColorSpace cs = img.ColorSpace; if (cs.HasICCProfile()) { iccStream = new PdfICCStream(doc.NextObjectId(), cs.GetICCProfile()); iccStream.NumComponents = new PdfNumeric(cs.GetNumComponents()); iccStream.AddFilter(new FlateFilter()); this.objects.Add(iccStream); } // else, create a new one PdfName name = new PdfName("XO" + xObjectsMap.Count); xObject = new PdfXObject(img.Bitmaps, name, doc.NextObjectId()); xObject.SubType = PdfName.Names.Image; xObject.Dictionary[PdfName.Names.Width] = new PdfNumeric(img.Width); xObject.Dictionary[PdfName.Names.Height] = new PdfNumeric(img.Height); xObject.Dictionary[PdfName.Names.BitsPerComponent] = new PdfNumeric(img.BitsPerPixel); // Check for ICC color space if (iccStream != null) { PdfArray ar = new PdfArray(); ar.Add(PdfName.Names.ICCBased); ar.Add(iccStream.GetReference()); xObject.Dictionary[PdfName.Names.ColorSpace] = ar; } else { xObject.Dictionary[PdfName.Names.ColorSpace] = new PdfName(img.ColorSpace.GetColorSpacePDFString()); } xObject.AddFilter(img.Filter); this.objects.Add(xObject); this.xObjectsMap.Add(url, xObject); } return xObject; } public PdfPage makePage(PdfResources resources, PdfContentStream contents, int pagewidth, int pageheight, Page currentPage) { PdfPage page = new PdfPage( resources, contents, pagewidth, pageheight, doc.NextObjectId()); if (currentPage != null) { foreach (string id in currentPage.getIDList()) { idReferences.setInternalGoToPageReference(id, page.GetReference()); } } /* add it to the list of objects */ this.objects.Add(page); page.SetParent(doc.Pages); doc.Pages.Kids.Add(page.GetReference()); return page; } public PdfLink makeLink(Rectangle rect, string destination, int linkType) { PdfLink link = new PdfLink(doc.NextObjectId(), rect); this.objects.Add(link); if (linkType == LinkSet.EXTERNAL) { if (destination.EndsWith(".pdf")) { // FileSpec PdfFileSpec fileSpec = new PdfFileSpec(doc.NextObjectId(), destination); this.objects.Add(fileSpec); PdfGoToRemote gotoR = new PdfGoToRemote(fileSpec, doc.NextObjectId()); this.objects.Add(gotoR); link.SetAction(gotoR); } else { // URI PdfUri uri = new PdfUri(destination); link.SetAction(uri); } } else { PdfObjectReference goToReference = getGoToReference(destination); PdfInternalLink internalLink = new PdfInternalLink(goToReference); link.SetAction(internalLink); } return link; } private PdfObjectReference getGoToReference(string destination) { PdfGoTo goTo; // Have we seen this 'id' in the document yet? if (idReferences.doesIDExist(destination)) { if (idReferences.doesGoToReferenceExist(destination)) { goTo = idReferences.getInternalLinkGoTo(destination); } else { goTo = idReferences.createInternalLinkGoTo(destination, doc.NextObjectId()); addTrailerObject(goTo); } } else { // id was not found, so create it idReferences.CreateUnvalidatedID(destination); idReferences.AddToIdValidationList(destination); goTo = idReferences.createInternalLinkGoTo(destination, doc.NextObjectId()); addTrailerObject(goTo); } return goTo.GetReference(); } private void addTrailerObject(PdfObject obj) { this.trailerObjects.Add(obj); } public PdfContentStream makeContentStream() { PdfContentStream obj = new PdfContentStream(doc.NextObjectId()); obj.AddFilter(new FlateFilter()); this.objects.Add(obj); return obj; } public PdfAnnotList makeAnnotList() { PdfAnnotList obj = new PdfAnnotList(doc.NextObjectId()); this.objects.Add(obj); return obj; } public void SetOptions(PdfRendererOptions options) { // Configure the /Info dictionary. info = new PdfInfo(doc.NextObjectId()); if (options.Title != null) { info.Title = new PdfString(options.Title); } if (options.Author != null) { info.Author = new PdfString(options.Author); } if (options.Subject != null) { info.Subject = new PdfString(options.Subject); } if (options.Keywords != String.Empty) { info.Keywords = new PdfString(options.Keywords); } if (options.Creator != null) { info.Creator = new PdfString(options.Creator); } if (options.Producer != null) { info.Producer = new PdfString(options.Producer); } info.CreationDate = new PdfString(PdfDate.Format(DateTime.Now)); this.objects.Add(info); // Configure the security options. if (options.UserPassword != null || options.OwnerPassword != null || options.HasPermissions) { SecurityOptions securityOptions = new SecurityOptions(); securityOptions.UserPassword = options.UserPassword; securityOptions.OwnerPassword = options.OwnerPassword; securityOptions.EnableAdding(options.EnableAdd); securityOptions.EnableChanging(options.EnableModify); securityOptions.EnableCopying(options.EnableCopy); securityOptions.EnablePrinting(options.EnablePrinting); doc.SecurityOptions = securityOptions; encrypt = doc.Writer.SecurityManager.GetEncrypt(doc.NextObjectId()); this.objects.Add(encrypt); } } public PdfOutline getOutlineRoot() { if (outlineRoot != null) { return outlineRoot; } outlineRoot = new PdfOutline(doc.NextObjectId(), null, null); addTrailerObject(outlineRoot); doc.Catalog.Outlines = outlineRoot; return outlineRoot; } public PdfOutline makeOutline(PdfOutline parent, string label, string destination) { PdfObjectReference goToRef = getGoToReference(destination); PdfOutline obj = new PdfOutline(doc.NextObjectId(), label, goToRef); if (parent != null) { parent.AddOutline(obj); } this.objects.Add(obj); return obj; } public PdfResources getResources() { return this.resources; } private void WritePdfObject(PdfObject obj) { xrefTable.Add(obj.ObjectId, doc.Writer.Position); doc.Writer.WriteLine(obj); } public void output() { foreach (PdfObject obj in this.objects) { WritePdfObject(obj); } objects.Clear(); } public void outputHeader() { doc.WriteHeader(); } public void outputTrailer() { output(); foreach (PdfXObject xobj in xObjectsMap.Values) { resources.AddXObject(xobj); } xrefTable.Add(doc.Catalog.ObjectId, doc.Writer.Position); doc.Writer.WriteLine(doc.Catalog); xrefTable.Add(doc.Pages.ObjectId, doc.Writer.Position); doc.Writer.WriteLine(doc.Pages); foreach (PdfObject o in trailerObjects) { WritePdfObject(o); } // output the xref table long xrefOffset = doc.Writer.Position; xrefTable.Write(doc.Writer); // output the file trailer PdfFileTrailer trailer = new PdfFileTrailer(); trailer.Size = new PdfNumeric(doc.ObjectCount + 1); trailer.Root = doc.Catalog.GetReference(); trailer.Id = doc.FileIdentifier; if (info != null) { trailer.Info = info.GetReference(); } if (info != null && encrypt != null) { trailer.Encrypt = encrypt.GetReference(); } trailer.XRefOffset = xrefOffset; doc.Writer.Write(trailer); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Reflection; using System.Collections.Generic; namespace System.Data { /// <summary> /// DataReaderExtensions /// </summary> public static class DataReaderExtensions { /// <summary> /// Ases the enumerable. /// </summary> /// <param name="r">The r.</param> /// <returns></returns> public static IEnumerable<IDataReader> AsEnumerable(this IDataReader r) { if (r == null) throw new ArgumentNullException("source"); while (r.Read()) yield return r; } ////? Still needed - YeildRows can do same //public static IEnumerable<Object[]> AsEnumerableValues(this IDataReader r) //{ // if (r == null) // throw new ArgumentNullException("source"); // while (r.Read()) // { // var values = new Object[r.FieldCount]; // r.GetValues(values); // yield return values; // } //} /// <summary> /// Fields the specified r. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="r">The r.</param> /// <param name="columnIndex">Index of the column.</param> /// <returns></returns> public static T Field<T>(this IDataReader r, int columnIndex) { if (r == null) throw new ArgumentNullException("r"); return DelegateFactory<T>.Field(r, columnIndex); } /// <summary> /// Fields the specified r. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="r">The r.</param> /// <param name="columnIndex">Index of the column.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static T Field<T>(this IDataReader r, int columnIndex, T defaultValue) { if (r == null) throw new ArgumentNullException("r"); return (!r.IsDBNull(columnIndex) ? DelegateFactory<T>.Field(r, columnIndex) : defaultValue); } /// <summary> /// Fields the specified r. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="r">The r.</param> /// <param name="columnName">Name of the column.</param> /// <returns></returns> public static T Field<T>(this IDataReader r, string columnName) { if (r == null) throw new ArgumentNullException("r"); return DelegateFactory<T>.Field(r, r.GetOrdinal(columnName)); } /// <summary> /// Fields the specified r. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="r">The r.</param> /// <param name="columnName">Name of the column.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static T Field<T>(this IDataReader r, string columnName, T defaultValue) { if (r == null) throw new ArgumentNullException("r"); int columnIndex = r.GetOrdinal(columnName); return (!r.IsDBNull(columnIndex) ? DelegateFactory<T>.Field(r, columnIndex) : defaultValue); } private static class DelegateFactory<T> { internal static readonly Func<IDataReader, int, T> Field = Create(typeof(T)); static DelegateFactory() { } private static Func<IDataReader, int, T> Create(Type type) { // reference types if (!type.IsValueType) { if (type == typeof(string)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetString", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(IDataReader)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetData", BindingFlags.NonPublic | BindingFlags.Static)); } // nullable types if (((type.IsGenericType) && (!type.IsGenericTypeDefinition)) && (typeof(Nullable<>) == type.GetGenericTypeDefinition())) { if (type == typeof(bool?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableBoolean", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(byte?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableByte", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(char?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableChar", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(DateTime?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableDateTime", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(Decimal)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableDecimal", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(double?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableDouble", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(float?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableFloat", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(Guid?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableGuid", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(short?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableInt16", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(int?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableInt32", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(long?)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetNullableInt64", BindingFlags.NonPublic | BindingFlags.Static)); } // value types if (type == typeof(bool)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetBoolean", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(byte)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetByte", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(char)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetChar", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(DateTime)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetDateTime", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(Decimal)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetDecimal", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(double)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetDouble", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(float)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetFloat", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(Guid)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetGuid", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(short)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetInt16", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(int)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetInt32", BindingFlags.NonPublic | BindingFlags.Static)); if (type == typeof(long)) return (Func<IDataReader, int, T>)Delegate.CreateDelegate(typeof(Func<IDataReader, int, T>), typeof(DelegateFactory<T>).GetMethod("GetInt64", BindingFlags.NonPublic | BindingFlags.Static)); throw new InvalidOperationException(); } #region Reference Types private static string GetString(IDataReader r, int columnIndex) { return (!r.IsDBNull(columnIndex) ? r.GetString(columnIndex) : null); } private static IDataReader GetData(IDataReader r, int columnIndex) { return (!r.IsDBNull(columnIndex) ? r.GetData(columnIndex) : null); } #endregion #region Nullable Types private static bool? GetNullableBoolean(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new bool?(r.GetBoolean(columnIndex))); } private static byte? GetNullableByte(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new byte?(r.GetByte(columnIndex))); } private static char? GetNullableChar(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new char?(r.GetChar(columnIndex))); } private static DateTime? GetNullableDateTime(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new DateTime?(r.GetDateTime(columnIndex))); } private static decimal? GetNullableDecimal(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new decimal?(r.GetDecimal(columnIndex))); } private static double? GetNullableDouble(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new double?(r.GetDouble(columnIndex))); } private static float? GetNullableFloat(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new float?(r.GetFloat(columnIndex))); } private static Guid? GetNullableGuid(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new Guid?(r.GetGuid(columnIndex))); } private static short? GetNullableInt16(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new short?(r.GetInt16(columnIndex))); } private static int? GetNullableInt32(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new int?(r.GetInt32(columnIndex))); } private static long? GetNullableInt64(IDataReader r, int columnIndex) { return (r.IsDBNull(columnIndex) ? null : new long?(r.GetInt64(columnIndex))); } #endregion #region Value Types private static bool GetBoolean(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetBoolean(columnIndex); } private static byte GetByte(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetByte(columnIndex); } private static char GetChar(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetChar(columnIndex); } private static DateTime GetDateTime(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetDateTime(columnIndex); } private static decimal GetDecimal(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetDecimal(columnIndex); } private static double GetDouble(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetDouble(columnIndex); } private static float GetFloat(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetFloat(columnIndex); } private static Guid GetGuid(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetGuid(columnIndex); } private static short GetInt16(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetInt16(columnIndex); } private static int GetInt32(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetInt32(columnIndex); } private static long GetInt64(IDataReader r, int columnIndex) { if (r.IsDBNull(columnIndex)) throw new InvalidCastException(string.Format("DataSetLinq_NonNullableCast({0})", typeof(T).ToString())); return r.GetInt64(columnIndex); } #endregion } } }
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 SafeBeaches.Areas.HelpPage.ModelDescriptions; using SafeBeaches.Areas.HelpPage.Models; namespace SafeBeaches.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); } } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\PlayerCameraManager.h:172 namespace UnrealEngine { [ManageType("ManagePlayerCameraManager")] public partial class ManagePlayerCameraManager : APlayerCameraManager, IManageWrapper { public ManagePlayerCameraManager(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_ClearCrossLevelReferences(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_Destroyed(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_ForceNetRelevant(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_ForceNetUpdate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_GatherCurrentMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_K2_DestroyActor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_LifeSpanExpired(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_MarkComponentsAsPendingKill(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_NotifyActorBeginCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_NotifyActorEndCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnRep_AttachmentReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnRep_Instigator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnRep_Owner(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnRep_ReplicatedMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnRep_ReplicateMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OutsideWorldBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostActorCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostNetInit(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostNetReceiveLocationAndRotation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostNetReceivePhysicState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostNetReceiveRole(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostUnregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PreInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PreRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_RegisterActorTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_RegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_ReregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_RerunConstructionScripts(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_Reset(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_RewindForReplay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_SetActorHiddenInGame(IntPtr self, bool bNewHidden); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_SetLifeSpan(IntPtr self, float inLifespan); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_SetReplicateMovement(IntPtr self, bool bInReplicateMovement); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_TearOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_TeleportSucceeded(IntPtr self, bool bIsATest); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_Tick(IntPtr self, float deltaSeconds); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_TornOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_UnregisterAllComponents(IntPtr self, bool bForReregister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerCameraManager_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// Overridable native event for when play begins for this actor. /// </summary> protected override void BeginPlay() => E__Supper__APlayerCameraManager_BeginPlay(this); /// <summary> /// Do anything needed to clear out cross level references; Called from ULevel::PreSave /// </summary> public override void ClearCrossLevelReferences() => E__Supper__APlayerCameraManager_ClearCrossLevelReferences(this); /// <summary> /// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending /// </summary> public override void Destroyed() => E__Supper__APlayerCameraManager_Destroyed(this); /// <summary> /// Forces this actor to be net relevant if it is not already by default /// </summary> public override void ForceNetRelevant() => E__Supper__APlayerCameraManager_ForceNetRelevant(this); /// <summary> /// Force actor to be updated to clients/demo net drivers /// </summary> public override void ForceNetUpdate() => E__Supper__APlayerCameraManager_ForceNetUpdate(this); /// <summary> /// Fills ReplicatedMovement property /// </summary> public override void GatherCurrentMovement() => E__Supper__APlayerCameraManager_GatherCurrentMovement(this); /// <summary> /// Invalidates anything produced by the last lighting build. /// </summary> public override void InvalidateLightingCacheDetailed(bool bTranslationOnly) => E__Supper__APlayerCameraManager_InvalidateLightingCacheDetailed(this, bTranslationOnly); /// <summary> /// Destroy the actor /// </summary> public override void DestroyActor() => E__Supper__APlayerCameraManager_K2_DestroyActor(this); /// <summary> /// Called when the lifespan of an actor expires (if he has one). /// </summary> public override void LifeSpanExpired() => E__Supper__APlayerCameraManager_LifeSpanExpired(this); /// <summary> /// Called to mark all components as pending kill when the actor is being destroyed /// </summary> public override void MarkComponentsAsPendingKill() => E__Supper__APlayerCameraManager_MarkComponentsAsPendingKill(this); /// <summary> /// Event when this actor has the mouse moved over it with the clickable interface. /// </summary> public override void NotifyActorBeginCursorOver() => E__Supper__APlayerCameraManager_NotifyActorBeginCursorOver(this); /// <summary> /// Event when this actor has the mouse moved off of it with the clickable interface. /// </summary> public override void NotifyActorEndCursorOver() => E__Supper__APlayerCameraManager_NotifyActorEndCursorOver(this); public override void OnRep_AttachmentReplication() => E__Supper__APlayerCameraManager_OnRep_AttachmentReplication(this); public override void OnRep_Instigator() => E__Supper__APlayerCameraManager_OnRep_Instigator(this); protected override void OnRep_Owner() => E__Supper__APlayerCameraManager_OnRep_Owner(this); public override void OnRep_ReplicatedMovement() => E__Supper__APlayerCameraManager_OnRep_ReplicatedMovement(this); public override void OnRep_ReplicateMovement() => E__Supper__APlayerCameraManager_OnRep_ReplicateMovement(this); /// <summary> /// Called on the client when the replication paused value is changed /// </summary> public override void OnReplicationPausedChanged(bool bIsReplicationPaused) => E__Supper__APlayerCameraManager_OnReplicationPausedChanged(this, bIsReplicationPaused); /// <summary> /// Called when the Actor is outside the hard limit on world bounds /// </summary> public override void OutsideWorldBounds() => E__Supper__APlayerCameraManager_OutsideWorldBounds(this); /// <summary> /// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay /// <para>For actors with a root component, the location and rotation will have already been set. </para> /// This is called before calling construction scripts, but after native components have been created /// </summary> public override void PostActorCreated() => E__Supper__APlayerCameraManager_PostActorCreated(this); /// <summary> /// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay /// </summary> public override void PostInitializeComponents() => E__Supper__APlayerCameraManager_PostInitializeComponents(this); /// <summary> /// Always called immediately after spawning and reading in replicated properties /// </summary> public override void PostNetInit() => E__Supper__APlayerCameraManager_PostNetInit(this); /// <summary> /// Update location and rotation from ReplicatedMovement. Not called for simulated physics! /// </summary> public override void PostNetReceiveLocationAndRotation() => E__Supper__APlayerCameraManager_PostNetReceiveLocationAndRotation(this); /// <summary> /// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity() /// </summary> public override void PostNetReceivePhysicState() => E__Supper__APlayerCameraManager_PostNetReceivePhysicState(this); /// <summary> /// Always called immediately after a new Role is received from the remote. /// </summary> public override void PostNetReceiveRole() => E__Supper__APlayerCameraManager_PostNetReceiveRole(this); /// <summary> /// Called after all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PostRegisterAllComponents() => E__Supper__APlayerCameraManager_PostRegisterAllComponents(this); /// <summary> /// Called after all currently registered components are cleared /// </summary> public override void PostUnregisterAllComponents() => E__Supper__APlayerCameraManager_PostUnregisterAllComponents(this); /// <summary> /// Called right before components are initialized, only called during gameplay /// </summary> public override void PreInitializeComponents() => E__Supper__APlayerCameraManager_PreInitializeComponents(this); /// <summary> /// Called before all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PreRegisterAllComponents() => E__Supper__APlayerCameraManager_PreRegisterAllComponents(this); /// <summary> /// Calls PrestreamTextures() for all the actor's meshcomponents. /// </summary> /// <param name="seconds">Number of seconds to force all mip-levels to be resident</param> /// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param> /// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param> public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups) => E__Supper__APlayerCameraManager_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups); /// <summary> /// Virtual call chain to register all tick functions for the actor class hierarchy /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterActorTickFunctions(bool bRegister) => E__Supper__APlayerCameraManager_RegisterActorTickFunctions(this, bRegister); /// <summary> /// Ensure that all the components in the Components array are registered /// </summary> public override void RegisterAllComponents() => E__Supper__APlayerCameraManager_RegisterAllComponents(this); /// <summary> /// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty. /// </summary> public override void ReregisterAllComponents() => E__Supper__APlayerCameraManager_ReregisterAllComponents(this); /// <summary> /// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location. /// </summary> public override void RerunConstructionScripts() => E__Supper__APlayerCameraManager_RerunConstructionScripts(this); /// <summary> /// Reset actor to initial state - used when restarting level without reloading. /// </summary> public override void Reset() => E__Supper__APlayerCameraManager_Reset(this); /// <summary> /// Called on the actor before checkpoint data is applied during a replay. /// <para>Only called if bReplayRewindable is set. </para> /// </summary> public override void RewindForReplay() => E__Supper__APlayerCameraManager_RewindForReplay(this); /// <summary> /// Sets the actor to be hidden in the game /// </summary> /// <param name="bNewHidden">Whether or not to hide the actor and all its components</param> public override void SetActorHiddenInGame(bool bNewHidden) => E__Supper__APlayerCameraManager_SetActorHiddenInGame(this, bNewHidden); /// <summary> /// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed. /// </summary> public override void SetLifeSpan(float inLifespan) => E__Supper__APlayerCameraManager_SetLifeSpan(this, inLifespan); /// <summary> /// Set whether this actor's movement replicates to network clients. /// </summary> /// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param> public override void SetReplicateMovement(bool bInReplicateMovement) => E__Supper__APlayerCameraManager_SetReplicateMovement(this, bInReplicateMovement); /// <summary> /// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true. /// </summary> public override void TearOff() => E__Supper__APlayerCameraManager_TearOff(this); /// <summary> /// Called from TeleportTo() when teleport succeeds /// </summary> public override void TeleportSucceeded(bool bIsATest) => E__Supper__APlayerCameraManager_TeleportSucceeded(this, bIsATest); /// <summary> /// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame. /// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para> /// </summary> /// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param> public override void Tick(float deltaSeconds) => E__Supper__APlayerCameraManager_Tick(this, deltaSeconds); /// <summary> /// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients. /// <para>@see bTearOff </para> /// </summary> public override void TornOff() => E__Supper__APlayerCameraManager_TornOff(this); /// <summary> /// Unregister all currently registered components /// </summary> /// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param> public override void UnregisterAllComponents(bool bForReregister) => E__Supper__APlayerCameraManager_UnregisterAllComponents(this, bForReregister); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__APlayerCameraManager_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__APlayerCameraManager_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__APlayerCameraManager_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__APlayerCameraManager_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__APlayerCameraManager_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__APlayerCameraManager_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__APlayerCameraManager_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__APlayerCameraManager_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__APlayerCameraManager_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__APlayerCameraManager_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__APlayerCameraManager_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__APlayerCameraManager_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__APlayerCameraManager_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__APlayerCameraManager_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__APlayerCameraManager_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManagePlayerCameraManager self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManagePlayerCameraManager(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManagePlayerCameraManager>(PtrDesc); } } }
// =============================================================================== // Microsoft Data Access Application Block for .NET 3.0 // // PostgreSql.cs // // This file contains the implementations of the AdoHelper supporting PostgreSql. // // For more information see the Documentation. // =============================================================================== // Release history // VERSION DESCRIPTION // 2.0 Added support for FillDataset, UpdateDataset and "Param" helper methods // 3.0 New abstract class supporting the same methods using ADO.NET interfaces // // =============================================================================== // Copyright (C) 2000-2001 Microsoft Corporation // All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR // FITNESS FOR A PARTICULAR PURPOSE. // ============================================================================== using System; using System.Collections; using System.Data; using Npgsql; using System.Xml; using System.IO; namespace org.swyn.foundation.db { /// <summary> /// The PostgreSql class is intended to encapsulate high performance, scalable best practices for /// common uses of the PostgreSql ADO.NET provider. It is created using the abstract factory in AdoHelper. /// </summary> public class PostgreSql : AdoHelper { /// <summary> /// Create an PostgreSql Helper. Needs to be a default constructor so that the Factory can create it /// </summary> public PostgreSql() { } #region Overrides /// <summary> /// Returns an array of NpgsqlParameters of the specified size /// </summary> /// <param name="size">size of the array</param> /// <returns>The array of NpgsqlParameters</returns> protected override IDataParameter[] GetDataParameters(int size) { return new NpgsqlParameter[size]; } /// <summary> /// Returns an NpgsqlConnection object for the given connection string /// </summary> /// <param name="connectionString">The connection string to be used to create the connection</param> /// <returns>An NpgsqlConnection object</returns> public override IDbConnection GetConnection(string connectionString) { return new NpgsqlConnection (connectionString ); } /// <summary> /// Returns an NpgsqlDataAdapter object /// </summary> /// <returns>The NpgsqlDataAdapter</returns> public override IDbDataAdapter GetDataAdapter() { return new NpgsqlDataAdapter(); } /// <summary> /// Calls the CommandBuilder.DeriveParameters method for the specified provider, doing any setup and cleanup necessary /// </summary> /// <param name="cmd">The IDbCommand referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the Parameters collection of the IDbCommand. </param> public override void DeriveParameters( IDbCommand cmd ) { bool mustCloseConnection = false; if( !( cmd is NpgsqlCommand ) ) throw new ArgumentException( "The command provided is not an NpgsqlCommand instance.", "cmd" ); if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); mustCloseConnection = true; } NpgsqlCommandBuilder.DeriveParameters( (NpgsqlCommand)cmd ); if (mustCloseConnection) { cmd.Connection.Close(); } } /// <summary> /// Returns an NpgsqlParameter object /// </summary> /// <returns>The NpgsqlParameter object</returns> public override IDataParameter GetParameter() { NpgsqlParameter parameter = new NpgsqlParameter(); parameter.Size = 255; return parameter; } /// <summary> /// Get an IDataParameter for use in a SQL command /// </summary> /// <param name="parameterName">The name of the parameter to create</param> /// <param name="value">The value of the specified parameter</param> /// <returns>An IDataParameter object</returns> public override IDataParameter GetParameter( string parameterName, object value ) { NpgsqlParameter parameter = new NpgsqlParameter(); parameter.ParameterName = parameterName; parameter.Value = value; parameter.Size = GetParameterSize(parameterName); return parameter; } /// <summary> /// This function will get and assemble the parameter's size dynamically from db or cache /// </summary> /// <param name="name">The parameter name</param> /// <returns>The size</returns> private int GetParameterSize(string name) { int Size=255; return Size; } /// <summary> /// This cleans up the parameter syntax for an PostgreSql call. This was split out from PrepareCommand so that it could be called independently. /// </summary> /// <param name="command">An IDbCommand object containing the CommandText to clean.</param> public override void CleanParameterSyntax(IDbCommand command) { if (command.CommandType == CommandType.Text) { command.CommandText = command.CommandText.Replace("@", ":"); } if (command.Parameters.Count > 0) { foreach (NpgsqlParameter parameter in command.Parameters) { parameter.ParameterName = parameter.ParameterName.Replace("@", ":"); } } } /// <summary> /// Execute an IDbCommand (that returns a resultset) against the provided IDbConnection. /// </summary> /// <example> /// <code> /// XmlReader r = helper.ExecuteXmlReader(command); /// </code></example> /// <param name="command">The IDbCommand to execute</param> /// <returns>An XmlReader containing the resultset generated by the command</returns> public override XmlReader ExecuteXmlReader(IDbCommand command) { bool mustCloseConnection = false; if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); mustCloseConnection = true; } CleanParameterSyntax(command); NpgsqlDataAdapter da = new NpgsqlDataAdapter((NpgsqlCommand)command); DataSet ds = new DataSet(); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.Fill(ds); StringReader stream = new StringReader(ds.GetXml()); if (mustCloseConnection) { command.Connection.Close(); } return new XmlTextReader(stream); } /// <summary> /// Provider specific code to set up the updating/ed event handlers used by UpdateDataset /// </summary> /// <param name="dataAdapter">DataAdapter to attach the event handlers to</param> /// <param name="rowUpdatingHandler">The handler to be called when a row is updating</param> /// <param name="rowUpdatedHandler">The handler to be called when a row is updated</param> protected override void AddUpdateEventHandlers(IDbDataAdapter dataAdapter, RowUpdatingHandler rowUpdatingHandler, RowUpdatedHandler rowUpdatedHandler) { if (rowUpdatingHandler != null) { this.m_rowUpdating = rowUpdatingHandler; ((NpgsqlDataAdapter)dataAdapter).RowUpdating += new NpgsqlRowUpdatingEventHandler(RowUpdating); } if (rowUpdatedHandler != null) { this.m_rowUpdated = rowUpdatedHandler; ((NpgsqlDataAdapter)dataAdapter).RowUpdated += new NpgsqlRowUpdatedEventHandler(RowUpdated); } } /// <summary> /// Handles the RowUpdating event /// </summary> /// <param name="obj">The object that published the event</param> /// <param name="e">The NpgsqlRowUpdatingEventArgs</param> protected void RowUpdating(object obj, NpgsqlRowUpdatingEventArgs e) { base.RowUpdating(obj, e); } /// <summary> /// Handles the RowUpdated event /// </summary> /// <param name="obj">The object that published the event</param> /// <param name="e">The NpgsqlRowUpdatedEventArgs</param> protected void RowUpdated(object obj, NpgsqlRowUpdatedEventArgs e) { base.RowUpdated(obj, e); } /// <summary> /// Handle any provider-specific issues with BLOBs here by "washing" the IDataParameter and returning a new one that is set up appropriately for the provider. /// See MS KnowledgeBase article: http://support.microsoft.com/default.aspx?scid=kb;en-us;322796 /// </summary> /// <param name="connection">The IDbConnection to use in cleansing the parameter</param> /// <param name="p">The parameter before cleansing</param> /// <returns>The parameter after it's been cleansed.</returns> protected override IDataParameter GetBlobParameter(IDbConnection connection, IDataParameter p) { // do nothing special for BLOBs...as far as we know now. return p; } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAccountBudgetProposalServiceClientTest { [Category("Autogenerated")][Test] public void GetAccountBudgetProposalRequestObject() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetProposalRequestObjectAsync() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudgetProposal() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetProposalAsync() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAccountBudgetProposalResourceNames() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal response = client.GetAccountBudgetProposal(request.ResourceNameAsAccountBudgetProposalName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAccountBudgetProposalResourceNamesAsync() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); GetAccountBudgetProposalRequest request = new GetAccountBudgetProposalRequest { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), }; gagvr::AccountBudgetProposal expectedResponse = new gagvr::AccountBudgetProposal { ResourceNameAsAccountBudgetProposalName = gagvr::AccountBudgetProposalName.FromCustomerAccountBudgetProposal("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_PROPOSAL_ID]"), ProposalType = gagve::AccountBudgetProposalTypeEnum.Types.AccountBudgetProposalType.Remove, ProposedStartTimeType = gagve::TimeTypeEnum.Types.TimeType.Unspecified, ProposedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Unknown, ProposedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Status = gagve::AccountBudgetProposalStatusEnum.Types.AccountBudgetProposalStatus.ApprovedHeld, ApprovedEndTimeType = gagve::TimeTypeEnum.Types.TimeType.Forever, ApprovedSpendingLimitType = gagve::SpendingLimitTypeEnum.Types.SpendingLimitType.Unknown, Id = -6774108720365892680L, BillingSetupAsBillingSetupName = gagvr::BillingSetupName.FromCustomerBillingSetup("[CUSTOMER_ID]", "[BILLING_SETUP_ID]"), AccountBudgetAsAccountBudgetName = gagvr::AccountBudgetName.FromCustomerAccountBudget("[CUSTOMER_ID]", "[ACCOUNT_BUDGET_ID]"), ProposedName = "proposed_name7d4b2591", ProposedStartDateTime = "proposed_start_date_time4e2f84a3", ApprovedStartDateTime = "approved_start_date_time20090a2c", ProposedEndDateTime = "proposed_end_date_time39aa28a5", ApprovedEndDateTime = "approved_end_date_time99d3ab5d", ProposedSpendingLimitMicros = 6806956772888455592L, ApprovedSpendingLimitMicros = 1674109600829643495L, ProposedPurchaseOrderNumber = "proposed_purchase_order_numbere58f9418", ProposedNotes = "proposed_notes1d6c3942", CreationDateTime = "creation_date_time2f8c0159", ApprovalDateTime = "approval_date_timecefef4db", }; mockGrpcClient.Setup(x => x.GetAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AccountBudgetProposal>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); gagvr::AccountBudgetProposal responseCallSettings = await client.GetAccountBudgetProposalAsync(request.ResourceNameAsAccountBudgetProposalName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AccountBudgetProposal responseCancellationToken = await client.GetAccountBudgetProposalAsync(request.ResourceNameAsAccountBudgetProposalName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAccountBudgetProposalRequestObject() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountBudgetProposalOperation(), ValidateOnly = true, }; MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse { Result = new MutateAccountBudgetProposalResult(), }; mockGrpcClient.Setup(x => x.MutateAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); MutateAccountBudgetProposalResponse response = client.MutateAccountBudgetProposal(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAccountBudgetProposalRequestObjectAsync() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountBudgetProposalOperation(), ValidateOnly = true, }; MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse { Result = new MutateAccountBudgetProposalResult(), }; mockGrpcClient.Setup(x => x.MutateAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountBudgetProposalResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); MutateAccountBudgetProposalResponse responseCallSettings = await client.MutateAccountBudgetProposalAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAccountBudgetProposalResponse responseCancellationToken = await client.MutateAccountBudgetProposalAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAccountBudgetProposal() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountBudgetProposalOperation(), }; MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse { Result = new MutateAccountBudgetProposalResult(), }; mockGrpcClient.Setup(x => x.MutateAccountBudgetProposal(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); MutateAccountBudgetProposalResponse response = client.MutateAccountBudgetProposal(request.CustomerId, request.Operation); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAccountBudgetProposalAsync() { moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient> mockGrpcClient = new moq::Mock<AccountBudgetProposalService.AccountBudgetProposalServiceClient>(moq::MockBehavior.Strict); MutateAccountBudgetProposalRequest request = new MutateAccountBudgetProposalRequest { CustomerId = "customer_id3b3724cb", Operation = new AccountBudgetProposalOperation(), }; MutateAccountBudgetProposalResponse expectedResponse = new MutateAccountBudgetProposalResponse { Result = new MutateAccountBudgetProposalResult(), }; mockGrpcClient.Setup(x => x.MutateAccountBudgetProposalAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAccountBudgetProposalResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AccountBudgetProposalServiceClient client = new AccountBudgetProposalServiceClientImpl(mockGrpcClient.Object, null); MutateAccountBudgetProposalResponse responseCallSettings = await client.MutateAccountBudgetProposalAsync(request.CustomerId, request.Operation, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAccountBudgetProposalResponse responseCancellationToken = await client.MutateAccountBudgetProposalAsync(request.CustomerId, request.Operation, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }