context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc."> // Copyright (C) Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.Editor { using System; using System.Collections; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; /// <summary> /// Google Play Game Services Setup dialog for Android. /// </summary> public class GPGSAndroidSetupUI : EditorWindow { /// <summary> /// The configuration data from the play games console "resource data" /// </summary> private string mConfigData = string.Empty; /// <summary> /// The name of the class to generate containing the resource constants. /// </summary> private string mClassName = "GPGSIds"; /// <summary>True if G+ is needed for this application.</summary> private bool mRequiresGooglePlus = false; /// <summary> /// The scroll position /// </summary> private Vector2 scroll; /// <summary> /// The directory for the constants class. /// </summary> private string mConstantDirectory = "Assets"; /// <summary> /// The web client identifier. /// </summary> private string mWebClientId = string.Empty; /// <summary> /// Menus the item for GPGS android setup. /// </summary> [MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)] public static void MenuItemFileGPGSAndroidSetup() { EditorWindow window = EditorWindow.GetWindow( typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title); window.minSize = new Vector2(500, 400); } /// <summary> /// Performs setup using the Android resources downloaded XML file /// from the play console. /// </summary> /// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns> /// <param name="clientId">The web client id.</param> /// <param name="classDirectory">the directory to write the constants file to.</param> /// <param name="className">Fully qualified class name for the resource Ids.</param> /// <param name="resourceXmlData">Resource xml data.</param> /// <param name="nearbySvcId">Nearby svc identifier.</param> /// <param name="requiresGooglePlus">Indicates this app requires G+</param> public static bool PerformSetup( string clientId, string classDirectory, string className, string resourceXmlData, string nearbySvcId, bool requiresGooglePlus) { if (string.IsNullOrEmpty(resourceXmlData) && !string.IsNullOrEmpty(nearbySvcId)) { return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId, requiresGooglePlus); } if (ParseResources(classDirectory, className, resourceXmlData)) { GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory); GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData); // check the bundle id and set it if needed. CheckBundleId(); return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId, requiresGooglePlus); } return false; } /// <summary> /// Provide static access to setup for facilitating automated builds. /// </summary> /// <param name="webClientId">The oauth2 client id for the game. This is only /// needed if the ID Token or access token are needed.</param> /// <param name="appId">App identifier.</param> /// <param name="nearbySvcId">Optional nearby connection serviceId</param> /// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param> /// <returns>true if successful</returns> public static bool PerformSetup(string webClientId, string appId, string nearbySvcId, bool requiresGooglePlus) { if (!string.IsNullOrEmpty(webClientId)) { if (!GPGSUtil.LooksLikeValidClientId(webClientId)) { GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError); return false; } string serverAppId = webClientId.Split('-')[0]; if (!serverAppId.Equals(appId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch); return false; } } // check for valid app id if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdError); return false; } if (nearbySvcId != null) { if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true)) { return false; } } GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId); GPGSProjectSettings.Instance.Set(GPGSUtil.REQUIREGOOGLEPLUSKEY, requiresGooglePlus); GPGSProjectSettings.Instance.Save(); GPGSUtil.UpdateGameInfo(); // check that Android SDK is there if (!GPGSUtil.HasAndroidSdk()) { Debug.LogError("Android SDK not found."); EditorUtility.DisplayDialog( GPGSStrings.AndroidSetup.SdkNotFound, GPGSStrings.AndroidSetup.SdkNotFoundBlurb, GPGSStrings.Ok); return false; } // Generate AndroidManifest.xml GPGSUtil.GenerateAndroidManifest(requiresGooglePlus); // refresh assets, and we're done AssetDatabase.Refresh(); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); GPGSProjectSettings.Instance.Save(); return true; } /// <summary> /// Called when this object is enabled by Unity editor. /// </summary> public void OnEnable() { GPGSProjectSettings settings = GPGSProjectSettings.Instance; mConstantDirectory = settings.Get("ConstDir", mConstantDirectory); mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY); mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY); mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY); mRequiresGooglePlus = settings.GetBool(GPGSUtil.REQUIREGOOGLEPLUSKEY, false); } /// <summary> /// Called when the GUI should be rendered. /// </summary> public void OnGUI() { GUI.skin.label.wordWrap = true; GUILayout.BeginVertical(); GUIStyle link = new GUIStyle(GUI.skin.label); link.normal.textColor = new Color(.7f, .7f, 1f); GUILayout.Space(10); GUILayout.Label(GPGSStrings.AndroidSetup.Blurb); if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false))) { Application.OpenURL("https://play.google.com/apps/publish"); } Rect last = GUILayoutUtility.GetLastRect(); last.y += last.height - 2; last.x += 3; last.width -= 6; last.height = 2; GUI.Box(last, string.Empty); GUILayout.Space(15); GUILayout.Label("Constants class name", EditorStyles.boldLabel); GUILayout.Label("Enter the fully qualified name of the class to create containing the constants"); GUILayout.Space(10); mConstantDirectory = EditorGUILayout.TextField( "Directory to save constants", mConstantDirectory, GUILayout.Width(480)); mClassName = EditorGUILayout.TextField( "Constants class name", mClassName, GUILayout.Width(480)); GUILayout.Label("Resources Definition", EditorStyles.boldLabel); GUILayout.Label("Paste in the Android Resources from the Play Console"); GUILayout.Space(10); scroll = GUILayout.BeginScrollView(scroll); mConfigData = EditorGUILayout.TextArea( mConfigData, GUILayout.Width(475), GUILayout.Height(Screen.height)); GUILayout.EndScrollView(); GUILayout.Space(10); // Requires G+ field GUILayout.BeginHorizontal(); GUILayout.Label(GPGSStrings.Setup.RequiresGPlusTitle, EditorStyles.boldLabel); mRequiresGooglePlus = EditorGUILayout.Toggle(mRequiresGooglePlus); GUILayout.EndHorizontal(); GUILayout.Label(GPGSStrings.Setup.RequiresGPlusBlurb); // Client ID field GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel); GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb); mWebClientId = EditorGUILayout.TextField( GPGSStrings.Setup.ClientId, mWebClientId, GUILayout.Width(450)); GUILayout.Space(10); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100))) { // check that the classname entered is valid try { if (GPGSUtil.LooksLikeValidPackageName(mClassName)) { DoSetup(); } } catch (Exception e) { GPGSUtil.Alert( GPGSStrings.Error, "Invalid classname: " + e.Message); } } if (GUILayout.Button("Cancel", GUILayout.Width(100))) { this.Close(); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.EndVertical(); } /// <summary> /// Starts the setup process. /// </summary> public void DoSetup() { if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null, mRequiresGooglePlus)) { CheckBundleId(); EditorUtility.DisplayDialog( GPGSStrings.Success, GPGSStrings.AndroidSetup.SetupComplete, GPGSStrings.Ok); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); this.Close(); } else { GPGSUtil.Alert( GPGSStrings.Error, "Invalid or missing XML resource data. Make sure the data is" + " valid and contains the app_id element"); } } /// <summary> /// Checks the bundle identifier. /// </summary> /// <remarks> /// Check the package id. If one is set the gpgs properties, /// and the player settings are the default or empty, set it. /// if the player settings is not the default, then prompt before /// overwriting. /// </remarks> public static void CheckBundleId() { string packageName = GPGSProjectSettings.Instance.Get( GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty); string currentId = PlayerSettings.bundleIdentifier; if (!string.IsNullOrEmpty(packageName)) { if (string.IsNullOrEmpty(currentId) || currentId == "com.Company.ProductName") { PlayerSettings.bundleIdentifier = packageName; } else if (currentId != packageName) { if (EditorUtility.DisplayDialog( "Set Bundle Identifier?", "The server configuration is using " + packageName + ", but the player settings is set to " + currentId + ".\nSet the Bundle Identifier to " + packageName + "?", "OK", "Cancel")) { PlayerSettings.bundleIdentifier = packageName; } } } else { Debug.Log("NULL package!!"); } } /// <summary> /// Parses the resources xml and set the properties. Also generates the /// constants file. /// </summary> /// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="res">Res. the data to parse.</param> private static bool ParseResources(string classDirectory, string className, string res) { XmlTextReader reader = new XmlTextReader(new StringReader(res)); bool inResource = false; string lastProp = null; Hashtable resourceKeys = new Hashtable(); string appId = null; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "string") { lastProp = reader.GetAttribute("name"); } else if (inResource && !string.IsNullOrEmpty(lastProp)) { if (reader.HasValue) { if (lastProp == "app_id") { appId = reader.Value; GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); } else if (lastProp == "package_name") { GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value); } else { resourceKeys[lastProp] = reader.Value; } lastProp = null; } } } reader.Close(); if (resourceKeys.Count > 0) { GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys); } return appId != null; } } } #endif
#region License /* /// Copyright 2002-2010 the original author or authors. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. */ #endregion using System; using System.Collections; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Spring.Context; using Spring.Context.Support; using Spring.Objects.Factory; using Spring.Objects.Factory.Config; using Spring.Objects.Factory.Support; namespace Spring.Testing.Microsoft { /// <summary> /// Convenient superclass for tests depending on a Spring context. /// The test instance itself is populated by Dependency Injection. /// </summary> /// /// <remarks> /// <p>Really for integration testing, not unit testing. /// You should <i>not</i> normally use the Spring container /// for unit tests: simply populate your objects in plain NUnit tests!</p> /// /// <p>This supports two modes of populating the test: /// <ul> /// <li>Via Property Dependency Injection. Simply express dependencies on objects /// in the test fixture, and they will be satisfied by autowiring by type.</li> /// <li>Via Field Injection. Declare protected variables of the required type /// which match named beans in the context. This is autowire by name, /// rather than type. This approach is based on an approach originated by /// Ara Abrahmian. Property Dependency Injection is the default: set the /// "populateProtectedVariables" property to true in the constructor to switch /// on Field Injection.</li> /// </ul></p> /// /// <p>This class will normally cache contexts based on a <i>context key</i>: /// normally the config locations String array describing the Spring resource /// descriptors making up the context. Unless the <code>SetDirty()</code> method /// is called by a test, the context will not be reloaded, even across different /// subclasses of this test. This is particularly beneficial if your context is /// slow to construct, for example if you are using Hibernate and the time taken /// to load the mappings is an issue.</p> /// /// <p>If you don't want this behavior, you can override the <code>ContextKey</code> /// property, most likely to return the test class. In conjunction with this you would /// probably override the <code>GetContext</code> method, which by default loads /// the locations specified by the <code>ConfigLocations</code> property.</p> /// /// <p><b>WARNING:</b> When doing integration tests from within VS.NET, only use /// assembly resource URLs. Else, you may see misleading failures when changing /// context locations.</p> /// </remarks> /// /// <author>Rod Johnson</author> /// <author>Rob Harrop</author> /// <author>Rick Evans</author> /// <author>Aleksandar Seovic (.NET)</author> public abstract class AbstractDependencyInjectionSpringContextTests : AbstractSpringContextTests { private bool populateProtectedVariables = false; private AutoWiringMode autowireMode = AutoWiringMode.ByType; private bool dependencyCheck = true; /// <summary> /// Application context this test will run against. /// </summary> protected IConfigurableApplicationContext applicationContext; /// <summary> /// Holds names of the fields that should be used for field injection. /// </summary> protected string[] managedVariableNames; private int loadCount = 0; /// <summary> /// Default constructor for AbstractDependencyInjectionSpringContextTests. /// </summary> public AbstractDependencyInjectionSpringContextTests() {} /// <summary> /// Gets or sets a flag specifying whether to populate protected /// variables of this test case. /// </summary> /// <value> /// A flag specifying whether to populate protected variables of this test case. /// Default is <b>false</b>. /// </value> public bool PopulateProtectedVariables { get { return populateProtectedVariables; } set { populateProtectedVariables = value; } } /// <summary> /// Gets or sets the autowire mode for test properties set by Dependency Injection. /// </summary> /// <value> /// The autowire mode for test properties set by Dependency Injection. /// The default is <see cref="AutoWiringMode.ByType"/>. /// </value> public AutoWiringMode AutowireMode { get { return autowireMode; } set { autowireMode = value; } } /// <summary> /// Gets or sets a flag specifying whether or not dependency checking /// should be performed for test properties set by Dependency Injection. /// </summary> /// <value> /// <p>A flag specifying whether or not dependency checking /// should be performed for test properties set by Dependency Injection.</p> /// <p>The default is <b>true</b>, meaning that tests cannot be run /// unless all properties are populated.</p> /// </value> public bool DependencyCheck { get { return dependencyCheck; } set { dependencyCheck = value; } } /// <summary> /// Gets the current number of context load attempts. /// </summary> public int LoadCount { get { return loadCount; } } /// <summary> /// Called to say that the "applicationContext" instance variable is dirty and /// should be reloaded. We need to do this if a test has modified the context /// (for example, by replacing an object definition). /// </summary> public void SetDirty() { SetDirty(ConfigLocations); } /// <summary> /// Test setup method. /// </summary> [TestInitialize] public virtual void TestInitialize() { this.applicationContext = GetContext(ContextKey); InjectDependencies(); try { OnTestInitialize(); } catch (Exception ex) { logger.Error("Setup error", ex); throw; } } /// <summary> /// Inject dependencies into 'this' instance (that is, this test instance). /// </summary> /// <remarks> /// <p>The default implementation populates protected variables if the /// <see cref="PopulateProtectedVariables"/> property is set, else /// uses autowiring if autowiring is switched on (which it is by default).</p> /// <p>You can certainly override this method if you want to totally control /// how dependencies are injected into 'this' instance.</p> /// </remarks> protected virtual void InjectDependencies() { if (PopulateProtectedVariables) { if (this.managedVariableNames == null) { InitManagedVariableNames(); } InjectProtectedVariables(); } else if (AutowireMode != AutoWiringMode.No) { IConfigurableListableObjectFactory factory = this.applicationContext.ObjectFactory; ((AbstractObjectFactory) factory).IgnoreDependencyType(typeof(AutoWiringMode)); factory.AutowireObjectProperties(this, AutowireMode, DependencyCheck); } } /// <summary> /// Gets a key for this context. Usually based on config locations, but /// a subclass overriding buildContext() might want to return its class. /// </summary> protected virtual object ContextKey { get { return ConfigLocations; } } /// <summary> /// Loads application context from the specified resource locations. /// </summary> /// <param name="locations">Resources to load object definitions from.</param> protected override IConfigurableApplicationContext LoadContextLocations(string[] locations) { ++this.loadCount; return base.LoadContextLocations(locations); } /// <summary> /// Retrieves the names of the fields that should be used for field injection. /// </summary> protected virtual void InitManagedVariableNames() { ArrayList managedVarNames = new ArrayList(); Type type = GetType(); do { FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance); if (logger.IsDebugEnabled) { logger.Debug("Found " + fields.Length + " fields on " + type); } for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; if (logger.IsDebugEnabled) { logger.Debug("Candidate field: " + field); } if (IsProtectedInstanceField(field)) { object oldValue = field.GetValue(this); if (oldValue == null) { managedVarNames.Add(field.Name); if (logger.IsDebugEnabled) { logger.Debug("Added managed variable '" + field.Name + "'"); } } else { if (logger.IsDebugEnabled) { logger.Debug("Rejected managed variable '" + field.Name + "'"); } } } } type = type.BaseType; } while (type != typeof (AbstractDependencyInjectionSpringContextTests)); this.managedVariableNames = (string[]) managedVarNames.ToArray(typeof (string)); } private static bool IsProtectedInstanceField(FieldInfo field) { return field.IsFamily; } /// <summary> /// Injects protected fields using Field Injection. /// </summary> protected virtual void InjectProtectedVariables() { for (int i = 0; i < this.managedVariableNames.Length; i++) { string fieldName = this.managedVariableNames[i]; Object obj = null; try { FieldInfo field = GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); if (field != null) { BeforeProtectedVariableInjection(field); obj = this.applicationContext.GetObject(fieldName, field.FieldType); field.SetValue(this, obj); if (logger.IsDebugEnabled) { logger.Debug("Populated field: " + field); } } else { if (logger.IsWarnEnabled) { logger.Warn("No field with name '" + fieldName + "'"); } } } catch (NoSuchObjectDefinitionException) { if (logger.IsWarnEnabled) { logger.Warn("No object definition with name '" + fieldName + "'"); } } } } /// <summary> /// Called right before a field is being injected /// </summary> protected virtual void BeforeProtectedVariableInjection(FieldInfo fieldInfo) { } /// <summary> /// Subclasses can override this method in order to /// add custom test setup logic. /// </summary> protected virtual void OnTestInitialize() {} /// <summary> /// Test teardown method. /// </summary> [TestCleanup] public void TestCleanup() { try { OnTestCleanup(); } catch (Exception ex) { logger.Error("OnTearDown error", ex); } } /// <summary> /// Subclasses can override this method in order to /// add custom test teardown logic. /// </summary> protected virtual void OnTestCleanup() {} /// <summary> /// Subclasses must implement this property to return the locations of their /// config files. A plain path will be treated as a file system location. /// </summary> /// <value>An array of config locations</value> protected abstract string[] ConfigLocations { get; } } }
//////////////////////////////////////////////////////////////////////////////// // // @module Google Ads Unity SDK // @author Osipov Stanislav (Stan's Assets) // @support stans.assets@gmail.com // //////////////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class IOSADBanner : EventDispatcherBase, GoogleMobileAdBanner { [DllImport ("__Internal")] private static extern void _GADCreateBannerAd(int gravity, int size, int id); [DllImport ("__Internal")] private static extern void _GADCreateBannerAdPos(int x, int y, int size, int id); [DllImport ("__Internal")] private static extern void _GADShowAd(int id); [DllImport ("__Internal")] private static extern void _GADHideAd(int id); [DllImport ("__Internal")] private static extern void _GADRefresh(int id); private int _id; private GADBannerSize _size; private TextAnchor _anchor; private bool _IsLoaded = false; private bool _IsOnScreen = false; private bool firstLoad = true; private bool _ShowOnLoad = true; //-------------------------------------- // INITIALIZE //-------------------------------------- public IOSADBanner(TextAnchor anchor, GADBannerSize size, int id) { _id = id; _size = size; _anchor = anchor; if(Application.platform == RuntimePlatform.IPhonePlayer) { _GADCreateBannerAd(gravity, (int) _size, _id); } } public IOSADBanner(int x, int y, GADBannerSize size, int id) { _id = id; _size = size; if(Application.platform == RuntimePlatform.IPhonePlayer) { _GADCreateBannerAdPos(x, y, (int) _size, _id); } } //-------------------------------------- // PUBLIC METHODS //-------------------------------------- public void Hide() { if(!_IsOnScreen) { return; } _IsOnScreen = false; if(Application.platform == RuntimePlatform.IPhonePlayer) { _GADHideAd(_id); } } public void Show() { if(_IsOnScreen) { return; } _IsOnScreen = true; if(Application.platform == RuntimePlatform.IPhonePlayer) { _GADShowAd(_id); } } public void Refresh() { if(!_IsLoaded) { return; } if(Application.platform == RuntimePlatform.IPhonePlayer) { _GADRefresh(_id); } } //-------------------------------------- // GET/SET //-------------------------------------- public int id { get { return _id; } } public GADBannerSize size { get { return _size; } } public bool IsLoaded { get { return _IsLoaded; } } public bool IsOnScreen { get { return _IsOnScreen; } } public bool ShowOnLoad { get { return _ShowOnLoad; } set { _ShowOnLoad = value; } } public TextAnchor anchor { get { return _anchor; } } public int gravity { get { switch(_anchor) { case TextAnchor.LowerCenter: return GoogleGravity.BOTTOM | GoogleGravity.CENTER; case TextAnchor.LowerLeft: return GoogleGravity.BOTTOM | GoogleGravity.LEFT; case TextAnchor.LowerRight: return GoogleGravity.BOTTOM | GoogleGravity.RIGHT; case TextAnchor.MiddleCenter: return GoogleGravity.CENTER; case TextAnchor.MiddleLeft: return GoogleGravity.CENTER | GoogleGravity.LEFT; case TextAnchor.MiddleRight: return GoogleGravity.CENTER | GoogleGravity.RIGHT; case TextAnchor.UpperCenter: return GoogleGravity.TOP | GoogleGravity.CENTER; case TextAnchor.UpperLeft: return GoogleGravity.TOP | GoogleGravity.LEFT; case TextAnchor.UpperRight: return GoogleGravity.TOP | GoogleGravity.RIGHT; } return GoogleGravity.TOP; } } //-------------------------------------- // EVENTS //-------------------------------------- public void OnBannerAdLoaded() { _IsLoaded = true; if(ShowOnLoad && firstLoad) { Show(); firstLoad = false; } dispatch(GoogleMobileAdEvents.ON_BANNER_AD_LOADED); } public void OnBannerAdFailedToLoad() { dispatch(GoogleMobileAdEvents.ON_BANNER_AD_FAILED_LOADING); } public void OnBannerAdOpened() { dispatch(GoogleMobileAdEvents.ON_BANNER_AD_OPENED); } public void OnBannerAdClosed() { dispatch(GoogleMobileAdEvents.ON_BANNER_AD_CLOSED); } public void OnBannerAdLeftApplication() { dispatch(GoogleMobileAdEvents.ON_BANNER_AD_LEFT_APPLICATION); } }
//--------------------------------------------------------------------------- // // <copyright file="LiveShapingItem.cs" company="Microsoft"> // Copyright (C) by Microsoft Corporation. All rights reserved. // </copyright> // // // Description: A proxy for a source item, used in live shaping. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using System.Windows.Data; namespace MS.Internal.Data { internal class LiveShapingItem : DependencyObject { internal LiveShapingItem(object item, LiveShapingList list, bool filtered=false, LiveShapingBlock block=null, bool oneTime=false) { _block = block; list.InitializeItem(this, item, filtered, oneTime); ForwardChanges = !oneTime; } internal object Item { get { return _item; } set { _item = value; } } internal LiveShapingBlock Block { get { return _block; } set { _block = value; } } LiveShapingList List { get { return Block.List; } } internal bool IsSortDirty { get { return TestFlag(PrivateFlags.IsSortDirty); } set { ChangeFlag(PrivateFlags.IsSortDirty, value); } } internal bool IsSortPendingClean { get { return TestFlag(PrivateFlags.IsSortPendingClean); } set { ChangeFlag(PrivateFlags.IsSortPendingClean, value); } } internal bool IsFilterDirty { get { return TestFlag(PrivateFlags.IsFilterDirty); } set { ChangeFlag(PrivateFlags.IsFilterDirty, value); } } internal bool IsGroupDirty { get { return TestFlag(PrivateFlags.IsGroupDirty); } set { ChangeFlag(PrivateFlags.IsGroupDirty, value); } } internal bool FailsFilter { get { return TestFlag(PrivateFlags.FailsFilter); } set { ChangeFlag(PrivateFlags.FailsFilter, value); } } internal bool ForwardChanges { get { return TestFlag(PrivateFlags.ForwardChanges); } set { ChangeFlag(PrivateFlags.ForwardChanges, value); } } internal bool IsDeleted { get { return TestFlag(PrivateFlags.IsDeleted); } set { ChangeFlag(PrivateFlags.IsDeleted, value); } } internal void FindPosition(out RBFinger<LiveShapingItem> oldFinger, out RBFinger<LiveShapingItem> newFinger, Comparison<LiveShapingItem> comparison) { Block.FindPosition(this, out oldFinger, out newFinger, comparison); } internal RBFinger<LiveShapingItem> GetFinger() { return Block.GetFinger(this); } private static readonly DependencyProperty StartingIndexProperty = DependencyProperty.Register("StartingIndex", typeof(int), typeof(LiveShapingItem)); internal int StartingIndex { get { return (int)GetValue(StartingIndexProperty); } set { SetValue(StartingIndexProperty, value); } } internal int GetAndClearStartingIndex() { int result = StartingIndex; ClearValue(StartingIndexProperty); return result; } internal void SetBinding(string path, DependencyProperty dp, bool oneTime=false, bool enableXT=false) { if (enableXT && oneTime) enableXT = false; if (!LookupEntry(dp.GlobalIndex).Found) { if (!String.IsNullOrEmpty(path)) { Binding binding; if (SystemXmlHelper.IsXmlNode(_item)) { binding = new Binding(); binding.XPath = path; } else { binding = new Binding(path); } binding.Source = _item; if (oneTime) binding.Mode = BindingMode.OneTime; BindingExpressionBase beb = BindingOperations.SetBinding(this, dp, binding); if (enableXT) beb.TargetWantsCrossThreadNotifications = true; } else if (!oneTime) { // when the path is empty, react to any property change INotifyPropertyChanged inpc = Item as INotifyPropertyChanged; if (inpc != null) { PropertyChangedEventManager.AddHandler(inpc, OnPropertyChanged, String.Empty); } } } } internal object GetValue(string path, DependencyProperty dp) { if (!String.IsNullOrEmpty(path)) { SetBinding(path, dp); // set up the binding, if not already done return GetValue(dp); // return the value } else { // when the path is empty, just return the item itself return Item; } } internal void Clear() { List.ClearItem(this); } // if a sort property changes on a foreign thread, we must mark the item // as sort-dirty immediately, in case the UI thread is trying to restore // live sorting. The item is no longer necessarily in the right position, // and so should not participate in comparisons. internal void OnCrossThreadPropertyChange(DependencyProperty dp) { List.OnItemPropertyChangedCrossThread(this, dp); } private static readonly DependencyProperty ParentGroupsProperty = DependencyProperty.Register("ParentGroups", typeof(object), typeof(LiveShapingItem)); internal void AddParentGroup(CollectionViewGroupInternal group) { object o = GetValue(ParentGroupsProperty); List<CollectionViewGroupInternal> list; if (o == null) { // no parents yet, store a singleton SetValue(ParentGroupsProperty, group); } else if ((list = o as List<CollectionViewGroupInternal>) == null) { // one parent, store a list list = new List<CollectionViewGroupInternal>(2); list.Add(o as CollectionViewGroupInternal); list.Add(group); SetValue(ParentGroupsProperty, list); } else { // many parents, add to the list list.Add(group); } } internal void RemoveParentGroup(CollectionViewGroupInternal group) { object o = GetValue(ParentGroupsProperty); List<CollectionViewGroupInternal> list = o as List<CollectionViewGroupInternal>; if (list == null) { // one parent, remove it if (o == group) { ClearValue(ParentGroupsProperty); } } else { // many parents, remove from the list list.Remove(group); if (list.Count == 1) { // collapse a singleton list SetValue(ParentGroupsProperty, list[0]); } } } internal List<CollectionViewGroupInternal> ParentGroups { get { return GetValue(ParentGroupsProperty) as List<CollectionViewGroupInternal>; } } internal CollectionViewGroupInternal ParentGroup { get { return GetValue(ParentGroupsProperty) as CollectionViewGroupInternal; } } protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { if (ForwardChanges) { List.OnItemPropertyChanged(this, e.Property); } } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { List.OnItemPropertyChanged(this, null); } private bool TestFlag(PrivateFlags flag) { return (_flags & flag) != 0; } private void ChangeFlag(PrivateFlags flag, bool value) { if (value) _flags |= flag; else _flags &= ~flag; } [Flags] private enum PrivateFlags { IsSortDirty = 0x00000001, // sort property has changed (even cross-thread) IsSortPendingClean = 0x00000002, // item is on the SortDirtyItems list IsFilterDirty = 0x00000004, // filter property has changed IsGroupDirty = 0x00000008, // grouping property has changed FailsFilter = 0x00000010, // item fails the filter ForwardChanges = 0x00000020, // inform list of changes IsDeleted = 0x00000040, // item is deleted - no live shaping needed } LiveShapingBlock _block; // the block where I appear object _item; // the source item I represent PrivateFlags _flags; } }
// --------------------------------------------------------------------------- // <copyright file="FileAttachment.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the FileAttachment class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.IO; using System.Text; /// <summary> /// Represents a file attachment. /// </summary> public sealed class FileAttachment : Attachment { private string fileName; private Stream contentStream; private byte[] content; private Stream loadToStream; private bool isContactPhoto; /// <summary> /// Initializes a new instance of the <see cref="FileAttachment"/> class. /// </summary> /// <param name="owner">The owner.</param> internal FileAttachment(Item owner) : base(owner) { } /// <summary> /// Initializes a new instance of the <see cref="FileAttachment"/> class. /// </summary> /// <param name="service">The service.</param> internal FileAttachment(ExchangeService service) : base(service) { } /// <summary> /// Gets the name of the XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetXmlElementName() { return XmlElementNames.FileAttachment; } /// <summary> /// Validates this instance. /// </summary> /// <param name="attachmentIndex">Index of this attachment.</param> internal override void Validate(int attachmentIndex) { if (string.IsNullOrEmpty(this.fileName) && (this.content == null) && (this.contentStream == null)) { throw new ServiceValidationException(string.Format(Strings.FileAttachmentContentIsNotSet, attachmentIndex)); } } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { bool result = base.TryReadElementFromXml(reader); if (!result) { if (reader.LocalName == XmlElementNames.IsContactPhoto) { this.isContactPhoto = reader.ReadElementValue<bool>(); } else if (reader.LocalName == XmlElementNames.Content) { if (this.loadToStream != null) { reader.ReadBase64ElementValue(this.loadToStream); } else { // If there's a file attachment content handler, use it. Otherwise // load the content into a byte array. // TODO: Should we mark the attachment to indicate that content is stored elsewhere? if (reader.Service.FileAttachmentContentHandler != null) { Stream outputStream = reader.Service.FileAttachmentContentHandler.GetOutputStream(this.Id); if (outputStream != null) { reader.ReadBase64ElementValue(outputStream); } else { this.content = reader.ReadBase64ElementValue(); } } else { this.content = reader.ReadBase64ElementValue(); } } result = true; } } return result; } /// <summary> /// For FileAttachment, the only thing need to patch is the AttachmentId. /// </summary> /// <param name="reader"></param> /// <returns></returns> internal override bool TryReadElementFromXmlToPatch(EwsServiceXmlReader reader) { return base.TryReadElementFromXml(reader); } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service"></param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { base.LoadFromJson(jsonProperty, service); foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.IsContactPhoto: this.isContactPhoto = jsonProperty.ReadAsBool(key); break; case XmlElementNames.Content: if (this.loadToStream != null) { jsonProperty.ReadAsBase64Content(key, this.loadToStream); } else { // If there's a file attachment content handler, use it. Otherwise // load the content into a byte array. // TODO: Should we mark the attachment to indicate that content is stored elsewhere? if (service.FileAttachmentContentHandler != null) { Stream outputStream = service.FileAttachmentContentHandler.GetOutputStream(this.Id); if (outputStream != null) { jsonProperty.ReadAsBase64Content(key, outputStream); } else { this.content = jsonProperty.ReadAsBase64Content(key); } } else { this.content = jsonProperty.ReadAsBase64Content(key); } } break; default: break; } } } /// <summary> /// Writes elements and content to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { base.WriteElementsToXml(writer); if (writer.Service.RequestedServerVersion > ExchangeVersion.Exchange2007_SP1) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.IsContactPhoto, this.isContactPhoto); } writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Content); if (!string.IsNullOrEmpty(this.FileName)) { using (FileStream fileStream = new FileStream(this.FileName, FileMode.Open, FileAccess.Read)) { writer.WriteBase64ElementValue(fileStream); } } else if (this.ContentStream != null) { writer.WriteBase64ElementValue(this.ContentStream); } else if (this.Content != null) { writer.WriteBase64ElementValue(this.Content); } else { EwsUtilities.Assert( false, "FileAttachment.WriteElementsToXml", "The attachment's content is not set."); } writer.WriteEndElement(); } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service"></param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonAttachment = base.InternalToJson(service) as JsonObject; if (service.RequestedServerVersion > ExchangeVersion.Exchange2007_SP1) { jsonAttachment.Add(XmlElementNames.IsContactPhoto, this.isContactPhoto); } if (!string.IsNullOrEmpty(this.FileName)) { using (FileStream fileStream = new FileStream(this.FileName, FileMode.Open, FileAccess.Read)) { jsonAttachment.AddBase64(XmlElementNames.Content, fileStream); } } else if (this.ContentStream != null) { jsonAttachment.AddBase64(XmlElementNames.Content, this.ContentStream); } else if (this.Content != null) { jsonAttachment.AddBase64(XmlElementNames.Content, this.Content); } else { EwsUtilities.Assert( false, "FileAttachment.WriteElementsToXml", "The attachment's content is not set."); } return jsonAttachment; } /// <summary> /// Loads the content of the file attachment into the specified stream. Calling this method results in a call to EWS. /// </summary> /// <param name="stream">The stream to load the content of the attachment into.</param> public void Load(Stream stream) { this.loadToStream = stream; try { this.Load(); } finally { this.loadToStream = null; } } /// <summary> /// Loads the content of the file attachment into the specified file. Calling this method results in a call to EWS. /// </summary> /// <param name="fileName">The name of the file to load the content of the attachment into. If the file already exists, it is overwritten.</param> public void Load(string fileName) { this.loadToStream = new FileStream(fileName, FileMode.Create); try { this.Load(); } finally { this.loadToStream.Dispose(); this.loadToStream = null; } this.fileName = fileName; this.content = null; this.contentStream = null; } /// <summary> /// Gets the name of the file the attachment is linked to. /// </summary> public string FileName { get { return this.fileName; } internal set { this.ThrowIfThisIsNotNew(); this.fileName = value; this.content = null; this.contentStream = null; } } /// <summary> /// Gets or sets the content stream. /// </summary> /// <value>The content stream.</value> internal Stream ContentStream { get { return this.contentStream; } set { this.ThrowIfThisIsNotNew(); this.contentStream = value; this.content = null; this.fileName = null; } } /// <summary> /// Gets the content of the attachment into memory. Content is set only when Load() is called. /// </summary> public byte[] Content { get { return this.content; } internal set { this.ThrowIfThisIsNotNew(); this.content = value; this.fileName = null; this.contentStream = null; } } /// <summary> /// Gets or sets a value indicating whether this attachment is a contact photo. /// </summary> public bool IsContactPhoto { get { EwsUtilities.ValidatePropertyVersion(this.Service, ExchangeVersion.Exchange2010, "IsContactPhoto"); return this.isContactPhoto; } set { EwsUtilities.ValidatePropertyVersion(this.Service, ExchangeVersion.Exchange2010, "IsContactPhoto"); this.ThrowIfThisIsNotNew(); this.isContactPhoto = value; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class DelayedTypeParameterTypeRepresentation : TypeRepresentation { // // State // private TypeRepresentation m_context; private int m_parameterNumber; // // Constructor Methods // public DelayedTypeParameterTypeRepresentation( AssemblyRepresentation owner , TypeRepresentation context , int parameterNumber ) : base( owner, BuiltInTypes.VAR, Attributes.None ) { m_context = context; m_parameterNumber = parameterNumber; } // // MetaDataEquality Methods // public override bool EqualsThroughEquivalence( object obj , EquivalenceSet set ) { if(obj is DelayedTypeParameterTypeRepresentation) { DelayedTypeParameterTypeRepresentation other = (DelayedTypeParameterTypeRepresentation)obj; if(m_parameterNumber == other.m_parameterNumber) { // // Don't compare the context with Equals, it would lead to an infinite recursion! // if(Object.ReferenceEquals( m_context, other.m_context )) { return true; } if(set != null) { if(set.AreEquivalent( this, this.m_context, other, other.m_context )) { return true; } } } } return false; } public override bool Equals( object obj ) { return this.EqualsThroughEquivalence( obj, null ); } public override int GetHashCode() { return (int)m_parameterNumber ^ m_context.GetHashCode(); } //--// // // Helper Methods // protected override void PerformInnerDelayedTypeAnalysis( TypeSystem typeSystem , ref ConversionContext context ) { m_extends = (ReferenceTypeRepresentation)typeSystem.WellKnownTypes.System_Object; foreach(TypeRepresentation td in m_context.GenericParametersDefinition[m_parameterNumber].Constraints) { if(td is InterfaceTypeRepresentation) { continue; } m_extends = td; break; } } //--// public override void ApplyTransformation( TransformationContext context ) { context.Push( this ); // // Load before calling the base method, because we might get a call to GetHashCode(). // context.Transform( ref m_context ); context.Transform( ref m_parameterNumber ); base.ApplyTransformation( context ); context.Pop(); } //--// protected override void SetShapeCategory( TypeSystem typeSystem ) { m_vTable.ShapeCategory = VTable.Shape.Invalid; } //--// protected override TypeRepresentation AllocateInstantiation( InstantiationContext ic ) { return ic.TypeParameters[m_parameterNumber]; } //--// public override GCInfo.Kind ClassifyAsPointer() { return GCInfo.Kind.Invalid; } //--// public override InstantiationFlavor GetInstantiationFlavor( TypeSystem typeSystem ) { if(m_extends.IsObject) { return InstantiationFlavor.Delayed; } if(m_extends == typeSystem.WellKnownTypes.System_ValueType) { return InstantiationFlavor.ValueType; } return m_extends.GetInstantiationFlavor( typeSystem ); } //--// // // Access Methods // public override bool IsOpenType { get { return true; } } public override bool IsDelayedType { get { return true; } } public override uint SizeOfHoldingVariable { get { return 0; } } public override bool CanPointToMemory { get { return false; // We don't know at this stage. } } public TypeRepresentation Context { get { return m_context; } } public int ParameterNumber { get { return m_parameterNumber; } } //--// // // Debug Methods // public override String ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder( "DelayedTypeParameterTypeRepresentation(" ); PrettyToString( sb, true, false ); sb.Append( "," ); sb.Append( m_context ); sb.Append( ")" ); return sb.ToString(); } internal override void PrettyToString( System.Text.StringBuilder sb , bool fPrefix , bool fWithAbbreviations ) { GenericContext gc = m_context.Generic; if(gc != null) { TypeRepresentation[] parameters = gc.Parameters; if(m_parameterNumber < parameters.Length) { parameters[m_parameterNumber].PrettyToString( sb, fPrefix, fWithAbbreviations ); return; } GenericParameterDefinition[] defs = gc.ParametersDefinition; if(defs != null && m_parameterNumber < defs.Length) { sb.Append( defs[m_parameterNumber].Name ); return; } } sb.Append( "{VAR," ); sb.Append( m_parameterNumber ); sb.Append( "}" ); } } }
// 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; namespace DotSpatial.Symbology { /// <summary> /// Calculates Jenks Natural Breaks /// </summary> /// <remarks> /// Ported from http://svn.mapwindow.org/svnroot/MapWinGIS4Dev/JenksBreaks.h /// </remarks> internal class JenksBreaksCalcuation { #region Fields private readonly List<JenksBreak> _classes; private readonly int _numClasses; private readonly int _numValues; private readonly List<JenksData> _values; private int _leftBound; // the id of classes between which optimization takes place private int _previousMaxId; // to prevent stalling in the local optimum private int _previousTargetId; private int _rightBound; // initially it's all classes, then it's reducing #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JenksBreaksCalcuation"/> class. /// </summary> /// <param name="values">Values used for calculation.</param> /// <param name="numClasses">Number of breaks that should be calculated.</param> public JenksBreaksCalcuation(IList<double> values, int numClasses) { _numClasses = numClasses; _numValues = values.Count; double classCount = _numValues / (double)numClasses; // fill values _values = new List<JenksData>(_numValues); for (int i = 0; i < _numValues; i++) { JenksData data = new JenksData(values[i], values[i] * values[i]) { ClassId = (int)Math.Floor(i * 1.0 / classCount) }; _values.Add(data); } _classes = new List<JenksBreak>(_numClasses); for (int i = 0; i < _numClasses; i++) { _classes.Add(new JenksBreak()); } // calculate initial deviations for classes int lastId = -1; for (int i = 0; i < _numValues; i++) { int classId = _values[i].ClassId; if (classId >= 0 && classId < _numClasses) { _classes[classId].Value += _values[i].Value; _classes[classId].Square += _values[i].Square; // saving bound between classes if (classId != lastId) { _classes[classId].StartId = i; lastId = classId; if (classId > 0) _classes[classId - 1].EndId = i - 1; } } } _classes[_numClasses - 1].EndId = _numValues - 1; for (int i = 0; i < _numClasses; i++) _classes[i].RefreshStandardDeviations(); } #endregion #region Methods /// <summary> /// Returning of results (indices of values to start each class) /// </summary> /// <returns>A list of the indices that start a class.</returns> public List<int> GetResults() { var results = new List<int>(_numClasses); for (int i = 0; i < _numClasses; i++) { results.Add(_classes[i].StartId); } return results; } /// <summary> /// Optimization routine /// </summary> public void Optimize() { // initialization double minValue = GetSumStandardDeviations(); // current best minimum _leftBound = 0; // we'll consider all classes in the beginning _rightBound = _classes.Count - 1; _previousMaxId = -1; _previousTargetId = -1; int numAttemmpts = 0; bool proceed = true; while (proceed) { for (int i = 0; i < _numValues; i++) { FindShift(); // when there are only 2 classes left we should stop on the local max value if (_rightBound - _leftBound == 0) { double val = GetSumStandardDeviations(); // the final minimum numAttemmpts++; if (numAttemmpts > 5) { return; } } } double value = GetSumStandardDeviations(); proceed = value < minValue; // if the deviations became smaller we'll execute one more loop if (value < minValue) minValue = value; } } // MakeShift() // Passing the value from one class to another to another. Criteria - standard deviation. private void FindShift() { // first we'll find classes with the smallest and largest SD int maxId = 0, minId = 0; double minValue = double.MaxValue, maxValue = 0.0; // use constant for (int i = _leftBound; i <= _rightBound; i++) { if (_classes[i].SDev > maxValue) { maxValue = _classes[i].SDev; maxId = i; } if (_classes[i].SDev < minValue) { minValue = _classes[i].SDev; minId = i; } } // then pass one observation from the max class in the direction of min class int valueId; int targetId; if (maxId > minId) { // <- we should find first value of max class valueId = _classes[maxId].StartId; targetId = maxId - 1; _classes[maxId].StartId++; _classes[targetId].EndId++; } else if (maxId < minId) { // -> we should find last value of max class valueId = _classes[maxId].EndId; targetId = maxId + 1; _classes[maxId].EndId--; _classes[targetId].StartId--; } else { // only one class left or the deviations withinb classes are equal return; } // Prevents stumbling in local optimum - algorithm will be repeating the same move // To prevent this we'll exclude part of classes with less standard deviation if (_previousMaxId == targetId && _previousTargetId == maxId) { // Now we choose which of the two states provides less deviation double value1 = GetSumStandardDeviations(); // change to second state MakeShift(maxId, targetId, valueId); double value2 = GetSumStandardDeviations(); // if first state is better revert to it if (value1 < value2) { MakeShift(targetId, maxId, valueId); } // now we can exclude part of the classes where no improvements can be expected int min = Math.Min(targetId, maxId); int max = Math.Max(targetId, maxId); double avg = GetSumStandardDeviations() / (_rightBound - _leftBound + 1); // analyze left side of distribution double sumLeft = 0, sumRight = 0; for (int j = _leftBound; j <= min; j++) { sumLeft += Math.Pow(_classes[j].SDev - avg, 2.0); } sumLeft /= min - _leftBound + 1; // analyze right side of distribution for (int j = _rightBound; j >= max; j--) { sumRight += Math.Pow(_classes[j].SDev - avg, 2.0); } sumRight /= _rightBound - max + 1; // exluding left part if (sumLeft >= sumRight) { _leftBound = max; } // exluding right part else if (sumLeft < sumRight) { _rightBound = min; } } else { MakeShift(maxId, targetId, valueId); } } /// <summary> /// Calculates the sum of standard deviations of individual variants from the class mean through all class. /// It's the objective function - should be minimized /// </summary> /// <returns>The sum of standard deviations.</returns> private double GetSumStandardDeviations() { double sum = 0.0; for (int i = 0; i < _numClasses; i++) { sum += _classes[i].SDev; } return sum; } // perform actual shift private void MakeShift(int maxId, int targetId, int valueId) { // saving the last shift _previousMaxId = maxId; _previousTargetId = targetId; var data = _values[valueId]; // removing from max class _classes[maxId].Value -= data.Value; _classes[maxId].Square -= data.Square; _classes[maxId].RefreshStandardDeviations(); // passing to target class _classes[targetId].Value += data.Value; _classes[targetId].Square += data.Square; _classes[targetId].RefreshStandardDeviations(); // mark that the value was passed _values[valueId].ClassId = targetId; } #endregion #region Classes private class JenksBreak { #region Constructors public JenksBreak() { Value = 0.0; Square = 0.0; SDev = 0.0; StartId = -1; EndId = -1; } #endregion #region Properties public int EndId { get; set; } public double SDev { get; set; } public double Square { get; set; } public int StartId { get; set; } public double Value { get; set; } #endregion #region Methods // the formula for every class is: sum((a[k])^2) - sum(a[k])^2/n public void RefreshStandardDeviations() { SDev = Square - (Math.Pow(Value, 2.0) / (EndId - StartId + 1)); } #endregion } private class JenksData { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="JenksData"/> class. /// </summary> /// <param name="value">The value.</param> /// <param name="square">The square.</param> public JenksData(double value, double square) { Value = value; Square = square; } #endregion #region Properties /// <summary> /// Gets or sets the number of the break to which a value belongs. /// </summary> public int ClassId { get; set; } public double Square { get; } public double Value { get; } #endregion } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("OrleansTaskScheduler RunQueue={RunQueue.Length}")] internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant { private readonly TraceLogger logger = TraceLogger.GetLogger("Scheduler.OrleansTaskScheduler", TraceLogger.LoggerType.Runtime); private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; // work group directory private bool applicationTurnsStopped; internal WorkQueue RunQueue { get; private set; } internal WorkerPool Pool { get; private set; } internal static TimeSpan TurnWarningLengthThreshold { get; set; } // This is the maximum number of pending work items for a single activation before we write a warning log. internal LimitValue MaxPendingItemsLimit { get; private set; } internal TimeSpan DelayWarningThreshold { get; private set; } public static OrleansTaskScheduler Instance { get; private set; } public int RunQueueLength { get { return RunQueue.Length; } } public OrleansTaskScheduler(int maxActiveThreads) : this(maxActiveThreads, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), NodeConfiguration.INJECT_MORE_WORKER_THREADS, LimitManager.GetDefaultLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS)) { } public OrleansTaskScheduler(GlobalConfiguration globalConfig, NodeConfiguration config) : this(config.MaxActiveThreads, config.DelayWarningThreshold, config.ActivationSchedulingQuantum, config.TurnWarningLengthThreshold, config.InjectMoreWorkerThreads, config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS)) { } private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum, TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads, LimitValue maxPendingItemsLimit) { Instance = this; DelayWarningThreshold = delayWarningThreshold; WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum; TurnWarningLengthThreshold = turnWarningLengthThreshold; applicationTurnsStopped = false; MaxPendingItemsLimit = maxPendingItemsLimit; workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>(); RunQueue = new WorkQueue(); logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads); Pool = new WorkerPool(this, maxActiveThreads, injectMoreWorkerThreads); IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength); if (!StatisticsCollector.CollectShedulerQueuesStats) return; FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo); FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo); } public int WorkItemGroupCount { get { return workgroupDirectory.Count; } } private float AverageRunQueueLengthLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count; } } private float AverageEnqueuedLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count; } } private float AverageArrivalRateLevelTwo { get { if (workgroupDirectory.IsEmpty) return 0; return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count; } } private float SumRunQueueLengthLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght); } } private float SumEnqueuedLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests); } } private float SumArrivalRateLevelTwo { get { return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate); } } public void Start() { Pool.Start(); } public void StopApplicationTurns() { #if DEBUG if (logger.IsVerbose) logger.Verbose("StopApplicationTurns"); #endif // Do not RunDown the application run queue, since it is still used by low priority system targets. applicationTurnsStopped = true; foreach (var group in workgroupDirectory.Values) { if (!group.IsSystemGroup) group.Stop(); } } public void Stop() { RunQueue.RunDown(); Pool.Stop(); } protected override IEnumerable<Task> GetScheduledTasks() { return new Task[0]; } protected override void QueueTask(Task task) { var contextObj = task.AsyncState; #if DEBUG if (logger.IsVerbose2) logger.Verbose2("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = contextObj as ISchedulingContext; var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped logger.Warn(ErrorCode.SchedulerAppTurnsStopped_2, string.Format("Dropping Task {0} because application turns are stopped", task)); return; } if (workItemGroup == null) { var todo = new TaskWorkItem(this, task, context); RunQueue.Add(todo); } else { var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.", task.Id, context); logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error); throw new InvalidOperationException(error); } } // Enqueue a work item to a given context public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context) { #if DEBUG if (logger.IsVerbose2) logger.Verbose2("QueueWorkItem " + context); #endif if (workItem is TaskWorkItem) { var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}." + " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.", workItem.ToString(), context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error); throw new InvalidOperationException(error); } var workItemGroup = GetWorkItemGroup(context); if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystemGroup) { // Drop the task on the floor if it's an application work item and application turns are stopped var msg = string.Format("Dropping work item {0} because application turns are stopped", workItem); logger.Warn(ErrorCode.SchedulerAppTurnsStopped_1, msg); return; } workItem.SchedulingContext = context; // We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start. // This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem. if (workItemGroup == null) { Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, this); t.Start(this); } else { // Create Task wrapper for this work item Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, workItemGroup.TaskRunner); t.Start(workItemGroup.TaskRunner); } } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public WorkItemGroup RegisterWorkContext(ISchedulingContext context) { if (context == null) return null; var wg = new WorkItemGroup(this, context); workgroupDirectory.TryAdd(context, wg); return wg; } // Only required if you have work groups flagged by a context that is not a WorkGroupingContext public void UnregisterWorkContext(ISchedulingContext context) { if (context == null) return; WorkItemGroup workGroup; if (workgroupDirectory.TryRemove(context, out workGroup)) workGroup.Stop(); } // public for testing only -- should be private, otherwise public WorkItemGroup GetWorkItemGroup(ISchedulingContext context) { if (context == null) return null; WorkItemGroup workGroup; if(workgroupDirectory.TryGetValue(context, out workGroup)) return workGroup; var error = String.Format("QueueWorkItem was called on a non-null context {0} but there is no valid WorkItemGroup for it.", context); logger.Error(ErrorCode.SchedulerQueueWorkItemWrongContext, error); throw new InvalidSchedulingContextException(error); } internal void CheckSchedulingContextValidity(ISchedulingContext context) { if (context == null) { throw new InvalidSchedulingContextException("CheckSchedulingContextValidity was called on a null SchedulingContext."); } GetWorkItemGroup(context); // GetWorkItemGroup throws for Invalid context } public TaskScheduler GetTaskScheduler(ISchedulingContext context) { if (context == null) return this; WorkItemGroup workGroup; return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this; } public override int MaximumConcurrencyLevel { get { return Pool.MaxActiveThreads; } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { //bool canExecuteInline = WorkerPoolThread.CurrentContext != null; var ctx = RuntimeContext.Current; bool canExecuteInline = ctx == null || ctx.ActivationContext==null; #if DEBUG if (logger.IsVerbose2) { logger.Verbose2("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}", task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline); } #endif if (!canExecuteInline) return false; if (taskWasPreviouslyQueued) canExecuteInline = TryDequeue(task); if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads // We are on a worker pool thread, so can execute this task bool done = TryExecuteTask(task); if (!done) { logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } return done; } /// <summary> /// Run the specified task synchronously on the current thread /// </summary> /// <param name="task"><c>Task</c> to be executed</param> public void RunTask(Task task) { #if DEBUG if (logger.IsVerbose2) logger.Verbose2("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif var context = RuntimeContext.CurrentActivationContext; var workItemGroup = GetWorkItemGroup(context); if (workItemGroup == null) { RuntimeContext.SetExecutionContext(null, this); bool done = TryExecuteTask(task); if (!done) logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}", task.Id, task.Status); } else { var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.", task.Id, context); logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error); throw new InvalidOperationException(error); } #if DEBUG if (logger.IsVerbose2) logger.Verbose2("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current); #endif } // Returns true if healthy, false if not public bool CheckHealth(DateTime lastCheckTime) { return Pool.DoHealthCheck(); } /// <summary> /// Action to be invoked when there is no more work for this scheduler /// </summary> internal Action OnIdle { get; set; } /// <summary> /// Invoked by WorkerPool when all threads go idle /// </summary> internal void OnAllWorkerThreadsIdle() { if (OnIdle == null || RunQueueLength != 0) return; #if DEBUG if (logger.IsVerbose2) logger.Verbose2("OnIdle"); #endif OnIdle(); } internal void PrintStatistics() { if (!logger.IsInfo) return; var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), Environment.NewLine); if (stats.Length > 0) logger.LogWithoutBulkingAndTruncating(Severity.Info, ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:" + Environment.NewLine + "{2}", RunQueue.Length, WorkItemGroupCount, stats); } internal void DumpSchedulerStatus(bool alwaysOutput = true) { if (!logger.IsVerbose && !alwaysOutput) return; PrintStatistics(); var sb = new StringBuilder(); sb.AppendLine("Dump of current OrleansTaskScheduler status:"); sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}", Environment.ProcessorCount, RunQueue.Length, workgroupDirectory.Count, applicationTurnsStopped ? "STOPPING" : "").AppendLine(); sb.AppendLine("RunQueue:"); RunQueue.DumpStatus(sb); Pool.DumpStatus(sb); foreach (var workgroup in workgroupDirectory.Values) sb.AppendLine(workgroup.DumpStatus()); logger.LogWithoutBulkingAndTruncating(Severity.Info, ErrorCode.SchedulerStatus, sb.ToString()); } } }
// 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 gcdv = Google.Cloud.Dialogflow.V2; using sys = System; namespace Google.Cloud.Dialogflow.V2 { /// <summary>Resource name for the <c>Participant</c> resource.</summary> public sealed partial class ParticipantName : gax::IResourceName, sys::IEquatable<ParticipantName> { /// <summary>The possible contents of <see cref="ParticipantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> ProjectConversationParticipant = 1, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> ProjectLocationConversationParticipant = 2, } private static gax::PathTemplate s_projectConversationParticipant = new gax::PathTemplate("projects/{project}/conversations/{conversation}/participants/{participant}"); private static gax::PathTemplate s_projectLocationConversationParticipant = new gax::PathTemplate("projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}"); /// <summary>Creates a <see cref="ParticipantName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ParticipantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ParticipantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ParticipantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ParticipantName"/> with the pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ParticipantName"/> constructed from the provided ids.</returns> public static ParticipantName FromProjectConversationParticipant(string projectId, string conversationId, string participantId) => new ParticipantName(ResourceNameType.ProjectConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Creates a <see cref="ParticipantName"/> with the pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ParticipantName"/> constructed from the provided ids.</returns> public static ParticipantName FromProjectLocationConversationParticipant(string projectId, string locationId, string conversationId, string participantId) => new ParticipantName(ResourceNameType.ProjectLocationConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string Format(string projectId, string conversationId, string participantId) => FormatProjectConversationParticipant(projectId, conversationId, participantId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string FormatProjectConversationParticipant(string projectId, string conversationId, string participantId) => s_projectConversationParticipant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ParticipantName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c>. /// </returns> public static string FormatProjectLocationConversationParticipant(string projectId, string locationId, string conversationId, string participantId) => s_projectLocationConversationParticipant.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))); /// <summary>Parses the given resource name string into a new <see cref="ParticipantName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ParticipantName"/> if successful.</returns> public static ParticipantName Parse(string participantName) => Parse(participantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ParticipantName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ParticipantName"/> if successful.</returns> public static ParticipantName Parse(string participantName, bool allowUnparsed) => TryParse(participantName, allowUnparsed, out ParticipantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ParticipantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ParticipantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string participantName, out ParticipantName result) => TryParse(participantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ParticipantName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/participants/{participant}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="participantName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ParticipantName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string participantName, bool allowUnparsed, out ParticipantName result) { gax::GaxPreconditions.CheckNotNull(participantName, nameof(participantName)); gax::TemplatedResourceName resourceName; if (s_projectConversationParticipant.TryParseName(participantName, out resourceName)) { result = FromProjectConversationParticipant(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectLocationConversationParticipant.TryParseName(participantName, out resourceName)) { result = FromProjectLocationConversationParticipant(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(participantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ParticipantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversationId = null, string locationId = null, string participantId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversationId = conversationId; LocationId = locationId; ParticipantId = participantId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ParticipantName"/> class from the component parts of pattern /// <c>projects/{project}/conversations/{conversation}/participants/{participant}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="participantId">The <c>Participant</c> ID. Must not be <c>null</c> or empty.</param> public ParticipantName(string projectId, string conversationId, string participantId) : this(ResourceNameType.ProjectConversationParticipant, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), participantId: gax::GaxPreconditions.CheckNotNullOrEmpty(participantId, nameof(participantId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Conversation</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConversationId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Participant</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ParticipantId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectConversationParticipant: return s_projectConversationParticipant.Expand(ProjectId, ConversationId, ParticipantId); case ResourceNameType.ProjectLocationConversationParticipant: return s_projectLocationConversationParticipant.Expand(ProjectId, LocationId, ConversationId, ParticipantId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ParticipantName); /// <inheritdoc/> public bool Equals(ParticipantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ParticipantName a, ParticipantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ParticipantName a, ParticipantName b) => !(a == b); } /// <summary>Resource name for the <c>Message</c> resource.</summary> public sealed partial class MessageName : gax::IResourceName, sys::IEquatable<MessageName> { /// <summary>The possible contents of <see cref="MessageName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> ProjectConversationMessage = 1, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> ProjectLocationConversationMessage = 2, } private static gax::PathTemplate s_projectConversationMessage = new gax::PathTemplate("projects/{project}/conversations/{conversation}/messages/{message}"); private static gax::PathTemplate s_projectLocationConversationMessage = new gax::PathTemplate("projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}"); /// <summary>Creates a <see cref="MessageName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="MessageName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static MessageName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MessageName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MessageName"/> with the pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MessageName"/> constructed from the provided ids.</returns> public static MessageName FromProjectConversationMessage(string projectId, string conversationId, string messageId) => new MessageName(ResourceNameType.ProjectConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Creates a <see cref="MessageName"/> with the pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="MessageName"/> constructed from the provided ids.</returns> public static MessageName FromProjectLocationConversationMessage(string projectId, string locationId, string conversationId, string messageId) => new MessageName(ResourceNameType.ProjectLocationConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string Format(string projectId, string conversationId, string messageId) => FormatProjectConversationMessage(projectId, conversationId, messageId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string FormatProjectConversationMessage(string projectId, string conversationId, string messageId) => s_projectConversationMessage.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MessageName"/> with pattern /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c>. /// </returns> public static string FormatProjectLocationConversationMessage(string projectId, string locationId, string conversationId, string messageId) => s_projectLocationConversationMessage.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))); /// <summary>Parses the given resource name string into a new <see cref="MessageName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="MessageName"/> if successful.</returns> public static MessageName Parse(string messageName) => Parse(messageName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MessageName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="MessageName"/> if successful.</returns> public static MessageName Parse(string messageName, bool allowUnparsed) => TryParse(messageName, allowUnparsed, out MessageName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MessageName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="MessageName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string messageName, out MessageName result) => TryParse(messageName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MessageName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/conversations/{conversation}/messages/{message}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/conversations/{conversation}/messages/{message}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="messageName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MessageName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string messageName, bool allowUnparsed, out MessageName result) { gax::GaxPreconditions.CheckNotNull(messageName, nameof(messageName)); gax::TemplatedResourceName resourceName; if (s_projectConversationMessage.TryParseName(messageName, out resourceName)) { result = FromProjectConversationMessage(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectLocationConversationMessage.TryParseName(messageName, out resourceName)) { result = FromProjectLocationConversationMessage(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(messageName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MessageName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string conversationId = null, string locationId = null, string messageId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConversationId = conversationId; LocationId = locationId; MessageId = messageId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="MessageName"/> class from the component parts of pattern /// <c>projects/{project}/conversations/{conversation}/messages/{message}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="conversationId">The <c>Conversation</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="messageId">The <c>Message</c> ID. Must not be <c>null</c> or empty.</param> public MessageName(string projectId, string conversationId, string messageId) : this(ResourceNameType.ProjectConversationMessage, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), conversationId: gax::GaxPreconditions.CheckNotNullOrEmpty(conversationId, nameof(conversationId)), messageId: gax::GaxPreconditions.CheckNotNullOrEmpty(messageId, nameof(messageId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Conversation</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string ConversationId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Message</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string MessageId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectConversationMessage: return s_projectConversationMessage.Expand(ProjectId, ConversationId, MessageId); case ResourceNameType.ProjectLocationConversationMessage: return s_projectLocationConversationMessage.Expand(ProjectId, LocationId, ConversationId, MessageId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as MessageName); /// <inheritdoc/> public bool Equals(MessageName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MessageName a, MessageName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MessageName a, MessageName b) => !(a == b); } public partial class Participant { /// <summary> /// <see cref="gcdv::ParticipantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ParticipantName ParticipantName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ParticipantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Message { /// <summary> /// <see cref="gcdv::MessageName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::MessageName MessageName { get => string.IsNullOrEmpty(Name) ? null : gcdv::MessageName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateParticipantRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetParticipantRequest { /// <summary> /// <see cref="gcdv::ParticipantName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ParticipantName ParticipantName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ParticipantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListParticipantsRequest { /// <summary> /// <see cref="ConversationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ConversationName ParentAsConversationName { get => string.IsNullOrEmpty(Parent) ? null : ConversationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class AnalyzeContentRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Participant"/> resource name property. /// </summary> public ParticipantName ParticipantAsParticipantName { get => string.IsNullOrEmpty(Participant) ? null : ParticipantName.Parse(Participant, allowUnparsed: true); set => Participant = value?.ToString() ?? ""; } } public partial class SuggestArticlesRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ParticipantName ParentAsParticipantName { get => string.IsNullOrEmpty(Parent) ? null : ParticipantName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } public partial class SuggestFaqAnswersRequest { /// <summary> /// <see cref="ParticipantName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public ParticipantName ParentAsParticipantName { get => string.IsNullOrEmpty(Parent) ? null : ParticipantName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="MessageName"/>-typed view over the <see cref="LatestMessage"/> resource name property. /// </summary> public MessageName LatestMessageAsMessageName { get => string.IsNullOrEmpty(LatestMessage) ? null : MessageName.Parse(LatestMessage, allowUnparsed: true); set => LatestMessage = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security; using System; using System.IO; // For Stream [SecuritySafeCritical] public class TestStream : Stream { public void DisposeWrapper(bool disposing) { Dispose(disposing); } public override bool CanRead { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } public override bool CanSeek { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } public override bool CanWrite { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public override void Flush() { throw new Exception("The method or operation is not implemented."); } public override long Length { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } } public override long Position { [SecuritySafeCritical] get { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] set { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public override int Read(byte[] buffer, int offset, int count) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override long Seek(long offset, SeekOrigin origin) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override void SetLength(long value) { throw new Exception("The method or operation is not implemented."); } [SecuritySafeCritical] public override void Write(byte[] buffer, int offset, int count) { throw new Exception("The method or operation is not implemented."); } } [SecuritySafeCritical] public class StreamDispose2 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Dispose with disposing set to true"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Dispose twice with disposing set to true"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(true); ts.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call Dispose with disposing set to false"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call Dispose twice with disposing set to false"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(false); ts.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Call Dispose twice with disposing set to false once and another time set to true"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(false); ts.DisposeWrapper(true); } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Call Dispose twice with disposing set to true once and another time set to false"); try { TestStream ts = new TestStream(); ts.DisposeWrapper(true); ts.DisposeWrapper(false); } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { StreamDispose2 test = new StreamDispose2(); TestLibrary.TestFramework.BeginTestCase("StreamDispose2"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; using System.Text; using System.Collections.Generic; using ZptSharp.Dom; using ZptSharp.Expressions; using System.Linq; using System.Collections.ObjectModel; namespace ZptSharp.Config { /// <summary> /// Represents per-operation configuration information which influences the behaviour of the rendering process. /// This class is immutable; use a builder to prepare &amp; build configuration objects in a mutable manner. /// </summary> /// <remarks> /// <para> /// Each of the methods of <see cref="IRendersZptFile" /> or <see cref="IRendersZptDocument" /> accepts an /// optional rendering configuration parameter, which influences how that rendering operation will behave. /// The default for both of these APIs, if configuration is omitted or <see langword="null" />, is to use /// a <see cref="Default" /> configuration instance. /// </para> /// <para> /// Because every instance of rendering configuration is immutable, a builder object must be used to set-up /// the configuration object before it is used. /// The primary way to do this is: /// </para> /// <list type="number"> /// <item><description>Use the <see cref="CreateBuilder" /> method to get a builder</description></item> /// <item><description>Alter the settings as desired upon the builder</description></item> /// <item><description>Use <see cref="RenderingConfig.Builder.GetConfig" /> to build the configuration object</description></item> /// </list> /// <para> /// An alternative way to get a customised rendering configuration is to copy the settings/state of an existing /// configuration object into a builder. This is performed via <see cref="CloneToNewBuilder" />. /// You may then use that builder from step 2 onward in the process described above, except that it will be /// pre-filled with the same state as in the cloned configuration. /// </para> /// </remarks> /// <example> /// <para> /// The following logic creates a new rendering configuration which has source annotation enabled. /// </para> /// <code language="csharp"> /// var builder = RenderingConfig.CreateBuilder(); /// builder.IncludeSourceAnnotation = true; /// var config = builder.GetConfig(); /// </code> /// <para> /// This logic then creates a second rendering configuration based upon the example above /// which also uses a default expression type of <c>string</c>. /// </para> /// <code language="csharp"> /// var builder2 = config.CloneToNewBuilder(); /// builder2.DefaultExpressionType = "string"; /// var config2 = builder2.GetConfig(); /// </code> /// </example> public partial class RenderingConfig { /// <summary> /// Gets the encoding which will be used to read &amp; write documents, where the document /// provider supports it. /// </summary> /// <remarks> /// <para> /// Not all document providers will honour this encoding configuration setting; /// it is respected only where the underlying DOM document reader/writer supports it. /// Refer to the documentation of the document provider used - the implementation of /// <see cref="IReadsAndWritesDocument" /> - to see if this configuration property is supported. /// </para> /// <para> /// Where supported, this configuration setting allows the reading &amp; writing of /// ZPT documents which use different character encodings. /// </para> /// <para> /// In all modern cases, of course, UTF8 is the recommended encoding. /// </para> /// </remarks> /// <seealso cref="IReadsAndWritesDocument"/> /// <value>The document encoding.</value> public virtual Encoding DocumentEncoding { get; private set; } /// <summary> /// Gets the type of document provider implementation which is to be used for the current rendering task. /// </summary> /// <remarks> /// <para> /// When using <see cref="IRendersZptFile"/>, this configuration property is irrelevant and ignored. /// The file-rendering service will select an appropriate document renderer type based upon /// the filename &amp; extension of the source file. /// </para> /// <para> /// This configuration property is important when making use of <see cref="IRendersZptDocument"/>, /// though. /// Because the document-rendering service does not use a file path, there is no filename or /// extension to analyse. /// When using the document rendering service, this configuration property is used to specify /// which document provider implementation should be used to read &amp; write the underlying DOM /// document. /// </para> /// </remarks> /// <seealso cref="IRendersZptDocument"/> /// <value>The document provider implementation type to be used by the document-renderer service.</value> public virtual Type DocumentProviderType { get; private set; } /// <summary> /// Gets a value which indicates whether the XML document declaration should be omitted when /// writing XML documents. Has no effect unless an XML-based document provider is used. /// </summary> /// <remarks> /// <para> /// This controls XML-style document provider implementations and instructs them whether to write or /// whether to omit the <c>&lt;?xml ... ?&gt;</c> declarations on the first line of the file. /// </para> /// <para> /// Obviously, document providers which render HTML and not XML documents will ignore this /// configuration setting. /// </para> /// </remarks> /// <value><c>true</c> if the XML document declaration should be omitted; otherwise, <c>false</c>.</value> public virtual bool OmitXmlDeclaration { get; private set; } /// <summary> /// Gets a 'factory delegate' which provides the root contexts for expression resolution. /// </summary> /// <remarks> /// <para> /// The root contexts are the variables which are available to all TALES expressions /// before any further variables are defined. /// They are essentially the pre-defined variables which are already in-scope at the /// root of the DOM document. /// These variables are available in their own right or also as properties of a special /// root contexts object, accessible via the TALES keyword <c>CONTEXTS</c>. /// That contexts keyword may not be overridden by any other variable definition, meaning /// that the root contexts are always available via that reference. /// </para> /// <para> /// This configuration property allows the use of a customised service which gets those /// root contexts. /// A developer may write their own implementation of <see cref="IGetsDictionaryOfNamedTalesValues" /> /// which contains any arbitrary logic to retrieve those variables. /// The format of this property is a 'factory delegate' (a function) taking a parameter of /// type <see cref="ExpressionContext" /> and returning the implementation of /// <see cref="IGetsDictionaryOfNamedTalesValues" />. /// </para> /// <para> /// For the majority of foreseen usages, this configuration property does not need to be used. /// If this property is <see langword="null"/> then the rendering process will use a default /// implementation of <see cref="IGetsDictionaryOfNamedTalesValues" /> which provides /// <xref href="GlobalContextsArticle?text=the+standard+root+contexts"/>. /// In particular, developers do not need to write their own implementation of /// <see cref="IGetsDictionaryOfNamedTalesValues" /> in order to simply add extra root /// contexts/variables to the rendering process. /// In order to add additional variables, developers should use the <see cref="ContextBuilder"/> /// configuration property instead. /// Passing model data to the rendering process also does not need a customised root contexts /// provider. /// Model data is passed as a separate parameter to the rendering process and is accessible via /// the built-in root context <c>here</c>. /// </para> /// <para> /// Please note that if this property is specified then it is up to the custom implementation of /// <see cref="IGetsDictionaryOfNamedTalesValues"/> to include the keyword options in the root /// contexts, using the name <c>options</c>. /// If the custom implementation does not do this, then the configuration property /// <see cref="KeywordOptions"/> will not be honoured. /// There are two ways in which a custom implementation may achieve this. /// </para> /// <list type="bullet"> /// <item><description> /// It may constructor-inject an instance of <see cref="RenderingConfig"/> and include the keyword /// options in its own output. /// </description></item> /// <item><description> /// It may derive from the standard implementation of <see cref="IGetsDictionaryOfNamedTalesValues"/> /// found in the ZptSharp implementations package and override/supplement its returned results. /// </description></item> /// </list> /// </remarks> /// <value>The root contexts provider.</value> public virtual Func<ExpressionContext, IGetsDictionaryOfNamedTalesValues> RootContextsProvider { get; private set; } /// <summary> /// Gets a collection of name/value pairs available at the root TALES context (variable) named <c>options</c>. /// </summary> /// <remarks> /// <para> /// Keyword options are a series of arbitrary name/value pairs. /// Their precise semantics are loosely-defined by the ZPT syntax specification and the functionality /// is very rarely-used in real-life implementations, nor is it recommended to begin using them if not /// absolutely neccesary. /// Keyword options could, for example, be used to contain arbitrary name/value arguments passed to a /// command-line app. /// In all foreseeable use-cases though, the model is a far better way to make data available /// to document templates. /// </para> /// <para> /// Note that because <c>options</c> is a root TALES context, if the <see cref="RootContextsProvider"/> /// configuration setting is also specified, then that could mean that this setting is not honoured. /// It is up to a custom implementation of the root contexts provider to include the keyword options. /// </para> /// </remarks> /// <value>The keyword options collection.</value> public virtual IReadOnlyDictionary<string,object> KeywordOptions { get; private set; } /// <summary> /// Gets a callback which is used to extend the root contexts, without needing to /// replace the <see cref="RootContextsProvider" />. /// </summary> /// <remarks> /// <para> /// This configuration setting provides a convenient way to add additional root contexts; /// pre-defined variables which are available to the entire rendering process. /// Using this setting avoids the need to use a custom <see cref="RootContextsProvider" /> /// implementation when all that was desired was to add extra variables. /// </para> /// </remarks> /// <value>The context builder action.</value> public virtual Action<IConfiguresRootContext, IServiceProvider> ContextBuilder { get; private set; } /// <summary> /// Gets a value which indicates whether or not source annotation should be written to the rendered document. /// </summary> /// <remarks> /// <para> /// Source annotation is a useful ZPT feature used for debugging and understanding the rendering process, /// such as when diagnosing a problem. /// When source annotation is enabled, each time there is an insertion of markup from a different source, an /// HTML/XML comment is added indicating that source and source line number. /// The insertion of markup most commonly refers to the usage of METAL macros and the filling of slots. /// It helps developers confidently understand "where did this output come from"? /// </para> /// <para> /// The "source" for any document is simplest when <see cref="IRendersZptFile"/> is used, since it /// is quite simply the path to the file, relative to <see cref="SourceAnnotationBasePath"/> where applicable. /// When <see cref="IRendersZptDocument"/> is used instead then a source info object would be passed (via /// optional parameter) to /// <see cref="IRendersZptDocument.RenderAsync(System.IO.Stream, object, RenderingConfig, System.Threading.CancellationToken, Rendering.IDocumentSourceInfo)"/>. /// A custom implementation of <see cref="Rendering.IDocumentSourceInfo"/> could represent anything, /// such as a database key, API URI or whatever application-specific information is applicable. /// </para> /// </remarks> /// <example> /// <para> /// Here is a sample of what source annotation could look like the following in the rendered output. /// It appears as an HTML or XML comment, designated by a block of <c>=</c> symbols. /// It then shows the string representation of the source information and the line number at which /// the included content originated. /// </para> /// <code language="html"> /// &lt;span&gt;This span element was originally defined in "MyMacro.pt", line 4&lt;/span&gt;&lt;!-- /// ============================================================================== /// MySourceFiles\MyMacro.pt (line 4) /// ============================================================================== /// --&gt; /// This is further content in the rendered output document. /// </code> /// </example> /// <seealso cref="Rendering.IDocumentSourceInfo"/> /// <seealso cref="SourceAnnotationBasePath"/> /// <value><c>true</c> if source annotation should be included in the output; otherwise, <c>false</c>.</value> public virtual bool IncludeSourceAnnotation { get; private set; } /// <summary> /// Gets a file system path which is used as the base path to shorten source annotation filenames, /// when <see cref="IncludeSourceAnnotation"/> is <see langword="true"/>. /// </summary> /// <remarks> /// <para> /// This configuration setting is only relevant when <see cref="IncludeSourceAnnotation"/> is <see langword="true"/> /// and also when documents are rendered from file system files, such as when <see cref="IRendersZptFile"/> /// is being used. /// In any other scenario this configuration setting will not be used and will have no effect. /// </para> /// <para> /// When source annotation comments are added to the rendered output, if the source of a document is /// a filesystem file, the comment will include the path to that file. /// If this configuration setting is not specified or is <see langword="null"/> then the full, /// absolute file path will be recorded in the comment. /// If this configuration setting is specified, and the source file (receiving the source annotation /// comment) is a descendent of this base path, then only the relative portion of the file path will /// be recorded in the source annotation comment. /// </para> /// <para> /// If the document file receiving the source annotation comment is not a descendent of this base path, /// then the full absolute path will still be used. /// </para> /// </remarks> /// <example> /// <para> /// These examples show a few combinations of what would be written in the source annotation comments for /// various scenarios. /// </para> /// <list type="bullet"> /// <item><description> /// If <see cref="IncludeSourceAnnotation"/> is <see langword="false"/> then no source annotation would be /// written at all, and this setting (and all other scenarios listed here) would be meaningless. /// </description></item> /// <item><description> /// If the source of the documents involved is not a file from a file system: <see cref="Rendering.FileSourceInfo"/> /// then this configuration setting is meaningless. The source information written to the comments would /// always come directly from the implementation of <see cref="Rendering.IDocumentSourceInfo"/>. /// </description></item> /// <item><description> /// If the source of the document were <c>C:\MyDirectory\MyFile.html</c> and this configuration setting is /// <see langword="null"/> then source annotation comments would refer to that document using the path /// <c>C:\MyDirectory\MyFile.html</c>. /// </description></item> /// <item><description> /// If the source of the document were <c>C:\MyDirectory\MyFile.html</c> and this configuration setting is /// <c>C:\MyDirectory</c> then source annotation comments would refer to that document using the path /// <c>MyFile.html</c>. /// </description></item> /// <item><description> /// If the source of the document were <c>C:\MyDirectory\MySubDir\MyFile.html</c> and this configuration setting is /// <c>C:\MyDirectory</c> then source annotation comments would refer to that document using the path /// <c>MySubDir\MyFile.html</c>. /// </description></item> /// <item><description> /// If the source of the document were <c>C:\OtherDirectory\MyFile.html</c> and this configuration setting is /// <c>C:\MyDirectory</c> then source annotation comments would refer to that document using the path /// <c>C:\OtherDirectory\MyFile.html</c>. /// The absolute path would be used because the source file is outside the base path. /// </description></item> /// </list> /// </example> /// <seealso cref="Rendering.IDocumentSourceInfo"/> /// <seealso cref="Rendering.FileSourceInfo"/> /// <seealso cref="IRendersZptFile"/> /// <seealso cref="IncludeSourceAnnotation"/> /// <value>The base path used for shorting the paths of source files in logs and source annotation.</value> public virtual string SourceAnnotationBasePath { get; private set; } /// <summary> /// Gets the default expression type name/prefix, used for TALES expressions which do not have a prefix. /// </summary> /// <remarks> /// <para> /// In TALES expressions used by the ZPT rendering process, prefixing the expression with an expression-type /// is optional. The rendering process always has a configured default expression type. Unprefixed expressions /// are assumed to be of that default type. /// </para> /// <para> /// This configuration setting permits the changing of that default expression type. /// </para> /// </remarks> /// <value>The default expression-type prefix.</value> public virtual string DefaultExpressionType { get; private set; } /// <summary> /// Gets a custom XML URL resolver which should be used to resolve XML namespaces for XML-based document providers. /// </summary> /// <remarks> /// <para> /// When using an XML-based document provider (and only when using an XML-based document provider), /// in order to fully validate these documents (and provide appropriate entity support), supporting /// assets are required. These can include DTDs, modules and the like. /// When making use of an XML document which conforms to a DTD, it is usually desirable (for both performance /// and security purposes) to use a custom XML URL resolver. This allows techniques such as caching, /// security-enforcement and perhaps even the local serving of those assets without making any /// HTTP(s) requests at all. /// </para> /// <para> /// When set, this configuration setting specifies the custom XML URL resolver which should be used by /// XML-based document providers. It has no effect at all upon HTML-based document providers. /// </para> /// <para> /// Please note that the official ZptSharp XML document provider includes a URL provider which serves /// XHTML assets from embedded resources, bypassing all HTTP requests. This built-in URL provider will /// be used if this configuration setting is <see langword="null"/>. /// </para> /// </remarks> public virtual System.Xml.XmlUrlResolver XmlUrlResolver { get; private set; } /// <summary> /// Creates and returns a new <see cref="RenderingConfig.Builder"/> instance which has its initial /// state/settings copied from the current configuration instance. /// </summary> /// <remarks> /// <para> /// Use this method to create a new configuration builder which is based upon the current configuration, /// but may then be modified before it is used to create a new configuration. /// Rendering configuration objects are immutable and cannot be altered after they have been built/created. /// This method is a convenience to allow the next-best-thing: creating a new builder, cloned from an /// existing configuration. /// </para> /// <para> /// This method does not allow editing of the configuration from which the builder was cloned. /// Changes made to the returned builder object will not affect the original configuration object. /// </para> /// </remarks> /// <returns>A configuration builder.</returns> public Builder CloneToNewBuilder() { return new Builder { DocumentEncoding = DocumentEncoding, DocumentProviderType = DocumentProviderType, RootContextsProvider = RootContextsProvider, ContextBuilder = ContextBuilder, IncludeSourceAnnotation = IncludeSourceAnnotation, KeywordOptions = KeywordOptions.ToDictionary(k => k.Key, v => v.Value), OmitXmlDeclaration = OmitXmlDeclaration, SourceAnnotationBasePath = SourceAnnotationBasePath, DefaultExpressionType = DefaultExpressionType, XmlUrlResolver = XmlUrlResolver, }; } /// <summary> /// Creates a new configuration builder object with a default set of state. /// </summary> /// <remarks> /// <para> /// The initial state of the builder object returned by this method will be the same as the state /// which would be created by <see cref="Default"/>. Refer to the documentation of the default /// property to see what that state would be. /// </para> /// <para> /// The builder may be used to set-up the intended state of a configuration object. /// Use <see cref="Builder.GetConfig"/> to build and return a configuration object from that builder, /// once the desired settings have been made. /// </para> /// </remarks> /// <seealso cref="Default"/> /// <returns>A configuration builder with default initial state.</returns> public static Builder CreateBuilder() => new Builder(); /// <summary> /// The constructor for <see cref="RenderingConfig"/> is intentionally <see langword="private"/>. /// Instances of this class must be created via a <see cref="Builder"/>. /// </summary> protected RenderingConfig() { DocumentEncoding = Encoding.UTF8; KeywordOptions = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>()); ContextBuilder = (c, s) => { }; DefaultExpressionType = WellKnownExpressionPrefix.Path; } /// <summary> /// Gets an instance of <see cref="RenderingConfig"/> with default values. /// </summary> /// <remarks> /// <para> /// The property values for a default rendering configuration are as follows. This applies /// to instances created via this static property and also the 'starting' state of a builder /// created via <see cref="CreateBuilder"/>. /// </para> /// <list type="table"> /// <item> /// <term><see cref="DocumentEncoding"/></term> /// <description><c>Encoding.UTF8</c></description> /// </item> /// <item> /// <term><see cref="DocumentProviderType"/></term> /// <description><see langword="null"/></description> /// </item> /// <item> /// <term><see cref="OmitXmlDeclaration"/></term> /// <description><see langword="false"/></description> /// </item> /// <item> /// <term><see cref="RootContextsProvider"/></term> /// <description><see langword="null"/></description> /// </item> /// <item> /// <term><see cref="KeywordOptions"/></term> /// <description>An empty dictionary</description> /// </item> /// <item> /// <term><see cref="ContextBuilder"/></term> /// <description>An empty/no-op action</description> /// </item> /// <item> /// <term><see cref="IncludeSourceAnnotation"/></term> /// <description><see langword="false"/></description> /// </item> /// <item> /// <term><see cref="SourceAnnotationBasePath"/></term> /// <description><see langword="null"/></description> /// </item> /// <item> /// <term><see cref="DefaultExpressionType"/></term> /// <description>The string <c>path</c></description> /// </item> /// <item> /// <term><see cref="XmlUrlResolver"/></term> /// <description><see langword="null"/></description> /// </item> /// </list> /// </remarks> /// <value>The default rendering config.</value> public static RenderingConfig Default { get { var builder = new Builder(); return builder.GetConfig(); } } } }
// // Color.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.ComponentModel; using System.Collections.Generic; using System.Globalization; namespace Xwt.Drawing { [TypeConverter (typeof(ColorValueConverter))] [Serializable] public struct Color : IEquatable<Color> { double r, g, b, a; [NonSerialized] HslColor hsl; public double Red { get { return r; } set { r = Normalize (value); hsl = null; } } public double Green { get { return g; } set { g = Normalize (value); hsl = null; } } public double Blue { get { return b; } set { b = Normalize (value); hsl = null; } } public double Alpha { get { return a; } set { a = Normalize (value); } } public double Hue { get { return Hsl.H; } set { Hsl = new HslColor (Normalize (value), Hsl.S, Hsl.L); } } public double Saturation { get { return Hsl.S; } set { Hsl = new HslColor (Hsl.H, Normalize (value), Hsl.L); } } public double Light { get { return Hsl.L; } set { Hsl = new HslColor (Hsl.H, Hsl.S, Normalize (value)); } } double Normalize (double v) { if (v < 0) return 0; if (v > 1) return 1; return v; } public double Brightness { get { return System.Math.Sqrt (Red * .241 + Green * .691 + Blue * .068); } } HslColor Hsl { get { if (hsl == null) hsl = (HslColor)this; return hsl; } set { hsl = value; Color c = (Color)value; r = c.r; b = c.b; g = c.g; } } public Color (double red, double green, double blue): this () { Red = red; Green = green; Blue = blue; Alpha = 1f; } public Color (double red, double green, double blue, double alpha): this () { Red = red; Green = green; Blue = blue; Alpha = alpha; } public Color WithAlpha (double alpha) { Color c = this; c.Alpha = alpha; return c; } public Color WithIncreasedLight (double lightIncrement) { Color c = this; c.Light += lightIncrement; return c; } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) /// </summary> /// <returns>The new color</returns> /// <param name="amount">Amount to change (can be positive or negative).</param> /// <remarks> /// This method adds or removes light to/from the color to make it more contrasted when /// compared to a neutral grey. /// The resulting effect is that light colors are made lighter, and dark colors /// are made darker. If the amount is negative, the effect is inversed (colors are /// made less contrasted) /// </remarks> public Color WithIncreasedContrast (double amount) { return WithIncreasedContrast (new Color (0.5, 0.5, 0.5), amount); } /// <summary> /// Returns a color which looks more contrasted (or less, if amount is negative) with /// respect to a provided reference color. /// </summary> /// <returns>The new color</returns> /// <param name="referenceColor">Reference color.</param> /// <param name="amount">Amount to change (can be positive or negative).</param> public Color WithIncreasedContrast (Color referenceColor, double amount) { Color c = this; if (referenceColor.Light > Light) c.Light -= amount; else c.Light += amount; return c; } public Color BlendWith (Color target, double amount) { if (amount < 0 || amount > 1) throw new ArgumentException ("Blend amount must be between 0 and 1"); return new Color (BlendValue (r, target.r, amount), BlendValue (g, target.g, amount), BlendValue (b, target.b, amount), target.Alpha); } double BlendValue (double s, double t, double amount) { return s + (t - s) * amount; } public static Color FromBytes (byte red, byte green, byte blue) { return FromBytes (red, green, blue, 255); } public static Color FromBytes (byte red, byte green, byte blue, byte alpha) { return new Color { Red = ((double)red) / 255.0, Green = ((double)green) / 255.0, Blue = ((double)blue) / 255.0, Alpha = ((double)alpha) / 255.0 }; } public static Color FromHsl (double h, double s, double l) { return FromHsl (h, s, l, 1); } public static Color FromHsl (double h, double s, double l, double alpha) { HslColor hsl = new HslColor (h, s, l); Color c = (Color)hsl; c.Alpha = alpha; c.hsl = hsl; return c; } public static Color FromName (string name) { Color color; TryParse (name, out color); return color; } public static bool TryParse (string name, out Color color) { if (name == null) throw new ArgumentNullException ("name"); if (name.Length == 0) { color = default (Color); return false; } if (name[0] != '#' && Colors.TryGetNamedColor (name, out color)) { return true; } uint val; if (!TryParseColourFromHex (name, out val)) { color = default (Color); return false; } color = Color.FromBytes ((byte)(val >> 24), (byte)((val >> 16) & 0xff), (byte)((val >> 8) & 0xff), (byte)(val & 0xff)); return true; } static bool TryParseColourFromHex (string str, out uint val) { val = 0; if (str[0] != '#' || str.Length > 9) return false; if (!uint.TryParse (str.Substring (1), System.Globalization.NumberStyles.HexNumber, null, out val)) return false; val = val << ((9 - str.Length) * 4); if (str.Length <= 7) val |= 0xff; return true; } public static bool operator == (Color c1, Color c2) { return c1.r == c2.r && c1.g == c2.g && c1.b == c2.b && c1.a == c2.a; } public static bool operator != (Color c1, Color c2) { return c1.r != c2.r || c1.g != c2.g || c1.b != c2.b || c1.a != c2.a; } public override bool Equals (object o) { if (!(o is Color)) return false; return (this == (Color) o); } public bool Equals(Color other) { return this == other; } public override int GetHashCode () { unchecked { var hash = r.GetHashCode (); hash = (hash * 397) ^ g.GetHashCode (); hash = (hash * 397) ^ b.GetHashCode (); hash = (hash * 397) ^ a.GetHashCode (); return hash; } } public override string ToString () { return string.Format ("[Color: Red={0}, Green={1}, Blue={2}, Alpha={3}]", Red, Green, Blue, Alpha); } public string ToHexString (bool withAlpha = true) { var rgb = "#" + ((int)(Red * 255)).ToString ("x2") + ((int)(Green * 255)).ToString ("x2") + ((int)(Blue * 255)).ToString ("x2"); if (withAlpha) return rgb + ((int)(Alpha * 255)).ToString ("x2"); else return rgb; } } class ColorValueConverter: TypeConverter { public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(string); } public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertTo (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { Color s = (Color)value; return s.ToHexString(); } public override object ConvertFrom (ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { Color c; if (Color.TryParse((string)value, out c)) return c; else throw new InvalidOperationException("Could not parse color value: " + 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskStoreInt32() { var test = new StoreBinaryOpTest__MaskStoreInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class StoreBinaryOpTest__MaskStoreInt32 { private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(StoreBinaryOpTest__MaskStoreInt32 testClass) { Avx2.MaskStore((Int32*)testClass._dataTable.outArrayPtr, _fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static StoreBinaryOpTest__MaskStoreInt32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public StoreBinaryOpTest__MaskStoreInt32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); typeof(Avx2).GetMethod(nameof(Avx2.MaskStore), new Type[] { typeof(Int32*), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(Int32*)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); Avx2.MaskStore( (Int32*)_dataTable.outArrayPtr, _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, left, right); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreBinaryOpTest__MaskStoreInt32(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, _fld1, _fld2); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); Avx2.MaskStore((Int32*)_dataTable.outArrayPtr, test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != ((left[0] < 0) ? right[0] : result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] < 0) ? right[i] : result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MaskStore)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// Cluster member metadata /// </summary> public partial class Cluster_host : XenObject<Cluster_host> { #region Constructors public Cluster_host() { } public Cluster_host(string uuid, XenRef<Cluster> cluster, XenRef<Host> host, bool enabled, XenRef<PIF> PIF, bool joined, List<cluster_host_operation> allowed_operations, Dictionary<string, cluster_host_operation> current_operations, Dictionary<string, string> other_config) { this.uuid = uuid; this.cluster = cluster; this.host = host; this.enabled = enabled; this.PIF = PIF; this.joined = joined; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.other_config = other_config; } /// <summary> /// Creates a new Cluster_host from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Cluster_host(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Cluster_host from a Proxy_Cluster_host. /// </summary> /// <param name="proxy"></param> public Cluster_host(Proxy_Cluster_host proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Cluster_host. /// </summary> public override void UpdateFrom(Cluster_host update) { uuid = update.uuid; cluster = update.cluster; host = update.host; enabled = update.enabled; PIF = update.PIF; joined = update.joined; allowed_operations = update.allowed_operations; current_operations = update.current_operations; other_config = update.other_config; } internal void UpdateFrom(Proxy_Cluster_host proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; cluster = proxy.cluster == null ? null : XenRef<Cluster>.Create(proxy.cluster); host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); enabled = (bool)proxy.enabled; PIF = proxy.PIF == null ? null : XenRef<PIF>.Create(proxy.PIF); joined = (bool)proxy.joined; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<cluster_host_operation>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_cluster_host_operation(proxy.current_operations); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Cluster_host ToProxy() { Proxy_Cluster_host result_ = new Proxy_Cluster_host(); result_.uuid = uuid ?? ""; result_.cluster = cluster ?? ""; result_.host = host ?? ""; result_.enabled = enabled; result_.PIF = PIF ?? ""; result_.joined = joined; result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations); result_.current_operations = Maps.convert_to_proxy_string_cluster_host_operation(current_operations); result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Cluster_host /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("cluster")) cluster = Marshalling.ParseRef<Cluster>(table, "cluster"); if (table.ContainsKey("host")) host = Marshalling.ParseRef<Host>(table, "host"); if (table.ContainsKey("enabled")) enabled = Marshalling.ParseBool(table, "enabled"); if (table.ContainsKey("PIF")) PIF = Marshalling.ParseRef<PIF>(table, "PIF"); if (table.ContainsKey("joined")) joined = Marshalling.ParseBool(table, "joined"); if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList<cluster_host_operation>(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) current_operations = Maps.convert_from_proxy_string_cluster_host_operation(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Cluster_host other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._cluster, other._cluster) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._enabled, other._enabled) && Helper.AreEqual2(this._PIF, other._PIF) && Helper.AreEqual2(this._joined, other._joined) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<Cluster_host> ProxyArrayToObjectList(Proxy_Cluster_host[] input) { var result = new List<Cluster_host>(); foreach (var item in input) result.Add(new Cluster_host(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Cluster_host server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static Cluster_host get_record(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_record(session.opaque_ref, _cluster_host); else return new Cluster_host(session.XmlRpcProxy.cluster_host_get_record(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get a reference to the Cluster_host instance with the specified UUID. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Cluster_host> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Cluster_host>.Create(session.XmlRpcProxy.cluster_host_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static string get_uuid(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_uuid(session.opaque_ref, _cluster_host); else return session.XmlRpcProxy.cluster_host_get_uuid(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Get the cluster field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Cluster> get_cluster(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_cluster(session.opaque_ref, _cluster_host); else return XenRef<Cluster>.Create(session.XmlRpcProxy.cluster_host_get_cluster(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get the host field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Host> get_host(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_host(session.opaque_ref, _cluster_host); else return XenRef<Host>.Create(session.XmlRpcProxy.cluster_host_get_host(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get the enabled field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static bool get_enabled(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_enabled(session.opaque_ref, _cluster_host); else return (bool)session.XmlRpcProxy.cluster_host_get_enabled(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Get the PIF field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<PIF> get_PIF(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_pif(session.opaque_ref, _cluster_host); else return XenRef<PIF>.Create(session.XmlRpcProxy.cluster_host_get_pif(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get the joined field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static bool get_joined(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_joined(session.opaque_ref, _cluster_host); else return (bool)session.XmlRpcProxy.cluster_host_get_joined(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Get the allowed_operations field of the given Cluster_host. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static List<cluster_host_operation> get_allowed_operations(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_allowed_operations(session.opaque_ref, _cluster_host); else return Helper.StringArrayToEnumList<cluster_host_operation>(session.XmlRpcProxy.cluster_host_get_allowed_operations(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get the current_operations field of the given Cluster_host. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static Dictionary<string, cluster_host_operation> get_current_operations(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_current_operations(session.opaque_ref, _cluster_host); else return Maps.convert_from_proxy_string_cluster_host_operation(session.XmlRpcProxy.cluster_host_get_current_operations(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Get the other_config field of the given Cluster_host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static Dictionary<string, string> get_other_config(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_other_config(session.opaque_ref, _cluster_host); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.cluster_host_get_other_config(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Add a new host to an existing cluster. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster">Cluster to join</param> /// <param name="_host">new cluster member</param> /// <param name="_pif">Network interface to use for communication</param> public static XenRef<Cluster_host> create(Session session, string _cluster, string _host, string _pif) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_create(session.opaque_ref, _cluster, _host, _pif); else return XenRef<Cluster_host>.Create(session.XmlRpcProxy.cluster_host_create(session.opaque_ref, _cluster ?? "", _host ?? "", _pif ?? "").parse()); } /// <summary> /// Add a new host to an existing cluster. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster">Cluster to join</param> /// <param name="_host">new cluster member</param> /// <param name="_pif">Network interface to use for communication</param> public static XenRef<Task> async_create(Session session, string _cluster, string _host, string _pif) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_cluster_host_create(session.opaque_ref, _cluster, _host, _pif); else return XenRef<Task>.Create(session.XmlRpcProxy.async_cluster_host_create(session.opaque_ref, _cluster ?? "", _host ?? "", _pif ?? "").parse()); } /// <summary> /// Remove a host from an existing cluster. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static void destroy(Session session, string _cluster_host) { if (session.JsonRpcClient != null) session.JsonRpcClient.cluster_host_destroy(session.opaque_ref, _cluster_host); else session.XmlRpcProxy.cluster_host_destroy(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Remove a host from an existing cluster. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Task> async_destroy(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_cluster_host_destroy(session.opaque_ref, _cluster_host); else return XenRef<Task>.Create(session.XmlRpcProxy.async_cluster_host_destroy(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Enable cluster membership for a disabled cluster host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static void enable(Session session, string _cluster_host) { if (session.JsonRpcClient != null) session.JsonRpcClient.cluster_host_enable(session.opaque_ref, _cluster_host); else session.XmlRpcProxy.cluster_host_enable(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Enable cluster membership for a disabled cluster host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Task> async_enable(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_cluster_host_enable(session.opaque_ref, _cluster_host); else return XenRef<Task>.Create(session.XmlRpcProxy.async_cluster_host_enable(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Remove a host from an existing cluster forcefully. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static void force_destroy(Session session, string _cluster_host) { if (session.JsonRpcClient != null) session.JsonRpcClient.cluster_host_force_destroy(session.opaque_ref, _cluster_host); else session.XmlRpcProxy.cluster_host_force_destroy(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Remove a host from an existing cluster forcefully. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Task> async_force_destroy(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_cluster_host_force_destroy(session.opaque_ref, _cluster_host); else return XenRef<Task>.Create(session.XmlRpcProxy.async_cluster_host_force_destroy(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Disable cluster membership for an enabled cluster host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static void disable(Session session, string _cluster_host) { if (session.JsonRpcClient != null) session.JsonRpcClient.cluster_host_disable(session.opaque_ref, _cluster_host); else session.XmlRpcProxy.cluster_host_disable(session.opaque_ref, _cluster_host ?? "").parse(); } /// <summary> /// Disable cluster membership for an enabled cluster host. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_cluster_host">The opaque_ref of the given cluster_host</param> public static XenRef<Task> async_disable(Session session, string _cluster_host) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_cluster_host_disable(session.opaque_ref, _cluster_host); else return XenRef<Task>.Create(session.XmlRpcProxy.async_cluster_host_disable(session.opaque_ref, _cluster_host ?? "").parse()); } /// <summary> /// Return a list of all the Cluster_hosts known to the system. /// Experimental. First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Cluster_host>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_all(session.opaque_ref); else return XenRef<Cluster_host>.Create(session.XmlRpcProxy.cluster_host_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the Cluster_host Records at once, in a single XML RPC call /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Cluster_host>, Cluster_host> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.cluster_host_get_all_records(session.opaque_ref); else return XenRef<Cluster_host>.Create<Proxy_Cluster_host>(session.XmlRpcProxy.cluster_host_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// Experimental. First published in XenServer 7.5. /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Reference to the Cluster object /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(XenRefConverter<Cluster>))] public virtual XenRef<Cluster> cluster { get { return _cluster; } set { if (!Helper.AreEqual(value, _cluster)) { _cluster = value; NotifyPropertyChanged("cluster"); } } } private XenRef<Cluster> _cluster = new XenRef<Cluster>("OpaqueRef:NULL"); /// <summary> /// Reference to the Host object /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(XenRefConverter<Host>))] public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host = new XenRef<Host>("OpaqueRef:NULL"); /// <summary> /// Whether the cluster host believes that clustering should be enabled on this host /// Experimental. First published in XenServer 7.5. /// </summary> public virtual bool enabled { get { return _enabled; } set { if (!Helper.AreEqual(value, _enabled)) { _enabled = value; NotifyPropertyChanged("enabled"); } } } private bool _enabled = false; /// <summary> /// Reference to the PIF object /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(XenRefConverter<PIF>))] public virtual XenRef<PIF> PIF { get { return _PIF; } set { if (!Helper.AreEqual(value, _PIF)) { _PIF = value; NotifyPropertyChanged("PIF"); } } } private XenRef<PIF> _PIF = new XenRef<PIF>("OpaqueRef:NULL"); /// <summary> /// Whether the cluster host has joined the cluster /// Experimental. First published in XenServer 7.5. /// </summary> public virtual bool joined { get { return _joined; } set { if (!Helper.AreEqual(value, _joined)) { _joined = value; NotifyPropertyChanged("joined"); } } } private bool _joined = true; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<cluster_host_operation> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; NotifyPropertyChanged("allowed_operations"); } } } private List<cluster_host_operation> _allowed_operations = new List<cluster_host_operation>() {}; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, cluster_host_operation> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, cluster_host_operation> _current_operations = new Dictionary<string, cluster_host_operation>() {}; /// <summary> /// Additional configuration /// Experimental. First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// 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! namespace Google.Apis.Indexing.v3 { /// <summary>The Indexing Service.</summary> public class IndexingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v3"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public IndexingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public IndexingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { UrlNotifications = new UrlNotificationsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "indexing"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://indexing.googleapis.com/"; #else "https://indexing.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://indexing.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Indexing API.</summary> public class Scope { /// <summary>Submit data to Google for indexing</summary> public static string Indexing = "https://www.googleapis.com/auth/indexing"; } /// <summary>Available OAuth 2.0 scope constants for use with the Indexing API.</summary> public static class ScopeConstants { /// <summary>Submit data to Google for indexing</summary> public const string Indexing = "https://www.googleapis.com/auth/indexing"; } /// <summary>Gets the UrlNotifications resource.</summary> public virtual UrlNotificationsResource UrlNotifications { get; } } /// <summary>A base abstract class for Indexing requests.</summary> public abstract class IndexingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new IndexingBaseServiceRequest instance.</summary> protected IndexingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Indexing parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "urlNotifications" collection of methods.</summary> public class UrlNotificationsResource { private const string Resource = "urlNotifications"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public UrlNotificationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets metadata about a Web Document. This method can _only_ be used to query URLs that were previously seen /// in successful Indexing API notifications. Includes the latest `UrlNotification` received via this API. /// </summary> public virtual GetMetadataRequest GetMetadata() { return new GetMetadataRequest(service); } /// <summary> /// Gets metadata about a Web Document. This method can _only_ be used to query URLs that were previously seen /// in successful Indexing API notifications. Includes the latest `UrlNotification` received via this API. /// </summary> public class GetMetadataRequest : IndexingBaseServiceRequest<Google.Apis.Indexing.v3.Data.UrlNotificationMetadata> { /// <summary>Constructs a new GetMetadata request.</summary> public GetMetadataRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>URL that is being queried.</summary> [Google.Apis.Util.RequestParameterAttribute("url", Google.Apis.Util.RequestParameterType.Query)] public virtual string Url { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "getMetadata"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v3/urlNotifications/metadata"; /// <summary>Initializes GetMetadata parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("url", new Google.Apis.Discovery.Parameter { Name = "url", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Notifies that a URL has been updated or deleted.</summary> /// <param name="body">The body of the request.</param> public virtual PublishRequest Publish(Google.Apis.Indexing.v3.Data.UrlNotification body) { return new PublishRequest(service, body); } /// <summary>Notifies that a URL has been updated or deleted.</summary> public class PublishRequest : IndexingBaseServiceRequest<Google.Apis.Indexing.v3.Data.PublishUrlNotificationResponse> { /// <summary>Constructs a new Publish request.</summary> public PublishRequest(Google.Apis.Services.IClientService service, Google.Apis.Indexing.v3.Data.UrlNotification body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Indexing.v3.Data.UrlNotification Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "publish"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v3/urlNotifications:publish"; /// <summary>Initializes Publish parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.Indexing.v3.Data { /// <summary>Output for PublishUrlNotification</summary> public class PublishUrlNotificationResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Description of the notification events received for this URL.</summary> [Newtonsoft.Json.JsonPropertyAttribute("urlNotificationMetadata")] public virtual UrlNotificationMetadata UrlNotificationMetadata { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// `UrlNotification` is the resource used in all Indexing API calls. It describes one event in the life cycle of a /// Web Document. /// </summary> public class UrlNotification : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Creation timestamp for this notification. Users should _not_ specify it, the field is ignored at the request /// time. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("notifyTime")] public virtual object NotifyTime { get; set; } /// <summary>The URL life cycle event that Google is being notified about.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary> /// The object of this notification. The URL must be owned by the publisher of this notification and, in case of /// `URL_UPDATED` notifications, it _must_ be crawlable by Google. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("url")] public virtual string Url { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Summary of the most recent Indexing API notifications successfully received, for a given URL.</summary> public class UrlNotificationMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Latest notification received with type `URL_REMOVED`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("latestRemove")] public virtual UrlNotification LatestRemove { get; set; } /// <summary>Latest notification received with type `URL_UPDATED`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("latestUpdate")] public virtual UrlNotification LatestUpdate { get; set; } /// <summary>URL to which this metadata refers.</summary> [Newtonsoft.Json.JsonPropertyAttribute("url")] public virtual string Url { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor.Experimental.GraphView; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.Experimental.VFX; using UnityEditor.VFX.UIElements; using Branch = UnityEditor.VFX.Operator.VFXOperatorDynamicBranch; namespace UnityEditor.VFX.UI { class VFXOperatorUI : VFXNodeUI { VisualElement m_EditButton; public VFXOperatorUI() { this.AddStyleSheetPath("VFXOperator"); m_Middle = new VisualElement(); m_Middle.name = "middle"; inputContainer.parent.Insert(1, m_Middle); m_EditButton = new VisualElement() {name = "edit"}; m_EditButton.Add(new VisualElement() { name = "icon" }); m_EditButton.AddManipulator(new Clickable(OnEdit)); this.AddManipulator(new SuperCollapser()); RegisterCallback<GeometryChangedEvent>(OnPostLayout); } VisualElement m_EditContainer; void OnEdit() { if (m_EditContainer != null) { if (m_EditContainer.parent != null) { m_EditContainer.RemoveFromHierarchy(); } else { expanded = true; RefreshPorts(); // refresh port to make sure outputContainer is added before the editcontainer. topContainer.Add(m_EditContainer); } UpdateCollapse(); } } VisualElement m_Middle; public new VFXOperatorController controller { get { return base.controller as VFXOperatorController; } } public override void GetPreferedWidths(ref float labelWidth, ref float controlWidth) { base.GetPreferedWidths(ref labelWidth, ref controlWidth); foreach (var port in GetPorts(true, false).Cast<VFXEditableDataAnchor>()) { float portLabelWidth = port.GetPreferredLabelWidth() + 1; float portControlWidth = port.GetPreferredControlWidth(); if (labelWidth < portLabelWidth) { labelWidth = portLabelWidth; } if (controlWidth < portControlWidth) { controlWidth = portControlWidth; } } } public override void ApplyWidths(float labelWidth, float controlWidth) { base.ApplyWidths(labelWidth, controlWidth); foreach (var port in GetPorts(true, false).Cast<VFXEditableDataAnchor>()) { port.SetLabelWidth(labelWidth); } inputContainer.style.width = labelWidth + controlWidth + 20; } public bool isEditable { get { return controller != null && controller.isEditable; } } protected VisualElement GetControllerEditor() { if (controller is VFXCascadedOperatorController) { var edit = new VFXCascadedOperatorEdit(); edit.controller = controller as VFXCascadedOperatorController; return edit; } if (controller is VFXNumericUniformOperatorController) { var edit = new VFXUniformOperatorEdit<VFXNumericUniformOperatorController, VFXOperatorNumericUniform>(); edit.controller = controller as VFXNumericUniformOperatorController; return edit; } if (controller is VFXBranchOperatorController) { var edit = new VFXUniformOperatorEdit<VFXBranchOperatorController, Branch>(); edit.controller = controller as VFXBranchOperatorController; return edit; } if (controller is VFXUnifiedOperatorController) { var edit = new VFXUnifiedOperatorEdit(); edit.controller = controller as VFXUnifiedOperatorController; return edit; } return null; } public override void BuildContextualMenu(ContextualMenuPopulateEvent evt) { if (evt.target == this && controller != null && controller.model is VFXInlineOperator) { evt.menu.AppendAction("Convert to Parameter", OnConvertToParameter, e => DropdownMenuAction.Status.Normal); evt.menu.AppendSeparator(); } } void OnConvertToParameter(DropdownMenuAction evt) { controller.ConvertToParameter(); } public override bool superCollapsed { get { return base.superCollapsed && (m_EditContainer == null || m_EditContainer.parent == null); } } protected override void SelfChange() { base.SelfChange(); bool hasMiddle = inputContainer.childCount != 0; if (hasMiddle) { if (m_Middle.parent == null) { inputContainer.parent.Insert(1, m_Middle); } } else if (m_Middle.parent != null) { m_Middle.RemoveFromHierarchy(); } if (isEditable) { if (m_EditButton.parent == null) { titleContainer.Insert(1, m_EditButton); } if (m_EditContainer == null) { m_EditContainer = GetControllerEditor(); if (m_EditContainer != null) m_EditContainer.name = "edit-container"; } } else { if (m_EditContainer != null && m_EditContainer.parent != null) { m_EditContainer.RemoveFromHierarchy(); } m_EditContainer = null; if (m_EditButton.parent != null) { m_EditButton.RemoveFromHierarchy(); } } } void OnPostLayout(GeometryChangedEvent e) { RefreshLayout(); } public override void RefreshLayout() { base.RefreshLayout(); if (!superCollapsed) { float settingsLabelWidth = 30; float settingsControlWidth = 50; GetPreferedSettingsWidths(ref settingsLabelWidth, ref settingsControlWidth); float labelWidth = 30; float controlWidth = 50; GetPreferedWidths(ref labelWidth, ref controlWidth); float newMinWidth = Mathf.Max(settingsLabelWidth + settingsControlWidth, labelWidth + controlWidth) + 20; if (resolvedStyle.minWidth != newMinWidth) { style.minWidth = newMinWidth; } ApplySettingsWidths(settingsLabelWidth, settingsControlWidth); ApplyWidths(labelWidth, controlWidth); } else { if (resolvedStyle.minWidth != 0f) { style.minWidth = 0f; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Drawing.Drawing2D; using System.Drawing.Internal; using System.Globalization; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { /// <summary> /// Defines an object used to draw lines and curves. /// </summary> public sealed partial class Pen : MarshalByRefObject, ICloneable, IDisposable #pragma warning disable SA1001 #if FEATURE_SYSTEM_EVENTS , ISystemColorTracker #endif #pragma warning restore SA1001 { #if FINALIZATION_WATCH private string _allocationSite = Graphics.GetAllocationStack(); #endif // Handle to native GDI+ pen object. private IntPtr _nativePen; // GDI+ doesn't understand system colors, so we need to cache the value here. private Color _color; private bool _immutable; // Tracks whether the dash style has been changed to something else than Solid during the lifetime of this object. private bool _dashStyleWasOrIsNotSolid; /// <summary> /// Creates a Pen from a native GDI+ object. /// </summary> private Pen(IntPtr nativePen) => SetNativePen(nativePen); internal Pen(Color color, bool immutable) : this(color) => _immutable = immutable; /// <summary> /// Initializes a new instance of the Pen class with the specified <see cref='Color'/>. /// </summary> public Pen(Color color) : this(color, (float)1.0) { } /// <summary> /// Initializes a new instance of the <see cref='Pen'/> class with the specified /// <see cref='Color'/> and <see cref='Width'/>. /// </summary> public Pen(Color color, float width) { _color = color; IntPtr pen = IntPtr.Zero; int status = Gdip.GdipCreatePen1(color.ToArgb(), width, (int)GraphicsUnit.World, out pen); Gdip.CheckStatus(status); SetNativePen(pen); #if FEATURE_SYSTEM_EVENTS if (_color.IsSystemColor) { SystemColorTracker.Add(this); } #endif } /// <summary> /// Initializes a new instance of the Pen class with the specified <see cref='Brush'/>. /// </summary> public Pen(Brush brush) : this(brush, (float)1.0) { } /// <summary> /// Initializes a new instance of the <see cref='Pen'/> class with the specified <see cref='Drawing.Brush'/> and width. /// </summary> public Pen(Brush brush, float width) { if (brush == null) { throw new ArgumentNullException(nameof(brush)); } IntPtr pen = IntPtr.Zero; int status = Gdip.GdipCreatePen2(new HandleRef(brush, brush.NativeBrush), width, (int)GraphicsUnit.World, out pen); Gdip.CheckStatus(status); SetNativePen(pen); } internal void SetNativePen(IntPtr nativePen) { Debug.Assert(nativePen != IntPtr.Zero); _nativePen = nativePen; } [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] internal IntPtr NativePen => _nativePen; /// <summary> /// Creates an exact copy of this <see cref='System.Drawing.Pen'/>. /// </summary> public object Clone() { IntPtr clonedPen = IntPtr.Zero; int status = Gdip.GdipClonePen(new HandleRef(this, NativePen), out clonedPen); Gdip.CheckStatus(status); return new Pen(clonedPen); } /// <summary> /// Cleans up Windows resources for this <see cref='System.Drawing.Pen'/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { #if FINALIZATION_WATCH if (!disposing && nativePen != IntPtr.Zero) { Debug.WriteLine("**********************\nDisposed through finalization:\n" + _allocationSite); } #endif if (!disposing) { // If we are finalizing, then we will be unreachable soon. Finalize calls dispose to // release resources, so we must make sure that during finalization we are // not immutable. _immutable = false; } else if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (_nativePen != IntPtr.Zero) { try { #if DEBUG int status = !Gdip.Initialized ? Gdip.Ok : #endif Gdip.GdipDeletePen(new HandleRef(this, NativePen)); #if DEBUG Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex)) { } finally { _nativePen = IntPtr.Zero; } } } /// <summary> /// Cleans up Windows resources for this <see cref='System.Drawing.Pen'/>. /// </summary> ~Pen() => Dispose(false); /// <summary> /// Gets or sets the width of this <see cref='System.Drawing.Pen'/>. /// </summary> public float Width { get { var width = new float[] { 0 }; int status = Gdip.GdipGetPenWidth(new HandleRef(this, NativePen), width); Gdip.CheckStatus(status); return width[0]; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenWidth(new HandleRef(this, NativePen), value); Gdip.CheckStatus(status); } } /// <summary> /// Sets the values that determine the style of cap used to end lines drawn by this <see cref='Pen'/>. /// </summary> public void SetLineCap(LineCap startCap, LineCap endCap, DashCap dashCap) { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenLineCap197819(new HandleRef(this, NativePen), unchecked((int)startCap), unchecked((int)endCap), unchecked((int)dashCap)); Gdip.CheckStatus(status); } /// <summary> /// Gets or sets the cap style used at the beginning of lines drawn with this <see cref='Pen'/>. /// </summary> public LineCap StartCap { get { int startCap = 0; int status = Gdip.GdipGetPenStartCap(new HandleRef(this, NativePen), out startCap); Gdip.CheckStatus(status); return (LineCap)startCap; } set { switch (value) { case LineCap.Flat: case LineCap.Square: case LineCap.Round: case LineCap.Triangle: case LineCap.NoAnchor: case LineCap.SquareAnchor: case LineCap.RoundAnchor: case LineCap.DiamondAnchor: case LineCap.ArrowAnchor: case LineCap.AnchorMask: case LineCap.Custom: break; default: throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(LineCap)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenStartCap(new HandleRef(this, NativePen), unchecked((int)value)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the cap style used at the end of lines drawn with this <see cref='Pen'/>. /// </summary> public LineCap EndCap { get { int endCap = 0; int status = Gdip.GdipGetPenEndCap(new HandleRef(this, NativePen), out endCap); Gdip.CheckStatus(status); return (LineCap)endCap; } set { switch (value) { case LineCap.Flat: case LineCap.Square: case LineCap.Round: case LineCap.Triangle: case LineCap.NoAnchor: case LineCap.SquareAnchor: case LineCap.RoundAnchor: case LineCap.DiamondAnchor: case LineCap.ArrowAnchor: case LineCap.AnchorMask: case LineCap.Custom: break; default: throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(LineCap)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenEndCap(new HandleRef(this, NativePen), unchecked((int)value)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the cap style used at the beginning or end of dashed lines drawn with this <see cref='Pen'/>. /// </summary> public DashCap DashCap { get { int dashCap = 0; int status = Gdip.GdipGetPenDashCap197819(new HandleRef(this, NativePen), out dashCap); Gdip.CheckStatus(status); return (DashCap)dashCap; } set { if (value != DashCap.Flat && value != DashCap.Round && value != DashCap.Triangle) { throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(DashCap)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenDashCap197819(new HandleRef(this, NativePen), unchecked((int)value)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the join style for the ends of two overlapping lines drawn with this <see cref='Pen'/>. /// </summary> public LineJoin LineJoin { get { int lineJoin = 0; int status = Gdip.GdipGetPenLineJoin(new HandleRef(this, NativePen), out lineJoin); Gdip.CheckStatus(status); return (LineJoin)lineJoin; } set { if (value < LineJoin.Miter || value > LineJoin.MiterClipped) { throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(LineJoin)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenLineJoin(new HandleRef(this, NativePen), unchecked((int)value)); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the limit of the thickness of the join on a mitered corner. /// </summary> public float MiterLimit { get { var miterLimit = new float[] { 0 }; int status = Gdip.GdipGetPenMiterLimit(new HandleRef(this, NativePen), miterLimit); Gdip.CheckStatus(status); return miterLimit[0]; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenMiterLimit(new HandleRef(this, NativePen), value); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the alignment for objects drawn with this <see cref='Pen'/>. /// </summary> public PenAlignment Alignment { get { PenAlignment penMode = 0; int status = Gdip.GdipGetPenMode(new HandleRef(this, NativePen), out penMode); Gdip.CheckStatus(status); return penMode; } set { if (value < PenAlignment.Center || value > PenAlignment.Right) { throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PenAlignment)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenMode(new HandleRef(this, NativePen), value); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets the geometrical transform for objects drawn with this <see cref='Pen'/>. /// </summary> public Matrix Transform { get { var matrix = new Matrix(); int status = Gdip.GdipGetPenTransform(new HandleRef(this, NativePen), new HandleRef(matrix, matrix.NativeMatrix)); Gdip.CheckStatus(status); return matrix; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (value == null) { throw new ArgumentNullException(nameof(value)); } int status = Gdip.GdipSetPenTransform(new HandleRef(this, NativePen), new HandleRef(value, value.NativeMatrix)); Gdip.CheckStatus(status); } } /// <summary> /// Resets the geometric transform for this <see cref='Pen'/> to identity. /// </summary> public void ResetTransform() { int status = Gdip.GdipResetPenTransform(new HandleRef(this, NativePen)); Gdip.CheckStatus(status); } /// <summary> /// Multiplies the transform matrix for this <see cref='Pen'/> by the specified <see cref='Matrix'/>. /// </summary> public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend); /// <summary> /// Multiplies the transform matrix for this <see cref='Pen'/> by the specified <see cref='Matrix'/> in the specified order. /// </summary> public void MultiplyTransform(Matrix matrix, MatrixOrder order) { if (matrix.NativeMatrix == IntPtr.Zero) { // Disposed matrices should result in a no-op. return; } int status = Gdip.GdipMultiplyPenTransform(new HandleRef(this, NativePen), new HandleRef(matrix, matrix.NativeMatrix), order); Gdip.CheckStatus(status); } /// <summary> /// Translates the local geometrical transform by the specified dimensions. This method prepends the translation /// to the transform. /// </summary> public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend); /// <summary> /// Translates the local geometrical transform by the specified dimensions in the specified order. /// </summary> public void TranslateTransform(float dx, float dy, MatrixOrder order) { int status = Gdip.GdipTranslatePenTransform(new HandleRef(this, NativePen), dx, dy, order); Gdip.CheckStatus(status); } /// <summary> /// Scales the local geometric transform by the specified amounts. This method prepends the scaling matrix to the transform. /// </summary> public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend); /// <summary> /// Scales the local geometric transform by the specified amounts in the specified order. /// </summary> public void ScaleTransform(float sx, float sy, MatrixOrder order) { int status = Gdip.GdipScalePenTransform(new HandleRef(this, NativePen), sx, sy, order); Gdip.CheckStatus(status); } /// <summary> /// Rotates the local geometric transform by the specified amount. This method prepends the rotation to the transform. /// </summary> public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend); /// <summary> /// Rotates the local geometric transform by the specified amount in the specified order. /// </summary> public void RotateTransform(float angle, MatrixOrder order) { int status = Gdip.GdipRotatePenTransform(new HandleRef(this, NativePen), angle, order); Gdip.CheckStatus(status); } private void InternalSetColor(Color value) { int status = Gdip.GdipSetPenColor(new HandleRef(this, NativePen), _color.ToArgb()); Gdip.CheckStatus(status); _color = value; } /// <summary> /// Gets the style of lines drawn with this <see cref='Pen'/>. /// </summary> public PenType PenType { get { int type = -1; int status = Gdip.GdipGetPenFillType(new HandleRef(this, NativePen), out type); Gdip.CheckStatus(status); return (PenType)type; } } /// <summary> /// Gets or sets the color of this <see cref='Pen'/>. /// </summary> public Color Color { get { if (_color == Color.Empty) { if (PenType != PenType.SolidColor) { throw new ArgumentException(SR.GdiplusInvalidParameter); } int colorARGB = 0; int status = Gdip.GdipGetPenColor(new HandleRef(this, NativePen), out colorARGB); Gdip.CheckStatus(status); _color = Color.FromArgb(colorARGB); } // GDI+ doesn't understand system colors, so we can't use GdipGetPenColor in the general case. return _color; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (value != _color) { Color oldColor = _color; _color = value; InternalSetColor(value); #if FEATURE_SYSTEM_EVENTS // NOTE: We never remove pens from the active list, so if someone is // changing their pen colors a lot, this could be a problem. if (value.IsSystemColor && !oldColor.IsSystemColor) { SystemColorTracker.Add(this); } #endif } } } /// <summary> /// Gets or sets the <see cref='Drawing.Brush'/> that determines attributes of this <see cref='Pen'/>. /// </summary> public Brush Brush { get { Brush brush = null; switch (PenType) { case PenType.SolidColor: brush = new SolidBrush(GetNativeBrush()); break; case PenType.HatchFill: brush = new HatchBrush(GetNativeBrush()); break; case PenType.TextureFill: brush = new TextureBrush(GetNativeBrush()); break; case PenType.PathGradient: brush = new PathGradientBrush(GetNativeBrush()); break; case PenType.LinearGradient: brush = new LinearGradientBrush(GetNativeBrush()); break; default: break; } return brush; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (value == null) { throw new ArgumentNullException(nameof(value)); } int status = Gdip.GdipSetPenBrushFill(new HandleRef(this, NativePen), new HandleRef(value, value.NativeBrush)); Gdip.CheckStatus(status); } } private IntPtr GetNativeBrush() { IntPtr nativeBrush = IntPtr.Zero; int status = Gdip.GdipGetPenBrushFill(new HandleRef(this, NativePen), out nativeBrush); Gdip.CheckStatus(status); return nativeBrush; } /// <summary> /// Gets or sets the style used for dashed lines drawn with this <see cref='Pen'/>. /// </summary> public DashStyle DashStyle { get { int dashStyle = 0; int status = Gdip.GdipGetPenDashStyle(new HandleRef(this, NativePen), out dashStyle); Gdip.CheckStatus(status); return (DashStyle)dashStyle; } set { if (value < DashStyle.Solid || value > DashStyle.Custom) { throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(DashStyle)); } if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenDashStyle(new HandleRef(this, NativePen), unchecked((int)value)); Gdip.CheckStatus(status); // If we just set the pen style to Custom without defining the custom dash pattern, // make sure that we can return a valid value. if (value == DashStyle.Custom) { EnsureValidDashPattern(); } if (value != DashStyle.Solid) { this._dashStyleWasOrIsNotSolid = true; } } } /// <summary> /// This method is called after the user sets the pen's dash style to custom. Here, we make sure that there /// is a default value set for the custom pattern. /// </summary> private void EnsureValidDashPattern() { int retval = 0; int status = Gdip.GdipGetPenDashCount(new HandleRef(this, NativePen), out retval); Gdip.CheckStatus(status); if (retval == 0) { // Set to a solid pattern. DashPattern = new float[] { 1 }; } } /// <summary> /// Gets or sets the distance from the start of a line to the beginning of a dash pattern. /// </summary> public float DashOffset { get { var dashOffset = new float[] { 0 }; int status = Gdip.GdipGetPenDashOffset(new HandleRef(this, NativePen), dashOffset); Gdip.CheckStatus(status); return dashOffset[0]; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } int status = Gdip.GdipSetPenDashOffset(new HandleRef(this, NativePen), value); Gdip.CheckStatus(status); } } /// <summary> /// Gets or sets an array of custom dashes and spaces. The dashes are made up of line segments. /// </summary> public float[] DashPattern { get { int status = Gdip.GdipGetPenDashCount(new HandleRef(this, NativePen), out int count); Gdip.CheckStatus(status); float[] pattern; // don't call GdipGetPenDashArray with a 0 count if (count > 0) { pattern = new float[count]; status = Gdip.GdipGetPenDashArray(new HandleRef(this, NativePen), pattern, count); Gdip.CheckStatus(status); } else if (DashStyle == DashStyle.Solid && !this._dashStyleWasOrIsNotSolid) { // Most likely we're replicating an existing System.Drawing bug here, it doesn't make much sense to // ask for a dash pattern when using a solid dash. throw new OutOfMemoryException(); } else if (DashStyle == DashStyle.Solid) { pattern = Array.Empty<float>(); } else { // special case (not handled inside GDI+) pattern = new float[1]; pattern[0] = 1.0f; } return pattern; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (value == null || value.Length == 0) { throw new ArgumentException(SR.InvalidDashPattern); } foreach (float val in value) { if (val <= 0) { throw new ArgumentException(SR.InvalidDashPattern); } } int count = value.Length; IntPtr buf = Marshal.AllocHGlobal(checked(4 * count)); try { Marshal.Copy(value, 0, buf, count); int status = Gdip.GdipSetPenDashArray(new HandleRef(this, NativePen), new HandleRef(buf, buf), count); Gdip.CheckStatus(status); } finally { Marshal.FreeHGlobal(buf); } } } /// <summary> /// Gets or sets an array of custom dashes and spaces. The dashes are made up of line segments. /// </summary> public float[] CompoundArray { get { int count = 0; int status = Gdip.GdipGetPenCompoundCount(new HandleRef(this, NativePen), out count); Gdip.CheckStatus(status); var array = new float[count]; status = Gdip.GdipGetPenCompoundArray(new HandleRef(this, NativePen), array, count); Gdip.CheckStatus(status); return array; } set { if (_immutable) { throw new ArgumentException(SR.Format(SR.CantChangeImmutableObjects, nameof(Pen))); } if (value.Length <= 1) { throw new ArgumentException(SR.GdiplusInvalidParameter); } foreach (float val in value) { if (val < 0 || val > 1) { throw new ArgumentException(SR.GdiplusInvalidParameter); } } int status = Gdip.GdipSetPenCompoundArray(new HandleRef(this, NativePen), value, value.Length); Gdip.CheckStatus(status); } } #if FEATURE_SYSTEM_EVENTS void ISystemColorTracker.OnSystemColorChanged() { if (NativePen != IntPtr.Zero) { InternalSetColor(_color); } } #endif } }
using System; using Utilities; using NUnit.Framework; namespace UtilitiesTest { [TestFixture] public class StringExtensionTests { #region Variables private string _string; #endregion #region Setup [SetUp] public void Initialize() { _string = string.Empty; } #endregion #region Tests #region IsDate Tests [Test] public void TestValidDateNoOutParam () { _string = "January 12, 2012"; Assert.IsTrue (_string.IsDate ()); } [Test] public void TestInvalidDateNoOutParam () { _string = "Not a date string."; Assert.IsFalse (_string.IsDate ()); } [Test] public void TestValidDateOutParam () { var expected = DateTime.Now; _string = expected.ToString (); DateTime actual; Assert.IsTrue (_string.IsDate (out actual)); Assert.AreEqual (expected, actual); } [Test] public void TestInvalidDateOutParam () { _string = "This is not a date string."; DateTime actual; Assert.IsFalse (_string.IsDate (out actual)); Assert.AreEqual (DateTime.MinValue, actual); } #endregion #region IsBool Tests [Test] public void TestValidBoolNoOutParam () { _string = "true"; Assert.IsTrue (_string.IsBool ()); } [Test] public void TestInvalidBoolNoOutParam () { _string = "This is not a boolean."; Assert.IsFalse (_string.IsBool ()); } [Test] public void TestValidBoolOutParam () { _string = "TrUe"; bool actual; Assert.IsTrue (_string.IsBool (out actual)); Assert.IsTrue (actual); } [Test] public void TestInvalidBoolOutParam () { _string = "This is not a boolean."; bool actual; Assert.IsFalse (_string.IsBool (out actual)); Assert.IsFalse (actual); } #endregion #region IsFloat Tests [Test] public void TestValidFloatNoOutParam () { _string = "2.34233"; Assert.IsTrue (_string.IsFloat ()); } [Test] public void TestInvalidFloatNoOutParam () { _string = "This is not a float"; Assert.IsFalse (_string.IsFloat ()); } [Test] public void TestValidFloatOutParam () { _string = "2.3242342"; float actual; Assert.IsTrue (_string.IsFloat (out actual)); Assert.IsTrue (2.3242342, actual); } [Test] public void TestInvalidFloatOutParam () { _string = "This is not a float."; float actual; Assert.IsFalse (_string.IsFloat (out actual)); Assert.AreSame (0, actual); } #endregion #region IsInt Tests [Test] public void TestValidIntNoOutParam () { _string = "123456"; Assert.IsTrue (_string.IsInt ()); } [Test] public void TestInvalidIntNoOutParam () { _string = "This is not an int."; Assert.IsFalse (_string.IsInt ()); } [Test] public void TestValidIntOutParam () { _string = "9000"; int actual; Assert.IsTrue (_string.IsInt (out actual)); Assert.AreEqual (9000, actual); } [Test] public void TestInvalidIntOutParam () { _string = "This is not an int."; int actual; Assert.IsFalse (_string.IsInt (out actual)); Assert.AreEqual (0, actual); } #endregion #region IsDouble Tests [Test] public void TestValidDoubleNoOutParam () { _string = "9000.00"; Assert.IsTrue (_string.IsDouble ()); } [Test] public void TestInvalidDoubleNoOutParam () { _string = "This is not a double."; Assert.IsFalse (_string.IsDouble ()); } [Test] public void TestValidDoubleOutParam () { _string = "9000.000"; double actual; Assert.IsTrue (_string.IsDouble (out actual)); Assert.AreEqual (9000.000, actual); } [Test] public void TestInvalidDoubleOutParam () { _string = "This is not a double."; double actual; Assert.IsFalse (_string.IsDouble (out actual)); Assert.AreEqual (0, actual); } #endregion #region IsChar Tests [Test] public void TestValidCharNoOutParam () { _string = "C"; Assert.IsTrue (_string.IsChar ()); } [Test] public void TestInvalidCharNoOutParam () { _string = "This is not a char."; Assert.IsFalse (_string.IsChar ()); } [Test] public void TestValidCharOutParam () { _string = "C"; char actual; Assert.IsTrue (_string.IsChar (out actual)); Assert.AreEqual ('C', actual); } [Test] public void TestInvalidCharOutParam () { _string = "This is not a char."; char actual; Assert.IsFalse (_string.IsChar (out actual)); Assert.AreEqual (0, actual); } #endregion #region IsLong Tests [Test] public void TestValidLongNoOutParam () { _string = "9999999999999"; Assert.IsTrue (_string.IsLong ()); } [Test] public void TestInvalidLongNoOutParam () { _string = "This is not a long."; Assert.IsFalse (_string.IsLong ()); } [Test] public void TestValidLongOutParam () { long expected = 9999999999999L; _string = "9999999999999"; long actual; Assert.IsTrue (_string.IsLong (out actual)); Assert.AreEqual (expected, actual); } [Test] public void TestInvalidLongTooLarge () { _string = "99999999999999999999999999"; Assert.IsFalse(_string.IsLong()); } #endregion #endregion } }
/* * UUnit system from UnityCommunity * Heavily modified * 0.4 release by pboechat * http://wiki.unity3d.com/index.php?title=UUnit * http://creativecommons.org/licenses/by-sa/3.0/ */ using System; using System.Text; using System.Collections.Generic; using System.Reflection; namespace PlayFab.UUnit { [AttributeUsage(AttributeTargets.Method)] public class UUnitTestAttribute : Attribute { } public class UUnitTestSuite { private const int TIME_ALIGNMENT_WIDTH = 10; private static readonly TimeSpan TestTimeout = TimeSpan.FromSeconds(15); private static readonly StringBuilder sb = new StringBuilder(); private readonly List<UUnitTestContext> _testContexts = new List<UUnitTestContext>(); private int _activeIndex = 0; private readonly UUnitTestReport _testReport = new UUnitTestReport(PlayFabSettings.BuildIdentifier); private UUnitActiveState _suiteState = UUnitActiveState.PENDING; private UUnitTestCase activeTestInstance = null; public string GenerateTestSummary() { sb.Length = 0; DateTime now = DateTime.UtcNow, eachStartTime, eachEndTime; int finished = 0, passed = 0, failed = 0, skipped = 0; foreach (var eachContext in _testContexts) { // Count tests if (eachContext.ActiveState == UUnitActiveState.COMPLETE) { finished++; eachStartTime = eachContext.StartTime; eachEndTime = eachContext.EndTime; if (eachContext.FinishState == UUnitFinishState.PASSED) passed++; else if (eachContext.FinishState == UUnitFinishState.SKIPPED) skipped++; else failed++; } else { eachStartTime = eachContext.ActiveState == UUnitActiveState.PENDING ? now : eachContext.StartTime; eachEndTime = now; } // line for each test report if (sb.Length != 0) sb.Append("\n"); var ms = (eachEndTime - eachStartTime).TotalMilliseconds.ToString("0"); for (var i = ms.Length; i < TIME_ALIGNMENT_WIDTH; i++) sb.Append(' '); sb.Append(ms).Append(" ms - ").Append(eachContext.FinishState); sb.Append(" - ").Append(eachContext.Name); if (!string.IsNullOrEmpty(eachContext.TestResultMsg)) { sb.Append(" - ").Append(eachContext.TestResultMsg); // TODO: stacktrace } } sb.AppendFormat("\nTesting complete: {0}/{1} test run, {2} tests passed, {3} tests failed, {4} tests skipped.", finished, _testContexts.Count, passed, failed, skipped); return sb.ToString(); } public TestSuiteReport GetInternalReport() { return _testReport.InternalReport; } public void FindAndAddAllTestCases(Type parent, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); #if NETFX_CORE var eachAssembly = typeof(UUnitTestCase).GetTypeInfo().Assembly; // We can only load assemblies known in advance on WSA #else var assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var eachAssembly in assemblies) #endif FindAndAddAllTestCases(eachAssembly, parent, filter); } public void FindAndAddAllTestCases(Assembly assembly, Type parent, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); var types = assembly.GetTypes(); foreach (var t in types) if (!t.GetTypeInfo().IsAbstract && t.GetTypeInfo().IsSubclassOf(parent)) AddTestsForType(t.AsType(), filter); } private void AddTestsForType(Type testCaseType, string filter = null) { if (_suiteState != UUnitActiveState.PENDING) throw new Exception("Must add all tests before executing tests."); var filterSet = AssembleFilter(filter); UUnitTestCase newTestCase = null; foreach (var constructorInfo in testCaseType.GetTypeInfo().GetConstructors()) { try { // .NET and some versions of Mono will throw an exception when the constructor is not parameterless... newTestCase = (UUnitTestCase)constructorInfo.Invoke(null); } catch (Exception) { } // Ignore it and try the next one // ... other versions of Mono will return null instead of throwing an exception. // Either way, newTestCase will be null until it is successfully constructed. if (newTestCase != null) break; } if (newTestCase == null) throw new Exception(testCaseType.Name + " must have a parameter-less constructor."); var methods = testCaseType.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); var attributesList = new List<object>(); foreach (var methodInfo in methods) { attributesList.Clear(); attributesList.AddRange(methodInfo.GetCustomAttributes(typeof(UUnitTestAttribute), false)); if (attributesList.Count == 0 || !MatchesFilters(methodInfo.Name, filterSet)) // There can only be 1, and we only care about attribute existence (no data on attribute), and it has to match the filter continue; Action<UUnitTestContext> eachTestDelegate = CreateDelegate<UUnitTestContext>(testCaseType.Name, newTestCase, methodInfo); if (eachTestDelegate != null) _testContexts.Add(new UUnitTestContext(newTestCase, eachTestDelegate, methodInfo.Name)); } } private static Action<T> CreateDelegate<T>(string typeName, object instance, MethodInfo methodInfo) { Action<T> eachTestDelegate; try { eachTestDelegate = methodInfo.CreateDelegate(typeof(Action<T>), instance) as Action<T>; } catch (Exception e) { var sb = new StringBuilder(); sb.Append(typeName).Append(".").Append(methodInfo.Name).Append(" must match the test delegate signature: Action<T>"); sb.Append("\n").Append(e); sb.Append("\nExpected Params: ["); var actionInfo = typeof(Action<T>).GetMethod("Invoke"); foreach (var param in actionInfo.GetParameters()) sb.Append(param.Name).Append(","); sb.Append("]"); sb.Append("\nActual Params: ["); foreach (var param in methodInfo.GetParameters()) sb.Append(param.Name).Append(","); sb.Append("]"); throw new Exception(sb.ToString()); } return eachTestDelegate; } private HashSet<string> AssembleFilter(string filter) { if (string.IsNullOrEmpty(filter)) return null; var filterWords = filter.ToLower().Split(new char[] { '\n', ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); if (filterWords.Length > 0) return new HashSet<string>(filterWords); return null; } private bool MatchesFilters(string name, HashSet<string> filterSet) { if (filterSet == null) return true; var nameLc = name.ToLower(); foreach (var eachFilter in filterSet) if (nameLc.Contains(eachFilter)) return true; return false; } /// <summary> /// Return that tests were run, and all of them reported success /// </summary> public bool AllTestsPassed() { return _testReport.AllTestsPassed(); } /// <summary> /// Tick the test suite. /// This should be called once per Update until it returns true. /// Once it returns true, testing is complete /// </summary> public bool TickTestSuite() { if (_suiteState == UUnitActiveState.COMPLETE) return true; if (_suiteState == UUnitActiveState.PENDING) _suiteState = UUnitActiveState.ACTIVE; // Check if we should cycle to the next test var nextTest = _activeIndex < _testContexts.Count ? _testContexts[_activeIndex] : null; if (nextTest != null && nextTest.ActiveState == UUnitActiveState.COMPLETE) { if (nextTest.FinishState == UUnitFinishState.FAILED && nextTest.retryCount < nextTest.TestInstance.maxRetry) { // Reset the test and try again nextTest.AttemptRetry(); } else { // Record this test result TrackTestResult(nextTest); // Retrys are expired, move to the next test _activeIndex++; nextTest = (_activeIndex >= _testContexts.Count) ? null : _testContexts[_activeIndex]; } } if (nextTest != null && nextTest.ActiveState == UUnitActiveState.PENDING) StartTest(nextTest); else if (nextTest != null) TickTest(nextTest); var testsDone = _activeIndex >= _testContexts.Count; if (testsDone && _suiteState == UUnitActiveState.ACTIVE) { _suiteState = UUnitActiveState.READY; ManageInstance(null, activeTestInstance); // Ensure that the final test is cleaned up } return _suiteState == UUnitActiveState.READY; } private void TrackTestResult(UUnitTestContext testContext) { _testReport.TestComplete(testContext.TestDelegate.Target.GetType().Name + "." + testContext.Name, testContext.FinishState, (int)(testContext.EndTime - testContext.StartTime).TotalMilliseconds, testContext.TestResultMsg, null); } /// <summary> /// Start a test, track which test is active, and manage timers /// </summary> private void StartTest(UUnitTestContext testContext) { ManageInstance(testContext.TestInstance, activeTestInstance); testContext.StartTime = DateTime.UtcNow; testContext.ActiveState = UUnitActiveState.ACTIVE; _testReport.TestStarted(); if (testContext.ActiveState == UUnitActiveState.ACTIVE) Wrap(testContext, testContext.TestInstance.SetUp); if (testContext.ActiveState == UUnitActiveState.ACTIVE) Wrap(testContext, testContext.TestDelegate); // Async tests can't resolve this tick, so just return } /// <summary> /// Ensure that exceptions in any test-functions are relayed to the testContext as failures /// </summary> private void Wrap(UUnitTestContext testContext, Action<UUnitTestContext> testFunc) { try { testFunc(testContext); } catch (UUnitSkipException uu) { // Silence the assert and ensure the test is marked as complete - The exception is just to halt the test process testContext.EndTest(UUnitFinishState.SKIPPED, uu.Message); } catch (UUnitException uu) { // Silence the assert and ensure the test is marked as complete - The exception is just to halt the test process testContext.EndTest(UUnitFinishState.FAILED, uu.Message + "\n" + uu.StackTrace); } catch (Exception e) { // Report this exception as an unhandled failure in the test testContext.EndTest(UUnitFinishState.FAILED, e.ToString()); } } /// <summary> /// Manage the ClassSetUp and ClassTearDown functions for each UUnitTestCase /// </summary> private void ManageInstance(UUnitTestCase newtestInstance, UUnitTestCase oldTestInstance) { if (ReferenceEquals(newtestInstance, oldTestInstance)) return; if (oldTestInstance != null) oldTestInstance.ClassTearDown(); if (newtestInstance != null) newtestInstance.ClassSetUp(); activeTestInstance = newtestInstance; } private void TickTest(UUnitTestContext testContext) { var now = DateTime.UtcNow; var timedOut = (now - testContext.StartTime) > TestTimeout; if (testContext.ActiveState != UUnitActiveState.READY && !timedOut) // Not finished & not timed out { Wrap(testContext, testContext.TestInstance.Tick); return; } else if (testContext.ActiveState == UUnitActiveState.ACTIVE && timedOut) { testContext.EndTest(UUnitFinishState.TIMEDOUT, "Test duration exceeded maxumum"); } testContext.EndTime = now; Wrap(testContext, testContext.TestInstance.TearDown); testContext.ActiveState = UUnitActiveState.COMPLETE; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using ALinq; using ALinq.Mapping; namespace NorthwindDemo { #if !FREE //[License("ansiboy", "EC4E10904943EE7F5C9C830F80CC1693")] #endif [Provider(typeof(ALinq.Firebird.FirebirdProvider))] public class FirebirdNorthwind : NorthwindDatabase { public FirebirdNorthwind(string connection, XmlMappingSource xmlMapping) : base(connection, xmlMapping) { } public FirebirdNorthwind(string connection) : base(connection) { } public FirebirdNorthwind(IDbConnection connection) :base(connection) { } public override void CreateDatabase() { base.CreateDatabase(); return; var conn = Connection; var command = conn.CreateCommand(); conn.Open(); try { #region PROCEDURE AddCategory command.CommandText = @" CREATE PROCEDURE AddCategory ( P1 VARCHAR(20), P2 VARCHAR(20)) RETURNS ( RETURN_VALUE INTEGER) AS BEGIN Insert Into Categories (CategoryID, CategoryName, Description) Values (NEXT VALUE FOR Seq_Categories, :p1, :p2); SELECT GEN_ID(Seq_Categories, 0) FROM RDB$DATABASE into RETURN_VALUE; SUSPEND ; END; "; if (Log != null) { Log.WriteLine(command.CommandText); Log.WriteLine(); } command.ExecuteNonQuery(); #endregion #region PROCEDURE GetCustomersByCity command.CommandText = @" --Procedure: GetCustomersByCity --DROP PROCEDURE GetCustomersByCity; RECREATE PROCEDURE GetCustomersByCity ( CITY VARCHAR(20)) RETURNS ( P0 VARCHAR(50), P2 VARCHAR(50), P1 VARCHAR(50), RETURN_VALUE VARCHAR(50)) AS BEGIN for select CustomerID, ContactName, CompanyName from Customers where City = :city into :p0, :p1, :p2 do suspend; END; "; if (Log != null) { Log.WriteLine(command.CommandText); Log.WriteLine(); } command.ExecuteNonQuery(); #endregion #region PROCEDURE GetCustomersCountByRegion command.CommandText = @" --Procedure: GetCustomersCountByRegion --DROP PROCEDURE GetCustomersCountByRegion; CREATE PROCEDURE GetCustomersCountByRegion ( P1 VARCHAR(20)) RETURNS ( RETURN_VALUE INTEGER) AS BEGIN select count(*) from Customers where Region = :P1 into :RETURN_VALUE; END"; if (Log != null) { Log.WriteLine(command.CommandText); Log.WriteLine(); } command.ExecuteNonQuery(); #endregion #region PROCEDURE SingleRowset_MultiShape command.CommandText = @" RECREATE PROCEDURE SINGLEROWSET_MULTISHAPE ( P0 INTEGER) RETURNS ( CUSTOMERID VARCHAR(50), CONTACTNAME VARCHAR(50), COMPANYNAME VARCHAR(50), ADDRESS VARCHAR(50), CITY VARCHAR(50), REGION VARCHAR(50), POSTALCODE VARCHAR(50), COUNTRY VARCHAR(50), PHONE VARCHAR(50), FAX VARCHAR(20)) AS BEGIN if(:p0 = 1) then for select CustomerID, ContactName, CompanyName from Customers where Region = 'WA' into :customerID, :ContactName, :CompanyName do suspend; if(:p0 = 2) then for select CustomerID, ContactName, CompanyName, Address, City, Region, PostalCode, Country, Phone,Fax from Customers where Region = 'WA' into :customerID, :ContactName, :CompanyName, :Address, :City, :Region, :PostalCode, :Country, :Phone, :Fax do suspend; END"; if (Log != null) { Log.WriteLine(command.CommandText); Log.WriteLine(); } command.ExecuteNonQuery(); #endregion #region PROCEDURE GetCustomerAndOrders command.CommandText = @" --Procedure: GETCUSTOMERANDORDERS --DROP PROCEDURE GETCUSTOMERANDORDERS; CREATE PROCEDURE GETCUSTOMERANDORDERS ( PARAM VARCHAR(15)) RETURNS ( CUSTOMERID VARCHAR(20), COMPANYNAME VARCHAR(20), CONTACTNAME VARCHAR(20), CONTACTTITLE VARCHAR(30), ADDRESS VARCHAR(20), CITY VARCHAR(20), REGION VARCHAR(20), POSTALCODE VARCHAR(20), COUNTRY VARCHAR(20), PHONE VARCHAR(20), FAX VARCHAR(20), ORDERID VARCHAR(20), EMPLOYEEID INTEGER, ORDERDATE TIMESTAMP, REQUIREDDATE TIMESTAMP, SHIPPEDDATE TIMESTAMP, SHIPVIA INTEGER, FREIGHT FLOAT, SHIPNAME VARCHAR(20), SHIPADDRESS VARCHAR(20), SHIPCITY VARCHAR(20), SHIPREGION VARCHAR(20), SHIPPOSTALCODE VARCHAR(20), SHIPCOUNTRY VARCHAR(20)) AS BEGIN for select CustomerID, CompanyName, ContactName, Address, City, Region, PostalCode, Country, Phone, Fax, CONTACTTITLE from Customers where City = :city into :customerID, :companyName, :contactName, :address, :city, :region, :postalCode, :country, :phone, :fax, :CONTACTTITLE do suspend; for select OrderID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, Shipvia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry from Orders where CustomerID = :customerID into :orderID, :customerID, :employeeID, :orderDate, :requiredDate, :shippedDate, :shipvia, :freight, :shipName, :shipAddress, :shipCity, :shipRegion, :shipPostalCode, :shipCountry do suspend; END;"; if (Log != null) { Log.WriteLine(command.CommandText); Log.WriteLine(); } command.ExecuteNonQuery(); #endregion } finally { conn.Close(); } } //???? [Function] public new int AddCategory( [Parameter]string name, [Parameter]string description) { var result = ExecuteMethodCall(this, ((MethodInfo)(MethodBase.GetCurrentMethod())), name, description).ReturnValue; return (int)result; } [Function] public int GetCustomersCountByRegion([Parameter]string region) { var result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), region); return ((int)(result.ReturnValue)); } [Function] public ISingleResult<PartialCustomersSetResult> GetCustomersByCity( [Parameter] string city ) { IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), city); return ((ISingleResult<PartialCustomersSetResult>)(result.ReturnValue)); } public class PartialCustomersSetResult { [Column] public string CustomerID; [Column] public string ContactName; [Column] public string CompanyName; } [Function] [ResultType(typeof(Customer))] [ResultType(typeof(PartialCustomersSetResult))] public IMultipleResults SingleRowset_MultiShape( [Parameter] int? param) { IExecuteResult result = ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), param); return ((IMultipleResults)(result.ReturnValue)); } [Function(Name = "GetCustomerAndOrders")] [ResultType(typeof(Customer))] [ResultType(typeof(Order))] public IMultipleResults GetCustomerAndOrders( [Parameter] string customerID) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID); return ((IMultipleResults)(result.ReturnValue)); } } }
// Copyright (c) 2007-2008, Gaudenz Alder using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.Collections.Generic; using System.Text; using System.Xml; namespace com.mxgraph { /// <summary> /// An abstract converter that renders display XML data onto a canvas. /// </summary> public abstract class mxGraphViewReader { /// <summary> /// Holds the canvas to be used for rendering the graph. /// </summary> protected mxICanvas canvas; /// <summary> /// Holds the global scale of the graph. This is set just before /// createCanvas is called. /// </summary> protected double scale = 1; /// <summary> /// Constructs a new graph view reader. /// </summary> public mxGraphViewReader(): this(null) { } /// <summary> /// Constructs a new graph view reader and reads the given display XML data. /// </summary> /// <param name="reader">Reader that represents the display XML data.</param> public mxGraphViewReader(XmlReader reader) { Read(reader); } /// <summary> /// Returns the canvas to be used for rendering. /// </summary> /// <param name="attrs">Specifies the attributes of the new canvas.</param> /// <returns>Returns a new canvas.</returns> public abstract mxICanvas CreateCanvas(Dictionary<string, Object> attrs); /// <summary> /// Returns the canvas that is used for rendering the graph. /// </summary> public mxICanvas Canvas { get { return canvas; } } /// <summary> /// Reads the given display XML data and parses all elements. /// </summary> /// <param name="reader">Reader that represents the display XML data.</param> public void Read(XmlReader reader) { if (reader != null) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { string tagName = reader.LocalName.ToUpper(); Dictionary<string, Object> attrs = new Dictionary<string, Object>(); if (reader.MoveToFirstAttribute()) { do { attrs[reader.LocalName] = reader.Value; } while (reader.MoveToNextAttribute()); } ParseElement(tagName, attrs); } } } } /// <summary> /// Parses the given element and paints it onto the canvas. /// </summary> /// <param name="tagName">Name of the node to be parsed.</param> /// <param name="attrs">Attributes of the node to be parsed.</param> public void ParseElement(string tagName, Dictionary<string, Object> attrs) { if (canvas == null && tagName.ToLower().Equals("graph")) { scale = mxUtils.GetDouble(attrs, "scale", 1); canvas = CreateCanvas(attrs); if (canvas != null) { canvas.Scale = scale; } } else if (canvas != null) { bool edge = tagName.ToLower().Equals("edge"); bool group = tagName.ToLower().Equals("group"); bool vertex = tagName.ToLower().Equals("vertex"); if ((edge && attrs.ContainsKey("points")) || ((vertex || group) && attrs.ContainsKey("x") && attrs.ContainsKey("y") && attrs.ContainsKey("width") && attrs.ContainsKey("height"))) { mxCellState state = new mxCellState(null, null, attrs); string label = ParseState(state, edge); canvas.DrawCell(state); canvas.DrawLabel(label, state, false); } } } /// <summary> /// Parses the bounds, absolute points and label information from the style /// of the state into its respective fields and returns the label of the /// cell. /// </summary> public string ParseState(mxCellState state, bool edge) { Dictionary<string, object> style = state.Style; // Parses the bounds state.X = mxUtils.GetDouble(style, "x"); state.Y = mxUtils.GetDouble(style, "y"); state.Width = mxUtils.GetDouble(style, "width"); state.Height = mxUtils.GetDouble(style, "height"); // Parses the absolute points list List<mxPoint> pts = ParsePoints(mxUtils.GetString(style, "points")); if (pts.Count > 0) { state.AbsolutePoints = pts; } // Parses the label and label bounds string label = mxUtils.GetString(style, "label"); if (label != null && label.Length > 0) { mxPoint offset = new mxPoint(mxUtils.GetDouble(style, "dx"), mxUtils.GetDouble(style, "dy")); mxRectangle vertexBounds = (!edge) ? state : null; state.LabelBounds = mxUtils.GetLabelPaintBounds(label, style, mxUtils.IsTrue(style, "html", false), offset, vertexBounds, scale); } return label; } /// <summary> /// Parses the list of points into an object-oriented representation. /// </summary> /// <param name="pts">String containing a list of points.</param> /// <returns>Returns the points as a list of mxPoints.</returns> public static List<mxPoint> ParsePoints(string pts) { List<mxPoint> result = new List<mxPoint>(); if (pts != null) { int len = pts.Length; string tmp = ""; string x = null; for (int i = 0; i < len; i++) { char c = pts[i]; if (c == ',' || c == ' ') { if (x == null) { x = tmp; } else { result.Add(new mxPoint(double.Parse(x), double.Parse(tmp))); x = null; } tmp = ""; } else { tmp += c; } } result.Add(new mxPoint(double.Parse(x), double.Parse(tmp))); } return result; } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: SecurityId.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Globalization; using Ecng.Common; using Ecng.Serialization; using StockSharp.Localization; /// <summary> /// Security ID. /// </summary> [DataContract] [Serializable] public struct SecurityId : IEquatable<SecurityId>, IPersistable { private string _securityCode; /// <summary> /// Security code. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.Str349Key)] [DescriptionLoc(LocalizedStrings.Str349Key, true)] [MainCategory] public string SecurityCode { get => _securityCode; set => _securityCode = value; } private string _boardCode; /// <summary> /// Electronic board code. /// </summary> [DataMember] [DisplayNameLoc(LocalizedStrings.BoardKey)] [DescriptionLoc(LocalizedStrings.BoardCodeKey, true)] [MainCategory] public string BoardCode { get => _boardCode; set => _boardCode = value; } private object _native; /// <summary> /// Native (internal) trading system security id. /// </summary> public object Native { get => _nativeAsInt != 0 ? _nativeAsInt : _native; set { _native = value; _nativeAsInt = 0; if (value is long l) _nativeAsInt = l; } } private long _nativeAsInt; /// <summary> /// Native (internal) trading system security id represented as integer. /// </summary> public long NativeAsInt { get => _nativeAsInt; set => _nativeAsInt = value; } private SecurityTypes? _securityType; /// <summary> /// Security type. /// </summary> [Obsolete] public SecurityTypes? SecurityType { get => _securityType; set => _securityType = value; } /// <summary> /// ID in SEDOL format (Stock Exchange Daily Official List). /// </summary> [DataMember] [DisplayName("SEDOL")] [DescriptionLoc(LocalizedStrings.Str351Key)] public string Sedol { get; set; } /// <summary> /// ID in CUSIP format (Committee on Uniform Securities Identification Procedures). /// </summary> [DataMember] [DisplayName("CUSIP")] [DescriptionLoc(LocalizedStrings.Str352Key)] public string Cusip { get; set; } /// <summary> /// ID in ISIN format (International Securities Identification Number). /// </summary> [DataMember] [DisplayName("ISIN")] [DescriptionLoc(LocalizedStrings.Str353Key)] public string Isin { get; set; } /// <summary> /// ID in RIC format (Reuters Instrument Code). /// </summary> [DataMember] [DisplayName("RIC")] [DescriptionLoc(LocalizedStrings.Str354Key)] public string Ric { get; set; } /// <summary> /// ID in Bloomberg format. /// </summary> [DataMember] [DisplayName("Bloomberg")] [DescriptionLoc(LocalizedStrings.Str355Key)] public string Bloomberg { get; set; } /// <summary> /// ID in IQFeed format. /// </summary> [DataMember] [DisplayName("IQFeed")] [DescriptionLoc(LocalizedStrings.Str356Key)] public string IQFeed { get; set; } /// <summary> /// ID in Interactive Brokers format. /// </summary> [DataMember] [DisplayName("InteractiveBrokers")] [DescriptionLoc(LocalizedStrings.Str357Key)] //[Nullable] public int? InteractiveBrokers { get; set; } /// <summary> /// ID in Plaza format. /// </summary> [DataMember] [DisplayName("Plaza")] [DescriptionLoc(LocalizedStrings.Str358Key)] public string Plaza { get; set; } private int _hashCode; /// <summary> /// Get the hash code of the object. /// </summary> /// <returns>A hash code.</returns> public override int GetHashCode() { return EnsureGetHashCode(); } private int EnsureGetHashCode() { if (_hashCode == 0) { _hashCode = (_nativeAsInt != 0 ? _nativeAsInt.GetHashCode() : _native?.GetHashCode()) ?? (_securityCode + _boardCode).ToLowerInvariant().GetHashCode(); } return _hashCode; } /// <summary> /// Compare <see cref="SecurityId"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> public override bool Equals(object other) { return other is SecurityId secId && Equals(secId); } /// <summary> /// Compare <see cref="SecurityId"/> on the equivalence. /// </summary> /// <param name="other">Another value with which to compare.</param> /// <returns><see langword="true" />, if the specified object is equal to the current object, otherwise, <see langword="false" />.</returns> public bool Equals(SecurityId other) { if (EnsureGetHashCode() != other.EnsureGetHashCode()) return false; if (_nativeAsInt != 0) return _nativeAsInt.Equals(other._nativeAsInt); if (_native != null) return _native.Equals(other._native); return _securityCode.EqualsIgnoreCase(other._securityCode) && _boardCode.EqualsIgnoreCase(other._boardCode); } /// <summary> /// Compare the inequality of two identifiers. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns><see langword="true" />, if identifiers are equal, otherwise, <see langword="false" />.</returns> public static bool operator !=(SecurityId left, SecurityId right) { return !(left == right); } /// <summary> /// Compare two identifiers for equality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns><see langword="true" />, if the specified identifiers are equal, otherwise, <see langword="false" />.</returns> public static bool operator ==(SecurityId left, SecurityId right) { return left.Equals(right); } /// <inheritdoc /> public override string ToString() { var id = $"{SecurityCode}@{BoardCode}"; if (Native != null) id += $",Native:{Native}"; //if (SecurityType != null) // id += $",Type:{SecurityType.Value}"; if (!Isin.IsEmpty()) id += $",ISIN:{Isin}"; if (!IQFeed.IsEmpty()) id += $",IQFeed:{IQFeed}"; if (InteractiveBrokers != null) id += $",IB:{InteractiveBrokers}"; return id; } /// <summary> /// Load settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Load(SettingsStorage storage) { SecurityCode = storage.GetValue<string>(nameof(SecurityCode)); BoardCode = storage.GetValue<string>(nameof(BoardCode)); } /// <summary> /// Save settings. /// </summary> /// <param name="storage">Settings storage.</param> public void Save(SettingsStorage storage) { storage.SetValue(nameof(SecurityCode), SecurityCode); storage.SetValue(nameof(BoardCode), BoardCode); } /// <summary> /// Board code for combined security. /// </summary> public const string AssociatedBoardCode = "ALL"; /// <summary> /// Create security id with board code set as <see cref="AssociatedBoardCode"/>. /// </summary> /// <param name="securityCode">Security code.</param> /// <returns>Security ID.</returns> public static SecurityId CreateAssociated(string securityCode) { return new SecurityId { SecurityCode = securityCode, BoardCode = AssociatedBoardCode, }; } /// <summary> /// "Money" security id. /// </summary> public static readonly SecurityId Money = new() { SecurityCode = "MONEY", BoardCode = AssociatedBoardCode }; /// <summary> /// "News" security id. /// </summary> public static readonly SecurityId News = new() { SecurityCode = "NEWS", BoardCode = AssociatedBoardCode }; } /// <summary> /// Converter to use with <see cref="SecurityId"/> properties. /// </summary> public class StringToSecurityIdTypeConverter : TypeConverter { /// <inheritdoc /> public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type sourceType) => sourceType == typeof(string) || base.CanConvertFrom(ctx, sourceType); /// <inheritdoc /> public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo culture, object value) { if (value is not string securityId) return base.ConvertFrom(ctx, culture, value); var isNullable = ctx.PropertyDescriptor?.PropertyType.IsNullable() == true; const string delimiter = "@"; var index = securityId.LastIndexOfIgnoreCase(delimiter); return index < 0 ? isNullable ? (SecurityId?)null : default(SecurityId) : new SecurityId { SecurityCode = securityId.Substring(0, index), BoardCode = securityId.Substring(index + delimiter.Length, securityId.Length - index - delimiter.Length) }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; internal static partial class Interop { internal static partial class procfs { internal const string RootPath = "/proc/"; private const string ExeFileName = "/exe"; private const string CmdLineFileName = "/cmdline"; private const string StatFileName = "/stat"; private const string MapsFileName = "/maps"; private const string StatusFileName = "/status"; private const string FileDescriptorDirectoryName = "/fd/"; private const string TaskDirectoryName = "/task/"; internal const string SelfExeFilePath = RootPath + "self" + ExeFileName; internal const string SelfCmdLineFilePath = RootPath + "self" + CmdLineFileName; internal const string ProcStatFilePath = RootPath + "stat"; internal struct ParsedStat { // Commented out fields are available in the stat data file but // are currently not used. If/when needed, they can be uncommented, // and the corresponding entry can be added back to StatParser, replacing // the MoveNext() with the appropriate ParseNext* call and assignment. internal int pid; internal string comm; internal char state; internal int ppid; //internal int pgrp; internal int session; //internal int tty_nr; //internal int tpgid; //internal uint flags; //internal ulong minflt; //internal ulong cminflt; //internal ulong majflt; //internal ulong cmajflt; internal ulong utime; internal ulong stime; //internal long cutime; //internal long cstime; //internal long priority; internal long nice; //internal long num_threads; //internal long itrealvalue; internal ulong starttime; internal ulong vsize; internal long rss; internal ulong rsslim; //internal ulong startcode; //internal ulong endcode; //internal ulong startstack; //internal ulong kstkesp; //internal ulong kstkeip; //internal ulong signal; //internal ulong blocked; //internal ulong sigignore; //internal ulong sigcatch; //internal ulong wchan; //internal ulong nswap; //internal ulong cnswap; //internal int exit_signal; //internal int processor; //internal uint rt_priority; //internal uint policy; //internal ulong delayacct_blkio_ticks; //internal ulong guest_time; //internal long cguest_time; } internal struct ParsedStatus { #if DEBUG internal int Pid; #endif internal ulong VmHWM; internal ulong VmRSS; internal ulong VmData; internal ulong VmSwap; internal ulong VmSize; internal ulong VmPeak; } internal struct ParsedMapsModule { internal string FileName; internal KeyValuePair<long, long> AddressRange; } internal static string GetExeFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + ExeFileName; } internal static string GetCmdLinePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + CmdLineFileName; } internal static string GetStatFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static string GetStatusFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatusFileName; } internal static string GetMapsFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + MapsFileName; } internal static string GetTaskDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + TaskDirectoryName; } internal static string GetFileDescriptorDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + FileDescriptorDirectoryName; } internal static IEnumerable<ParsedMapsModule> ParseMapsModules(int pid) { try { return ParseMapsModulesCore(File.ReadLines(GetMapsFilePathForProcess(pid))); } catch (IOException) { } catch (UnauthorizedAccessException) { } return Array.Empty<ParsedMapsModule>(); } private static IEnumerable<ParsedMapsModule> ParseMapsModulesCore(IEnumerable<string> lines) { Debug.Assert(lines != null); // Parse each line from the maps file into a ParsedMapsModule result foreach (string line in lines) { // Use a StringParser to avoid string.Split costs var parser = new StringParser(line, separator: ' ', skipEmpty: true); // Parse the address range KeyValuePair<long, long> addressRange = parser.ParseRaw(delegate (string s, ref int start, ref int end) { long startingAddress = 0, endingAddress = 0; int pos = s.IndexOf('-', start, end - start); if (pos > 0) { if (long.TryParse(s.AsSpan(start, pos), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out startingAddress)) { long.TryParse(s.AsSpan(pos + 1, end - (pos + 1)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out endingAddress); } } return new KeyValuePair<long, long>(startingAddress, endingAddress); }); // Parse the permissions (we only care about entries with 'r' and 'x' set) if (!parser.ParseRaw(delegate (string s, ref int start, ref int end) { bool sawRead = false, sawExec = false; for (int i = start; i < end; i++) { if (s[i] == 'r') sawRead = true; else if (s[i] == 'x') sawExec = true; } return sawRead & sawExec; })) { continue; } // Skip past the offset, dev, and inode fields parser.MoveNext(); parser.MoveNext(); parser.MoveNext(); // Parse the pathname if (!parser.MoveNext()) { continue; } string pathname = parser.ExtractCurrentToEnd(); // We only get here if a we have a non-empty pathname and // the permissions included both readability and executability. // Yield the result. yield return new ParsedMapsModule { FileName = pathname, AddressRange = addressRange }; } } private static string GetStatFilePathForThread(int pid, int tid) { // Perf note: Calling GetTaskDirectoryPathForProcess will allocate a string, // which we then use in another Concat call to produce another string. The straightforward alternative, // though, since we have five input strings, is to use the string.Concat overload that takes a params array. // This results in allocating not only the params array but also a defensive copy inside of Concat, // which means allocating two five-element arrays. This two-string approach will result not only in fewer // allocations, but also typically in less memory allocated, and it's a bit more maintainable. return GetTaskDirectoryPathForProcess(pid) + tid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static bool TryReadStatFile(int pid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForProcess(pid), out result, reusableReader); Debug.Assert(!b || result.pid == pid, "Expected process ID from stat file to match supplied pid"); return b; } internal static bool TryReadStatFile(int pid, int tid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForThread(pid, tid), out result, reusableReader); Debug.Assert(!b || result.pid == tid, "Expected thread ID from stat file to match supplied tid"); return b; } internal static bool TryReadStatusFile(int pid, out ParsedStatus result, ReusableTextReader reusableReader) { bool b = TryParseStatusFile(GetStatusFilePathForProcess(pid), out result, reusableReader); #if DEBUG Debug.Assert(!b || result.Pid == pid, "Expected process ID from status file to match supplied pid"); #endif return b; } internal static bool TryParseStatFile(string statFilePath, out ParsedStat result, ReusableTextReader reusableReader) { if (!TryReadFile(statFilePath, reusableReader, out string statFileContents)) { // Between the time that we get an ID and the time that we try to read the associated stat // file(s), the process could be gone. result = default(ParsedStat); return false; } var parser = new StringParser(statFileContents, ' '); var results = default(ParsedStat); results.pid = parser.ParseNextInt32(); results.comm = parser.MoveAndExtractNextInOuterParens(); results.state = parser.ParseNextChar(); results.ppid = parser.ParseNextInt32(); parser.MoveNextOrFail(); // pgrp results.session = parser.ParseNextInt32(); parser.MoveNextOrFail(); // tty_nr parser.MoveNextOrFail(); // tpgid parser.MoveNextOrFail(); // flags parser.MoveNextOrFail(); // majflt parser.MoveNextOrFail(); // cmagflt parser.MoveNextOrFail(); // minflt parser.MoveNextOrFail(); // cminflt results.utime = parser.ParseNextUInt64(); results.stime = parser.ParseNextUInt64(); parser.MoveNextOrFail(); // cutime parser.MoveNextOrFail(); // cstime parser.MoveNextOrFail(); // priority results.nice = parser.ParseNextInt64(); parser.MoveNextOrFail(); // num_threads parser.MoveNextOrFail(); // itrealvalue results.starttime = parser.ParseNextUInt64(); results.vsize = parser.ParseNextUInt64(); results.rss = parser.ParseNextInt64(); results.rsslim = parser.ParseNextUInt64(); // The following lines are commented out as there's no need to parse through // the rest of the entry (we've gotten all of the data we need). Should any // of these fields be needed in the future, uncomment all of the lines up // through and including the one that's needed. For now, these are being left // commented to document what's available in the remainder of the entry. //parser.MoveNextOrFail(); // startcode //parser.MoveNextOrFail(); // endcode //parser.MoveNextOrFail(); // startstack //parser.MoveNextOrFail(); // kstkesp //parser.MoveNextOrFail(); // kstkeip //parser.MoveNextOrFail(); // signal //parser.MoveNextOrFail(); // blocked //parser.MoveNextOrFail(); // sigignore //parser.MoveNextOrFail(); // sigcatch //parser.MoveNextOrFail(); // wchan //parser.MoveNextOrFail(); // nswap //parser.MoveNextOrFail(); // cnswap //parser.MoveNextOrFail(); // exit_signal //parser.MoveNextOrFail(); // processor //parser.MoveNextOrFail(); // rt_priority //parser.MoveNextOrFail(); // policy //parser.MoveNextOrFail(); // delayacct_blkio_ticks //parser.MoveNextOrFail(); // guest_time //parser.MoveNextOrFail(); // cguest_time result = results; return true; } internal static bool TryParseStatusFile(string statusFilePath, out ParsedStatus result, ReusableTextReader reusableReader) { if (!TryReadFile(statusFilePath, reusableReader, out string fileContents)) { // Between the time that we get an ID and the time that we try to read the associated stat // file(s), the process could be gone. result = default(ParsedStatus); return false; } ParsedStatus results = default(ParsedStatus); ReadOnlySpan<char> statusFileContents = fileContents.AsSpan(); int unitSliceLength = -1; #if DEBUG int nonUnitSliceLength = -1; #endif while (!statusFileContents.IsEmpty) { int startIndex = statusFileContents.IndexOf(':'); if (startIndex == -1) { // Reached end of file break; } ReadOnlySpan<char> title = statusFileContents.Slice(0, startIndex); statusFileContents = statusFileContents.Slice(startIndex + 1); int endIndex = statusFileContents.IndexOf('\n'); if (endIndex == -1) { endIndex = statusFileContents.Length - 1; unitSliceLength = statusFileContents.Length - 3; #if DEBUG nonUnitSliceLength = statusFileContents.Length; #endif } else { unitSliceLength = endIndex - 3; #if DEBUG nonUnitSliceLength = endIndex; #endif } ReadOnlySpan<char> value = default; bool valueParsed = true; #if DEBUG if (title.SequenceEqual("Pid".AsSpan())) { value = statusFileContents.Slice(0, nonUnitSliceLength); valueParsed = int.TryParse(value, out results.Pid); } #endif if (title.SequenceEqual("VmHWM".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out results.VmHWM); } else if (title.SequenceEqual("VmRSS".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out results.VmRSS); } else if (title.SequenceEqual("VmData".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out ulong vmData); results.VmData += vmData; } else if (title.SequenceEqual("VmSwap".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out results.VmSwap); } else if (title.SequenceEqual("VmSize".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out results.VmSize); } else if (title.SequenceEqual("VmPeak".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out results.VmPeak); } else if (title.SequenceEqual("VmStk".AsSpan())) { value = statusFileContents.Slice(0, unitSliceLength); valueParsed = ulong.TryParse(value, out ulong vmStack); results.VmData += vmStack; } Debug.Assert(valueParsed); statusFileContents = statusFileContents.Slice(endIndex + 1); } results.VmData *= 1024; results.VmPeak *= 1024; results.VmSize *= 1024; results.VmSwap *= 1024; results.VmRSS *= 1024; results.VmHWM *= 1024; result = results; return true; } private static bool TryReadFile(string filePath, ReusableTextReader reusableReader, out string fileContents) { try { using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, useAsync: false)) { fileContents = reusableReader.ReadAllText(fileStream); return true; } } catch (IOException) { fileContents = null; return false; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.AzureStack.Management.Fabric.Admin { using Microsoft.AzureStack; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Fabric; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// IpPoolsOperations operations. /// </summary> internal partial class IpPoolsOperations : IServiceOperations<FabricAdminClient>, IIpPoolsOperations { /// <summary> /// Initializes a new instance of the IpPoolsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal IpPoolsOperations(FabricAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the FabricAdminClient /// </summary> public FabricAdminClient Client { get; private set; } /// <summary> /// Get an ip pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='ipPool'> /// Ip pool name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IpPool>> GetWithHttpMessagesAsync(string location, string ipPool, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (ipPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ipPool"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("ipPool", ipPool); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/ipPools/{ipPool}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{ipPool}", System.Uri.EscapeDataString(ipPool)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IpPool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IpPool>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create an ip pool. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='ipPool'> /// Ip pool name. /// </param> /// <param name='pool'> /// Ip pool object to send. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IpPool>> CreateWithHttpMessagesAsync(string location, string ipPool, IpPool pool, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (ipPool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ipPool"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (pool == null) { throw new ValidationException(ValidationRules.CannotBeNull, "pool"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("ipPool", ipPool); tracingParameters.Add("pool", pool); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/ipPools/{ipPool}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{ipPool}", System.Uri.EscapeDataString(ipPool)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(pool != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(pool, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IpPool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<IpPool>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all ip pools at a certain location. /// </summary> /// <param name='location'> /// Location of the resource. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IpPool>>> ListWithHttpMessagesAsync(string location, ODataQuery<IpPool> odataQuery = default(ODataQuery<IpPool>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("location", location); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/System.{location}/providers/Microsoft.Fabric.Admin/fabricLocations/{location}/ipPools").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IpPool>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IpPool>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a list of all ip pools at a certain location. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<IpPool>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<IpPool>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<IpPool>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.IO.Tests { public partial class PathTestsBase { public static TheoryData<string> TestData_EmbeddedNull => new TheoryData<string> { "a\0b" }; public static TheoryData<string> TestData_EmptyString => new TheoryData<string> { "" }; public static TheoryData<string> TestData_ControlChars => new TheoryData<string> { "\t", "\r\n", "\b", "\v", "\n" }; public static TheoryData<string> TestData_NonDriveColonPaths => new TheoryData<string> { @"bad:path", @"C:\some\bad:path", @"http://www.microsoft.com", @"file://www.microsoft.com", @"bad::$DATA", @"C :", @"C :\somedir" }; public static TheoryData<string> TestData_Spaces => new TheoryData<string> { " ", " " }; public static TheoryData<string> TestData_Periods => new TheoryData<string> { // One and two periods have special meaning (current and parent dir) "...", "...." }; public static TheoryData<string> TestData_Wildcards => new TheoryData<string> { "*", "?" }; public static TheoryData<string> TestData_ExtendedWildcards => new TheoryData<string> { // These are supported by Windows although .NET blocked them historically "\"", "<", ">" }; public static TheoryData<string> TestData_UnicodeWhiteSpace => new TheoryData<string> { "\u00A0", // Non-breaking Space "\u2028", // Line separator "\u2029", // Paragraph separator }; public static TheoryData<string> TestData_InvalidUnc => new TheoryData<string> { // .NET used to validate properly formed UNCs @"\\", @"\\LOCALHOST", @"\\LOCALHOST\", @"\\LOCALHOST\\", @"\\LOCALHOST\.." }; public static TheoryData<string> TestData_InvalidDriveLetters => new TheoryData<string> { { @"@:\foo" }, // 064 = @ 065 = A { @"[:\\" }, // 091 = [ 090 = Z { @"`:\foo "}, // 096 = ` 097 = a { @"{:\\" }, // 123 = { 122 = z { @"@:/foo" }, { @"[://" }, { @"`:/foo "}, { @"{:/" }, { @"]:" } }; public static TheoryData<string> TestData_ValidDriveLetters => new TheoryData<string> { { @"A:\foo" }, // 064 = @ 065 = A { @"Z:\\" }, // 091 = [ 090 = Z { @"a:\foo "}, // 096 = ` 097 = a { @"z:\\" }, // 123 = { 122 = z { @"B:/foo" }, { @"D://" }, { @"E:/foo "}, { @"F:/" }, { @"G:" } }; public static TheoryData<string, string> TestData_GetDirectoryName => new TheoryData<string, string> { { ".", "" }, { "..", "" }, { "baz", "" }, { Path.Combine("dir", "baz"), "dir" }, { "dir.foo" + Path.AltDirectorySeparatorChar + "baz.txt", "dir.foo" }, { Path.Combine("dir", "baz", "bar"), Path.Combine("dir", "baz") }, { Path.Combine("..", "..", "files.txt"), Path.Combine("..", "..") }, { Path.DirectorySeparatorChar + "foo", Path.DirectorySeparatorChar.ToString() }, { Path.DirectorySeparatorChar.ToString(), null } }; public static TheoryData<string, string> TestData_GetDirectoryName_Windows => new TheoryData<string, string> { { @"C:\", null }, { @"C:/", null }, { @"C:", null }, { @"dir\\baz", "dir" }, { @"dir//baz", "dir" }, { @"C:\foo", @"C:\" }, { @"C:foo", "C:" } }; public static TheoryData<string, string> TestData_GetExtension => new TheoryData<string, string> { { @"file.exe", ".exe" }, { @"file", "" }, { @"file.", "" }, { @"file.s", ".s" }, { @"test/file", "" }, { @"test/file.extension", ".extension" }, { @"test\file", "" }, { @"test\file.extension", ".extension" }, { "file.e xe", ".e xe"}, { "file. ", ". "}, { " file. ", ". "}, { " file.extension", ".extension"} }; public static TheoryData<string, string> TestData_GetFileName => new TheoryData<string, string> { { ".", "." }, { "..", ".." }, { "file", "file" }, { "file.", "file." }, { "file.exe", "file.exe" }, { " . ", " . " }, { " .. ", " .. " }, { "fi le", "fi le" }, { Path.Combine("baz", "file.exe"), "file.exe" }, { Path.Combine("baz", "file.exe") + Path.AltDirectorySeparatorChar, "" }, { Path.Combine("bar", "baz", "file.exe"), "file.exe" }, { Path.Combine("bar", "baz", "file.exe") + Path.DirectorySeparatorChar, "" } }; public static TheoryData<string, string> TestData_GetFileNameWithoutExtension => new TheoryData<string, string> { { "", "" }, { "file", "file" }, { "file.exe", "file" }, { Path.Combine("bar", "baz", "file.exe"), "file" }, { Path.Combine("bar", "baz") + Path.DirectorySeparatorChar, "" } }; public static TheoryData<string, string> TestData_GetPathRoot_Unc => new TheoryData<string, string> { { @"\\test\unc\path\to\something", @"\\test\unc" }, { @"\\a\b\c\d\e", @"\\a\b" }, { @"\\a\b\", @"\\a\b" }, { @"\\a\b", @"\\a\b" }, { @"\\test\unc", @"\\test\unc" }, }; // TODO: Include \\.\ as well public static TheoryData<string, string> TestData_GetPathRoot_DevicePaths => new TheoryData<string, string> { { @"\\?\UNC\test\unc\path\to\something", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\test\unc" }, { @"\\?\UNC\test\unc", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\test\unc" }, { @"\\?\UNC\a\b1", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\a\b1" }, { @"\\?\UNC\a\b2\", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\UNC" : @"\\?\UNC\a\b2" }, { @"\\?\C:\foo\bar.txt", PathFeatures.IsUsingLegacyPathNormalization() ? @"\\?\C:" : @"\\?\C:\" } }; public static TheoryData<string, string> TestData_GetPathRoot_Windows => new TheoryData<string, string> { { @"C:", @"C:" }, { @"C:\", @"C:\" }, { @"C:\\", @"C:\" }, { @"C:\foo1", @"C:\" }, { @"C:\\foo2", @"C:\" }, }; protected static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath) { string original = Path.GetTempPath(); Assert.NotNull(original); try { Environment.SetEnvironmentVariable(envVar, newTempPath); Assert.Equal( Path.GetFullPath(expected), Path.GetFullPath(Path.GetTempPath())); } finally { Environment.SetEnvironmentVariable(envVar, original); Assert.Equal(original, Path.GetTempPath()); } } } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ using System; using System.Diagnostics; using System.IO; using React.Exceptions; namespace React { /// <summary> /// Handles compiling JavaScript files via Babel (http://babeljs.io/). /// </summary> public class Babel : IBabel { /// <summary> /// Cache key for JavaScript compilation /// </summary> protected const string JSX_CACHE_KEY = "JSX_v3_{0}"; /// <summary> /// Suffix to append to compiled files /// </summary> protected const string COMPILED_FILE_SUFFIX = ".generated.js"; /// <summary> /// Suffix to append to source map files /// </summary> protected const string SOURE_MAP_FILE_SUFFIX = ".map"; /// <summary> /// Number of lines in the header prepended to compiled files. /// </summary> protected const int LINES_IN_HEADER = 5; /// <summary> /// Environment this transformer has been created in /// </summary> protected readonly IReactEnvironment _environment; /// <summary> /// Cache used for storing compiled JavaScript /// </summary> protected readonly ICache _cache; /// <summary> /// File system wrapper /// </summary> protected readonly IFileSystem _fileSystem; /// <summary> /// Hash algorithm for file-based cache /// </summary> protected readonly IFileCacheHash _fileCacheHash; /// <summary> /// Site-wide configuration /// </summary> protected readonly IReactSiteConfiguration _config; /// <summary> /// The serialized Babel configuration /// </summary> protected readonly string _babelConfig; /// <summary> /// Initializes a new instance of the <see cref="Babel"/> class. /// </summary> /// <param name="environment">The ReactJS.NET environment</param> /// <param name="cache">The cache to use for compilation</param> /// <param name="fileSystem">File system wrapper</param> /// <param name="fileCacheHash">Hash algorithm for file-based cache</param> /// <param name="siteConfig">Site-wide configuration</param> public Babel(IReactEnvironment environment, ICache cache, IFileSystem fileSystem, IFileCacheHash fileCacheHash, IReactSiteConfiguration siteConfig) { _environment = environment; _cache = cache; _fileSystem = fileSystem; _fileCacheHash = fileCacheHash; _config = siteConfig; _babelConfig = siteConfig.BabelConfig.Serialize(_config.BabelVersion ?? BabelVersions.Babel7); } /// <summary> /// Transforms a JavaScript file. Results of the transformation are cached. /// </summary> /// <param name="filename">Name of the file to load</param> /// <returns>JavaScript</returns> public virtual string TransformFile(string filename) { return TransformFileWithSourceMap(filename, false).Code; } /// <summary> /// Transforms a JavaScript file via Babel and also returns a source map to map the /// compiled source to the original version. Results of the transformation are cached. /// </summary> /// <param name="filename">Name of the file to load</param> /// <param name="forceGenerateSourceMap"> /// <c>true</c> to re-transform the file if a cached version with no source map is available /// </param> /// <returns>JavaScript and source map</returns> public virtual JavaScriptWithSourceMap TransformFileWithSourceMap( string filename, bool forceGenerateSourceMap = false ) { var cacheKey = string.Format(JSX_CACHE_KEY, filename); // 1. Check in-memory cache. We need to invalidate any in-memory cache if there's no // source map cached and forceGenerateSourceMap is true. var cached = _cache.Get<JavaScriptWithSourceMap>(cacheKey); var cacheIsValid = cached != null && (!forceGenerateSourceMap || cached.SourceMap != null); if (cacheIsValid) { return cached; } // 2. Check on-disk cache var contents = _fileSystem.ReadAsString(filename); var hash = _fileCacheHash.CalculateHash(contents); var output = LoadFromFileCache(filename, hash, forceGenerateSourceMap); if (output == null) { // 3. Not cached, perform the transformation try { output = TransformWithHeader(filename, contents, hash); } catch (BabelException ex) { // Add the filename to the error message throw new BabelException(string.Format( "In file \"{0}\": {1}", filename, ex.Message ), ex); } } // Cache the result from above (either disk cache or live transformation) to memory var fullPath = _fileSystem.MapPath(filename); _cache.Set( cacheKey, output, slidingExpiration: TimeSpan.FromMinutes(30), cacheDependencyFiles: new[] { fullPath } ); return output; } /// <summary> /// Loads a transformed JavaScript file from the disk cache. If the cache is invalid or there is /// no cached version, returns <c>null</c>. /// </summary> /// <param name="filename">Name of the file to load</param> /// /// <param name="hash">Hash of the input file, to validate the cache</param> /// <param name="forceGenerateSourceMap"> /// <c>true</c> to re-transform the file if a cached version with no source map is available /// </param> /// <returns></returns> protected virtual JavaScriptWithSourceMap LoadFromFileCache(string filename, string hash, bool forceGenerateSourceMap) { var cacheFilename = GetOutputPath(filename); if (!_fileSystem.FileExists(cacheFilename)) { // Cache file doesn't exist on disk return null; } var cacheContents = _fileSystem.ReadAsString(cacheFilename); if (!_fileCacheHash.ValidateHash(cacheContents, hash)) { // Hash of the cache is invalid (file changed since the time the cache was written). return null; } // Cache is valid :D // See if we have a source map cached alongside the file SourceMap sourceMap = null; var sourceMapFilename = GetSourceMapOutputPath(filename); if (_fileSystem.FileExists(sourceMapFilename)) { try { var sourceMapString = _fileSystem.ReadAsString(sourceMapFilename); if (!string.IsNullOrEmpty(sourceMapString)) { sourceMap = SourceMap.FromJson(sourceMapString); } } catch (Exception e) { // Just ignore it Trace.WriteLine("Error reading source map file: " + e.Message); } } // If forceGenerateSourceMap is true, we need to explicitly ignore this cached version // if there's no source map if (forceGenerateSourceMap && sourceMap == null) { return null; } return new JavaScriptWithSourceMap { Code = cacheContents, SourceMap = sourceMap, Hash = hash, }; } /// <summary> /// Transforms JavaScript via Babel, and prepends a header used for caching /// purposes. /// </summary> /// <param name="filename">Name of the file being transformed</param> /// <param name="contents">Contents of the input file</param> /// <param name="hash">Hash of the input. If null, it will be calculated</param> /// <returns>JavaScript</returns> protected virtual JavaScriptWithSourceMap TransformWithHeader( string filename, string contents, string hash = null ) { var result = TransformWithSourceMap(contents, filename); if (string.IsNullOrEmpty(hash)) { hash = _fileCacheHash.CalculateHash(contents); } // Prepend header to generated code var header = GetFileHeader(hash, result.BabelVersion); result.Code = header + result.Code; result.Hash = hash; if (result.SourceMap != null && result.SourceMap.Mappings != null) { // Since we prepend a header to the code, the source map no longer matches up exactly // (it's off by the number of lines in the header). Fix this issue by adding five // blank lines to the source map. This is kinda hacky but saves us having to load a // proper source map library. If this ever breaks, I'll replace it with actual proper // source map modification code (https://gist.github.com/Daniel15/4bdb15836bfd960c2956). result.SourceMap.Mappings = ";;;;;" + result.SourceMap.Mappings; } return result; } /// <summary> /// Transforms JavaScript via Babel. The result is not cached. Use /// <see cref="TransformFile"/> if loading from a file since this will cache the result. /// </summary> /// <param name="input">JavaScript</param> /// <param name="filename">Name of the file being transformed</param> /// <returns>JavaScript</returns> public virtual string Transform(string input, string filename = "unknown.jsx") { try { var output = _environment.ExecuteWithBabel<string>( "ReactNET_transform", input, _babelConfig, filename ); return output; } catch (Exception ex) { throw new BabelException(ex.Message, ex); } } /// <summary> /// Transforms JavaScript via Babel and also returns a source map to map the compiled /// source to the original version. The result is not cached. /// </summary> /// <param name="input">JavaScript</param> /// <param name="filename">Name of the file being transformed</param> /// <returns>JavaScript and source map</returns> public virtual JavaScriptWithSourceMap TransformWithSourceMap( string input, string filename = "unknown" ) { try { return _environment.ExecuteWithBabel<JavaScriptWithSourceMap>( "ReactNET_transform_sourcemap", input, _babelConfig, filename ); } catch (Exception ex) { throw new BabelException(ex.Message, ex); } } /// <summary> /// Gets the header prepended to transformed files. Contains a hash that is used to /// validate the cache. /// </summary> /// <param name="hash">Hash of the input</param> /// <param name="babelVersion">Version of Babel used to perform this transformation</param> /// <returns>Header for the cache</returns> protected virtual string GetFileHeader(string hash, string babelVersion) { return string.Format( @"{0} // Automatically generated by ReactJS.NET. Do not edit, your changes will be overridden. // Version: {1} with Babel {3} // Generated at: {2} /////////////////////////////////////////////////////////////////////////////// ", _fileCacheHash.AddPrefix(hash), _environment.Version, DateTime.Now, babelVersion); } /// <summary> /// Returns the path the specified file's compilation will be cached to /// </summary> /// <param name="path">Path of the input file</param> /// <returns>Output path of the compiled file</returns> public virtual string GetOutputPath(string path) { return Path.Combine( Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + COMPILED_FILE_SUFFIX ); } /// <summary> /// Returns the path the specified file's source map will be cached to if /// <see cref="TransformAndSaveFile"/> is called. /// </summary> /// <param name="path">Path of the input file</param> /// <returns>Output path of the source map</returns> public virtual string GetSourceMapOutputPath(string path) { return GetOutputPath(path) + SOURE_MAP_FILE_SUFFIX; } /// <summary> /// Transforms JavaScript via Babel and saves the result into a ".generated.js" file /// alongside the original file. /// </summary> /// <param name="filename">Name of the file to load</param> /// <returns>File contents</returns> public virtual string TransformAndSaveFile( string filename ) { var outputPath = GetOutputPath(filename); var contents = _fileSystem.ReadAsString(filename); if (CacheIsValid(contents, outputPath)) return outputPath; var result = TransformWithHeader(filename, contents, null); var sourceMapPath = GetSourceMapOutputPath(filename); _fileSystem.WriteAsString(outputPath, result.Code); _fileSystem.WriteAsString(sourceMapPath, result.SourceMap == null ? string.Empty : result.SourceMap.ToJson()); return outputPath; } /// <summary> /// Checks whether an input file (given as inputFileContents) should be transpiled /// by calculating the hash and comparing it to the hash value stored /// in the file given by outputPath. If the outputPath file does not /// exist the input file should always be transpiled. /// </summary> /// <param name="inputFileContents">The contents of the input file.</param> /// <param name="outputPath">The output path of the (possibly previously) generated file.</param> /// <returns>Returns false if the file should be transpiled, true otherwise.</returns> public virtual bool CacheIsValid(string inputFileContents, string outputPath) { if (!_fileSystem.FileExists(outputPath)) return false; var hashForInputFile = _fileCacheHash.CalculateHash(inputFileContents); var existingOutputContents = _fileSystem.ReadAsString(outputPath); var fileHasNotChanged = _fileCacheHash.ValidateHash(existingOutputContents, hashForInputFile); return fileHasNotChanged; } } }
using XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { class TwMap30 : TwMap { public override int MapIndex => 30; public override int MapID => 0x0C01; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 1; private const int NPCONE = 1; private const int NPCTWO = 2; private const int TORCHSWITCH = 3; private const int SPRUNGTRAP = 1; private const int TOSOURCE = 2; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This teleport will only take you to the main entrance."); TeleportParty(player, type, doMsgs, 1, 1, 19, Direction.South); } protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) { int charges = 0; charges = GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES); if ((GetFlag(player, type, doMsgs, FlagTypeTile, TOSOURCE) == 0)) { if (IsFlagOn(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES)) { if (UsedItem(player, type, ref doMsgs, RODOFDISSEMINATION, RODOFDISSEMINATION)) { if (charges < 12) { ShowText(player, type, doMsgs, "You dispel the wall!"); charges++; SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES, charges); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallInvisible(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { ShowText(player, type, doMsgs, "The item's powers have faded!"); ShowText(player, type, doMsgs, "Now, take this portal back to the rod's source; and try to find a pathway...again."); SetFlag(player, type, doMsgs, FlagTypeTile, TOSOURCE, 1); SetWallItem(player, type, doMsgs, GATEWAY, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ClearWallInvisible(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } else { ShowText(player, type, doMsgs, "This wall seems to shimmer, yet it is solid."); } } } else if (GetFlag(player, type, doMsgs, FlagTypeTile, TOSOURCE) == 1) { SetWallItem(player, type, doMsgs, GATEWAY, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); TeleportParty(player, type, doMsgs, 12, 1, 72, Direction.North); } } protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The tedious journey to this place has made you tired."); ShowText(player, type, doMsgs, "Even so, some walls here seem to fade and shimmer as being pulled upon by unseen forces."); ShowText(player, type, doMsgs, "Grinding sounds of stone echo through these odd shadowy halls. The scent of powerful magics fills your nostrils and fires your mind."); } protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC1) == 1 && GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC2) == 1) { ShowText(player, type, doMsgs, "The messages of the two old men prove to be the key to opening this secret wall!"); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); SetWallItem(player, type, doMsgs, PORTAL, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC1) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC2) == 1) { ShowText(player, type, doMsgs, "Hmmm...seems like you're missing part of the ritual. Another may know the second half; then you may find a way through here!"); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This enormous hallway seems to be devoid of any useful purpose. It's as though the walls here are only boundaries of internally hidden rooms."); } protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableAutomaps(player, type, doMsgs); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES, 1); ShowText(player, type, doMsgs, "Magical energy radiates from all around you."); ShowText(player, type, doMsgs, "These mystical teleports project dazzling colors of light that refract and reflect off of each other with blinding beauty."); ShowText(player, type, doMsgs, "Three shafts of pure light pour down from above onto the Rod of Dissemination, restoring its magical properties."); } protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Two small dwellings stand opposite each other in this small room. Strange mumblings are coming from the southern one."); ShowText(player, type, doMsgs, "Northward, however, you can just make out low hissing sounds and snarls."); } protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Deep sorrowful moans surround you in this dingy place."); ShowText(player, type, doMsgs, "Odd shadows flicker and fold in on one another against the walls. The shadows themselves seem alive."); } protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; if (HasItem(player, type, doMsgs, RODOFDISSEMINATION)) { ShowText(player, type, doMsgs, "Stains of combat cover the floor, but there is nothing of interest here... except a few Erebus fiends!"); } else if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.NICEBOOTY) == 0)) { SetTreasure(player, type, doMsgs, RODOFDISSEMINATION, MANAAMPHORA, ZEUSSCROLL, 0, 0, 10000); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.NICEBOOTY, 1); ErebusTxt(player, type, doMsgs); } else { SetTreasure(player, type, doMsgs, RODOFDISSEMINATION, 0, 0, 0, 0, 5000); ErebusTxt(player, type, doMsgs); } switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 25); } AddEncounter(player, type, doMsgs, 5, 26); break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 25); } AddEncounter(player, type, doMsgs, 6, 26); break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 25); } AddEncounter(player, type, doMsgs, 6, 26); break; } } private void ErebusTxt(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A large Erebus Fiend orders his minions to attack you, as he waves a mystical staff about and sends magical flames at you from his fingertips!"); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { int charges = 0; int tilenumber = 0; charges = GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES); ShowText(player, type, doMsgs, "The statue seems to shimmer, yet it is apparently solid."); if (IsFlagOn(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES)) { if (UsedItem(player, type, ref doMsgs, RODOFDISSEMINATION, RODOFDISSEMINATION)) { if (charges < 12) { ShowText(player, type, doMsgs, "You dispel the statue!"); charges++; SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES, charges); if (GetFacing(player, type, doMsgs) == Direction.North) { tilenumber = GetTile(player, type, doMsgs) - 16; } if (GetFacing(player, type, doMsgs) == Direction.East) { tilenumber = GetTile(player, type, doMsgs) + 1; } if (GetFacing(player, type, doMsgs) == Direction.South) { tilenumber = GetTile(player, type, doMsgs) + 16; } if (GetFacing(player, type, doMsgs) == Direction.West) { tilenumber = GetTile(player, type, doMsgs) - 1; } ClearTileBlock(player, type, doMsgs, tilenumber); SetFloorItem(player, type, doMsgs, 0, tilenumber); } else { ShowText(player, type, doMsgs, "The item's powers have faded and pull you back to their source."); TeleportParty(player, type, doMsgs, 12, 1, 72, Direction.North); SetTileBlock(player, type, doMsgs, tilenumber); } } } } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "By dispelling this statue you've released the imprisoned creature! It intends to reward you with death!"); AddEncounter(player, type, doMsgs, 01, 27); } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC1) == 0)) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, NPCONE) == 0)) { ShowPortrait(player, type, doMsgs, KAALROTH); ShowText(player, type, doMsgs, "A sinewy beast stares angrily at you for your intrusion into his home."); ShowText(player, type, doMsgs, "'You have no business here. Leave before I become enraged and destroy you!'"); SetFlag(player, type, doMsgs, FlagTypeParty, NPCONE, 2); } else if (GetFlag(player, type, doMsgs, FlagTypeParty, NPCTWO) == 1 || IsFlagOn(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC2)) { ShowPortrait(player, type, doMsgs, KAALROTH); ShowText(player, type, doMsgs, "'Ahh, you've met my twin, I see."); ShowText(player, type, doMsgs, "Say his chant in time with mine, and at the wall, the ingress shall be thine.'"); ShowText(player, type, doMsgs, "Ieoa then turns away pleased with his 'creativity'%."); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC1, 1); SetFlag(player, type, doMsgs, FlagTypeParty, NPCONE, 2); } } else { ShowText(player, type, doMsgs, "Ieoa has left the dungeon."); } } protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, KAALROTH); if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC2) == 0)) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, NPCTWO) == 0)) { ShowText(player, type, doMsgs, "A sinewy beast stares angrily at you for your intrusion into his home."); ShowText(player, type, doMsgs, "'Away with you, go bother my brother to the west.'"); SetFlag(player, type, doMsgs, FlagTypeParty, NPCTWO, 1); if ((GetFlag(player, type, doMsgs, FlagTypeParty, NPCONE) == 0)) { SetFlag(player, type, doMsgs, FlagTypeParty, NPCONE, 1); } } else if (GetFlag(player, type, doMsgs, FlagTypeParty, NPCONE) == 2) { ShowText(player, type, doMsgs, "'Did you enjoy your talk with Ieoa?"); ShowText(player, type, doMsgs, "My verse shan't be before if you wish to find the door. Seek Ieoa, the twin; with his rhyme you begin.'"); ShowText(player, type, doMsgs, "Aoei then turns away pleased with his 'creativity'%."); SetFlag(player, type, doMsgs, FlagTypeParty, NPCTWO, 1); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TALKED_TO_NPC2, 1); } } else { ShowText(player, type, doMsgs, "Aoei has left the dungeon."); } } protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "You happen across some feuding Kaalroths that dismiss their argument for some tasty combat."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 28); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 28); } break; default: for (i = 1; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 28); } break; } } protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "A warring party of Night Elf Pilgrims drags you into the fray."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 29); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 29); } break; default: for (i = 1; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 29); } break; } } protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "You suddenly feel out matched as a small nest of dragons charges at you!"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; default: for (i = 1; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; } } protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Shimmering moans and shadowy figures surround you!"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 31); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 31); } break; default: for (i = 1; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 31); } break; } } protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A huge Red Dragon sends a barrage of flames towards you!"); if (GetPartyLevel(player, type, doMsgs, 48)) { AddEncounter(player, type, doMsgs, 1, 32); } else if (GetPartyLevel(player, type, doMsgs, 36)) { AddEncounter(player, type, doMsgs, 1, 24); } else { AddEncounter(player, type, doMsgs, 1, 23); } } protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This jeweled teleport will send you to the final confrontation. The Queen awaits."); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.TOTHEQUEEN, 1); TeleportParty(player, type, doMsgs, 12, 2, 255, Direction.West); } protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Perhaps the way out is near!!!"); TeleportParty(player, type, doMsgs, 12, 1, 193, Direction.North); } protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "An arsenal of creatures bars your way here."); switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 1, 25); AddEncounter(player, type, doMsgs, 5, 33); break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 25); } AddEncounter(player, type, doMsgs, 6, 33); break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 28); } AddEncounter(player, type, doMsgs, 6, 33); break; } } protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Servants of Dissemination attack!"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; case 2: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 34); } for (i = 5; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; default: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 34); } break; } } protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The marble statue crumbles away, releasing an ominous beast of power."); AddEncounter(player, type, doMsgs, 01, 35); } protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, WRAITH); ShowText(player, type, doMsgs, "'I am frozen in time here! I tried to use the Portal without the proper knowledge!"); ShowText(player, type, doMsgs, "Learn from me! Do not use the Portal below!'"); } protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) { ShowText(player, type, doMsgs, "You've sprung an ancient trap that seems not to have harmed you...much."); DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1); } } protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) { if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) { if ((GetFlag(player, type, doMsgs, FlagTypeParty, TORCHSWITCH) == 0)) { ShowText(player, type, doMsgs, "A dragon's face is carved on the wall where the torch here hangs. As you walk by the wall it comes to life and spews waves of fire over you!"); DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 5); } else { ShowText(player, type, doMsgs, "The carved dragon on the wall remains silent."); } SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1); } } protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "'You must defeat us to proceed! We are everlasting forces here!'"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 36); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 36); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 36); } break; } } protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This MUST lead out of this level."); TeleportParty(player, type, doMsgs, 12, 1, 152, Direction.East); } protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The end must be near; you can see huge forces of creatures moving about nearby."); ShowText(player, type, doMsgs, "Waste not your charges on futile walls!"); } protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The Guardians here launch a spread of evil magic towards you. The mysterious vapors envelop your body as a ring of opaque fog."); SetDebuff(player, type, doMsgs, POISON, 10, 700); ModAttribute(player, type, doMsgs, DEFENSE, - 1); ModAttribute(player, type, doMsgs, AGILITY, - 1); } protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Creatures surprise you!"); if ((GetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP) == 0)) { DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 6); ModifyGold(player, type, doMsgs, - 2500); SetFlag(player, type, doMsgs, FlagTypeTile, SPRUNGTRAP, 1); } switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 22); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 22); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 22); } break; } } protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "You surprise some beasts examining an interesting sword."); if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.GREATBOOTY) == 0)) { SetTreasure(player, type, doMsgs, PHOSPHORESCENTBLADE, HEALAMPHORA, HEALAMPHORA, BARBARIANAXE, ETHERICVESTMENT, 25000); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.GREATBOOTY, 1); } switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 25); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 22); } break; default: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 24); } break; } } protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, GNOMEWIZARD); ShowText(player, type, doMsgs, "An old hermit squints at you, 'The Portal you seek cannot be entered yet. Your task will end in futility!"); ShowText(player, type, doMsgs, "You must gain in ways before you gain the wisdom.'"); ShowText(player, type, doMsgs, "The rantings of a fool, eh?"); } protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This portal, however, you can enter."); TeleportParty(player, type, doMsgs, 12, 1, 136, Direction.North); } protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "Some young dragons are scrounging for food, they notice you and attempt to make you their meal."); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 2; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; case 2: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; default: for (i = 1; i <= 5; i++) { AddEncounter(player, type, doMsgs, i, 30); } break; } } protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) { int i = 0; ShowText(player, type, doMsgs, "You've happened upon some very unpleasant sorts!"); switch (GetPartyCount(player, type, doMsgs)) { case 1: for (i = 1; i <= 3; i++) { AddEncounter(player, type, doMsgs, i, 3); } break; case 2: for (i = 1; i <= 4; i++) { AddEncounter(player, type, doMsgs, i, 4); } break; default: for (i = 1; i <= 6; i++) { AddEncounter(player, type, doMsgs, i, 6); } break; } } protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) { if (IsFlagOff(player, type, doMsgs, FlagTypeParty, TORCHSWITCH)) { ShowText(player, type, doMsgs, "A lever here is marked DO NOT TOUCH!"); ShowText(player, type, doMsgs, "Using your better judgement, you move the lever."); ShowText(player, type, doMsgs, "You hear clicks and sliding noises of stone on stone echo through nearby corridors."); SetFlag(player, type, doMsgs, FlagTypeParty, TORCHSWITCH, 1); } else { ShowText(player, type, doMsgs, "You decidedly move the switch again, thinking it best not to fiddle with things so well marked."); SetFlag(player, type, doMsgs, FlagTypeParty, TORCHSWITCH, 0); } } protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A glowing teleport stands ready."); TeleportParty(player, type, doMsgs, 12, 1, 237, Direction.South); } protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A glowing teleport stands ready."); TeleportParty(player, type, doMsgs, 12, 1, 0, Direction.West); } protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A glowing teleport stands ready."); TeleportParty(player, type, doMsgs, 12, 1, 144, Direction.North); } protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "A war party of adventurers prepare an offensive."); switch (GetPartyCount(player, type, doMsgs)) { case 1: AddEncounter(player, type, doMsgs, 01, 15); AddEncounter(player, type, doMsgs, 02, 17); AddEncounter(player, type, doMsgs, 06, 16); break; case 2: AddEncounter(player, type, doMsgs, 01, 20); AddEncounter(player, type, doMsgs, 02, 18); AddEncounter(player, type, doMsgs, 03, 19); AddEncounter(player, type, doMsgs, 04, 16); break; default: AddEncounter(player, type, doMsgs, 01, 15); AddEncounter(player, type, doMsgs, 02, 20); AddEncounter(player, type, doMsgs, 03, 17); AddEncounter(player, type, doMsgs, 04, 18); AddEncounter(player, type, doMsgs, 05, 19); AddEncounter(player, type, doMsgs, 06, 16); break; } } protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "It's unusually dim in this room. It appears as though a violent battle has recently taken place;"); ShowText(player, type, doMsgs, "seeing that charred remains litter the floor and scorch marked stone decorates the walls!"); } protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableAutomaps(player, type, doMsgs); } protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, RODOFDISSEMINATION) && (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES) == 0)) { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.ITEMUSES, 1); ShowText(player, type, doMsgs, "The Rod of Dissemination ignites with magical fury! Use it to blaze your own pathway through these magical walls."); } } } }
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Networking; #if ENABLE_IOS_ON_DEMAND_RESOURCES using UnityEngine.iOS; #endif #if UNITY_EDITOR using UnityEditor; #if UNITY_2018_3_OR_NEWER using UnityEditor.SceneManagement; #endif #endif using System.Collections; //added System.IO for loading/saving cached bundleIndexes using System.IO; namespace UMA.AssetBundles { public abstract class AssetBundleLoadOperation : IEnumerator { public object Current { get { return null; } } public bool MoveNext() { return !IsDone(); } public void Reset() { } abstract public bool Update(); abstract public bool IsDone(); } public abstract class AssetBundleDownloadOperation : AssetBundleLoadOperation { bool done; public string assetBundleName { get; private set; } public float downloadProgress { get; protected set; } public LoadedAssetBundle assetBundle { get; protected set; } public string error { get; protected set; } protected AssetBundle bundle; protected AssetBundleLoadDecrypted decryptedLoadOperation = null; protected abstract bool downloadIsDone { get; } protected abstract void FinishDownload(); public override bool Update() { if (!done && downloadIsDone) { FinishDownload(); done = true; } return !done; } public override bool IsDone() { return done; } protected virtual bool WasBundleEncrypted() { if (AssetBundleManager.BundleEncryptionKey != "") { var encryptedAsset = bundle.LoadAsset<UMAEncryptedBundle>("EncryptedData"); if (encryptedAsset) { byte[] decryptedData = new byte[0]; try { decryptedData = EncryptionUtil.Decrypt(encryptedAsset.data, AssetBundleManager.BundleEncryptionKey, encryptedAsset.IV); } catch(System.Exception e) { if (Debug.isDebugBuild) Debug.LogError("[AssetBundleLoadOperation] could not decrypt " + assetBundleName+ "Error message was "+e.Message+" : "+e.StackTrace); return false; } bundle.Unload (true); decryptedLoadOperation = new AssetBundleLoadDecrypted(decryptedData, assetBundleName); return true; } } return false; } public abstract string GetSourceURL(); public AssetBundleDownloadOperation(string assetBundleName) { this.assetBundleName = assetBundleName; } } #if ENABLE_IOS_ON_DEMAND_RESOURCES /// <summary> /// Read asset bundle asynchronously from iOS / tvOS asset catalog that is downloaded // using on demand resources functionality. /// </summary> public class AssetBundleDownloadFromODROperation : AssetBundleDownloadOperation { OnDemandResourcesRequest request; public AssetBundleDownloadFromODROperation(string assetBundleName) : base(assetBundleName) { // Work around Xcode crash when opening Resources tab when a // resource name contains slash character request = OnDemandResources.PreloadAsync(new string[] { assetBundleName.Replace('/', '>') }); } public override bool Update() { if (decryptedLoadOperation != null) { decryptedLoadOperation.Update(); if (decryptedLoadOperation.IsDone()) { assetBundle = decryptedLoadOperation.assetBundle; downloadProgress = 1f; return false; } else //keep updating { downloadProgress = 0.9f + (decryptedLoadOperation.progress / 100); return true; } } else { return base.Update(); } } protected override bool downloadIsDone { get { if (decryptedLoadOperation != null) { return decryptedLoadOperation.assetBundle == null ? false : true; } return (request == null) || request.isDone; } } public override string GetSourceURL() { return "odr://" + assetBundleName; } protected override void FinishDownload() { error = request.error; if (!string.IsNullOrEmpty(error)) return; var path = "res://" + assetBundleName; bundle = AssetBundle.LoadFromFile(path); if (bundle == null) { error = string.Format("Failed to load {0}", path); request.Dispose(); } else { if (!WasBundleEncrypted()) { assetBundle = new LoadedAssetBundle(bundle); // At the time of unload request is already set to null, so capture it to local variable. var localRequest = request; // Dispose of request only when bundle is unloaded to keep the ODR pin alive. assetBundle.unload += () => { localRequest.Dispose(); }; } } request = null; } } #endif #if ENABLE_IOS_APP_SLICING /// <summary> /// Read asset bundle synchronously from an iOS / tvOS asset catalog /// </summary> public class AssetBundleOpenFromAssetCatalogOperation : AssetBundleDownloadOperation { public AssetBundleOpenFromAssetCatalogOperation(string assetBundleName) : base(assetBundleName) { var path = "res://" + assetBundleName; bundle = AssetBundle.LoadFromFile(path); if (bundle == null) error = string.Format("Failed to load {0}", path); else if(!WasBundleEncrypted()) assetBundle = new LoadedAssetBundle(bundle); } public override bool Update() { if (decryptedLoadOperation != null) { decryptedLoadOperation.Update(); if (decryptedLoadOperation.IsDone()) { assetBundle = decryptedLoadOperation.assetBundle; downloadProgress = 1f; return false; } else //keep updating { downloadProgress = 0.9f + (decryptedLoadOperation.progress / 100); return true; } } else { downloadProgress = 1f; return base.Update(); } } protected override bool downloadIsDone { get { if (decryptedLoadOperation != null) { return decryptedLoadOperation.assetBundle == null ? false : true; } return true; } } protected override void FinishDownload() { } public override string GetSourceURL() { return "res://" + assetBundleName; } } #endif public class AssetBundleDownloadFromWebOperation : AssetBundleDownloadOperation { UnityWebRequest m_WWW; string m_Url; int zeroDownload = 0; bool m_isJsonIndex = false; int retryAttempts = 0; int maxRetryAttempts = 5; public AssetBundleDownloadFromWebOperation(string assetBundleName, UnityWebRequest www, bool isJsonIndex = false) : base(assetBundleName) { if (www == null) throw new System.ArgumentNullException("www"); m_Url = www.url; m_isJsonIndex = isJsonIndex; m_WWW = www; } public override bool Update() { if (decryptedLoadOperation != null) { decryptedLoadOperation.Update(); if (decryptedLoadOperation.IsDone()) { assetBundle = decryptedLoadOperation.assetBundle; downloadProgress = 1f; m_WWW.Dispose(); m_WWW = null; return false; } else //keep updating { downloadProgress = 0.9f + (decryptedLoadOperation.progress / 100); return true; } } else { base.Update(); } // TODO: iOS AppSlicing and OnDemandResources will need something like this too // This checks that the download is actually happening and restarts it if it is not //fixes a bug in SimpleWebServer where it would randomly stop working for some reason if (!downloadIsDone) { //We actually need to know if progress has stalled, not just if there is none //so set the progress after we compare //downloadProgress = m_WWW.progress; if (!string.IsNullOrEmpty(m_WWW.error)) { if (Debug.isDebugBuild) Debug.Log("[AssetBundleLoadOperation] download error for "+ m_WWW.url+" : " + m_WWW.error); } else { if(m_WWW.downloadProgress == downloadProgress) { zeroDownload++; } else { downloadProgress = m_WWW.downloadProgress; zeroDownload = 0; } #if UNITY_EDITOR //Sometimes SimpleWebServer randomly looses it port connection //Sometimes restarting the download helps, sometimes it needs to be completely restarted if (SimpleWebServer.Instance != null) { if (zeroDownload == 150) { if (Debug.isDebugBuild) Debug.Log("[AssetBundleLoadOperation] progress was zero for 150 frames restarting dowload"); m_WWW.Dispose();//sometimes makes a difference when the download fails m_WWW = null; #if UNITY_2018_1_OR_NEWER m_WWW = UnityWebRequestAssetBundle.GetAssetBundle(m_Url); #else m_WWW = UnityWebRequest.GetAssetBundle(m_Url); #endif #if UNITY_2017_2_OR_NEWER m_WWW.SendWebRequest(); #else m_WWW.Send(); #endif } if (zeroDownload == 300)//If we are in the editor we can restart the Server and this will make it work { if (Debug.isDebugBuild) Debug.LogWarning("[AssetBundleLoadOperation] progress was zero for 300 frames restarting the server"); //we wont be able to do the following from a build int port = SimpleWebServer.Instance.Port; SimpleWebServer.Start(port); m_WWW.Dispose(); m_WWW = null; #if UNITY_2018_1_OR_NEWER m_WWW = UnityWebRequestAssetBundle.GetAssetBundle(m_Url); #else m_WWW = UnityWebRequest.GetAssetBundle(m_Url); #endif #if UNITY_2017_2_OR_NEWER m_WWW.SendWebRequest(); #else m_WWW.Send(); #endif zeroDownload = 0; } } else #endif if((downloadProgress == 0 && zeroDownload == 500) || zeroDownload >= Mathf.Clamp((2500 * downloadProgress), 500,2500))//let this number get larger the more has been downloaded (cos its really annoying to be at 98% and have it fail) { //when we cannot download because WiFi is connected but a hotspot needs authentication //or because the user has run out of mobile data the www class takes a while error out if ((AssetBundleManager.ConnectionChecker != null && !AssetBundleManager.ConnectionChecker.InternetAvailable) || retryAttempts > maxRetryAttempts) { if (retryAttempts > maxRetryAttempts) { //there was some unknown error with the connection //tell the user we could not complete the download error = "Downloading of " + assetBundleName + " failed after 10 attempts. Something is wrong with the internet connection."; m_WWW.Dispose(); m_WWW = null; } else { //if we have a connection checker and no connection, leave the www alone so it times out on its own if (Debug.isDebugBuild) Debug.Log("[AssetBundleLoadOperation] progress was zero for "+ zeroDownload+" frames and the ConnectionChecker said there was no Internet Available."); } } else { if (Debug.isDebugBuild) Debug.Log("[AssetBundleLoadOperation] progress was zero for " + zeroDownload + " frames restarting dowload"); m_WWW.Dispose(); m_WWW = null; //m_WWW = new WWW(m_Url);//make sure this still caches if (AssetBundleManager.AssetBundleIndexObject != null) #if UNITY_2018_1_OR_NEWER m_WWW = UnityWebRequestAssetBundle.GetAssetBundle(m_Url, AssetBundleManager.AssetBundleIndexObject.GetAssetBundleHash(assetBundleName), 0); #else m_WWW = UnityWebRequest.GetAssetBundle(m_Url, AssetBundleManager.AssetBundleIndexObject.GetAssetBundleHash(assetBundleName), 0); #endif else #if UNITY_2018_1_OR_NEWER m_WWW = UnityWebRequestAssetBundle.GetAssetBundle(m_Url); #else m_WWW = UnityWebRequest.GetAssetBundle(m_Url); #endif //but increment the retry either way so the failed Ui shows sooner retryAttempts++; } zeroDownload = 0; } } return true; } else { if (string.IsNullOrEmpty(error)) downloadProgress = 1f; else downloadProgress = 0; return false; } } protected override bool downloadIsDone { get { if(decryptedLoadOperation != null) { return decryptedLoadOperation.assetBundle == null ? false : true; } return (m_WWW == null) || m_WWW.isDone; } } protected override void FinishDownload() { if(m_WWW != null) error = m_WWW.error; if (!string.IsNullOrEmpty(error)) { if (Debug.isDebugBuild) Debug.LogWarning("[AssetBundleLoadOperation.AssetBundleDownloadFromWebOperation] URL was "+ m_Url + " error was " + error); return; } if (!m_isJsonIndex) { bundle = DownloadHandlerAssetBundle.GetContent(m_WWW); if (bundle == null) { if (Debug.isDebugBuild) Debug.LogWarning("[AssetBundleLoadOperation.AssetBundleDownloadFromWebOperation] "+assetBundleName+" was not a valid assetBundle"); m_WWW.Dispose(); m_WWW = null; } else if (!WasBundleEncrypted()) { assetBundle = new LoadedAssetBundle(bundle); m_WWW.Dispose(); m_WWW = null; } } else { string indexData = m_WWW.downloadHandler.text; if (indexData == "") { if (Debug.isDebugBuild) Debug.LogWarning("[AssetBundleLoadOperation.AssetBundleDownloadFromWebOperation] The JSON AssetBundleIndex was empty"); } else { assetBundle = new LoadedAssetBundle(m_WWW.downloadHandler.text); } m_WWW.Dispose(); m_WWW = null; } } public override string GetSourceURL() { return m_Url; } } /// <summary> /// Loads the bytes of a decrypted asset bundle from memory asynchroniously; /// </summary> public class AssetBundleLoadDecrypted : AssetBundleDownloadOperation { AssetBundleCreateRequest m_Operation = null; public float progress; public AssetBundleLoadDecrypted(byte[] decryptedData, string assetBundleName) : base(assetBundleName) { m_Operation = AssetBundle.LoadFromMemoryAsync(decryptedData); } protected override bool downloadIsDone { get { return true; } } //update needs to return true if more updates are required public override bool Update() { progress = m_Operation.progress; if (progress == 1) { FinishDownload(); return false; } progress = m_Operation.progress; return true; } protected override void FinishDownload() { bundle = m_Operation.assetBundle; if (bundle == null) { if (Debug.isDebugBuild) Debug.LogWarning("[AssetBundleLoadOperation.AssetBundleLoadDecrypted] could not create bundle from decrypted bytes for " + assetBundleName); } else { //Debug.Log("[AssetBundleLoadOperation.AssetBundleLoadEncrypted] " + assetBundleName+" loaded from decrypted bytes successfully"); assetBundle = new LoadedAssetBundle(bundle); } m_Operation = null; } public override bool IsDone() { return m_Operation == null || m_Operation.isDone; } //just inherited junk public override string GetSourceURL() { return ""; } } #if UNITY_EDITOR public class AssetBundleLoadLevelSimulationOperation : AssetBundleLoadOperation { AsyncOperation m_Operation = null; public AssetBundleLoadLevelSimulationOperation(string assetBundleName, string levelName, bool isAdditive) { string[] levelPaths = UnityEditor.AssetDatabase.GetAssetPathsFromAssetBundleAndAssetName(assetBundleName, levelName); if (levelPaths.Length == 0) { ///@TODO: The error needs to differentiate that an asset bundle name doesn't exist // from that the right scene does not exist in the asset bundle... if (Debug.isDebugBuild) Debug.LogError("There is no scene with name \"" + levelName + "\" in " + assetBundleName); return; } if (isAdditive) { #if UNITY_2018_3_OR_NEWER m_Operation = EditorSceneManager.LoadSceneAsyncInPlayMode(levelPaths[0], new LoadSceneParameters(LoadSceneMode.Additive)); #else m_Operation = EditorApplication.LoadLevelAdditiveAsyncInPlayMode(levelPaths[0]); #endif } else { #if UNITY_2018_3_OR_NEWER m_Operation = EditorSceneManager.LoadSceneAsyncInPlayMode(levelPaths[0], new LoadSceneParameters(LoadSceneMode.Single)); #else m_Operation = EditorApplication.LoadLevelAsyncInPlayMode(levelPaths[0]); #endif } } public override bool Update() { return false; } public override bool IsDone() { return m_Operation == null || m_Operation.isDone; } } #endif public class AssetBundleLoadLevelOperation : AssetBundleLoadOperation { protected string m_AssetBundleName; protected string m_LevelName; protected bool m_IsAdditive; protected string m_DownloadingError; protected AsyncOperation m_Request; public AssetBundleLoadLevelOperation(string assetbundleName, string levelName, bool isAdditive) { m_AssetBundleName = assetbundleName; m_LevelName = levelName; m_IsAdditive = isAdditive; } public float Progress { get { float progress = 0; if (m_Request != null) { if (m_Request.isDone) { progress = 1f; } else { //asyncOperation progress shows 99% when the scene is loaded but not activated which is not very helpful since this is what takes the time! progress = Mathf.Clamp01(m_Request.progress / 0.9f); } } return progress; } } public override bool Update() { if (m_Request != null) return false; LoadedAssetBundle loadedBundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError); if (loadedBundle != null) { m_Request = SceneManager.LoadSceneAsync(m_LevelName, m_IsAdditive ? LoadSceneMode.Additive : LoadSceneMode.Single); return false; } else return true; } public override bool IsDone() { // Return if meeting downloading error. // m_DownloadingError might come from the dependency downloading. if (m_Request == null && !string.IsNullOrEmpty(m_DownloadingError)) { if (Debug.isDebugBuild) Debug.LogError(m_DownloadingError); return true; } return m_Request != null && m_Request.isDone; } } public abstract class AssetBundleLoadAssetOperation : AssetBundleLoadOperation { public abstract T GetAsset<T>() where T : UnityEngine.Object; } public class AssetBundleLoadAssetOperationSimulation : AssetBundleLoadAssetOperation { Object m_SimulatedObject; public AssetBundleLoadAssetOperationSimulation(Object simulatedObject) { m_SimulatedObject = simulatedObject; } public override T GetAsset<T>() { return m_SimulatedObject as T; } public override bool Update() { return false; } public override bool IsDone() { return true; } } public class AssetBundleLoadAssetOperationFull : AssetBundleLoadAssetOperation { protected string m_AssetBundleName; protected string m_AssetName; protected string m_DownloadingError; protected System.Type m_Type; protected AssetBundleRequest m_Request = null; public AssetBundleLoadAssetOperationFull(string bundleName, string assetName, System.Type type) { m_AssetBundleName = bundleName; m_AssetName = assetName; m_Type = type; } public override T GetAsset<T>() { if (m_Request != null && m_Request.isDone) return m_Request.asset as T; else return null; } // Returns true if more Update calls are required. public override bool Update() { if (m_Request != null) return false; LoadedAssetBundle loadedBundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError); if (loadedBundle != null) { /// When asset bundle download fails this throws an exception but this should be caught above now m_Request = loadedBundle.m_AssetBundle.LoadAssetAsync(m_AssetName, m_Type); return false; } else { return true; } } public override bool IsDone() { // Return if meeting downloading error. // m_DownloadingError might come from the dependency downloading. if (m_Request == null && !string.IsNullOrEmpty(m_DownloadingError)) { if (Debug.isDebugBuild) Debug.LogError(m_DownloadingError); return true; } return m_Request != null && m_Request.isDone; } } /// <summary> /// Operation for loading the AssetBundleIndex /// </summary> public class AssetBundleLoadIndexOperation : AssetBundleLoadAssetOperationFull { //made protected so descendent class can inherit protected bool _isJsonIndex; public AssetBundleLoadIndexOperation(string bundleName, string assetName, System.Type type, bool isJsonIndex = false) : base(bundleName, assetName, type) { _isJsonIndex = isJsonIndex; } // Returns true if more Update calls are required. public override bool Update() { //base.Update(); if (m_Request == null) { LoadedAssetBundle loadedBundle = AssetBundleManager.GetLoadedAssetBundle(m_AssetBundleName, out m_DownloadingError); if (loadedBundle != null) { if (_isJsonIndex) { AssetBundleManager.AssetBundleIndexObject = ScriptableObject.CreateInstance<AssetBundleIndex>(); JsonUtility.FromJsonOverwrite(loadedBundle.m_data, AssetBundleManager.AssetBundleIndexObject); } else { if (loadedBundle.m_AssetBundle == null) { if (Debug.isDebugBuild) Debug.LogWarning("AssetBundle was null for " + m_AssetBundleName); return false; } m_Request = loadedBundle.m_AssetBundle.LoadAssetAsync<AssetBundleIndex>(m_AssetName); } } } if (m_Request != null && m_Request.isDone) { AssetBundleManager.AssetBundleIndexObject = GetAsset<AssetBundleIndex>(); //If there is an AssetBundleManager.m_ConnectionChecker and it is set to m_ConnectionChecker.UseBundleIndexCaching //cache this so we can use it offline if we need to if(AssetBundleManager.ConnectionChecker != null && AssetBundleManager.ConnectionChecker.UseBundleIndexCaching == true) if (AssetBundleManager.AssetBundleIndexObject != null) { if (Debug.isDebugBuild) Debug.Log("Caching downloaded index with Build version " + AssetBundleManager.AssetBundleIndexObject.bundlesPlayerVersion); var cachedIndexPath = Path.Combine(Application.persistentDataPath, "cachedBundleIndex"); if (!Directory.Exists(cachedIndexPath)) Directory.CreateDirectory(cachedIndexPath); cachedIndexPath = Path.Combine(cachedIndexPath, m_AssetBundleName + ".json"); File.WriteAllText(cachedIndexPath, JsonUtility.ToJson(AssetBundleManager.AssetBundleIndexObject)); } return false; } if (AssetBundleManager.AssetBundleIndexObject != null) { return false; } else { // if there has been an error make this return false //It wont need any more updates and ABM needs to put it in failed downloads if(string.IsNullOrEmpty(m_DownloadingError)) return true; else { return false; } } } } public class AssetBundleLoadCachedIndexOperation : AssetBundleLoadIndexOperation { public AssetBundleLoadCachedIndexOperation(string bundleName, string assetName, System.Type type, bool isJsonIndex = false) : base(bundleName, assetName, type, isJsonIndex) { var cachedIndexPath = Path.Combine(Application.persistentDataPath, "cachedBundleIndex"); if (!Directory.Exists(cachedIndexPath)) Directory.CreateDirectory(cachedIndexPath); cachedIndexPath = Path.Combine(cachedIndexPath, bundleName+".json"); if (File.Exists(cachedIndexPath)) { if (Debug.isDebugBuild) Debug.Log("Cached index found for " + cachedIndexPath); AssetBundleManager.AssetBundleIndexObject = ScriptableObject.CreateInstance<AssetBundleIndex>(); JsonUtility.FromJsonOverwrite(File.ReadAllText(cachedIndexPath), AssetBundleManager.AssetBundleIndexObject); //AssetBundleManager.AssetBundleIndexObject = JsonUtility.FromJson<AssetBundleIndex>(File.ReadAllText(cachedIndexPath)); } else { //we need an error saying no cached index existed m_DownloadingError = "No cached Index existed for bundleName"; } } public override bool Update() { return false; } public override bool IsDone() { return true; } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NLog.Common; using NLog.Conditions; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class FilteringTargetWrapperTests : NLogTestBase { [Fact] public void FilteringTargetWrapperSyncTest1() { var myMockCondition = new MyMockCondition(true); var myTarget = new MyTarget(); var wrapper = new FilteringTargetWrapper { WrappedTarget = myTarget, Condition = myMockCondition, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.Equal(1, myMockCondition.CallCount); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } [Fact] public void FilteringTargetWrapperAsyncTest1() { var myMockCondition = new MyMockCondition(true); var myTarget = new MyAsyncTarget(); var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(1, myTarget.WriteCount); Assert.Equal(1, myMockCondition.CallCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } [Fact] public void FilteringTargetWrapperAsyncWithExceptionTest1() { var myMockCondition = new MyMockCondition(true); var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); Assert.Equal(1, myTarget.WriteCount); Assert.Equal(1, myMockCondition.CallCount); continuationHit.Reset(); lastException = null; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.NotNull(lastException); Assert.IsType<InvalidOperationException>(lastException); Assert.Equal(2, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } [Fact] public void FilteringTargetWrapperSyncTest2() { var myMockCondition = new MyMockCondition(false); var myTarget = new MyTarget(); var wrapper = new FilteringTargetWrapper { WrappedTarget = myTarget, Condition = myMockCondition, }; myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; bool continuationHit = false; AsyncContinuation continuation = ex => { lastException = ex; continuationHit = true; }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.Equal(1, myMockCondition.CallCount); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(1, myMockCondition.CallCount); continuationHit = false; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); Assert.True(continuationHit); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } [Fact] public void FilteringTargetWrapperAsyncTest2() { var myMockCondition = new MyMockCondition(false); var myTarget = new MyAsyncTarget(); var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(1, myMockCondition.CallCount); continuationHit.Reset(); wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } [Fact] public void FilteringTargetWrapperAsyncWithExceptionTest2() { var myMockCondition = new MyMockCondition(false); var myTarget = new MyAsyncTarget { ThrowExceptions = true, }; var wrapper = new FilteringTargetWrapper(myTarget, myMockCondition); myTarget.Initialize(null); wrapper.Initialize(null); var logEvent = new LogEventInfo(); Exception lastException = null; var continuationHit = new ManualResetEvent(false); AsyncContinuation continuation = ex => { lastException = ex; continuationHit.Set(); }; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(1, myMockCondition.CallCount); continuationHit.Reset(); lastException = null; wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation)); continuationHit.WaitOne(); Assert.Null(lastException); Assert.Equal(0, myTarget.WriteCount); Assert.Equal(2, myMockCondition.CallCount); } class MyAsyncTarget : Target { public int WriteCount { get; private set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo logEvent) { WriteCount++; ThreadPool.QueueUserWorkItem( s => { if (ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int WriteCount { get; set; } protected override void Write(LogEventInfo logEvent) { WriteCount++; } } class MyMockCondition : ConditionExpression { private bool result; public int CallCount { get; set; } public MyMockCondition(bool result) { this.result = result; } protected override object EvaluateNode(LogEventInfo context) { CallCount++; return result; } public override string ToString() { return "fake"; } } } }
//----------------------------------------------------------------------- // <copyright file="DataPortalException.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>This exception is returned for any errors occuring</summary> //----------------------------------------------------------------------- using System; #if !NETFX_CORE using System.Security.Permissions; #endif namespace Csla { /// <summary> /// This exception is returned for any errors occurring /// during the server-side DataPortal invocation. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] [Serializable] public class DataPortalException : Exception { /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Text describing the exception.</param> /// <param name="businessObject">The business object /// as it was at the time of the exception.</param> public DataPortalException(string message, object businessObject) : base(message) { _innerStackTrace = String.Empty; _businessObject = businessObject; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message">Text describing the exception.</param> /// <param name="ex">Inner exception.</param> /// <param name="businessObject">The business object /// as it was at the time of the exception.</param> public DataPortalException(string message, Exception ex, object businessObject) : base(message, ex) { _innerStackTrace = ex.StackTrace; _businessObject = businessObject; } /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="message"> /// Exception message. /// </param> /// <param name="ex"> /// Inner exception. /// </param> public DataPortalException(string message, Exception ex) : base(message, ex) { _innerStackTrace = ex.StackTrace; } #if !NETFX_PHONE || PCL46 || PCL259 #if !NETCORE && !PCL46 && !ANDROID && !NETSTANDARD2_0 && !PCL259 /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="info">Info about the exception.</param> public DataPortalException(WcfPortal.WcfErrorInfo info) : base(info.Message) { this.ErrorInfo = new Csla.Server.Hosts.HttpChannel.HttpErrorInfo(info); } #endif /// <summary> /// Creates an instance of the object. /// </summary> /// <param name="info">Info about the exception.</param> public DataPortalException(Csla.Server.Hosts.HttpChannel.HttpErrorInfo info) : base(info.Message) { this.ErrorInfo = info; } /// <summary> /// Gets a string representation /// of this object. /// </summary> public override string ToString() { var sb = new System.Text.StringBuilder(); sb.AppendLine(base.ToString()); if (ErrorInfo != null) { sb.AppendLine("------------------------------"); var error = this.ErrorInfo; while (error != null) { sb.AppendFormat("{0}: {1}", error.ExceptionTypeName, error.Message); sb.Append(Environment.NewLine); sb.Append(error.StackTrace); sb.Append(Environment.NewLine); error = error.InnerError; } } return sb.ToString(); } /// <summary> /// Gets information about the original /// server-side exception. That exception /// is not an exception on the client side, /// but this property returns information /// about the exception. /// </summary> public Csla.Server.Hosts.HttpChannel.HttpErrorInfo ErrorInfo { get; private set; } #endif private object _businessObject; private string _innerStackTrace; /// <summary> /// Returns a reference to the business object /// from the server-side DataPortal. /// </summary> /// <remarks> /// Remember that this object may be in an invalid /// or undefined state. This is the business object /// (and any child objects) as it existed when the /// exception occured on the server. Thus the object /// state may have been altered by the server and /// may no longer reflect data in the database. /// </remarks> public object BusinessObject { get { return _businessObject; } } /// <summary> /// Gets the original server-side exception. /// </summary> /// <returns>An exception object.</returns> /// <remarks> /// When an exception occurs in business code behind /// the data portal, it is wrapped in a /// <see cref="Csla.Server.DataPortalException"/>, which /// is then wrapped in a /// <see cref="Csla.DataPortalException"/>. This property /// unwraps and returns the original exception /// thrown by the business code on the server. /// </remarks> public Exception BusinessException { get { var result = this.InnerException; if (result != null) result = result.InnerException; if (result is DataPortalException dpe && dpe.InnerException != null) result = dpe.InnerException; if (result is Csla.Reflection.CallMethodException cme && cme.InnerException != null) result = cme.InnerException; return result; } } /// <summary> /// Get the combined stack trace from the server /// and client. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")] public override string StackTrace { get { return String.Format("{0}{1}{2}", _innerStackTrace, Environment.NewLine, base.StackTrace); } } #if !(ANDROID || IOS) && !NETFX_CORE && !NETSTANDARD2_0 /// <summary> /// Creates an instance of the object for serialization. /// </summary> /// <param name="info">Serialiation info object.</param> /// <param name="context">Serialization context object.</param> protected DataPortalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _businessObject = info.GetValue("_businessObject", typeof(object)); _innerStackTrace = info.GetString("_innerStackTrace"); } /// <summary> /// Serializes the object. /// </summary> /// <param name="info">Serialiation info object.</param> /// <param name="context">Serialization context object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("_businessObject", _businessObject); info.AddValue("_innerStackTrace", _innerStackTrace); } #endif } }
using System; using System.IO; using Rhino.Queues.Model; using Rhino.Queues.Storage; using Xunit; namespace Rhino.Queues.Tests.Storage { using System.Linq; public class CanUseQueue { public CanUseQueue() { if (Directory.Exists("test.esent")) Directory.Delete("test.esent", true); } [Fact] public void CanCreateNewQueueFactory() { using (var qf = CreateQueueStorage()) { qf.Initialize(); } } [Fact] public void CanRegisterReceivedMessageIds() { using (var qf = CreateQueueStorage()) { qf.Initialize(); var random = MessageId.GenerateRandom(); qf.Global(actions => { actions.MarkReceived(random); actions.Commit(); }); qf.Global(actions => { Assert.True(actions.GetAlreadyReceivedMessageIds().Contains(random)); actions.Commit(); }); } } [Fact] public void CanDeleteOldEntries() { using (var qf = CreateQueueStorage()) { qf.Initialize(); var random = MessageId.GenerateRandom(); qf.Global(actions => { for (int i = 0; i < 5; i++) { actions.MarkReceived(MessageId.GenerateRandom()); } actions.MarkReceived(random); for (int i = 0; i < 5; i++) { actions.MarkReceived(MessageId.GenerateRandom()); } actions.Commit(); }); qf.Global(actions => { actions.DeleteOldestReceivedMessageIds(6, 10).ToArray();//consume & activate actions.Commit(); }); qf.Global(actions => { var array = actions.GetAlreadyReceivedMessageIds().ToArray(); Assert.Equal(6, array.Length); Assert.Equal(random, array[0]); actions.Commit(); }); } } [Fact] public void CallingDeleteOldEntriesIsSafeIfThereAreNotEnoughEntries() { using (var qf = CreateQueueStorage()) { qf.Initialize(); var random = MessageId.GenerateRandom(); qf.Global(actions => { for (int i = 0; i < 5; i++) { actions.MarkReceived(MessageId.GenerateRandom()); } actions.MarkReceived(random); actions.Commit(); }); qf.Global(actions => { actions.DeleteOldestReceivedMessageIds(10, 10).ToArray();//consume & activate actions.Commit(); }); qf.Global(actions => { var array = actions.GetAlreadyReceivedMessageIds().ToArray(); Assert.Equal(6, array.Length); Assert.Equal(random, array[5]); actions.Commit(); }); } } [Fact] public void CanPutSingleMessageInQueue() { using (var qf = CreateQueueStorage()) { qf.Initialize(); qf.Global(actions => { actions.CreateQueueIfDoesNotExists("h"); actions.Commit(); }); MessageBookmark bookmark = null; var guid = Guid.NewGuid(); var identifier = Guid.NewGuid(); qf.Global(actions => { bookmark = actions.GetQueue("h").Enqueue(new Message { Queue = "h", Data = new byte[] { 13, 12, 43, 5 }, SentAt = new DateTime(2004, 5, 5), Id = new MessageId { SourceInstanceId = guid, MessageIdentifier = identifier } }); actions.Commit(); }); qf.Global(actions => { actions.GetQueue("h").SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); actions.Commit(); }); qf.Global(actions => { var message = actions.GetQueue("h").Dequeue(null); Assert.Equal(new byte[] { 13, 12, 43, 5 }, message.Data); Assert.Equal(identifier, message.Id.MessageIdentifier); Assert.Equal(guid, message.Id.SourceInstanceId); Assert.Equal("h", message.Queue); Assert.Equal(new DateTime(2004, 5, 5), message.SentAt); actions.Commit(); }); } } [Fact] public void WillGetMessagesBackInOrder() { using (var qf = CreateQueueStorage()) { qf.Initialize(); qf.Global(actions => { actions.CreateQueueIfDoesNotExists("h"); actions.Commit(); }); qf.Global(actions => { var queue = actions.GetQueue("h"); var bookmark = queue.Enqueue(new Message { Queue = "h", Id = MessageId.GenerateRandom(), Data = new byte[] { 1 }, }); queue.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); bookmark = queue.Enqueue(new Message { Queue = "h", Id = MessageId.GenerateRandom(), Data = new byte[] { 2 }, }); queue.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); bookmark = queue.Enqueue(new Message { Queue = "h", Id = MessageId.GenerateRandom(), Data = new byte[] { 3 }, }); queue.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); actions.Commit(); }); qf.Global(actions => { var m1 = actions.GetQueue("h").Dequeue(null); var m2 = actions.GetQueue("h").Dequeue(null); var m3 = actions.GetQueue("h").Dequeue(null); Assert.Equal(new byte[] { 1 }, m1.Data); Assert.Equal(new byte[] { 2 }, m2.Data); Assert.Equal(new byte[] { 3 }, m3.Data); actions.Commit(); }); } } [Fact] public void WillNotGiveMessageToTwoClient() { using (var qf = CreateQueueStorage()) { qf.Initialize(); qf.Global(actions => { actions.CreateQueueIfDoesNotExists("h"); actions.Commit(); }); qf.Global(actions => { var queue = actions.GetQueue("h"); var bookmark = queue.Enqueue(new Message { Queue = "h", Id = MessageId.GenerateRandom(), Data = new byte[] { 1 }, }); queue.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); bookmark = queue.Enqueue(new Message { Queue = "h", Id = MessageId.GenerateRandom(), Data = new byte[] { 2 }, }); queue.SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); actions.Commit(); }); qf.Global(actions => { var m1 = actions.GetQueue("h").Dequeue(null); qf.Global(queuesActions => { var m2 = queuesActions.GetQueue("h").Dequeue(null); Assert.Equal(new byte[] { 2 }, m2.Data); queuesActions.Commit(); }); Assert.Equal(new byte[] { 1 }, m1.Data); actions.Commit(); }); } } [Fact] public void WillGiveNullWhenNoItemsAreInQueue() { using (var qf = CreateQueueStorage()) { qf.Initialize(); qf.Global(actions => { actions.CreateQueueIfDoesNotExists("h"); actions.Commit(); }); qf.Global(actions => { var message = actions.GetQueue("h").Dequeue(null); Assert.Null(message); actions.Commit(); }); } } private static QueueStorage CreateQueueStorage() { return new QueueStorage("test.esent", new QueueManagerConfiguration()); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xrm.Sdk; #if DLAB_UNROOT_NAMESPACE || DLAB_XRM using DLaB.Xrm.Exceptions; namespace DLaB.Xrm.Plugin #else using Source.DLaB.Xrm.Exceptions; namespace Source.DLaB.Xrm.Plugin #endif { /// <summary> /// Extension Class for Plugins /// </summary> #if !DLAB_XRM_DEBUG [DebuggerNonUserCode] #endif public static class Extensions { #region List<RegisteredEvent> #region AddEvent /// <summary> /// Defaults the execute method to be InternalExecute and run against all entities. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="message"></param> public static void AddEvent(this List<RegisteredEvent> events, PipelineStage stage, MessageType message) { events.AddEvent(stage, null, message, null); } /// <summary> /// Runs against all entities. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="message"></param> /// <param name="execute"></param> public static void AddEvent(this List<RegisteredEvent> events, PipelineStage stage, MessageType message, Action<IExtendedPluginContext> execute) { events.AddEvent(stage, null, message, execute); } /// <summary> /// Defaults the execute method to be InternalExecute and runs against the specified entity. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="entityLogicalName"></param> /// <param name="message"></param> public static void AddEvent(this List<RegisteredEvent> events, PipelineStage stage, string entityLogicalName, MessageType message) { events.AddEvent(stage, entityLogicalName, message, null); } /// <summary> /// Runs against the specified entity /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="entityLogicalName"></param> /// <param name="message"></param> /// <param name="execute"></param> public static void AddEvent(this List<RegisteredEvent> events, PipelineStage stage, string entityLogicalName, MessageType message, Action<IExtendedPluginContext> execute){ events.Add(new RegisteredEvent(stage, message, execute, entityLogicalName)); } #endregion AddEvent #region AddEvents /// <summary> /// Defaults the execute method to be InternalExecute and run against all entities. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="messages"></param> public static void AddEvents(this List<RegisteredEvent> events, PipelineStage stage, params MessageType[] messages) { events.AddEvents(stage, null, null, messages); } /// <summary> /// Defaults the execute method to be InternalExecute and runs against the specified entity. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="messages"></param> /// <param name="entityLogicalName"></param> public static void AddEvents(this List<RegisteredEvent> events, PipelineStage stage, string entityLogicalName, params MessageType[] messages) { events.AddEvents(stage, entityLogicalName, null, messages); } /// <summary> /// Runs against all entities. /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="messages"></param> /// <param name="execute"></param> public static void AddEvents(this List<RegisteredEvent> events, PipelineStage stage, Action<IExtendedPluginContext> execute, params MessageType[] messages) { events.AddEvents(stage, null, execute, messages); } /// <summary> /// Runs against the specified entity /// </summary> /// <param name="events"></param> /// <param name="stage"></param> /// <param name="entityLogicalName"></param> /// <param name="execute"></param> /// <param name="messages"></param> public static void AddEvents(this List<RegisteredEvent> events, PipelineStage stage, string entityLogicalName, Action<IExtendedPluginContext> execute, params MessageType[] messages) { foreach (var message in messages) { events.Add(new RegisteredEvent(stage, message, execute, entityLogicalName)); } } #endregion AddEvent #endregion List<RegisteredEvent> #region IExtendedPluginContext #region GetContextInfo /// <summary> /// Gets the context information. /// </summary> /// <returns></returns> public static string GetContextInfo(this IExtendedPluginContext context) { return "**** Context Info ****" + Environment.NewLine + "Plugin: " + context.PluginTypeName + Environment.NewLine + "* Registered Event *" + Environment.NewLine + context.Event.ToString(" ") + Environment.NewLine + context.ToStringDebug(); } #endregion GetContextInfo /// <summary> /// Determines whether a shared variable exists that specifies that the plugin or the plugin and specific message type should be prevented from executing. /// This is used in conjunction with PreventPluginExecution /// </summary> /// <returns></returns> public static bool HasPluginExecutionBeenPrevented(this IExtendedPluginContext context) { return context.HasPluginExecutionBeenPreventedInternal(context.Event, GetPreventPluginSharedVariableName(context.PluginTypeName)); } /// <summary> /// Cast the Target to the given Entity Type T. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T GetTarget<T>(this IExtendedPluginContext context) where T : Entity { // Obtain the target business entity from the input parmameters. try { return ((IPluginExecutionContext)context).GetTarget<T>(); } catch (Exception ex) { context.LogException(ex); } return null; } #endregion IExtendedPluginContext #region IPluginExecutionContext #region AssertEntityImageAttributesExist /// <summary> /// Checks the Pre/Post Entity Images to determine if the image collections contains an image with the given key, that contains the attributes. /// Throws an exception if the image name is contained in both the Pre and Post Image. /// </summary> /// <param name="context">The context.</param> /// <param name="imageName">Name of the image.</param> /// <param name="attributeNames">The attribute names.</param> public static void AssertEntityImageAttributesExist(this IPluginExecutionContext context, string imageName, params string[] attributeNames) { AssertEntityImageRegistered(context, imageName); var imageCollection = context.PreEntityImages.TryGetValue(imageName, out Entity preImage) ? InvalidPluginStepRegistrationException.ImageCollection.Pre : InvalidPluginStepRegistrationException.ImageCollection.Post; context.PostEntityImages.TryGetValue(imageName, out Entity postImage); var image = preImage ?? postImage; var missingAttributes = attributeNames.Where(attribute => !image.Contains(attribute)).ToList(); if (missingAttributes.Any()) { throw InvalidPluginStepRegistrationException.ImageMissingRequiredAttributes(imageCollection, imageName, missingAttributes); } } #endregion AssertEntityImageAttributesExist #region AssertEntityImageRegistered /// <summary> /// Checks the Pre/Post Entity Images to determine if the the collection contains an image with the given key. /// Throws an exception if the image name is contained in both the Pre and Post Image. /// </summary> /// <param name="context">The context.</param> /// <param name="imageName">Name of the image.</param> public static void AssertEntityImageRegistered(this IPluginExecutionContext context, string imageName) { var pre = context.PreEntityImages.ContainsKey(imageName); var post = context.PostEntityImages.ContainsKey(imageName); if (pre && post) { throw new Exception($"Both Preimage and Post Image Contain the Image \"{imageName}\". Unable to determine what entity collection to search for the given attributes."); } if (!pre && !post) { throw InvalidPluginStepRegistrationException.ImageMissing(imageName); } } #endregion AssertEntityImageRegistered #region CalledFrom /// <summary> /// Returns true if the current plugin maps to the Registered Event, or the current plugin has been triggered by the given registered event /// </summary> /// <param name="context">The context.</param> /// <param name="event">The event.</param> /// <returns></returns> public static bool CalledFrom(this IPluginExecutionContext context, RegisteredEvent @event) { return context.GetContexts().Any(c => c.MessageName == @event.MessageName && c.PrimaryEntityName == @event.EntityLogicalName && c.Stage == (int)@event.Stage); } /// <summary> /// Returns true if the current plugin maps to the parameters given, or the current plugin has been triggered by the given parameters /// </summary> /// <returns></returns> public static bool CalledFrom(this IPluginExecutionContext context, string entityLogicalName = null, MessageType message = null, int? stage = null) { if (message == null && entityLogicalName == null && stage == null) { throw new Exception("At least one parameter for IPluginExecutionContext.CalledFrom must be populated"); } return context.GetContexts().Any(c => (message == null || c.MessageName == message.Name) && (entityLogicalName == null || c.PrimaryEntityName == entityLogicalName) && (stage == null || c.Stage == stage.Value)); } #endregion CalledFrom #region CoalesceTarget /// <summary> /// Creates a new Entity of type T, adding the attributes from both the Target and the Post Image if they exist. /// If imageName is null, the first non-null image found is used. /// Does not return null. /// Does not return a reference to Target /// </summary> /// <param name="context">The context</param> /// <param name="imageName">Name of the image.</param> /// <returns></returns> public static T CoalesceTargetWithPreEntity<T>(this IPluginExecutionContext context, string imageName = null) where T : Entity { return DereferenceTarget<T>(context).CoalesceEntity(context.GetPreEntity<T>(imageName)); } /// <summary> /// Creates a new Entity of type T, adding the attributes from both the Target and the Post Image if they exist. /// If imageName is null, the first non-null image found is used. /// Does not return null. /// Does not return a reference to Target /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="imageName">Name of the image.</param> /// <returns></returns> public static T CoalesceTargetWithPostEntity<T>(this IPluginExecutionContext context, string imageName = null) where T : Entity { return DereferenceTarget<T>(context).CoalesceEntity(context.GetPostEntity<T>(imageName)); } #endregion CoalesceTarget #region GetContexts /// <summary> /// The current PluginExecutionContext and the parent context hierarchy of the plugin. /// </summary> public static IEnumerable<IPluginExecutionContext> GetContexts(this IPluginExecutionContext context) { yield return context; foreach (var parent in context.GetParentContexts()) { yield return parent; } } /// <summary> /// Iterates through all parent contexts. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static IEnumerable<IPluginExecutionContext> GetParentContexts(this IPluginExecutionContext context) { var parent = context.ParentContext; while (parent != null) { yield return parent; parent = parent.ParentContext; } } #endregion GetContexts /// <summary> /// Gets the event by iterating over all of the expected registered events to ensure that the plugin has been invoked by an expected event. /// For any given plug-in event at an instance in time, we would expect at most 1 result to match. /// </summary> /// <param name="context">The context.</param> /// <param name="events">The events.</param> /// <returns></returns> public static RegisteredEvent GetEvent(this IPluginExecutionContext context, IEnumerable<RegisteredEvent> events) { return events.Where( e => (int) e.Stage == context.Stage && (e.MessageName == context.MessageName || e.Message == RegisteredEvent.Any) && (string.IsNullOrWhiteSpace(e.EntityLogicalName) || e.EntityLogicalName == context.PrimaryEntityName)) .OrderBy(e => e.MessageName == RegisteredEvent.Any) // Favor the specific message match first .FirstOrDefault(); } #region GetFirstSharedVariable /// <summary> /// Gets the variable value from the PluginExecutionContext.SharedVariables or anywhere in the Plugin Context Hierarchy collection, cast to type 'T', or default(T) if the collection doesn't contain a variable with the given name. /// </summary> /// <typeparam name="T">Type of the variable to be returned</typeparam> /// <param name="context"></param> /// <param name="variableName"></param> /// <returns></returns> public static T GetFirstSharedVariable<T>(this IPluginExecutionContext context, string variableName) { while (context != null) { if (context.SharedVariables.ContainsKey(variableName)) { return context.SharedVariables.GetParameterValue<T>(variableName); } context = context.ParentContext; } return default(T); } /// <summary> /// Gets the variable value from the PluginExecutionContext.SharedVariables or anywhere in the Plugin Context Hierarchy collection, or null if the collection doesn't contain a variable with the given name. /// </summary> /// <param name="context"></param> /// <param name="variableName"></param> /// <returns></returns> public static object GetFirstSharedVariable(this IPluginExecutionContext context, string variableName) { while (context != null) { if (context.SharedVariables.ContainsKey(variableName)) { return context.SharedVariables.GetParameterValue(variableName); } context = context.ParentContext; } return null; } #endregion GetFirstSharedVariable /// <summary> /// Gets the type of the message. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static MessageType GetMessageType(this IPluginExecutionContext context) { return new MessageType(context.MessageName); } #region Get(Pre/Post)Entities /// <summary> /// If the imageName is populated and the PreEntityImages contains the given imageName Key, the Value is cast to the Entity type T, else null is returned /// If the imageName is not populated, than the first image in PreEntityImages with a value, is cast to the Entity type T, else null is returned /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <param name="imageName"></param> /// <returns></returns> public static T GetPreEntity<T>(this IExecutionContext context, string imageName = null) where T : Entity { return context.PreEntityImages.GetEntity<T>(imageName, DLaBExtendedPluginContextBase.PluginImageNames.PreImage); } /// <summary> /// If the imageName is populated and the PostEntityImages contains the given imageName Key, the Value is cast to the Entity type T, else null is returned /// If the imageName is not populated, than the first image in PostEntityImages with a value, is cast to the Entity type T, else null is returned /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context"></param> /// <param name="imageName"></param> /// <returns></returns> public static T GetPostEntity<T>(this IExecutionContext context, string imageName = null) where T : Entity { return context.PostEntityImages.GetEntity<T>(imageName, DLaBExtendedPluginContextBase.PluginImageNames.PostImage); } #endregion Get(Pre/Post)Entities /// <summary> /// Gets the pipeline stage. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static PipelineStage GetPipelineStage(this IPluginExecutionContext context) { return (PipelineStage)context.Stage; } #region GetTarget /// <summary> /// Dereferences the target so an update to it will not cause an update to the actual target and result in a crm update post plugin execution /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <returns></returns> private static T DereferenceTarget<T>(IPluginExecutionContext context) where T : Entity { var target = context.GetTarget<T>(); return target?.Clone() ?? Activator.CreateInstance<T>(); } /// <summary> /// Cast the Target to the given Entity Type T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <returns></returns> public static T GetTarget<T>(this IPluginExecutionContext context) where T : Entity { var parameters = context.InputParameters; if (!parameters.ContainsKey(ParameterName.Target) || !(parameters[ParameterName.Target] is Entity)) { return null; } // Obtain the target business entity from the input parmameters. return ((Entity)parameters[ParameterName.Target]).AsEntity<T>(); } /// <summary> /// Finds and returns the Target as an Entity Reference (Delete Plugins) /// </summary> /// <returns></returns> public static EntityReference GetTargetEntityReference(this IPluginExecutionContext context) { EntityReference entity = null; var parameters = context.InputParameters; if (parameters.ContainsKey(ParameterName.Target) && parameters[ParameterName.Target] is EntityReference) { entity = (EntityReference)parameters[ParameterName.Target]; } return entity; } #endregion GetTarget #region Prevent Plugin Execution #region PreventPluginExecution /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <param name="context">The context.</param> /// <param name="pluginTypeFullName">The Full Type Name of the Plugin to Prevent</param> /// <param name="messageType">Type of the message.</param> public static void PreventPluginExecution(this IPluginExecutionContext context, string pluginTypeFullName, MessageType messageType) { context.PreventPluginExecution(pluginTypeFullName, messageType.Name); } /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <param name="context">The context.</param> /// <param name="pluginTypeFullName">The Full Type Name of the Plugin to Prevent</param> /// <param name="event">Type of the event.</param> /// <exception cref="ArgumentNullException"></exception> public static void PreventPluginExecution(this IPluginExecutionContext context, string pluginTypeFullName, RegisteredEvent @event) { if (@event == null) throw new ArgumentNullException(nameof(@event)); context.PreventPluginExecution(pluginTypeFullName, @event.MessageName, @event.EntityLogicalName, @event.Stage); } /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <param name="context">The context.</param> /// <param name="pluginTypeFullName">The Full Type Name of the Plugin to Prevent</param> /// <param name="messageName">Name of the message.</param> /// <param name="logicalName">Name of the logical.</param> /// <param name="stage">The stage.</param> public static void PreventPluginExecution(this IPluginExecutionContext context, string pluginTypeFullName, string messageName = null, string logicalName = null, PipelineStage? stage = null) { var preventionName = GetPreventPluginSharedVariableName(pluginTypeFullName); if (!context.SharedVariables.TryGetValue(preventionName, out object value)) { value = new Entity(); context.SharedVariables.Add(preventionName, value); } // Wish I could use a Hash<T> here, but CRM won't serialize it. I'll Hack the Entity Object for now var hash = ((Entity)value).Attributes; var rule = GetPreventionRule(messageName, logicalName, stage); if (!hash.Contains(rule)) { hash.Add(rule, null); } } #endregion PreventPluginExecution #region PreventPluginExecution<T> /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <typeparam name="T">The type of the plugin.</typeparam> /// <param name="context">The context.</param> /// <param name="messageType">Type of the message.</param> public static void PreventPluginExecution<T>(this IPluginExecutionContext context, MessageType messageType) where T : IRegisteredEventsPlugin { context.PreventPluginExecution<T>(messageType.Name); } /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <typeparam name="T">The type of the plugin.</typeparam> /// <param name="context">The context.</param> /// <param name="event">Type of the event.</param> public static void PreventPluginExecution<T>(this IPluginExecutionContext context, RegisteredEvent @event) where T : IRegisteredEventsPlugin { context.PreventPluginExecution(typeof(T).FullName, @event); } /// <summary> /// Adds a shared Variable to the context that is checked by the GenericPluginBase to determine if it should be skipped * NOTE * The Plugin has to finish executing for the Shared Variable to be passed to a new plugin /// </summary> /// <typeparam name="T">The type of the plugin.</typeparam> public static void PreventPluginExecution<T>(this IPluginExecutionContext context, string messageName = null, string logicalName = null, PipelineStage? stage = null) where T : IRegisteredEventsPlugin { context.PreventPluginExecution(typeof(T).FullName, messageName, logicalName, stage); } #endregion PreventPluginExecution<T> private static string GetPreventionRule(string messageName = null, string logicalName = null, PipelineStage? stage = null) { var rule = messageName == null ? string.Empty : "MessageName:" + messageName + "|"; rule += logicalName == null ? string.Empty : "LogicalName:" + logicalName + "|"; rule += stage == null ? string.Empty : "Stage:" + stage + "|"; return rule; } private static string GetPreventPluginSharedVariableName(string pluginTypeName) { return pluginTypeName + "PreventExecution"; } #region HasPluginExecutionBeenPrevented /// <summary> /// Determines whether a shared variable exists that specifies that the plugin or the plugin and specifc message type should be prevented from executing. /// This is used in conjunction with PreventPluginExecution /// </summary> /// <typeparam name="T">The type of the plugin.</typeparam> /// <returns></returns> public static bool HasPluginExecutionBeenPrevented<T>(this IPluginExecutionContext context, RegisteredEvent @event) where T : IRegisteredEventsPlugin { var preventionName = GetPreventPluginSharedVariableName(typeof(T).FullName); return context.HasPluginExecutionBeenPreventedInternal(@event, preventionName); } private static bool HasPluginExecutionBeenPreventedInternal(this IPluginExecutionContext context, RegisteredEvent @event, string preventionName) { var value = context.GetFirstSharedVariable(preventionName); if (value == null) { return false; } var hash = ((Entity)value).Attributes; return hash.Contains(string.Empty) || hash.Contains(GetPreventionRule(@event.MessageName)) || hash.Contains(GetPreventionRule(@event.MessageName, @event.EntityLogicalName)) || hash.Contains(GetPreventionRule(@event.MessageName, stage: @event.Stage)) || hash.Contains(GetPreventionRule(@event.MessageName, @event.EntityLogicalName, @event.Stage)) || hash.Contains(GetPreventionRule(logicalName: @event.EntityLogicalName)) || hash.Contains(GetPreventionRule(logicalName: @event.EntityLogicalName, stage: @event.Stage)) || hash.Contains(GetPreventionRule(stage: @event.Stage)); } #endregion HasPluginExecutionBeenPrevented #endregion Prevent Plugin Execution #endregion IPluginExecutionContext } }
using System; using CocosSharp; using Random = CocosSharp.CCRandom; namespace tests { public class EaseSpriteDemo : TestNavigationLayer { protected CCSprite m_grossini; protected CCSprite m_kathia; protected String m_strTitle; protected CCSprite m_tamara; public override string Title { get { return "No title"; } } public EaseSpriteDemo () : base () { m_grossini = new CCSprite(TestResource.s_pPathGrossini); m_tamara = new CCSprite(TestResource.s_pPathSister1); m_kathia = new CCSprite(TestResource.s_pPathSister2); AddChild(m_grossini, 3); AddChild(m_kathia, 2); AddChild(m_tamara, 1); } public override void OnEnter() { base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size; float spirteHalfWidth = m_grossini.ContentSize.Width / 2.0f; m_grossini.Position = new CCPoint(spirteHalfWidth + 10.0f, windowSize.Height * 0.3f); m_kathia.Position = new CCPoint(spirteHalfWidth + 10.0f, windowSize.Height * 0.6f); m_tamara.Position = new CCPoint(spirteHalfWidth + 10.0f, windowSize.Height * 0.9f); } public override void RestartCallback(object sender) { CCScene s = new EaseActionsTestScene(); s.AddChild(EaseTest.restartEaseAction()); Director.ReplaceScene(s); } public override void NextCallback(object sender) { CCScene s = new EaseActionsTestScene(); s.AddChild(EaseTest.nextEaseAction()); Director.ReplaceScene(s); } public override void BackCallback(object sender) { CCScene s = new EaseActionsTestScene(); s.AddChild(EaseTest.backEaseAction()); Director.ReplaceScene(s); } public void PositionForTwo() { m_grossini.Position = new CCPoint(60, 120); m_tamara.Position = new CCPoint(60, 220); m_kathia.Visible = false; } } public class SpriteEase : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var size = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy(3, new CCPoint(size.Width - 130, 0)); var move_back = (CCFiniteTimeAction) move.Reverse(); var move_ease_in = new CCEaseIn(move, 2.5f); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseOut(move, 2.5f); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime(0.25f); var seq1 = new CCSequence(move, delay, move_back, delay) { Tag = 1 }; var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay) { Tag = 1 }; var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay) { Tag = 1 }; m_grossini.RepeatForever (seq1); m_tamara.RepeatForever (seq2); m_kathia.RepeatForever (seq3); Schedule(testStopAction, 6.25f); } public override string Title { get { return "EaseIn - EaseOut - Stop"; } } public void testStopAction(float dt) { Unschedule(testStopAction); m_kathia.StopAction(1); m_tamara.StopAction(1); m_grossini.StopAction(1); } } public class SpriteEaseInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var size = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(size.Width - 130, 0)); var move_ease_inout1 = new CCEaseInOut(move, 0.65f); var move_ease_inout_back1 = move_ease_inout1.Reverse(); var move_ease_inout2 = new CCEaseInOut(move, 1.35f); var move_ease_inout_back2 = move_ease_inout2.Reverse(); var move_ease_inout3 = new CCEaseInOut(move, 1.0f); var move_ease_inout_back3 = move_ease_inout3.Reverse() as CCFiniteTimeAction; var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move_ease_inout1, delay, move_ease_inout_back1, delay); var seq2 = new CCSequence(move_ease_inout2, delay, move_ease_inout_back2, delay); var seq3 = new CCSequence(move_ease_inout3, delay, move_ease_inout_back3, delay); m_tamara.RunAction(new CCRepeatForever ((CCFiniteTimeAction)seq1)); m_kathia.RunAction(new CCRepeatForever ((CCFiniteTimeAction)seq2)); m_grossini.RunAction(new CCRepeatForever ((CCFiniteTimeAction)seq3)); } public override string Title { get { return "EaseInOut and rates"; } } } public class SpriteEaseExponential : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease_in = new CCEaseExponentialIn(move); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseExponentialOut(move); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay); var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); m_kathia.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "ExpIn - ExpOut actions"; } } } public class SpriteEaseExponentialInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease = new CCEaseExponentialInOut(move); var move_ease_back = move_ease.Reverse(); //-. reverse() var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease, delay, move_ease_back, delay); PositionForTwo(); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); } public override string Title { get { return "EaseExponentialInOut action"; } } } public class SpriteEaseSine : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease_in = new CCEaseSineIn(move); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseSineOut(move); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay); var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); m_kathia.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "EaseSineIn - EaseSineOut"; } } } public class SpriteEaseSineInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease = new CCEaseSineInOut(move); var move_ease_back = move_ease.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease, delay, move_ease_back, delay); PositionForTwo(); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); } public override string Title { get { return "EaseSineInOut action"; } } } public class SpriteEaseElastic : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease_in = new CCEaseElasticIn(move); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseElasticOut(move); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay); var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); m_kathia.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "Elastic In - Out actions"; } } } public class SpriteEaseElasticInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_ease_inout1 = new CCEaseElasticInOut(move, 0.3f); var move_ease_inout_back1 = move_ease_inout1.Reverse(); var move_ease_inout2 = new CCEaseElasticInOut(move, 0.45f); var move_ease_inout_back2 = move_ease_inout2.Reverse(); var move_ease_inout3 = new CCEaseElasticInOut(move, 0.6f); var move_ease_inout_back3 = move_ease_inout3.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move_ease_inout1, delay, move_ease_inout_back1, delay); var seq2 = new CCSequence(move_ease_inout2, delay, move_ease_inout_back2, delay); var seq3 = new CCSequence(move_ease_inout3, delay, move_ease_inout_back3, delay); m_tamara.RunAction(new CCRepeatForever (seq1)); m_kathia.RunAction(new CCRepeatForever (seq2)); m_grossini.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "EaseElasticInOut action"; } } } public class SpriteEaseBounce : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease_in = new CCEaseBounceIn(move); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseBounceOut(move); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay); var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); m_kathia.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "Bounce In - Out actions"; } } } public class SpriteEaseBounceInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease = new CCEaseBounceInOut(move); var move_ease_back = move_ease.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease, delay, move_ease_back, delay); PositionForTwo(); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); } public override string Title { get { return "EaseBounceInOut action"; } } } public class SpriteEaseBack : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease_in = new CCEaseBackIn(move); var move_ease_in_back = move_ease_in.Reverse(); var move_ease_out = new CCEaseBackOut(move); var move_ease_out_back = move_ease_out.Reverse(); var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease_in, delay, move_ease_in_back, delay); var seq3 = new CCSequence(move_ease_out, delay, move_ease_out_back, delay); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); m_kathia.RunAction(new CCRepeatForever (seq3)); } public override string Title { get { return "Back In - Out actions"; } } } public class SpriteEaseBackInOut : EaseSpriteDemo { public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; var move = new CCMoveBy (3, new CCPoint(s.Width - 130, 0)); var move_back = move.Reverse(); var move_ease = new CCEaseBackInOut(move); var move_ease_back = move_ease.Reverse() as CCFiniteTimeAction; var delay = new CCDelayTime (0.25f); var seq1 = new CCSequence(move, delay, move_back, delay); var seq2 = new CCSequence(move_ease, delay, move_ease_back, delay); PositionForTwo(); m_grossini.RunAction(new CCRepeatForever (seq1)); m_tamara.RunAction(new CCRepeatForever (seq2)); } public override string Title { get { return "EaseBackInOut action"; } } } public class SpeedTest : EaseSpriteDemo { CCSpeed speedAction1, speedAction2, speedAction3; public override void OnEnter() { base.OnEnter(); var s = Layer.VisibleBoundsWorldspace.Size; // rotate and jump var jump1 = new CCJumpBy (4, new CCPoint(-s.Width + 80, 0), 100, 4); var jump2 = jump1.Reverse(); var rot1 = new CCRotateBy (4, 360 * 2); var rot2 = rot1.Reverse(); var seq3_1 = new CCSequence(jump2, jump1); var seq3_2 = new CCSequence(rot1, rot2); var spawn = new CCSpawn(seq3_1, seq3_2); speedAction1 = new CCSpeed(new CCRepeatForever (spawn), 1.0f); speedAction2 = new CCSpeed(new CCRepeatForever (spawn), 2.0f); speedAction3 = new CCSpeed(new CCRepeatForever (spawn), 0.5f); m_grossini.RunAction(speedAction1); m_tamara.RunAction(speedAction2); m_kathia.RunAction(speedAction3); } public override string Title { get { return "Speed action"; } } } public class EaseActionsTestScene : TestScene { protected override void NextTestCase() { } protected override void PreviousTestCase() { } protected override void RestTestCase() { } public override void runThisTest() { var pLayer = EaseTest.nextEaseAction(); AddChild(pLayer); Director.ReplaceScene(this); } } public static class EaseTest { public const int MAX_LAYER = 13; public const int kTagAction1 = 1; public const int kTagAction2 = 2; public const int kTagSlider = 1; private static int sceneIdx = -1; public static CCLayer createEaseLayer(int nIndex) { switch (nIndex) { case 0: return new SpriteEase(); case 1: return new SpriteEaseInOut(); case 2: return new SpriteEaseExponential(); case 3: return new SpriteEaseExponentialInOut(); case 4: return new SpriteEaseSine(); case 5: return new SpriteEaseSineInOut(); case 6: return new SpriteEaseElastic(); case 7: return new SpriteEaseElasticInOut(); case 8: return new SpriteEaseBounce(); case 9: return new SpriteEaseBounceInOut(); case 10: return new SpriteEaseBack(); case 11: return new SpriteEaseBackInOut(); case 12: return new SpeedTest(); } return null; } public static CCLayer nextEaseAction() { sceneIdx++; sceneIdx %= MAX_LAYER; var pLayer = createEaseLayer(sceneIdx); return pLayer; } public static CCLayer backEaseAction() { sceneIdx--; var total = MAX_LAYER; if (sceneIdx < 0) sceneIdx += total; var pLayer = createEaseLayer(sceneIdx); return pLayer; } public static CCLayer restartEaseAction() { var pLayer = createEaseLayer(sceneIdx); return pLayer; } } }
using System; using System.Linq; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Buffers; using System.Threading.Tasks; using System.Reflection; using System.Collections.Generic; using SuperSocket; using SuperSocket.Command; using SuperSocket.ProtoBase; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; using SuperSocket.Server; using System.Threading; using SuperSocket.Tests.Command; using Autofac.Extensions.DependencyInjection; using Autofac; using Microsoft.Extensions.Configuration; namespace SuperSocket.Tests { [Trait("Category", "Autofac")] public class AutofacTest : TestClassBase { public AutofacTest(ITestOutputHelper outputHelper) : base(outputHelper) { } [Theory] [InlineData(typeof(RegularHostConfigurator))] [InlineData(typeof(SecureHostConfigurator))] [Trait("Category", "Autofac.Commands")] public async Task TestCommands(Type hostConfiguratorType) { var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType); using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator) .UseCommand() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterType<ADD>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<MULT>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<SUB>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); }) .BuildAsServer()) { Assert.Equal("TestServer", server.Name); Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port)); OutputHelper.WriteLine("Connected."); using (var stream = await hostConfigurator.GetClientStream(client)) using (var streamReader = new StreamReader(stream, Utf8Encoding, true)) using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4)) { await streamWriter.WriteAsync("ADD 1 2 3\r\n"); await streamWriter.FlushAsync(); var line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); await streamWriter.WriteAsync("MULT 2 5\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("10", line); await streamWriter.WriteAsync("SUB 8 2\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); } await server.StopAsync(); } } [Theory] [InlineData(typeof(RegularHostConfigurator))] [InlineData(typeof(SecureHostConfigurator))] [Trait("Category", "Autofac.CommandsWithCustomSession")] public async Task TestCommandsWithCustomSession(Type hostConfiguratorType) { var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType); using (var server = CreateSocketServerBuilder<StringPackageInfo, CommandLinePipelineFilter>(hostConfigurator) .UseCommand() .UseSession<MySession>() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterType<ADD>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<MULT>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<SUB>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<DIV>().As<IAsyncCommand<MySession, StringPackageInfo>>(); }) .BuildAsServer()) { Assert.Equal("TestServer", server.Name); Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, hostConfigurator.Listener.Port)); OutputHelper.WriteLine("Connected."); using (var stream = await hostConfigurator.GetClientStream(client)) using (var streamReader = new StreamReader(stream, Utf8Encoding, true)) using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4)) { await streamWriter.WriteAsync("ADD 1 2 3\r\n"); await streamWriter.FlushAsync(); var line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); await streamWriter.WriteAsync("MULT 2 5\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("10", line); await streamWriter.WriteAsync("SUB 8 2\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); await streamWriter.WriteAsync("DIV 8 2\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("4", line); } await server.StopAsync(); } } [Fact] [Trait("Category", "Autofac.MultipleServerHost")] public async Task TestCommandsWithCustomSessionMultipleServerHost() { using (var server = MultipleServerHostBuilder.Create() .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.Sources.Clear(); configApp.AddInMemoryCollection(new Dictionary<string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", DefaultServerPort.ToString() } }); }) .AddServer<StringPackageInfo, CommandLinePipelineFilter>(builder => { builder .UseCommand() .UseSession<MySession>() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterType<ADD>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<MULT>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<SUB>().As<IAsyncCommand<IAppSession, StringPackageInfo>>(); builder.RegisterType<DIV>().As<IAsyncCommand<MySession, StringPackageInfo>>(); }); }).BuildAsServer()) { Assert.Equal("TestServer", server.Name); Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await client.ConnectAsync(GetDefaultServerEndPoint()); OutputHelper.WriteLine("Connected."); using (var stream = new NetworkStream(client)) using (var streamReader = new StreamReader(stream, Utf8Encoding, true)) using (var streamWriter = new StreamWriter(stream, Utf8Encoding, 1024 * 1024 * 4)) { await streamWriter.WriteAsync("ADD 1 2 3\r\n"); await streamWriter.FlushAsync(); var line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); await streamWriter.WriteAsync("MULT 2 5\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("10", line); await streamWriter.WriteAsync("SUB 8 2\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("6", line); await streamWriter.WriteAsync("DIV 8 2\r\n"); await streamWriter.FlushAsync(); line = await streamReader.ReadLineAsync(); Assert.Equal("4", line); } await server.StopAsync(); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/reservations/reservation_note.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.Reservations { /// <summary>Holder for reflection information generated from booking/reservations/reservation_note.proto</summary> public static partial class ReservationNoteReflection { #region Descriptor /// <summary>File descriptor for booking/reservations/reservation_note.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ReservationNoteReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Citib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9ub3RlLnByb3Rv", "EiBob2xtcy50eXBlcy5ib29raW5nLnJlc2VydmF0aW9ucxouYm9va2luZy9p", "bmRpY2F0b3JzL3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxozYm9va2lu", "Zy9pbmRpY2F0b3JzL3Jlc2VydmF0aW9uX25vdGVfaW5kaWNhdG9yLnByb3Rv", "GjVvcGVyYXRpb25zL25vdGVfcmVxdWVzdHMvbm90ZV9yZXF1ZXN0X2luZGlj", "YXRvci5wcm90bxosb3BlcmF0aW9ucy9ub3RlX3JlcXVlc3RzL25vdGVfY2F0", "ZWdvcnkucHJvdG8aHXByaW1pdGl2ZS9wYl9sb2NhbF9kYXRlLnByb3RvGjdz", "dXBwbHkvaW5jaWRlbnRhbF9pdGVtcy9pbmNpZGVudGFsX2l0ZW1faW5kaWNh", "dG9yLnByb3RvIqgFCg9SZXNlcnZhdGlvbk5vdGUSSwoJZW50aXR5X2lkGAEg", "ASgLMjguaG9sbXMudHlwZXMuYm9va2luZy5pbmRpY2F0b3JzLlJlc2VydmF0", "aW9uTm90ZUluZGljYXRvchJPCgtzb3VyY2Vfbm90ZRgCIAEoCzI6LmhvbG1z", "LnR5cGVzLm9wZXJhdGlvbnMubm90ZV9yZXF1ZXN0cy5Ob3RlUmVxdWVzdElu", "ZGljYXRvchJECghjYXRlZ29yeRgDIAEoDjIyLmhvbG1zLnR5cGVzLm9wZXJh", "dGlvbnMubm90ZV9yZXF1ZXN0cy5Ob3RlQ2F0ZWdvcnkSFwoPYWRkaXRpb25h", "bF9ub3RlGAQgASgJEh8KF2luY2x1ZGVfb25fY29uZmlybWF0aW9uGAUgASgI", "ElEKE2xvZGdpbmdfcmVzZXJ2YXRpb24YBiABKAsyNC5ob2xtcy50eXBlcy5i", "b29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3ISGwoTc291", "cmNlX25vdGVfc3ViamVjdBgHIAEoCRIUCgxpc19mdWxmaWxsZWQYCCABKAgS", "IQoZcGVybWFuZW50X29uX2d1ZXN0X3JlY29yZBgJIAEoCBJYChJpbmNpZGVu", "dGFsX2l0ZW1faWQYCiABKAsyPC5ob2xtcy50eXBlcy5zdXBwbHkuaW5jaWRl", "bnRhbF9pdGVtcy5JbmNpZGVudGFsSXRlbUluZGljYXRvchI6Cg5pbmNfc3Rh", "cnRfZGF0ZRgLIAEoCzIiLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5QYkxvY2Fs", "RGF0ZRI4CgxpbmNfZW5kX2RhdGUYDCABKAsyIi5ob2xtcy50eXBlcy5wcmlt", "aXRpdmUuUGJMb2NhbERhdGVCOVoUYm9va2luZy9yZXNlcnZhdGlvbnOqAiBI", "T0xNUy5UeXBlcy5Cb29raW5nLlJlc2VydmF0aW9uc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.NoteRequests.NoteCategoryReflection.Descriptor, global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationNote), global::HOLMS.Types.Booking.Reservations.ReservationNote.Parser, new[]{ "EntityId", "SourceNote", "Category", "AdditionalNote", "IncludeOnConfirmation", "LodgingReservation", "SourceNoteSubject", "IsFulfilled", "PermanentOnGuestRecord", "IncidentalItemId", "IncStartDate", "IncEndDate" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ReservationNote : pb::IMessage<ReservationNote> { private static readonly pb::MessageParser<ReservationNote> _parser = new pb::MessageParser<ReservationNote>(() => new ReservationNote()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReservationNote> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Reservations.ReservationNoteReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNote() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNote(ReservationNote other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; SourceNote = other.sourceNote_ != null ? other.SourceNote.Clone() : null; category_ = other.category_; additionalNote_ = other.additionalNote_; includeOnConfirmation_ = other.includeOnConfirmation_; LodgingReservation = other.lodgingReservation_ != null ? other.LodgingReservation.Clone() : null; sourceNoteSubject_ = other.sourceNoteSubject_; isFulfilled_ = other.isFulfilled_; permanentOnGuestRecord_ = other.permanentOnGuestRecord_; IncidentalItemId = other.incidentalItemId_ != null ? other.IncidentalItemId.Clone() : null; IncStartDate = other.incStartDate_ != null ? other.IncStartDate.Clone() : null; IncEndDate = other.incEndDate_ != null ? other.IncEndDate.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationNote Clone() { return new ReservationNote(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "source_note" field.</summary> public const int SourceNoteFieldNumber = 2; private global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator sourceNote_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator SourceNote { get { return sourceNote_; } set { sourceNote_ = value; } } /// <summary>Field number for the "category" field.</summary> public const int CategoryFieldNumber = 3; private global::HOLMS.Types.Operations.NoteRequests.NoteCategory category_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.NoteRequests.NoteCategory Category { get { return category_; } set { category_ = value; } } /// <summary>Field number for the "additional_note" field.</summary> public const int AdditionalNoteFieldNumber = 4; private string additionalNote_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string AdditionalNote { get { return additionalNote_; } set { additionalNote_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "include_on_confirmation" field.</summary> public const int IncludeOnConfirmationFieldNumber = 5; private bool includeOnConfirmation_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IncludeOnConfirmation { get { return includeOnConfirmation_; } set { includeOnConfirmation_ = value; } } /// <summary>Field number for the "lodging_reservation" field.</summary> public const int LodgingReservationFieldNumber = 6; private global::HOLMS.Types.Booking.Indicators.ReservationIndicator lodgingReservation_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationIndicator LodgingReservation { get { return lodgingReservation_; } set { lodgingReservation_ = value; } } /// <summary>Field number for the "source_note_subject" field.</summary> public const int SourceNoteSubjectFieldNumber = 7; private string sourceNoteSubject_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SourceNoteSubject { get { return sourceNoteSubject_; } set { sourceNoteSubject_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "is_fulfilled" field.</summary> public const int IsFulfilledFieldNumber = 8; private bool isFulfilled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool IsFulfilled { get { return isFulfilled_; } set { isFulfilled_ = value; } } /// <summary>Field number for the "permanent_on_guest_record" field.</summary> public const int PermanentOnGuestRecordFieldNumber = 9; private bool permanentOnGuestRecord_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool PermanentOnGuestRecord { get { return permanentOnGuestRecord_; } set { permanentOnGuestRecord_ = value; } } /// <summary>Field number for the "incidental_item_id" field.</summary> public const int IncidentalItemIdFieldNumber = 10; private global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator incidentalItemId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator IncidentalItemId { get { return incidentalItemId_; } set { incidentalItemId_ = value; } } /// <summary>Field number for the "inc_start_date" field.</summary> public const int IncStartDateFieldNumber = 11; private global::HOLMS.Types.Primitive.PbLocalDate incStartDate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate IncStartDate { get { return incStartDate_; } set { incStartDate_ = value; } } /// <summary>Field number for the "inc_end_date" field.</summary> public const int IncEndDateFieldNumber = 12; private global::HOLMS.Types.Primitive.PbLocalDate incEndDate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate IncEndDate { get { return incEndDate_; } set { incEndDate_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReservationNote); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReservationNote other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (!object.Equals(SourceNote, other.SourceNote)) return false; if (Category != other.Category) return false; if (AdditionalNote != other.AdditionalNote) return false; if (IncludeOnConfirmation != other.IncludeOnConfirmation) return false; if (!object.Equals(LodgingReservation, other.LodgingReservation)) return false; if (SourceNoteSubject != other.SourceNoteSubject) return false; if (IsFulfilled != other.IsFulfilled) return false; if (PermanentOnGuestRecord != other.PermanentOnGuestRecord) return false; if (!object.Equals(IncidentalItemId, other.IncidentalItemId)) return false; if (!object.Equals(IncStartDate, other.IncStartDate)) return false; if (!object.Equals(IncEndDate, other.IncEndDate)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (sourceNote_ != null) hash ^= SourceNote.GetHashCode(); if (Category != 0) hash ^= Category.GetHashCode(); if (AdditionalNote.Length != 0) hash ^= AdditionalNote.GetHashCode(); if (IncludeOnConfirmation != false) hash ^= IncludeOnConfirmation.GetHashCode(); if (lodgingReservation_ != null) hash ^= LodgingReservation.GetHashCode(); if (SourceNoteSubject.Length != 0) hash ^= SourceNoteSubject.GetHashCode(); if (IsFulfilled != false) hash ^= IsFulfilled.GetHashCode(); if (PermanentOnGuestRecord != false) hash ^= PermanentOnGuestRecord.GetHashCode(); if (incidentalItemId_ != null) hash ^= IncidentalItemId.GetHashCode(); if (incStartDate_ != null) hash ^= IncStartDate.GetHashCode(); if (incEndDate_ != null) hash ^= IncEndDate.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (sourceNote_ != null) { output.WriteRawTag(18); output.WriteMessage(SourceNote); } if (Category != 0) { output.WriteRawTag(24); output.WriteEnum((int) Category); } if (AdditionalNote.Length != 0) { output.WriteRawTag(34); output.WriteString(AdditionalNote); } if (IncludeOnConfirmation != false) { output.WriteRawTag(40); output.WriteBool(IncludeOnConfirmation); } if (lodgingReservation_ != null) { output.WriteRawTag(50); output.WriteMessage(LodgingReservation); } if (SourceNoteSubject.Length != 0) { output.WriteRawTag(58); output.WriteString(SourceNoteSubject); } if (IsFulfilled != false) { output.WriteRawTag(64); output.WriteBool(IsFulfilled); } if (PermanentOnGuestRecord != false) { output.WriteRawTag(72); output.WriteBool(PermanentOnGuestRecord); } if (incidentalItemId_ != null) { output.WriteRawTag(82); output.WriteMessage(IncidentalItemId); } if (incStartDate_ != null) { output.WriteRawTag(90); output.WriteMessage(IncStartDate); } if (incEndDate_ != null) { output.WriteRawTag(98); output.WriteMessage(IncEndDate); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (sourceNote_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceNote); } if (Category != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Category); } if (AdditionalNote.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(AdditionalNote); } if (IncludeOnConfirmation != false) { size += 1 + 1; } if (lodgingReservation_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(LodgingReservation); } if (SourceNoteSubject.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SourceNoteSubject); } if (IsFulfilled != false) { size += 1 + 1; } if (PermanentOnGuestRecord != false) { size += 1 + 1; } if (incidentalItemId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(IncidentalItemId); } if (incStartDate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(IncStartDate); } if (incEndDate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(IncEndDate); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReservationNote other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.sourceNote_ != null) { if (sourceNote_ == null) { sourceNote_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator(); } SourceNote.MergeFrom(other.SourceNote); } if (other.Category != 0) { Category = other.Category; } if (other.AdditionalNote.Length != 0) { AdditionalNote = other.AdditionalNote; } if (other.IncludeOnConfirmation != false) { IncludeOnConfirmation = other.IncludeOnConfirmation; } if (other.lodgingReservation_ != null) { if (lodgingReservation_ == null) { lodgingReservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } LodgingReservation.MergeFrom(other.LodgingReservation); } if (other.SourceNoteSubject.Length != 0) { SourceNoteSubject = other.SourceNoteSubject; } if (other.IsFulfilled != false) { IsFulfilled = other.IsFulfilled; } if (other.PermanentOnGuestRecord != false) { PermanentOnGuestRecord = other.PermanentOnGuestRecord; } if (other.incidentalItemId_ != null) { if (incidentalItemId_ == null) { incidentalItemId_ = new global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator(); } IncidentalItemId.MergeFrom(other.IncidentalItemId); } if (other.incStartDate_ != null) { if (incStartDate_ == null) { incStartDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } IncStartDate.MergeFrom(other.IncStartDate); } if (other.incEndDate_ != null) { if (incEndDate_ == null) { incEndDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } IncEndDate.MergeFrom(other.IncEndDate); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Indicators.ReservationNoteIndicator(); } input.ReadMessage(entityId_); break; } case 18: { if (sourceNote_ == null) { sourceNote_ = new global::HOLMS.Types.Operations.NoteRequests.NoteRequestIndicator(); } input.ReadMessage(sourceNote_); break; } case 24: { category_ = (global::HOLMS.Types.Operations.NoteRequests.NoteCategory) input.ReadEnum(); break; } case 34: { AdditionalNote = input.ReadString(); break; } case 40: { IncludeOnConfirmation = input.ReadBool(); break; } case 50: { if (lodgingReservation_ == null) { lodgingReservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } input.ReadMessage(lodgingReservation_); break; } case 58: { SourceNoteSubject = input.ReadString(); break; } case 64: { IsFulfilled = input.ReadBool(); break; } case 72: { PermanentOnGuestRecord = input.ReadBool(); break; } case 82: { if (incidentalItemId_ == null) { incidentalItemId_ = new global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator(); } input.ReadMessage(incidentalItemId_); break; } case 90: { if (incStartDate_ == null) { incStartDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(incStartDate_); break; } case 98: { if (incEndDate_ == null) { incEndDate_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(incEndDate_); break; } } } } } #endregion } #endregion Designer generated code
/* Copyright 2006 - 2010 Intel 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.Drawing; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using OpenSource.UPnP; namespace UPnPAuthor { /// <summary> /// Summary description for ContainerProperty. /// </summary> public class ContainerProperty : System.Windows.Forms.Form { public UPnPComplexType.RestrictionExtension re; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton RestrictionRadioButton; private System.Windows.Forms.RadioButton ExtensionRadioButton; private System.Windows.Forms.ComboBox BaseComboBox; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox PatternTextBox; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.Button CancelButton; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ContainerProperty(UPnPComplexType[] ComplexTypes, UPnPComplexType.GenericContainer gc) { // // Required for Windows Form Designer support // InitializeComponent(); BaseComboBox.SelectedIndex=0; foreach(UPnPComplexType ct in ComplexTypes) { BaseComboBox.Items.Add(ct); } if(gc.GetType()==typeof(UPnPComplexType.ComplexContent)) { UPnPComplexType.ComplexContent cc = (UPnPComplexType.ComplexContent)gc; if(cc.RestExt != null && cc.RestExt.GetType()==typeof(UPnPComplexType.Restriction)) { UPnPComplexType.Restriction r = (UPnPComplexType.Restriction)((UPnPComplexType.ComplexContent)gc).RestExt; PatternTextBox.Text = r.PATTERN; } } else if(gc.GetType()==typeof(UPnPComplexType.SimpleContent)) { UPnPComplexType.SimpleContent cc = (UPnPComplexType.SimpleContent)gc; if(cc.RestExt != null && cc.RestExt.GetType()==typeof(UPnPComplexType.Restriction)) { UPnPComplexType.Restriction r = (UPnPComplexType.Restriction)((UPnPComplexType.ComplexContent)gc).RestExt; PatternTextBox.Text = r.PATTERN; } } // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.RestrictionRadioButton = new System.Windows.Forms.RadioButton(); this.ExtensionRadioButton = new System.Windows.Forms.RadioButton(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.BaseComboBox = new System.Windows.Forms.ComboBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.PatternTextBox = new System.Windows.Forms.TextBox(); this.OKButton = new System.Windows.Forms.Button(); this.CancelButton = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // RestrictionRadioButton // this.RestrictionRadioButton.Checked = true; this.RestrictionRadioButton.Location = new System.Drawing.Point(8, 120); this.RestrictionRadioButton.Name = "RestrictionRadioButton"; this.RestrictionRadioButton.Size = new System.Drawing.Size(80, 24); this.RestrictionRadioButton.TabIndex = 0; this.RestrictionRadioButton.TabStop = true; this.RestrictionRadioButton.Text = "Restriction"; this.RestrictionRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonChanged); // // ExtensionRadioButton // this.ExtensionRadioButton.Location = new System.Drawing.Point(8, 144); this.ExtensionRadioButton.Name = "ExtensionRadioButton"; this.ExtensionRadioButton.Size = new System.Drawing.Size(72, 24); this.ExtensionRadioButton.TabIndex = 1; this.ExtensionRadioButton.Text = "Extension"; this.ExtensionRadioButton.CheckedChanged += new System.EventHandler(this.OnRadioButtonChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.BaseComboBox); this.groupBox1.Location = new System.Drawing.Point(8, 8); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(344, 48); this.groupBox1.TabIndex = 2; this.groupBox1.TabStop = false; this.groupBox1.Text = "Base"; // // BaseComboBox // this.BaseComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.BaseComboBox.Items.AddRange(new object[] { "any", "string", "normalizedString", "token", "byte", "unsignedByte", "base64Binary", "base64Binary", "hexBinary", "integer", "positiveInteger", "negativeInteger", "nonNegativeInteger", "nonPositiveInteger", "int", "unsignedInt", "long", "unsignedLong", "short", "unsignedShort", "decimal", "float", "double", "boolean", "time", "dateTime", "duration", "date", "gMonth", "gYear", "gYearMonth", "gDay", "gMonthDay", "Name", "QName", "NCName", "anyURI"}); this.BaseComboBox.Location = new System.Drawing.Point(8, 16); this.BaseComboBox.MaxDropDownItems = 16; this.BaseComboBox.Name = "BaseComboBox"; this.BaseComboBox.Size = new System.Drawing.Size(328, 21); this.BaseComboBox.TabIndex = 0; // // groupBox2 // this.groupBox2.Controls.Add(this.PatternTextBox); this.groupBox2.Location = new System.Drawing.Point(8, 64); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(344, 48); this.groupBox2.TabIndex = 3; this.groupBox2.TabStop = false; this.groupBox2.Text = "Pattern"; // // PatternTextBox // this.PatternTextBox.Location = new System.Drawing.Point(8, 16); this.PatternTextBox.Name = "PatternTextBox"; this.PatternTextBox.Size = new System.Drawing.Size(328, 20); this.PatternTextBox.TabIndex = 0; this.PatternTextBox.Text = ""; // // OKButton // this.OKButton.Location = new System.Drawing.Point(280, 136); this.OKButton.Name = "OKButton"; this.OKButton.TabIndex = 4; this.OKButton.Text = "OK"; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // CancelButton // this.CancelButton.Location = new System.Drawing.Point(192, 136); this.CancelButton.Name = "CancelButton"; this.CancelButton.TabIndex = 5; this.CancelButton.Text = "Cancel"; // // ContainerProperty // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(368, 174); this.Controls.Add(this.CancelButton); this.Controls.Add(this.OKButton); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.ExtensionRadioButton); this.Controls.Add(this.RestrictionRadioButton); this.Name = "ContainerProperty"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "ContainerProperty"; this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void OnRadioButtonChanged(object sender, System.EventArgs e) { if(ExtensionRadioButton.Checked) { PatternTextBox.Enabled = false; } else { PatternTextBox.Enabled = true; } } private void OKButton_Click(object sender, System.EventArgs e) { if(RestrictionRadioButton.Checked) { UPnPComplexType.Restriction r = new UPnPComplexType.Restriction(); r.PATTERN = PatternTextBox.Text; r.baseType = BaseComboBox.SelectedItem.ToString(); if(BaseComboBox.SelectedItem.GetType()==typeof(UPnPComplexType)) { r.baseTypeNS = ((UPnPComplexType)BaseComboBox.SelectedItem).Name_NAMESPACE; } re = r; } else { UPnPComplexType.Extension ex = new UPnPComplexType.Extension(); ex.baseType = BaseComboBox.SelectedItem.ToString(); if(BaseComboBox.SelectedItem.GetType()==typeof(UPnPComplexType)) { ex.baseTypeNS = ((UPnPComplexType)BaseComboBox.SelectedItem).Name_NAMESPACE; } re = ex; } DialogResult = DialogResult.OK; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Management.ZoneBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementZoneInfo))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ManagementViewZone))] public partial class ManagementZone : iControlInterface { public ManagementZone() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_zone_file //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void add_zone_file( ManagementZoneInfo [] zone_records, string [] src_file_names, bool [] sync_ptrs ) { this.Invoke("add_zone_file", new object [] { zone_records, src_file_names, sync_ptrs}); } public System.IAsyncResult Beginadd_zone_file(ManagementZoneInfo [] zone_records,string [] src_file_names,bool [] sync_ptrs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_zone_file", new object[] { zone_records, src_file_names, sync_ptrs}, callback, asyncState); } public void Endadd_zone_file(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_zone_option //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void add_zone_option( ManagementZoneInfo [] zones ) { this.Invoke("add_zone_option", new object [] { zones}); } public System.IAsyncResult Beginadd_zone_option(ManagementZoneInfo [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_zone_option", new object[] { zones}, callback, asyncState); } public void Endadd_zone_option(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // add_zone_text //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void add_zone_text( ManagementZoneInfo [] zone_records, string [] [] text, bool [] sync_ptrs ) { this.Invoke("add_zone_text", new object [] { zone_records, text, sync_ptrs}); } public System.IAsyncResult Beginadd_zone_text(ManagementZoneInfo [] zone_records,string [] [] text,bool [] sync_ptrs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_zone_text", new object[] { zone_records, text, sync_ptrs}, callback, asyncState); } public void Endadd_zone_text(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_zone //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void delete_zone( ManagementViewZone [] view_zones ) { this.Invoke("delete_zone", new object [] { view_zones}); } public System.IAsyncResult Begindelete_zone(ManagementViewZone [] view_zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_zone", new object[] { view_zones}, callback, asyncState); } public void Enddelete_zone(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_zone_option //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void delete_zone_option( ManagementZoneInfo [] zones ) { this.Invoke("delete_zone_option", new object [] { zones}); } public System.IAsyncResult Begindelete_zone_option(ManagementZoneInfo [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_zone_option", new object[] { zones}, callback, asyncState); } public void Enddelete_zone_option(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_zone //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public ManagementZoneInfo [] get_zone( ManagementViewZone [] view_zones ) { object [] results = this.Invoke("get_zone", new object [] { view_zones}); return ((ManagementZoneInfo [])(results[0])); } public System.IAsyncResult Beginget_zone(ManagementViewZone [] view_zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_zone", new object[] { view_zones}, callback, asyncState); } public ManagementZoneInfo [] Endget_zone(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((ManagementZoneInfo [])(results[0])); } //----------------------------------------------------------------------- // get_zone_name //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public ManagementViewZone [] get_zone_name( string [] view_names ) { object [] results = this.Invoke("get_zone_name", new object [] { view_names}); return ((ManagementViewZone [])(results[0])); } public System.IAsyncResult Beginget_zone_name(string [] view_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_zone_name", new object[] { view_names}, callback, asyncState); } public ManagementViewZone [] Endget_zone_name(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((ManagementViewZone [])(results[0])); } //----------------------------------------------------------------------- // get_zone_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public ManagementZoneInfo [] get_zone_v2( ManagementViewZone [] view_zones ) { object [] results = this.Invoke("get_zone_v2", new object [] { view_zones}); return ((ManagementZoneInfo [])(results[0])); } public System.IAsyncResult Beginget_zone_v2(ManagementViewZone [] view_zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_zone_v2", new object[] { view_zones}, callback, asyncState); } public ManagementZoneInfo [] Endget_zone_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((ManagementZoneInfo [])(results[0])); } //----------------------------------------------------------------------- // set_zone_option //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void set_zone_option( ManagementZoneInfo [] zones ) { this.Invoke("set_zone_option", new object [] { zones}); } public System.IAsyncResult Beginset_zone_option(ManagementZoneInfo [] zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_zone_option", new object[] { zones}, callback, asyncState); } public void Endset_zone_option(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // transfer_zone //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] public void transfer_zone( string [] server_names, string [] src_zone_names, string [] dst_view_names, ManagementZoneInfo [] zone_records ) { this.Invoke("transfer_zone", new object [] { server_names, src_zone_names, dst_view_names, zone_records}); } public System.IAsyncResult Begintransfer_zone(string [] server_names,string [] src_zone_names,string [] dst_view_names,ManagementZoneInfo [] zone_records, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("transfer_zone", new object[] { server_names, src_zone_names, dst_view_names, zone_records}, callback, asyncState); } public void Endtransfer_zone(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // zone_exist //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/Zone", RequestNamespace="urn:iControl:Management/Zone", ResponseNamespace="urn:iControl:Management/Zone")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] zone_exist( ManagementViewZone [] view_zones ) { object [] results = this.Invoke("zone_exist", new object [] { view_zones}); return ((bool [])(results[0])); } public System.IAsyncResult Beginzone_exist(ManagementViewZone [] view_zones, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("zone_exist", new object[] { view_zones}, callback, asyncState); } public bool [] Endzone_exist(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Text.RegularExpressions; using TracerX.Properties; namespace TracerX.Viewer { internal partial class FilterDialog : Form { private MainForm _mainForm = MainForm.TheMainForm; private ColumnHeader _clickedHeader; private bool _suppressEvents = true; private ListViewItemSorter _threadIdSorter; private ListViewItemSorter _sessionSorter; private ListViewItemSorter _threadNameSorter; private ListViewItemSorter _loggerSorter; private ListViewItemSorter _methodSorter; public FilterDialog() { InitializeComponent(); this.Icon = Properties.Resources.scroll_view; InitTraceLevels(); InitSessions(); InitThreadIds(); InitThreadNames(); InitLoggers(); InitMethods(); InitText(); } public FilterDialog(ColumnHeader clickedHeader) : this() { _clickedHeader = clickedHeader; if (_clickedHeader == _mainForm.headerLevel) { tabControl1.SelectedTab = traceLevelPage; } else if (_clickedHeader == _mainForm.headerSession) { tabControl1.SelectedTab = sessionPage; } else if (_clickedHeader == _mainForm.headerLogger) { tabControl1.SelectedTab = loggerPage; } else if (_clickedHeader == _mainForm.headerMethod) { tabControl1.SelectedTab = methodPage; } else if (_clickedHeader == _mainForm.headerThreadId) { tabControl1.SelectedTab = threadIdPage; } else if (_clickedHeader == _mainForm.headerThreadName) { tabControl1.SelectedTab = threadNamePage; } else if (_clickedHeader == _mainForm.headerText) { tabControl1.SelectedTab = textPage; } } // Create a delegate to compare the Checked states of two ListViewItems // for sorting via ListViewItemSorter. private ListViewItemSorter.RowComparer _checkComparer = delegate(ListViewItem x, ListViewItem y) { if (x.Checked == y.Checked) return 0; if (x.Checked) return 1; else return -1; }; protected override void OnLoad(EventArgs e) { base.OnLoad(e); ok.Enabled = false; apply.Enabled = false; _suppressEvents = false; } private void AnyListView_ItemChecked(object sender, ItemCheckedEventArgs e) { if (_suppressEvents) return; ok.Enabled = true; apply.Enabled = true; IndicateTabFilter(sessionPage, sessionListView); IndicateTabFilter(loggerPage, loggerListView); IndicateTabFilter(methodPage, methodListView); IndicateTabFilter(threadNamePage, threadNameListView); IndicateTabFilter(threadIdPage, threadIdListView); } private void IndicateTabFilter(TabPage page, ListView listView) { bool isFiltered = listView.CheckedItems.Count != listView.Items.Count; if (page.Text[0] == '*') { if (!isFiltered) { page.Text = page.Text.Trim('*'); } } else { if (isFiltered) { page.Text = "*" + page.Text; } } } // For some reason, the AnyListView_ItemChecked event occurs when switching // between tabs that have ListViews. Use the Selecting and SelectedIndexChanged // events to prevent OK and Apply from getting enabled just by switching tabs. private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e) { _suppressEvents = true; } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { _suppressEvents = false; } private void ok_Click(object sender, EventArgs e) { apply_Click(null, null); } private void apply_Click(object sender, EventArgs e) { _mainForm.VisibleTraceLevels = SelectedTraceLevels; ApplySessionSelection(); ApplyThreadIdSelection(); ApplyThreadNameSelection(); ApplyLoggerSelection(); ApplyMethodSelection(); ApplyTextSelection(); ok.Enabled = false; apply.Enabled = false; _mainForm.RebuildAllRows(); } #region Trace Levels private void InitTraceLevels() { // Display only the trace levels that actually exist in the file. int index = 0; traceLevelListBox.Items.Clear(); foreach (TraceLevel level in Enum.GetValues(typeof(TraceLevel))) { if (level != TraceLevel.Inherited && (level & _mainForm.ValidTraceLevels) != 0) { traceLevelListBox.Items.Add(level); traceLevelListBox.SetItemChecked(index, (level & _mainForm.VisibleTraceLevels) != 0); ++index; } } IndicateTraceLevelFilter(_mainForm.ValidTraceLevels != _mainForm.VisibleTraceLevels); } private void IndicateTraceLevelFilter(bool isFiltered) { if (traceLevelPage.Text[0] == '*') { if (!isFiltered) { traceLevelPage.Text = traceLevelPage.Text.Trim('*'); } } else { if (isFiltered) { traceLevelPage.Text = "*" + traceLevelPage.Text; } } } public TraceLevel SelectedTraceLevels { get { TraceLevel retval = TraceLevel.Inherited; // I.e. 0. foreach (TraceLevel level in traceLevelListBox.CheckedItems) { retval |= level; } return retval; } } private void traceLevelListBox_ItemCheck(object sender, ItemCheckEventArgs e) { if (_suppressEvents) return; //ok.Enabled = e.NewValue == CheckState.Checked || traceLevelListBox.CheckedItems.Count > 1; apply.Enabled = true; ok.Enabled = true; int checkedCount = traceLevelListBox.CheckedItems.Count; if (e.NewValue == CheckState.Checked) { ++checkedCount; } else { --checkedCount; } IndicateTraceLevelFilter(checkedCount != traceLevelListBox.Items.Count); } private void selectAllTraceLevels_Click(object sender, EventArgs e) { for (int i = 0; i < traceLevelListBox.Items.Count; ++i) { traceLevelListBox.SetItemChecked(i, true); } } private void clearAllTraceLevels_Click(object sender, EventArgs e) { for (int i = 0; i < traceLevelListBox.Items.Count; ++i) { traceLevelListBox.SetItemChecked(i, false); } } private void invertTraceLevels_Click(object sender, EventArgs e) { for (int i = 0; i < traceLevelListBox.Items.Count; ++i) { bool x = traceLevelListBox.GetItemChecked(i); traceLevelListBox.SetItemChecked(i, !x); } } private void traceLevelListBox_Format(object sender, ListControlConvertEventArgs e) { e.Value = Enum.GetName(typeof(TraceLevel), e.ListItem); } #endregion Trace Levels #region Sessions private void InitSessions() { sessionListView.BeginUpdate(); // Populate the session listview from SessionObjects.AllSessions. lock (SessionObjects.Lock) { foreach (Reader.Session ses in SessionObjects.AllSessionObjects) { ListViewItem item = new ListViewItem(new string[] { string.Empty, ses.Name }); item.Checked = ses.Visible; item.Tag = ses; this.sessionListView.Items.Add(item); } } sessionCheckCol.Width = -1; sessionListView.EndUpdate(); IndicateTabFilter(sessionPage, sessionListView); } private void ApplySessionSelection() { foreach (ListViewItem item in sessionListView.Items) { Reader.Session ses = (Reader.Session)item.Tag; ses.Visible = item.Checked; } } private void checkAllSessions_Click(object sender, EventArgs e) { foreach (ListViewItem item in sessionListView.Items) { item.Checked = true; } } private void uncheckAllSessionss_Click(object sender, EventArgs e) { foreach (ListViewItem item in sessionListView.Items) { item.Checked = false; } } private void invertSessions_Click(object sender, EventArgs e) { foreach (ListViewItem item in sessionListView.Items) { item.Checked = !item.Checked; } } private void sessionListView_ColumnClick(object sender, ColumnClickEventArgs e) { _suppressEvents = true; // Create the sorting objects the first time they are required. if (_sessionSorter == null) { // Create a delegate for comparing the IDs of the Session objects that // correspond to two ListViewItems. ListViewItemSorter.RowComparer idComparer = delegate(ListViewItem x, ListViewItem y) { // The ListViewItem tags are ThreadObjects. int xint = ((Reader.Session)x.Tag).Index; int yint = ((Reader.Session)y.Tag).Index; return xint - yint; }; sessionCol.Tag = idComparer; sessionCheckCol.Tag = _checkComparer; _sessionSorter = new ListViewItemSorter(sessionListView); } _sessionSorter.Sort(e.Column); _suppressEvents = false; } #endregion Sessions #region Thread Ids private void InitThreadIds() { threadIdListView.BeginUpdate(); // Populate the thread ID listview from ThreadObjects.AllThreads. lock (ThreadObjects.Lock) { foreach (ThreadObject thread in ThreadObjects.AllThreadObjects) { ListViewItem item = new ListViewItem(new string[] { string.Empty, thread.Id.ToString() }); item.Checked = thread.Visible; item.Tag = thread; this.threadIdListView.Items.Add(item); } } threadCheckCol.Width = -1; //threadIdCol.Width = -1; threadIdListView.EndUpdate(); IndicateTabFilter(threadIdPage, threadIdListView); } private void ApplyThreadIdSelection() { foreach (ListViewItem item in threadIdListView.Items) { ThreadObject thread = (ThreadObject)item.Tag; thread.Visible = item.Checked; } } private void checkAllThreadIds_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadIdListView.Items) { item.Checked = true; } } private void uncheckAllThreadIds_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadIdListView.Items) { item.Checked = false; } } private void invertThreadIDs_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadIdListView.Items) { item.Checked = !item.Checked; } } private void threadIdListView_ColumnClick(object sender, ColumnClickEventArgs e) { _suppressEvents = true; // Create the sorting objects the first time they are required. if (_threadIdSorter == null) { // Create a delegate for comparing the IDs of the ThreadObjects that // correspond to two ListViewItems. ListViewItemSorter.RowComparer idComparer = delegate(ListViewItem x, ListViewItem y) { // The ListViewItem tags are ThreadObjects. int xint = ((ThreadObject)x.Tag).Id; int yint = ((ThreadObject)y.Tag).Id; return xint - yint; }; threadIdCol.Tag = idComparer; threadCheckCol.Tag = _checkComparer; _threadIdSorter = new ListViewItemSorter(threadIdListView); } _threadIdSorter.Sort(e.Column); _suppressEvents = false; } #endregion Thread Ids #region Thread Names private void InitThreadNames() { threadNameListView.BeginUpdate(); // Populate the thread name listview from ThreadNames.AllThreads. lock (ThreadNames.Lock) { foreach (ThreadName thread in ThreadNames.AllThreadNames) { ListViewItem item = new ListViewItem(new string[] { string.Empty, thread.Name }); item.Checked = thread.Visible; item.Tag = thread; this.threadNameListView.Items.Add(item); } } threadNameCheckCol.Width = -1; //threadNameNameCol.Width = -1; threadNameListView.EndUpdate(); IndicateTabFilter(threadNamePage, threadNameListView); } private void ApplyThreadNameSelection() { foreach (ListViewItem item in threadNameListView.Items) { ThreadName thread = (ThreadName)item.Tag; thread.Visible = item.Checked; } } private void checkAllThreadNames_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadNameListView.Items) { item.Checked = true; } } private void uncheckAllThreadNames_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadNameListView.Items) { item.Checked = false; } } private void invertThreadNames_Click(object sender, EventArgs e) { foreach (ListViewItem item in threadNameListView.Items) { item.Checked = !item.Checked; } } private void threadNameListView_ColumnClick(object sender, ColumnClickEventArgs e) { _suppressEvents = true; // Create the sorting objects the first time they are required. if (_threadNameSorter == null) { _threadNameSorter = new ListViewItemSorter(threadNameListView); threadNameCheckCol.Tag = _checkComparer; } _threadNameSorter.Sort(e.Column); _suppressEvents = false; } #endregion Thread Names #region Loggers private void InitLoggers() { lock (LoggerObjects.Lock) { foreach (LoggerObject logger in LoggerObjects.AllLoggers) { ListViewItem item = new ListViewItem(new string[] { string.Empty, logger.Name }); item.Checked = logger.Visible; item.Tag = logger; this.loggerListView.Items.Add(item); } } SortLoggers(loggerNameCol.Index); IndicateTabFilter(loggerPage, loggerListView); } private void checkAllLoggers_Click(object sender, EventArgs e) { foreach (ListViewItem item in loggerListView.Items) { item.Checked = true; } } private void uncheckAllLoggers_Click(object sender, EventArgs e) { foreach (ListViewItem item in loggerListView.Items) { item.Checked = false; } } private void invertLoggers_Click(object sender, EventArgs e) { foreach (ListViewItem item in loggerListView.Items) { item.Checked = !item.Checked; } } private void ApplyLoggerSelection() { foreach (ListViewItem item in loggerListView.Items) { LoggerObject logger = (LoggerObject)item.Tag; logger.Visible = item.Checked; } } private void loggerListView_ColumnClick(object sender, ColumnClickEventArgs e) { SortLoggers(e.Column); } private void SortLoggers(int colIndex) { _suppressEvents = true; // Create the sorter object the first time it is required. if (_loggerSorter == null) { loggerCheckCol.Tag = _checkComparer; _loggerSorter = new ListViewItemSorter(loggerListView); } _loggerSorter.Sort(colIndex); _suppressEvents = false; } #endregion Loggers #region Methods private void InitMethods() { lock (MethodObjects.Lock) { foreach (MethodObject method in MethodObjects.AllMethods) { ListViewItem item = new ListViewItem(new string[] { string.Empty, method.Name }); item.Checked = method.Visible; item.Tag = method; this.methodListView.Items.Add(item); } calledMethodsChk.Checked = Settings.Default.ShowCalledMethods; } IndicateTabFilter(methodPage, methodListView); } private void checkAllMethodss_Click(object sender, EventArgs e) { foreach (ListViewItem item in methodListView.Items) { item.Checked = true; } } private void uncheckAllMethods_Click(object sender, EventArgs e) { foreach (ListViewItem item in methodListView.Items) { item.Checked = false; } } private void invertMethods_Click(object sender, EventArgs e) { foreach (ListViewItem item in methodListView.Items) { item.Checked = !item.Checked; } } private void ApplyMethodSelection() { foreach (ListViewItem item in methodListView.Items) { MethodObject method = (MethodObject)item.Tag; method.Visible = item.Checked; } Settings.Default.ShowCalledMethods = calledMethodsChk.Checked; } private void methodListView_ColumnClick(object sender, ColumnClickEventArgs e) { _suppressEvents = true; // Create the sorter object the first time it is required. if (_methodSorter == null) { methodCheckCol.Tag = _checkComparer; _methodSorter = new ListViewItemSorter(methodListView); } _methodSorter.Sort(e.Column); _suppressEvents = false; } private void calledMethodsChk_CheckedChanged(object sender, EventArgs e) { ok.Enabled = true; apply.Enabled = true; } #endregion Methods #region Text // Text filter settings live here. Others have their own classes. private static string _includeText; private static string _excludeText; private static bool _includeChecked; private static bool _excludeChecked; private static bool _caseChecked; private static bool _wildChecked; private static bool _regexChecked; private static StringMatcher _includeMatcher; private static StringMatcher _excludeMatcher; public static event EventHandler TextFilterOnOff; /// <summary>True if text filtering is in effect.</summary> public static bool TextFilterOn { get { return _includeChecked || _excludeChecked; } } /// <summary>Turns text filtering off.</summary> public static void TextFilterDisable() { if (TextFilterOn) { _includeChecked = false; _excludeChecked = false; OnTextFilterOnOff(null); } } /// <summary>Determines if the string passes the text filter.</summary> public static bool TextFilterTestString(string line) { bool pass = true; if (_includeChecked) { pass = _includeMatcher.Matches(line); } if (pass && _excludeChecked) { pass = !_excludeMatcher.Matches(line); } return pass; } private static void OnTextFilterOnOff(object sender) { if (TextFilterOnOff != null) TextFilterOnOff(sender, EventArgs.Empty); } // Initialize the controls based on the static properties. private void InitText() { txtContains.Text = _includeText; chkContain.Checked = _includeChecked; txtDoesNotContain.Text = _excludeText; chkDoesNotContain.Checked = _excludeChecked; chkCase.Checked = _caseChecked; radWildcard.Checked = _wildChecked; radRegex.Checked = _regexChecked; //if (TextFilterOn) textPage.Text = "*" + textPage.Text; } // Set the static properties based on the controls. private void ApplyTextSelection() { bool wasOn = TextFilterOn; MatchType matchType; _includeChecked = chkContain.Checked && !string.IsNullOrEmpty(txtContains.Text); _includeText = txtContains.Text; _excludeChecked = chkDoesNotContain.Checked && !string.IsNullOrEmpty(txtDoesNotContain.Text); _excludeText = txtDoesNotContain.Text; _caseChecked = chkCase.Checked; _wildChecked = radWildcard.Checked; _regexChecked = radRegex.Checked; // TODO: radNormal.Checked? if (_regexChecked) { matchType = MatchType.RegularExpression; } else if (_wildChecked) { matchType = MatchType.Wildcard; } else { matchType = MatchType.Simple; } if (_includeChecked) { _includeMatcher = new StringMatcher(_includeText, chkCase.Checked, matchType); } if (_excludeChecked) { _excludeMatcher = new StringMatcher(_excludeText, chkCase.Checked, matchType); } if (TextFilterOn != wasOn) OnTextFilterOnOff(this); } private void Text_CheckboxChanged(object sender, EventArgs e) { txtContains.Enabled = chkContain.Checked; txtDoesNotContain.Enabled = chkDoesNotContain.Checked; if (_suppressEvents) return; ok.Enabled = true; apply.Enabled = true; textPage.Text = textPage.Text.Trim('*'); if (chkContain.Checked || chkDoesNotContain.Checked) { textPage.Text = "*" + textPage.Text; } } private void Text_FilterTextChanged(object sender, EventArgs e) { if (_suppressEvents) return; ok.Enabled = true; apply.Enabled = true; } #endregion Text } }
namespace System.Workflow.ComponentModel { using System; using System.Collections; using System.Diagnostics; using System.ComponentModel; using System.Collections.Generic; using System.Workflow.ComponentModel.Design; internal sealed class FaultAndCancellationHandlingFilter : ActivityExecutionFilter, IActivityEventListener<ActivityExecutionStatusChangedEventArgs> { public static DependencyProperty FaultProcessedProperty = DependencyProperty.RegisterAttached("FaultProcessed", typeof(bool), typeof(FaultAndCancellationHandlingFilter), new PropertyMetadata(false)); #region Execute Signal public override ActivityExecutionStatus Execute(Activity activity, ActivityExecutionContext executionContext) { if (activity == null) throw new ArgumentNullException("activity"); if (executionContext == null) throw new ArgumentNullException("executionContext"); if (!(activity is CompositeActivity)) throw new InvalidOperationException("activity"); executionContext.Activity.HoldLockOnStatusChange(this); return base.Execute(activity, executionContext); } public override ActivityExecutionStatus HandleFault(Activity activity, ActivityExecutionContext executionContext, Exception exception) { if (activity.HasPrimaryClosed != true) return base.HandleFault(activity, executionContext, exception); //We are handed fault again. Quiten Fault & Cancellation Handlers if any running. Activity handlersActivity = FaultAndCancellationHandlingFilter.GetFaultHandlers(executionContext.Activity); if (handlersActivity != null && (handlersActivity.ExecutionStatus != ActivityExecutionStatus.Closed && handlersActivity.ExecutionStatus != ActivityExecutionStatus.Initialized)) { if (handlersActivity.ExecutionStatus == ActivityExecutionStatus.Executing) executionContext.CancelActivity(handlersActivity); return ActivityExecutionStatus.Faulting; } else { handlersActivity = FaultAndCancellationHandlingFilter.GetCancellationHandler(executionContext.Activity); if (handlersActivity != null && (handlersActivity.ExecutionStatus != ActivityExecutionStatus.Closed && handlersActivity.ExecutionStatus != ActivityExecutionStatus.Initialized)) { if (handlersActivity.ExecutionStatus == ActivityExecutionStatus.Executing) executionContext.CancelActivity(handlersActivity); return ActivityExecutionStatus.Faulting; } } if ((bool)activity.GetValue(FaultAndCancellationHandlingFilter.FaultProcessedProperty)) SafeReleaseLockOnStatusChange(executionContext); return base.HandleFault(activity, executionContext, exception); } #endregion #region IActivityEventListener<ActivityExecutionStatusChangedEventArgs> Members public void OnEvent(object sender, ActivityExecutionStatusChangedEventArgs e) { ActivityExecutionContext context = sender as ActivityExecutionContext; if (context == null) throw new ArgumentException("sender"); // waiting for primary activity to close if (e.Activity == context.Activity) { if (context.Activity.HasPrimaryClosed && !(bool)context.Activity.GetValue(FaultAndCancellationHandlingFilter.FaultProcessedProperty)) { context.Activity.SetValue(FaultAndCancellationHandlingFilter.FaultProcessedProperty, true); if (context.Activity.WasExecuting && context.Activity.ExecutionResult == ActivityExecutionResult.Faulted && context.Activity.GetValue(ActivityExecutionContext.CurrentExceptionProperty) != null) { // execute exceptionHandlers, iff activity has transitioned from Executing to Faulting. CompositeActivity exceptionHandlersActivity = FaultAndCancellationHandlingFilter.GetFaultHandlers(context.Activity); if (exceptionHandlersActivity != null) { // listen for FaultHandler status change events exceptionHandlersActivity.RegisterForStatusChange(Activity.ClosedEvent, this); // execute exception handlers context.ExecuteActivity(exceptionHandlersActivity); } else { // compensate completed children if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) SafeReleaseLockOnStatusChange(context); // no children to compensate...release lock on to the close status of the activity } } else if (context.Activity.ExecutionResult == ActivityExecutionResult.Canceled) { // if primary activity is closed and outcome is canceled, then run the cancel handler Activity cancelHandler = FaultAndCancellationHandlingFilter.GetCancellationHandler(context.Activity); if (cancelHandler != null) { // execute the cancel handler cancelHandler.RegisterForStatusChange(Activity.ClosedEvent, this); context.ExecuteActivity(cancelHandler); } else { // run default compensation if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) SafeReleaseLockOnStatusChange(context); // release lock on to the close status of the activity } } else // release lock on to the close status of the activity SafeReleaseLockOnStatusChange(context); } } else if ((e.Activity is FaultHandlersActivity || e.Activity is CancellationHandlerActivity) && (e.ExecutionStatus == ActivityExecutionStatus.Closed) ) { // remove subscriber e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this); // fetch the exception , it would be null if it was handled if (context.Activity.GetValue(ActivityExecutionContext.CurrentExceptionProperty) != null) { // the exception was not handled by exceptionHandlers.... do default exceptionHandling // compesate completed children if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) SafeReleaseLockOnStatusChange(context); // no children to compensate.Release lock on to the close status of the activity } else// the exception was handled by the exceptionHandlers. Release lock on to the close status of the parent activity SafeReleaseLockOnStatusChange(context); } else if (e.ExecutionStatus == ActivityExecutionStatus.Closed) { // compensation of a child was in progress. // remove subscriber for this e.Activity.UnregisterForStatusChange(Activity.ClosedEvent, this); // see if there are other children to be compensated if (!CompensationUtils.TryCompensateLastCompletedChildActivity(context, context.Activity, this)) SafeReleaseLockOnStatusChange(context); // release lock on to the close status of the parent activity } } void SafeReleaseLockOnStatusChange(ActivityExecutionContext context) { try { context.Activity.ReleaseLockOnStatusChange(this); } catch (Exception) { context.Activity.RemoveProperty(FaultAndCancellationHandlingFilter.FaultProcessedProperty); throw; } } #endregion #region Helper Methods internal static CompositeActivity GetFaultHandlers(Activity activityWithExceptionHandlers) { CompositeActivity exceptionHandlers = null; CompositeActivity compositeActivity = activityWithExceptionHandlers as CompositeActivity; if (compositeActivity != null) { foreach (Activity activity in ((ISupportAlternateFlow)compositeActivity).AlternateFlowActivities) { if (activity is FaultHandlersActivity) { exceptionHandlers = activity as CompositeActivity; break; } } } return exceptionHandlers; } internal static Activity GetCancellationHandler(Activity activityWithCancelHandler) { Activity cancelHandler = null; CompositeActivity compositeActivity = activityWithCancelHandler as CompositeActivity; if (compositeActivity != null) { foreach (Activity activity in ((ISupportAlternateFlow)compositeActivity).AlternateFlowActivities) { if (activity is CancellationHandlerActivity) { cancelHandler = activity; break; } } } return cancelHandler; } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: BinaryWriter ** ** ** Purpose: Writes primitive values to a stream ** ** ===========================================================*/ namespace System.Runtime.Serialization.Formatters.Binary { using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using System.Globalization; using System.Runtime.Serialization.Formatters; using System.Configuration.Assemblies; using System.Threading; using System.Runtime.Remoting; using System.Runtime.Serialization; internal sealed class __BinaryWriter { internal Stream sout; internal FormatterTypeStyle formatterTypeStyle; internal Hashtable objectMapTable; internal ObjectWriter objectWriter = null; internal BinaryWriter dataWriter = null; // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal int m_nestedObjectCount; #pragma warning restore 0414 private int nullCount = 0; //Count of consecutive array nulls // Constructor internal __BinaryWriter(Stream sout, ObjectWriter objectWriter, FormatterTypeStyle formatterTypeStyle) { SerTrace.Log( this, "BinaryWriter "); this.sout = sout; this.formatterTypeStyle = formatterTypeStyle; this.objectWriter = objectWriter; m_nestedObjectCount = 0; dataWriter = new BinaryWriter(sout, Encoding.UTF8); } internal void WriteBegin() { BCLDebug.Trace("BINARY", "\n%%%%%BinaryWriterBegin%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); } internal void WriteEnd() { BCLDebug.Trace("BINARY", "\n%%%%%BinaryWriterEnd%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); dataWriter.Flush(); } // Methods to write a value onto the stream internal void WriteBoolean(Boolean value) { dataWriter.Write(value); } internal void WriteByte(Byte value) { dataWriter.Write(value); } private void WriteBytes(Byte[] value) { dataWriter.Write(value); } private void WriteBytes(byte[] byteA, int offset, int size) { dataWriter.Write(byteA, offset, size); } internal void WriteChar(Char value) { dataWriter.Write(value); } internal void WriteChars(Char[] value) { dataWriter.Write(value); } internal void WriteDecimal(Decimal value) { WriteString(value.ToString(CultureInfo.InvariantCulture)); } internal void WriteSingle(Single value) { dataWriter.Write(value); } internal void WriteDouble(Double value) { dataWriter.Write(value); } internal void WriteInt16(Int16 value) { dataWriter.Write(value); } internal void WriteInt32(Int32 value) { dataWriter.Write(value); } internal void WriteInt64(Int64 value) { dataWriter.Write(value); } internal void WriteSByte(SByte value) { WriteByte((Byte)value); } internal void WriteString(String value) { dataWriter.Write(value); } internal void WriteTimeSpan(TimeSpan value) { WriteInt64(value.Ticks); } internal void WriteDateTime(DateTime value) { WriteInt64(value.ToBinaryRaw()); } internal void WriteUInt16(UInt16 value) { dataWriter.Write(value); } internal void WriteUInt32(UInt32 value) { dataWriter.Write(value); } internal void WriteUInt64(UInt64 value) { dataWriter.Write(value); } internal void WriteObjectEnd(NameInfo memberNameInfo, NameInfo typeNameInfo) { } internal void WriteSerializationHeaderEnd() { MessageEnd record = new MessageEnd(); record.Dump(sout); record.Write(this); } // Methods to write Binary Serialization Record onto the stream, a record is composed of primitive types internal void WriteSerializationHeader(int topId, int headerId, int minorVersion, int majorVersion) { SerializationHeaderRecord record = new SerializationHeaderRecord(BinaryHeaderEnum.SerializedStreamHeader, topId, headerId, minorVersion, majorVersion); record.Dump(); record.Write(this); } internal BinaryMethodCall binaryMethodCall; internal void WriteMethodCall() { if (binaryMethodCall == null) binaryMethodCall = new BinaryMethodCall(); binaryMethodCall.Dump(); binaryMethodCall.Write(this); } internal Object[] WriteCallArray(String uri, String methodName, String typeName, Type[] instArgs, Object[] args, Object methodSignature, Object callContext, Object[] properties) { if (binaryMethodCall == null) binaryMethodCall = new BinaryMethodCall(); return binaryMethodCall.WriteArray(uri, methodName, typeName, instArgs, args, methodSignature, callContext, properties); } internal BinaryMethodReturn binaryMethodReturn; internal void WriteMethodReturn() { if (binaryMethodReturn == null) binaryMethodReturn = new BinaryMethodReturn(); binaryMethodReturn.Dump(); binaryMethodReturn.Write(this); } internal Object[] WriteReturnArray(Object returnValue, Object[] args, Exception exception, Object callContext, Object[] properties) { if (binaryMethodReturn == null) binaryMethodReturn = new BinaryMethodReturn(); return binaryMethodReturn.WriteArray(returnValue, args, exception, callContext, properties); } internal BinaryObject binaryObject; internal BinaryObjectWithMap binaryObjectWithMap; internal BinaryObjectWithMapTyped binaryObjectWithMapTyped; //internal BinaryCrossAppDomainMap crossAppDomainMap; internal void WriteObject(NameInfo nameInfo, NameInfo typeNameInfo, int numMembers, String[] memberNames, Type[] memberTypes, WriteObjectInfo[] memberObjectInfos) { InternalWriteItemNull(); int assemId; #if _DEBUG nameInfo.Dump("WriteObject nameInfo"); typeNameInfo.Dump("WriteObject typeNameInfo"); #endif int objectId = (int)nameInfo.NIobjectId; //if (objectId < 0) // objectId = --m_nestedObjectCount; if (objectId > 0) { BCLDebug.Trace("BINARY", "-----Top Level Object-----"); } String objectName = null; if (objectId < 0) { // Nested Object objectName = typeNameInfo.NIname; } else { // Non-Nested objectName = nameInfo.NIname; } SerTrace.Log( this, "WriteObject objectName ",objectName); if (objectMapTable == null) { objectMapTable = new Hashtable(); } ObjectMapInfo objectMapInfo = (ObjectMapInfo)objectMapTable[objectName]; if (objectMapInfo != null && objectMapInfo.isCompatible(numMembers, memberNames, memberTypes)) { // Object if (binaryObject == null) binaryObject = new BinaryObject(); binaryObject.Set(objectId, objectMapInfo.objectId); #if _DEBUG binaryObject.Dump(); #endif binaryObject.Write(this); } else if (!typeNameInfo.NItransmitTypeOnObject) { // ObjectWithMap if (binaryObjectWithMap == null) binaryObjectWithMap = new BinaryObjectWithMap(); // BCL types are not placed into table assemId = (int)typeNameInfo.NIassemId; binaryObjectWithMap.Set(objectId, objectName, numMembers, memberNames, assemId); binaryObjectWithMap.Dump(); binaryObjectWithMap.Write(this); if (objectMapInfo == null) objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } else { // ObjectWithMapTyped BinaryTypeEnum[] binaryTypeEnumA = new BinaryTypeEnum[numMembers]; Object[] typeInformationA = new Object[numMembers]; int[] assemIdA = new int[numMembers]; for (int i=0; i<numMembers; i++) { Object typeInformation = null; binaryTypeEnumA[i] = BinaryConverter.GetBinaryTypeInfo(memberTypes[i], memberObjectInfos[i], null, objectWriter, out typeInformation, out assemId); typeInformationA[i] = typeInformation; assemIdA[i] = assemId; SerTrace.Log( this, "WriteObject ObjectWithMapTyped memberNames " ,memberNames[i],", memberType ",memberTypes[i]," binaryTypeEnum ",((Enum)binaryTypeEnumA[i]).ToString() ,", typeInformation ",typeInformationA[i]," assemId ",assemIdA[i]); } if (binaryObjectWithMapTyped == null) binaryObjectWithMapTyped = new BinaryObjectWithMapTyped(); // BCL types are not placed in table assemId = (int)typeNameInfo.NIassemId; binaryObjectWithMapTyped.Set(objectId, objectName, numMembers,memberNames, binaryTypeEnumA, typeInformationA, assemIdA, assemId); #if _DEBUG binaryObjectWithMapTyped.Dump(); #endif binaryObjectWithMapTyped.Write(this); if (objectMapInfo == null) objectMapTable.Add(objectName, new ObjectMapInfo(objectId, numMembers, memberNames, memberTypes)); } } internal BinaryObjectString binaryObjectString; internal BinaryCrossAppDomainString binaryCrossAppDomainString; internal void WriteObjectString(int objectId, String value) { InternalWriteItemNull(); if (binaryObjectString == null) binaryObjectString = new BinaryObjectString(); binaryObjectString.Set(objectId, value); #if _DEBUG binaryObjectString.Dump(); #endif binaryObjectString.Write(this); } internal BinaryArray binaryArray; [System.Security.SecurityCritical] // auto-generated internal void WriteSingleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Array array) { InternalWriteItemNull(); #if _DEBUG arrayNameInfo.Dump("WriteSingleArray arrayNameInfo"); arrayElemTypeNameInfo.Dump("WriteSingleArray arrayElemTypeNameInfo"); #endif BinaryArrayTypeEnum binaryArrayTypeEnum; Int32[] lengthA = new Int32[1]; lengthA[0] = length; Int32[] lowerBoundA = null; Object typeInformation = null; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Single; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.SingleOffset; lowerBoundA = new Int32[1]; lowerBoundA[0] = lowerBound; } int assemId; BinaryTypeEnum binaryTypeEnum = BinaryConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo.NItype, objectInfo, arrayElemTypeNameInfo.NIname, objectWriter, out typeInformation, out assemId); if (binaryArray == null) binaryArray = new BinaryArray(); binaryArray.Set((int)arrayNameInfo.NIobjectId, (int)1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); if (arrayNameInfo.NIobjectId >0) { BCLDebug.Trace("BINARY", "-----Top Level Object-----"); } #if _DEBUG binaryArray.Dump(); #endif binaryArray.Write(this); if (Converter.IsWriteAsByteArray(arrayElemTypeNameInfo.NIprimitiveTypeEnum) && (lowerBound == 0)) { //array is written out as an array of bytes if (arrayElemTypeNameInfo.NIprimitiveTypeEnum == InternalPrimitiveTypeE.Byte) WriteBytes((Byte[])array); else if (arrayElemTypeNameInfo.NIprimitiveTypeEnum == InternalPrimitiveTypeE.Char) WriteChars((char[])array); else WriteArrayAsBytes(array, Converter.TypeLength(arrayElemTypeNameInfo.NIprimitiveTypeEnum)); } } byte[] byteBuffer = null; int chunkSize = 4096; [System.Security.SecurityCritical] // auto-generated private void WriteArrayAsBytes(Array array, int typeLength) { InternalWriteItemNull(); int byteLength = array.Length*typeLength; int arrayOffset = 0; if (byteBuffer == null) byteBuffer = new byte[chunkSize]; while (arrayOffset < array.Length) { int numArrayItems = Math.Min(chunkSize/typeLength, array.Length-arrayOffset); int bufferUsed = numArrayItems*typeLength; Buffer.InternalBlockCopy(array, arrayOffset*typeLength, byteBuffer, 0, bufferUsed); #if BIGENDIAN // we know that we are writing a primitive type, so just do a simple swap for (int i = 0; i < bufferUsed; i += typeLength) { for (int j = 0; j < typeLength / 2; j++) { byte tmp = byteBuffer[i + j]; byteBuffer[i + j] = byteBuffer[i + typeLength-1 - j]; byteBuffer[i + typeLength-1 - j] = tmp; } } #endif WriteBytes(byteBuffer, 0, bufferUsed); arrayOffset += numArrayItems; } } internal void WriteJaggedArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound) { #if _DEBUG arrayNameInfo.Dump("WriteRectangleArray arrayNameInfo"); arrayElemTypeNameInfo.Dump("WriteRectangleArray arrayElemTypeNameInfo"); #endif InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum; Int32[] lengthA = new Int32[1]; lengthA[0] = length; Int32[] lowerBoundA = null; Object typeInformation = null; int assemId = 0; if (lowerBound == 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.Jagged; } else { binaryArrayTypeEnum = BinaryArrayTypeEnum.JaggedOffset; lowerBoundA = new Int32[1]; lowerBoundA[0] = lowerBound; } BinaryTypeEnum binaryTypeEnum = BinaryConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo.NItype, objectInfo, arrayElemTypeNameInfo.NIname, objectWriter, out typeInformation, out assemId); if (binaryArray == null) binaryArray = new BinaryArray(); binaryArray.Set((int)arrayNameInfo.NIobjectId, (int)1, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); if (arrayNameInfo.NIobjectId >0) { BCLDebug.Trace("BINARY", "-----Top Level Object-----"); } #if _DEBUG binaryArray.Dump(); #endif binaryArray.Write(this); } internal void WriteRectangleArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int rank, int[] lengthA, int[] lowerBoundA) { #if _DEBUG arrayNameInfo.Dump("WriteRectangleArray arrayNameInfo"); arrayElemTypeNameInfo.Dump("WriteRectangleArray arrayElemTypeNameInfo"); #endif InternalWriteItemNull(); BinaryArrayTypeEnum binaryArrayTypeEnum = BinaryArrayTypeEnum.Rectangular; Object typeInformation = null; int assemId = 0; BinaryTypeEnum binaryTypeEnum = BinaryConverter.GetBinaryTypeInfo(arrayElemTypeNameInfo.NItype, objectInfo, arrayElemTypeNameInfo.NIname, objectWriter, out typeInformation, out assemId); if (binaryArray == null) binaryArray = new BinaryArray(); for (int i=0; i<rank; i++) { if (lowerBoundA[i] != 0) { binaryArrayTypeEnum = BinaryArrayTypeEnum.RectangularOffset; break; } } binaryArray.Set((int)arrayNameInfo.NIobjectId, rank, lengthA, lowerBoundA, binaryTypeEnum, typeInformation, binaryArrayTypeEnum, assemId); if (arrayNameInfo.NIobjectId >0) { BCLDebug.Trace("BINARY", "-----Top Level Object-----"); } #if _DEBUG binaryArray.Dump(); #endif binaryArray.Write(this); } [System.Security.SecurityCritical] // auto-generated internal void WriteObjectByteArray(NameInfo memberNameInfo, NameInfo arrayNameInfo, WriteObjectInfo objectInfo, NameInfo arrayElemTypeNameInfo, int length, int lowerBound, Byte[] byteA) { #if _DEBUG arrayNameInfo.Dump("WriteObjectByteArray arrayNameInfo"); arrayElemTypeNameInfo.Dump("WriteObjectByteArray arrayElemTypeNameInfo"); #endif InternalWriteItemNull(); WriteSingleArray(memberNameInfo, arrayNameInfo, objectInfo, arrayElemTypeNameInfo, length, lowerBound, byteA); } internal MemberPrimitiveUnTyped memberPrimitiveUnTyped; internal MemberPrimitiveTyped memberPrimitiveTyped; internal void WriteMember(NameInfo memberNameInfo, NameInfo typeNameInfo, Object value) { #if _DEBUG SerTrace.Log("BinaryWriter", "Write Member memberName ",memberNameInfo.NIname,", value ",value); memberNameInfo.Dump("WriteMember memberNameInfo"); typeNameInfo.Dump("WriteMember typeNameInfo"); #endif InternalWriteItemNull(); InternalPrimitiveTypeE typeInformation = typeNameInfo.NIprimitiveTypeEnum; // Writes Members with primitive values if (memberNameInfo.NItransmitTypeOnMember) { if (memberPrimitiveTyped == null) memberPrimitiveTyped = new MemberPrimitiveTyped(); memberPrimitiveTyped.Set((InternalPrimitiveTypeE)typeInformation, value); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { BCLDebug.Trace("BINARY","-----",memberNameInfo.NIname,"-----"); } memberPrimitiveTyped.Dump(); memberPrimitiveTyped.Write(this); } else { if (memberPrimitiveUnTyped == null) memberPrimitiveUnTyped = new MemberPrimitiveUnTyped(); memberPrimitiveUnTyped.Set(typeInformation, value); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { BCLDebug.Trace("BINARY", "-----",memberNameInfo.NIname,"-----"); } memberPrimitiveUnTyped.Dump(); memberPrimitiveUnTyped.Write(this); } } internal ObjectNull objectNull; internal void WriteNullMember(NameInfo memberNameInfo, NameInfo typeNameInfo) { #if _DEBUG typeNameInfo.Dump("WriteNullMember typeNameInfo"); #endif InternalWriteItemNull(); if (objectNull == null) objectNull = new ObjectNull(); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { objectNull.SetNullCount(1); BCLDebug.Trace("BINARY", "-----",memberNameInfo.NIname,"-----"); objectNull.Dump(); objectNull.Write(this); nullCount = 0; } } internal MemberReference memberReference; internal void WriteMemberObjectRef(NameInfo memberNameInfo, int idRef) { InternalWriteItemNull(); if (memberReference == null) memberReference = new MemberReference(); memberReference.Set(idRef); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { BCLDebug.Trace("BINARY", "-----",memberNameInfo.NIname,"-----"); } memberReference.Dump(); memberReference.Write(this); } internal void WriteMemberNested(NameInfo memberNameInfo) { InternalWriteItemNull(); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { BCLDebug.Trace("BINARY", "-----",memberNameInfo.NIname,"-----"); } } internal void WriteMemberString(NameInfo memberNameInfo, NameInfo typeNameInfo, String value) { InternalWriteItemNull(); if (memberNameInfo.NIisArrayItem) { BCLDebug.Trace("BINARY", "-----item-----"); } else { BCLDebug.Trace("BINARY", "-----",memberNameInfo.NIname,"-----"); } WriteObjectString((int)typeNameInfo.NIobjectId, value); } internal void WriteItem(NameInfo itemNameInfo, NameInfo typeNameInfo, Object value) { InternalWriteItemNull(); WriteMember(itemNameInfo, typeNameInfo, value); } internal void WriteNullItem(NameInfo itemNameInfo, NameInfo typeNameInfo) { nullCount++; InternalWriteItemNull(); } internal void WriteDelayedNullItem() { nullCount++; } internal void WriteItemEnd() { InternalWriteItemNull(); } private void InternalWriteItemNull() { if (nullCount > 0) { if (objectNull == null) objectNull = new ObjectNull(); objectNull.SetNullCount(nullCount); BCLDebug.Trace("BINARY", "-----item-----"); objectNull.Dump(); objectNull.Write(this); nullCount = 0; } } internal void WriteItemObjectRef(NameInfo nameInfo, int idRef) { InternalWriteItemNull(); WriteMemberObjectRef(nameInfo, idRef); } internal BinaryAssembly binaryAssembly; internal BinaryCrossAppDomainAssembly crossAppDomainAssembly; internal void WriteAssembly(Type type, String assemblyString, int assemId, bool isNew) { SerTrace.Log( this,"WriteAssembly type ",type,", id ",assemId,", name ", assemblyString,", isNew ",isNew); //If the file being tested wasn't built as an assembly, then we're going to get null back //for the assembly name. This is very unfortunate. InternalWriteItemNull(); if (assemblyString==null) { assemblyString=String.Empty; } if (isNew) { if (binaryAssembly == null) binaryAssembly = new BinaryAssembly(); binaryAssembly.Set(assemId, assemblyString); binaryAssembly.Dump(); binaryAssembly.Write(this); } } // Method to write a value onto a stream given its primitive type code internal void WriteValue(InternalPrimitiveTypeE code, Object value) { SerTrace.Log( this, "WriteValue Entry ",((Enum)code).ToString()," " , ((value==null)?"<null>":value.GetType().ToString()) , " ",value); switch (code) { case InternalPrimitiveTypeE.Boolean: WriteBoolean(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Byte: WriteByte(Convert.ToByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Char: WriteChar(Convert.ToChar(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Double: WriteDouble(Convert.ToDouble(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int16: WriteInt16(Convert.ToInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int32: WriteInt32(Convert.ToInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Int64: WriteInt64(Convert.ToInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.SByte: WriteSByte(Convert.ToSByte(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Single: WriteSingle(Convert.ToSingle(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt16: WriteUInt16(Convert.ToUInt16(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt32: WriteUInt32(Convert.ToUInt32(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.UInt64: WriteUInt64(Convert.ToUInt64(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.Decimal: WriteDecimal(Convert.ToDecimal(value, CultureInfo.InvariantCulture)); break; case InternalPrimitiveTypeE.TimeSpan: WriteTimeSpan((TimeSpan)value); break; case InternalPrimitiveTypeE.DateTime: WriteDateTime((DateTime)value); break; default: throw new SerializationException(Environment.GetResourceString("Serialization_TypeCode",((Enum)code).ToString())); } SerTrace.Log( this, "Write Exit "); } } internal sealed class ObjectMapInfo { internal int objectId; int numMembers; String[] memberNames; Type[] memberTypes; internal ObjectMapInfo(int objectId, int numMembers, String[] memberNames, Type[] memberTypes) { this.objectId = objectId; this.numMembers = numMembers; this.memberNames = memberNames; this.memberTypes = memberTypes; } internal bool isCompatible(int numMembers, String[] memberNames, Type[] memberTypes) { bool result = true; if (this.numMembers == numMembers) { for (int i=0; i<numMembers; i++) { if (!(this.memberNames[i].Equals(memberNames[i]))) { result = false; break; } if ((memberTypes != null) && (this.memberTypes[i] != memberTypes[i])) { result = false; break; } } } else result = false; return result; } } }
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 TsAngular2.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; } } }
using System; using System.Collections; using System.Data; using PCSComUtils.Admin.DS; using PCSComUtils.Framework.TableFrame.DS; using PCSComUtils.PCSExc; using PCSComUtils.Common.DS; using PCSComUtils.MasterSetup.DS; using PCSComUtils.DataContext; using PCSComUtils.DataAccess; using System.Linq; namespace PCSComUtils.Common.BO { public class UtilsBO { #region IUtilsBO Members //************************************************************************** /// <Description> /// Get list of QA status /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// THIENHD /// </Authors> /// <History> /// 15-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataTable GetQAStatus() { const string ID_FIELD = "ID"; const string VALUE_FIELD = "VALUE"; // TODO: Add ProductItemInfoBO.GetQAStatus implementation try { DataTable dtQAStatus = new DataTable(); dtQAStatus.Columns.Add(ID_FIELD); dtQAStatus.Columns.Add(VALUE_FIELD); DataRow drNewRow = dtQAStatus.NewRow(); drNewRow = dtQAStatus.NewRow(); dtQAStatus.Rows.Add(drNewRow); drNewRow = dtQAStatus.NewRow(); drNewRow[ID_FIELD] = "1"; drNewRow[VALUE_FIELD] = "not source quality assured and requires inspection"; dtQAStatus.Rows.Add(drNewRow); drNewRow = dtQAStatus.NewRow(); drNewRow[ID_FIELD] = "2"; drNewRow[VALUE_FIELD] = "not source quality assured but does not require inspection"; dtQAStatus.Rows.Add(drNewRow); drNewRow = dtQAStatus.NewRow(); drNewRow[ID_FIELD] = "3"; drNewRow[VALUE_FIELD] = "source quality assured"; dtQAStatus.Rows.Add(drNewRow); return dtQAStatus; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } public DataTable GetMaterialReceiptType() { // TODO: Add ProductItemInfoBO.GetQAStatus implementation try { DataTable dtTable = new DataTable(); dtTable.Columns.Add(Constants.ID_FIELD); dtTable.Columns.Add(Constants.VALUE_FIELD); DataRow drNewRow; drNewRow = dtTable.NewRow(); drNewRow[Constants.ID_FIELD] = "1"; drNewRow[Constants.VALUE_FIELD] = "PO"; dtTable.Rows.Add(drNewRow); drNewRow = dtTable.NewRow(); drNewRow[Constants.ID_FIELD] = "2"; drNewRow[Constants.VALUE_FIELD] = "WO"; dtTable.Rows.Add(drNewRow); return dtTable; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get From Date, To Date of current period /// </Description> /// <Inputs></Inputs> /// <Outputs> /// DateTime, DateTime /// </Outputs> /// <Returns></Returns> /// <Authors> /// Tuan TQ, Isphere Software Co., Ltd /// </Authors> /// <History> /// Created Date: 05-May-2005 /// </History> /// <Notes></Notes> //************************************************************************** public void GetDateOfCurrentPeriod(out DateTime p_dtm_FromDate, out DateTime p_dtm_ToDate) { try { string str_Condition = Constants.WHERE_KEYWORD + " " + Sys_PeriodTable.ACTIVATE_FLD + " = " + Constants.TRUE_VALUE.ToString(); DataTable table = (new UtilsDS()).GetRows(Sys_PeriodTable.TABLE_NAME, str_Condition); if (table != null) { if (table.Rows.Count != 0) { p_dtm_FromDate = DateTime.Parse(table.Rows[0][Sys_PeriodTable.FROMDATE_FLD].ToString()); p_dtm_ToDate = DateTime.Parse(table.Rows[0][Sys_PeriodTable.TODATE_FLD].ToString()); return; } } //otherwise, get current date on DB server p_dtm_FromDate = GetDBDate(); p_dtm_ToDate = GetDBDate(); } catch (Exception ex) { throw ex; } } public DateTime GetDBDate() { // TODO: Add UtilsBO.GetDBDate implementation try { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.GetDBDate(); } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } public string GetNoByMask(string strTableName, string strFieldName, DateTime dtEntryDate, string strFormat) { // TODO: Add UtilsBO.GetDBDate implementation try { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.GetNoByMask(strTableName, strFieldName, dtEntryDate, strFormat); } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } public string GetNoByMask(string pstrTableName, string pstrFieldName, string pstrPrefix, string pstrFormat) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.GetNoByMask(pstrTableName, pstrFieldName, pstrPrefix, pstrFormat); } public string GetNoByMask(string pstrTableName, string pstrFieldName, string pstrPrefix, string pstrFormat, DateTime entryDate, out int revision) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.GetNoByMask(pstrTableName, pstrFieldName, pstrPrefix, pstrFormat, entryDate, out revision); } public string GetNoByMask(string pstrUsername, string pstrTableName, string pstrFieldName, string pstrPrefix, string pstrFormat) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.GetNoByMask(pstrUsername, pstrTableName, pstrFieldName, pstrPrefix, pstrFormat); } #endregion /// <summary> /// Get comma-separated list of In stock tranaction type ID /// </summary> /// <returns></returns> /// <author> Tuan TQ. 28 Dec, 2005</author> public string GetInStockTransTypeID() { return (new UtilsDS()).GetInStockTransTypeID(); } public Sys_Menu_EntryVO GetMenuInfoForCK(string pstrFormName, string pstrTableName, string pstrTransNoFieldName, string pstrPrefix) { Sys_Menu_EntryDS dsMenu = new Sys_Menu_EntryDS(); return dsMenu.GetMenuByFormLoadForCK(pstrFormName, pstrTableName, pstrTransNoFieldName, pstrPrefix); } /// <summary> /// Get comma-separated list of Out stock tranaction type ID /// </summary> /// <returns></returns> /// <author> Tuan TQ. 28 Dec, 2005</author> public string GetOutStockTransTypeID() { return (new UtilsDS()).GetOutStockTransTypeID(); } public ArrayList GetWorkingDayByYear(int pintYear) { return (new UtilsDS()).GetWorkingDayByYear(pintYear); } /// <summary> /// Get list of Holiday in a specific year /// </summary> /// <param name="pdtmStartDate"></param> /// <param name="penuSchedule"></param> /// <returns></returns> public ArrayList GetHolidaysInYear(DateTime pdtmStartDate, ScheduleMethodEnum penuSchedule) { return (new UtilsDS()).GetHolidaysInYear(pdtmStartDate, penuSchedule); } public ArrayList GetHolidaysInYear(int pintYear) { return (new UtilsDS()).GetHolidaysInYear(pintYear); } /// <summary> /// Get working date after adding pintNumberOfDay /// </summary> /// <param name="pdtmDate"></param> /// <param name="pintNumberOfDay"></param> /// <param name="penuSchedule"> /// 1: Forward /// 2: Backword /// </param> /// <returns></returns> public DateTime ConvertWorkingDay(DateTime pdtmDate, int pintNumberOfDay, ScheduleMethodEnum penuSchedule) { try { DateTime dtmConvert = pdtmDate;//new DateTime(pdtmDate.Year, pdtmDate.Month, pdtmDate.Day); UtilsDS dsUtil = new UtilsDS(); ArrayList arrDayOfWeek = dsUtil.GetWorkingDayByYear(pdtmDate.Year); ArrayList arrHolidays = dsUtil.GetHolidaysInYear(pdtmDate, penuSchedule); switch (penuSchedule) { case ScheduleMethodEnum.Forward: for (int i = 0; i < pintNumberOfDay; i++) { //Add day dtmConvert = dtmConvert.AddDays(1); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } break; case ScheduleMethodEnum.Backward: for (int i = 0; i < pintNumberOfDay; i++) { //Add day dtmConvert = dtmConvert.AddDays(-1); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(-1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(-1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } break; } return dtmConvert; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Get working date after adding pintNumberOfDay /// </summary> /// <param name="pdtmDate"></param> /// <param name="pintNumberOfDay"></param> /// <param name="penuSchedule"> /// 1: Forward /// 2: Backword /// </param> /// <returns></returns> public DateTime ConvertWorkingDay(DateTime pdtmDate, decimal pdecNumberOfDay, ScheduleMethodEnum penuSchedule) { try { int intNumberOfDay = (int)decimal.Floor(pdecNumberOfDay); double dblRemainder = (double)(pdecNumberOfDay - (decimal)intNumberOfDay); DateTime dtmConvert = pdtmDate;//new DateTime(pdtmDate.Year, pdtmDate.Month, pdtmDate.Day); UtilsDS dsUtil = new UtilsDS(); ArrayList arrDayOfWeek = dsUtil.GetWorkingDayByYear(pdtmDate.Year); ArrayList arrHolidays = dsUtil.GetHolidaysInYear(pdtmDate, penuSchedule); switch (penuSchedule) { case ScheduleMethodEnum.Forward: for (int i = 0; i < intNumberOfDay; i++) { //Add day dtmConvert = dtmConvert.AddDays(1); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //Add remainder dtmConvert = dtmConvert.AddDays(dblRemainder); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(1); } break; case ScheduleMethodEnum.Backward: for (int i = 0; i < intNumberOfDay; i++) { //Add day dtmConvert = dtmConvert.AddDays(-1); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(-1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //Add remainder dtmConvert = dtmConvert.AddDays(-dblRemainder); //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } //goto next day if the day is off day while (arrDayOfWeek.Contains(dtmConvert.DayOfWeek)) { dtmConvert = dtmConvert.AddDays(-1); if (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } } //goto next day if the day is holidayday while (arrHolidays.Contains(new DateTime(dtmConvert.Year, dtmConvert.Month, dtmConvert.Day))) { dtmConvert = dtmConvert.AddDays(-1); } break; } return dtmConvert; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public object GetUMInfor(int pintUMID) { try { MST_UnitOfMeasureDS dsUM = new MST_UnitOfMeasureDS(); return dsUM.GetObjectVO(pintUMID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public string GetCCNCodeFromID(int pintCCNID) { try { MST_CCNDS dsCCN = new MST_CCNDS(); return dsCCN.GetCCNCodeFromID(pintCCNID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListCarrier() { try { MST_CarrierDS dsCarrier = new MST_CarrierDS(); return dsCarrier.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListUnitOfMeasure() { try { MST_UnitOfMeasureDS dsUnit = new MST_UnitOfMeasureDS(); return dsUnit.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListCurrency() { try { MST_CurrencyDS dsCurrency = new MST_CurrencyDS(); return dsCurrency.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataSet ListCCN() { try { MST_CCNDS dsCCN = new MST_CCNDS(); return dsCCN.List(); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListCCNForCheckListBox() { try { MST_CCNDS dsCCN = new MST_CCNDS(); return dsCCN.ListAllCCN(); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListUser() { try { Sys_UserDS dsSysUser = new Sys_UserDS(); return dsSysUser.ListAllUsers(); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListAllMenu() { Sys_Menu_EntryDS dsSysMenu = new Sys_Menu_EntryDS(); return dsSysMenu.List().Tables[0]; } public DataSet ListMasterLocationByCCNID(int pintCCNID) { try { MST_MasterLocationDS dsMasterLocation = new MST_MasterLocationDS(); return dsMasterLocation.ListByCCNID(pintCCNID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataSet ListLocationByMasterLocationID(int pintMasterLocationID) { try { MST_LocationDS dsLocation = new MST_LocationDS(); return dsLocation.ListByMasterLocationID(pintMasterLocationID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataSet ListBinByLocationID(int pintLocationID) { try { MST_BINDS dsBIN = new MST_BINDS(); return dsBIN.ListByLocationID(pintLocationID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataSet ListReasonByCCNID(int pintCCNID) { try { MST_ReasonDS dsReason = new MST_ReasonDS(); return dsReason.ListByCCNID(pintCCNID); } catch (PCSException ex) { throw ex; } catch (Exception ex) { throw ex; } } public DataTable ListCountry() { try { MST_CountryDS dsCountry = new MST_CountryDS(); return dsCountry.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListCityByCountry(int pintCountryID) { try { MST_CityDS dsCity = new MST_CityDS(); return dsCity.ListByCountry(pintCountryID); } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListAllCity() { try { MST_CityDS dsCity = new MST_CityDS(); return dsCity.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListAddCharge() { try { MST_AddChargeDS dsAddCharge = new MST_AddChargeDS(); return dsAddCharge.List().Tables[0]; } catch (PCSException ex) { throw ex.CauseException; } catch (Exception ex) { throw ex; } } public DataTable ListReasonByCCN(int pintCCNID) { MST_ReasonDS dsReason = new MST_ReasonDS(); return dsReason.List(pintCCNID).Tables[0]; } public DataTable GetRows(string pstrTableName, string pstrFieldName, string pstrFieldValue, Hashtable phashOtherConditions, string pstrConditionByRecord) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.IsTableOrViewConfigured(pstrTableName) ? objUtilsDS.GetRows(pstrTableName, pstrFieldName, pstrFieldValue, phashOtherConditions, pstrConditionByRecord) : null; } public DataTable GetRows(string pstrTableName, string pstrFieldName, string pstrFieldValue, Hashtable phashOtherConditions) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.IsTableOrViewConfigured(pstrTableName) ? objUtilsDS.GetRows(pstrTableName, pstrFieldName, pstrFieldValue, phashOtherConditions, string.Empty) : null; } public DataTable GetRows(string pstrTableName, string pstrExpression) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.IsTableOrViewConfigured(pstrTableName) ? objUtilsDS.GetRows(pstrTableName, pstrExpression) : null; } /// <summary> /// This method is used to get the DataTable result /// from a specific table with a specific search field key. /// This function will be used on form that need to search for ID from Code, Name /// such as Product Code, or Product description /// </summary> /// <param name="pstrTableName">Table Name</param> /// <param name="pstrFieldName">Filter Field</param> /// <param name="pstrFieldValue">Filter Value</param> /// <param name="pstrExpression">Expression or Where Clause</param> /// <returns>Result</returns> public DataTable GetRowsWithWhere(string pstrTableName, string pstrFieldName, string pstrFieldValue, string pstrExpression) { UtilsDS objUtilsDS = new UtilsDS(); return objUtilsDS.IsTableOrViewConfigured(pstrTableName) ? objUtilsDS.GetRowsWithWhere(pstrTableName, pstrFieldName, pstrFieldValue, pstrExpression) : null; } public decimal GetUMRate(int pintInUMID, int pintOutUMID) { MST_UMRateDS dsUMRate = new MST_UMRateDS(); return dsUMRate.GetUMRate(pintInUMID, pintOutUMID); } public decimal GetExchangeRate(int pintCurrencyID, DateTime pdtmPostDate) { MST_ExchangeRateDS dsMST = new MST_ExchangeRateDS(); return dsMST.GetLastExchangeRate(pintCurrencyID, pdtmPostDate); } public bool IsSystemAdmin(string pstrUserName) { Sys_UserDS dsUser = new Sys_UserDS(); return dsUser.IsSystemAdmin(pstrUserName); } /// <summary> /// This method will create a DataTable with two columns and hold following data: /// - R: Regular Time : 0 /// - O: Over Time : 1 /// - S: Sunday Time : 2 /// </summary> /// <returns></returns> public DataTable GetHourCode() { // TODO: Add ProductItemInfoBO.GetQAStatus implementation try { DataTable dtHourCode = new DataTable(); dtHourCode.Columns.Add(Constants.ID_FIELD); dtHourCode.Columns.Add(Constants.VALUE_FIELD); DataRow drNewRow; drNewRow = dtHourCode.NewRow(); drNewRow[Constants.ID_FIELD] = "0"; drNewRow[Constants.VALUE_FIELD] = "Regular Time"; dtHourCode.Rows.Add(drNewRow); drNewRow = dtHourCode.NewRow(); drNewRow[Constants.ID_FIELD] = "1"; drNewRow[Constants.VALUE_FIELD] = "Over Time"; dtHourCode.Rows.Add(drNewRow); drNewRow = dtHourCode.NewRow(); drNewRow[Constants.ID_FIELD] = "2"; drNewRow[Constants.VALUE_FIELD] = "Sunday Time"; dtHourCode.Rows.Add(drNewRow); return dtHourCode; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// This method will create a DataTable with two columns and hold following data: /// - S: Setup : 0 /// - R: Run : 1 /// </summary> /// <returns></returns> public DataTable GetSetupRunCode() { try { DataTable dtSetupRunCode = new DataTable(); dtSetupRunCode.Columns.Add(Constants.ID_FIELD); dtSetupRunCode.Columns.Add(Constants.VALUE_FIELD); DataRow drNewRow; drNewRow = dtSetupRunCode.NewRow(); drNewRow[Constants.ID_FIELD] = "0"; drNewRow[Constants.VALUE_FIELD] = "Setup"; dtSetupRunCode.Rows.Add(drNewRow); drNewRow = dtSetupRunCode.NewRow(); drNewRow[Constants.ID_FIELD] = "1"; drNewRow[Constants.VALUE_FIELD] = "Run"; dtSetupRunCode.Rows.Add(drNewRow); return dtSetupRunCode; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } /// <summary> /// Get Machine and Labor setup code /// Get Machine and Labor load code /// </summary> /// <returns></returns> /// public DataTable GetMLSetupLoadCode() { try { DataTable dtCode = new DataTable(); dtCode.Columns.Add(Constants.ID_FIELD); dtCode.Columns.Add(Constants.VALUE_FIELD); DataRow drNewRow; drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "COM"; drNewRow[Constants.VALUE_FIELD] = "Operation Complete"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "EHL"; drNewRow[Constants.VALUE_FIELD] = "Operation on engineering hold"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "IP"; drNewRow[Constants.VALUE_FIELD] = "Operation in process/No Problems"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "MHL"; drNewRow[Constants.VALUE_FIELD] = "Operation waiting materials"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "NS"; drNewRow[Constants.VALUE_FIELD] = "Operation not started/No Problems"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "OHL"; drNewRow[Constants.VALUE_FIELD] = "Operation waiting am operator"; dtCode.Rows.Add(drNewRow); drNewRow = dtCode.NewRow(); drNewRow[Constants.ID_FIELD] = "THL"; drNewRow[Constants.VALUE_FIELD] = "Operation waiting tooling"; dtCode.Rows.Add(drNewRow); return dtCode; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Execute PO report and return data table /// </summary> /// <param name="pstrSql">Query string to be executed</param> /// <returns>Result DataTable</returns> public DataTable ExecutePOReport(ref string pstrSql, int pintPOMasterID) { try { UtilsDS dsUtils = new UtilsDS(); return dsUtils.ExecutePOReport(ref pstrSql, pintPOMasterID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public object GetWorkOrderMasterInforForMaterialReceipt(int pintWorkOrderMasterID) { try { return null; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public object GetWorkOrderDetailInforForMaterialReceipt(int pintWorkOrderDetailID) { try { return null; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public object GetPurchaseOrderMasterInforForMaterialReceipt(int pintPurchaseOrderMasterID) { try { return null; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public object GetPurchaseOrderDetailInforForMaterialReceipt(int pintPurchaseOrderDetailID) { try { return null; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Get Master Location object by ID /// </summary> /// <param name="pintMasterLocID"></param> /// <returns></returns> /// <author>TuanDM</author> public MST_MasterLocationVO GetMasterLocByID(int pintMasterLocID) { try { return (MST_MasterLocationVO)new MST_MasterLocationDS().GetObjectVO(pintMasterLocID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Get database version /// </summary> /// <returns></returns> /// <author>DuongNA</author> public string GetDBVersion() { string strVersion = string.Empty; try { Sys_ParamDS dsSysParam = new Sys_ParamDS(); // HACK: dungla 10-21-2005 // use DB_VERSION from SystemParam instead of Constant strVersion = dsSysParam.GetNameValue(SystemParam.DB_VERSION); // END: dungla 10-21-2005 } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } return strVersion; } public bool GetRoundedQuantity() { bool blnRoundedQuantity = false; const string ZERO = "0"; const string ROUNDED_QUANTITY = "RoundedQuantity"; try { Sys_ParamDS dsSysParam = new Sys_ParamDS(); string strValue = dsSysParam.GetNameValue(ROUNDED_QUANTITY); blnRoundedQuantity = !strValue.Equals(ZERO); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } return blnRoundedQuantity; } /// <summary> /// Get All system params /// </summary> /// <returns>DataTable of All System Params</returns> public DataTable GetSystemParams() { try { Sys_ParamDS dsSysParam = new Sys_ParamDS(); return dsSysParam.List().Tables[0]; } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } /// <summary> /// Get MST_PartyVO object from ID /// </summary> /// <param name="pintPartyID">Party ID</param> /// <returns>MST_PartyVO</returns> /// <author>DungLA</author> public object GetPartyInfo(int pintPartyID) { MST_PartyDS dsParty = new MST_PartyDS(); return dsParty.GetObjectVO(pintPartyID); } /// <summary> /// Get MST_CCNVO object from ID /// </summary> /// <param name="pintCCNID">CCNID</param> /// <returns>MST_CCNVO</returns> /// <author>DungLA</author> public object GetCCNInfo(int pintCCNID) { MST_CCNDS dsCCN = new MST_CCNDS(); return dsCCN.GetObjectVO(pintCCNID); } /// <summary> /// /// </summary> /// <param name="pstrUserName"></param> /// <returns></returns> public bool UserNameBelongToAdministratorRole(string pstrUserName) { Sys_RoleDS dsRole = new Sys_RoleDS(); return dsRole.UserNameBelongToAdministratorRole(pstrUserName); } public DataSet GetRightToModify(string pstrUserName, string pstrTableName, string pstrPrimaryKeyField, int pintMasterID) { Sys_RoleDS dsRole = new Sys_RoleDS(); return dsRole.GetRightToModify(pstrUserName, pstrTableName, pstrPrimaryKeyField, pintMasterID); } public void UpdateUserNameModifyTransaction(string pstrUserName, string pstrTableName, string pstrPrimaryKeyField, int pintMasterID) { Sys_RoleDS dsRole = new Sys_RoleDS(); dsRole.UpdateUserNameModifyTransaction(pstrUserName, pstrTableName, pstrPrimaryKeyField, pintMasterID); } public DataSet GetDefaultInfomation() { Sys_RoleDS dsRole = new Sys_RoleDS(); return dsRole.GetDefaultInfomation(); } public string GetConditionByRecord(string pstrUserName, string pstrTableName) { return (new sysGenerateTableFormDS()).GetConditionByRecord(pstrUserName, pstrTableName); } public DataTable GetPurposeByTransTypeID(int pintTransTypeID) { return new UtilsDS().GetPurPoseByTransType(pintTransTypeID); } public int GetTransTypeIDByCode(string pstrCode) { return new MST_TranTypeDS().GetTranTypeID(pstrCode); } /// <summary> /// Get home currency of CCN /// </summary> /// <param name="pintCCNID">CCN</param> /// <returns>Home Currency Code</returns> public string GetHomeCurrency(int pintCCNID) { MST_CurrencyDS dsCurrency = new MST_CurrencyDS(); return dsCurrency.GetCurrencyByCCN(pintCCNID); } /// <summary> /// Get USD Currency /// </summary> /// <returns>USD MST_CurrencyVO object</returns> public object GetUSDCurrency() { MST_CurrencyDS dsCurrency = new MST_CurrencyDS(); return dsCurrency.GetUSDCurrency(); } #region HACKED: Thachnn: split function /// <summary> /// Split the input ArrayList of String to string element. Ex: 1 2 3 4 5 6 7 8 9 ----> (1,2,3) (4,5,6) (7,8,9) /// </summary> /// <author>Thachnn 27/04/2006</author> /// <exception cref="">InvalidCastException</exception> /// <param name="parrNeedToSplit">ArrayList of string. If each element is not string, it will raise Invalid Cast Exception </param> /// <param name="pnSplitElementLength">Length of each output element, if this parameter is <=0, it will return empty ArrayList</param> /// <returns>ArrayList, each element is in format ( , , , ) </returns> public static ArrayList GetSplitList(ArrayList parrNeedToSplit, int pnSplitElementLength) { const string COMMA = ","; const string OPEN = "("; const string CLOSE = ")"; #region exception case if (parrNeedToSplit.Count == 0 || pnSplitElementLength <= 0) { return new ArrayList(); } if (parrNeedToSplit.Count == 1) { ArrayList arrRet = new ArrayList(1); arrRet.Add(OPEN + parrNeedToSplit[0] + CLOSE); return arrRet; } if (pnSplitElementLength == 1) // improve speed { ArrayList arrRet = new ArrayList(parrNeedToSplit.Count); foreach (string str in parrNeedToSplit) { arrRet.Add(OPEN + str + CLOSE); } return arrRet; } #endregion exception case int nCounter = 0; ArrayList arr = new ArrayList(); //ArrayList arrTemp = parrNeedToSplit.GetRange(0, pnSplitElementLength); string strConcat = string.Empty; foreach (object obj in parrNeedToSplit) { if (obj != null) { string str = obj.ToString(); strConcat = strConcat + str + COMMA; nCounter++; if (nCounter == pnSplitElementLength) { if (strConcat.EndsWith(COMMA)) { strConcat = strConcat.Substring(0, strConcat.Length - 1); } arr.Add(OPEN + strConcat + CLOSE); // reset nCounter = 0; strConcat = string.Empty; } } } // add the last (not full element) to the return ArrayList if (0 < nCounter && nCounter <= pnSplitElementLength) { if (strConcat.EndsWith(COMMA)) { strConcat = strConcat.Substring(0, strConcat.Length - 1); } arr.Add(OPEN + strConcat + CLOSE); // reset nCounter = 0; strConcat = string.Empty; } return arr; } #endregion ENDHACKED: Thachnn: split function public void GetMenuInfo(string pstrFormName, out string strTableName, out string strTransNoFieldName, out string strPrefix, out string strFormat) { strTableName = string.Empty; strTransNoFieldName = string.Empty; strPrefix = string.Empty; strFormat = string.Empty; Sys_Menu_EntryDS dsMenu = new Sys_Menu_EntryDS(); dsMenu.GetMenuByFormLoad(pstrFormName, out strTableName, out strTransNoFieldName, out strPrefix, out strFormat); } /// <summary> /// Update selected state for multi selection form /// </summary> /// <param name="pstrTableName">Temp Table Name</param> /// <param name="pstrFilter">Filter string</param> /// <param name="pblnSelected">Select state</param> /// <returns></returns> public DataSet UpdateSelected(string pstrTableName, string pstrFilter, bool pblnSelected) { UtilsDS dsUtils = new UtilsDS(); return dsUtils.UpdateSelected(pstrTableName, pstrFilter, pblnSelected); } public DataSet UpdateSelectedRow(string pstrTableName, string pstrFilter, bool pblnSelected, int iProductID, int iWorkOrderMasterID, int iWorkOrderDetailID, int iComponentI) { UtilsDS dsUtils = new UtilsDS(); return dsUtils.UpdateSelectedRow(pstrTableName, pstrFilter, pblnSelected, iProductID, iWorkOrderMasterID, iWorkOrderDetailID, iComponentI); } public void UpdateTempTable(DataSet pdtbData) { UtilsDS dsUtils = new UtilsDS(); dsUtils.UpdateTempTable(pdtbData); } public PRO_Shift GetShiftDefault(string strShiftCode) { using (var db = new PCSDataContext(Utils.Instance.ConnectionString)) return db.PRO_Shifts.SingleOrDefault(e => e.ShiftDesc == strShiftCode); } } }
namespace LuaInterface { using System; using System.IO; using System.Collections; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using Lua511; /* * Cached method */ struct MethodCache { private MethodBase _cachedMethod; public MethodBase cachedMethod { get { return _cachedMethod; } set { _cachedMethod = value; MethodInfo mi = value as MethodInfo; if (mi != null) { IsReturnVoid = string.Compare(mi.ReturnType.Name, "System.Void", true) == 0; } } } public bool IsReturnVoid; // List or arguments public object[] args; // Positions of out parameters public int[] outList; // Types of parameters public MethodArgs[] argTypes; } /* * Parameter information */ struct MethodArgs { // Position of parameter public int index; // Type-conversion function public ExtractValue extractValue; public bool isParamsArray; public Type paramsArrayType; } /* * Argument extraction with type-conversion function */ delegate object ExtractValue(IntPtr luaState, int stackPos); /* * Wrapper class for methods/constructors accessed from Lua. * * Author: Fabio Mascarenhas * Version: 1.0 */ class LuaMethodWrapper { private ObjectTranslator _Translator; private MethodBase _Method; private MethodCache _LastCalledMethod = new MethodCache(); private string _MethodName; private MemberInfo[] _Members; private IReflect _TargetType; private ExtractValue _ExtractTarget; private object _Target; private BindingFlags _BindingType; /* * Constructs the wrapper for a known MethodBase instance */ public LuaMethodWrapper(ObjectTranslator translator, object target, IReflect targetType, MethodBase method) { _Translator = translator; _Target = target; _TargetType = targetType; if (targetType != null) _ExtractTarget = translator.typeChecker.getExtractor(targetType); _Method = method; _MethodName = method.Name; if (method.IsStatic) { _BindingType = BindingFlags.Static; } else { _BindingType = BindingFlags.Instance; } } /* * Constructs the wrapper for a known method name */ public LuaMethodWrapper(ObjectTranslator translator, IReflect targetType, string methodName, BindingFlags bindingType) { _Translator = translator; _MethodName = methodName; _TargetType = targetType; if (targetType != null) _ExtractTarget = translator.typeChecker.getExtractor(targetType); _BindingType = bindingType; //CP: Removed NonPublic binding search and added IgnoreCase _Members = targetType.UnderlyingSystemType.GetMember(methodName, MemberTypes.Method, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase/*|BindingFlags.NonPublic*/); } /// <summary> /// Convert C# exceptions into Lua errors /// </summary> /// <returns>num of things on stack</returns> /// <param name="e">null for no pending exception</param> int SetPendingException(Exception e) { return _Translator.interpreter.SetPendingException(e); } /* * Calls the method. Receives the arguments from the Lua stack * and returns values in it. */ public int call(IntPtr luaState) { MethodBase methodToCall = _Method; object targetObject = _Target; bool failedCall = true; int nReturnValues = 0; if (!LuaDLL.lua_checkstack(luaState, 5)) throw new LuaException("Lua stack overflow"); bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (methodToCall == null) // Method from name { if (isStatic) targetObject = null; else targetObject = _ExtractTarget(luaState, 1); //LuaDLL.lua_remove(luaState,1); // Pops the receiver if (_LastCalledMethod.cachedMethod != null) // Cached? { int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject int numArgsPassed = LuaDLL.lua_gettop(luaState) - numStackToSkip; MethodBase method = _LastCalledMethod.cachedMethod; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) throw new LuaException("Lua stack overflow"); object [] args = _LastCalledMethod.args; try { for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) { MethodArgs type = _LastCalledMethod.argTypes [i]; int index = i + 1 + numStackToSkip; Func<int, object> valueExtractor = (currentParam) => { return type.extractValue (luaState, currentParam); }; if (_LastCalledMethod.argTypes [i].isParamsArray) { int count = index - _LastCalledMethod.argTypes.Length; Array paramArray = _Translator.TableToArray (valueExtractor, type.paramsArrayType, index, count); args [_LastCalledMethod.argTypes [i].index] = paramArray; } else { args [type.index] = valueExtractor (index); } if (_LastCalledMethod.args[_LastCalledMethod.argTypes[i].index] == null && !LuaDLL.lua_isnil(luaState, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((_BindingType & BindingFlags.Static) == BindingFlags.Static) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); else _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } failedCall = false; } catch (TargetInvocationException e) { // Failure of method invocation return SetPendingException(e.GetBaseException()); } catch (Exception e) { if (_Members.Length == 1) // Is the method overloaded? // No, throw error return SetPendingException(e); } } } // Cache miss if (failedCall) { // System.Diagnostics.Debug.WriteLine("cache miss on " + methodName); // If we are running an instance variable, we can now pop the targetObject from the stack if (!isStatic) { if (targetObject == null) { _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName)); LuaDLL.lua_pushnil(luaState); return 1; } LuaDLL.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (MemberInfo member in _Members) { candidateName = member.ReflectedType.Name + "." + member.Name; MethodBase m = (MethodInfo)member; bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod); if (isMethod) { hasMatch = true; break; } } if (!hasMatch) { string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName); _Translator.throwError(luaState, msg); LuaDLL.lua_pushnil(luaState); return 1; } } } else // Method from MethodBase instance { if (methodToCall.ContainsGenericParameters) { bool isMethod = _Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod); if (methodToCall.IsGenericMethodDefinition) { //need to make a concrete type of the generic method definition List<Type> typeArgs = new List<Type>(); foreach (object arg in _LastCalledMethod.args) typeArgs.Add(arg.GetType()); MethodInfo concreteMethod = (methodToCall as MethodInfo).MakeGenericMethod(typeArgs.ToArray()); _Translator.push(luaState, concreteMethod.Invoke(targetObject, _LastCalledMethod.args)); failedCall = false; } else if (methodToCall.ContainsGenericParameters) { _Translator.throwError(luaState, "unable to invoke method on generic class as the current method is an open generic method"); LuaDLL.lua_pushnil(luaState); return 1; } } else { if (!methodToCall.IsStatic && !methodToCall.IsConstructor && targetObject == null) { targetObject = _ExtractTarget(luaState, 1); LuaDLL.lua_remove(luaState, 1); // Pops the receiver } if (!_Translator.matchParameters(luaState, methodToCall, ref _LastCalledMethod)) { _Translator.throwError(luaState, "invalid arguments to method call"); LuaDLL.lua_pushnil(luaState); return 1; } } } if (failedCall) { if (!LuaDLL.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) throw new LuaException("Lua stack overflow"); try { if (isStatic) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); else _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } } catch (TargetInvocationException e) { return SetPendingException(e.GetBaseException()); } catch (Exception e) { return SetPendingException(e); } } // Pushes out and ref return values for (int index = 0; index < _LastCalledMethod.outList.Length; index++) { nReturnValues++; //for(int i=0;i<lastCalledMethod.outList.Length;i++) _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]); } //by isSingle 2010-09-10 11:26:31 //Desc: // if not return void,we need add 1, // or we will lost the function's return value // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0) { nReturnValues++; } return nReturnValues < 1 ? 1 : nReturnValues; } } /// <summary> /// We keep track of what delegates we have auto attached to an event - to allow us to cleanly exit a LuaInterface session /// </summary> class EventHandlerContainer : IDisposable { Dictionary<Delegate, RegisterEventHandler> dict = new Dictionary<Delegate, RegisterEventHandler>(); public void Add(Delegate handler, RegisterEventHandler eventInfo) { dict.Add(handler, eventInfo); } public void Remove(Delegate handler) { bool found = dict.Remove(handler); Debug.Assert(found); } /// <summary> /// Remove any still registered handlers /// </summary> public void Dispose() { foreach (KeyValuePair<Delegate, RegisterEventHandler> pair in dict) { pair.Value.RemovePending(pair.Key); } dict.Clear(); } } /* * Wrapper class for events that does registration/deregistration * of event handlers. * * Author: Fabio Mascarenhas * Version: 1.0 */ class RegisterEventHandler { object target; EventInfo eventInfo; EventHandlerContainer pendingEvents; public RegisterEventHandler(EventHandlerContainer pendingEvents, object target, EventInfo eventInfo) { this.target = target; this.eventInfo = eventInfo; this.pendingEvents = pendingEvents; } /* * Adds a new event handler */ public Delegate Add(LuaFunction function) { //CP: Fix by Ben Bryant for event handling with one parameter //link: http://luaforge.net/forum/message.php?msg_id=9266 Delegate handlerDelegate = CodeGeneration.Instance.GetDelegate(eventInfo.EventHandlerType, function); eventInfo.AddEventHandler(target, handlerDelegate); pendingEvents.Add(handlerDelegate, this); return handlerDelegate; //MethodInfo mi = eventInfo.EventHandlerType.GetMethod("Invoke"); //ParameterInfo[] pi = mi.GetParameters(); //LuaEventHandler handler=CodeGeneration.Instance.GetEvent(pi[1].ParameterType,function); //Delegate handlerDelegate=Delegate.CreateDelegate(eventInfo.EventHandlerType,handler,"HandleEvent"); //eventInfo.AddEventHandler(target,handlerDelegate); //pendingEvents.Add(handlerDelegate, this); //return handlerDelegate; } /* * Removes an existing event handler */ public void Remove(Delegate handlerDelegate) { RemovePending(handlerDelegate); pendingEvents.Remove(handlerDelegate); } /* * Removes an existing event handler (without updating the pending handlers list) */ internal void RemovePending(Delegate handlerDelegate) { eventInfo.RemoveEventHandler(target, handlerDelegate); } } /* * Base wrapper class for Lua function event handlers. * Subclasses that do actual event handling are created * at runtime. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaEventHandler { public LuaFunction handler = null; // CP: Fix provided by Ben Bryant for delegates with one param // link: http://luaforge.net/forum/message.php?msg_id=9318 public void handleEvent(object[] args) { handler.Call(args); } //public void handleEvent(object sender,object data) //{ // handler.call(new object[] { sender,data },new Type[0]); //} } /* * Wrapper class for Lua functions as delegates * Subclasses with correct signatures are created * at runtime. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaDelegate { public Type[] returnTypes; public LuaFunction function; public LuaDelegate() { function = null; returnTypes = null; } public object callFunction(object[] args, object[] inArgs, int[] outArgs) { // args is the return array of arguments, inArgs is the actual array // of arguments passed to the function (with in parameters only), outArgs // has the positions of out parameters object returnValue; int iRefArgs; object[] returnValues = function.call(inArgs, returnTypes); if (returnTypes[0] == typeof(void)) { returnValue = null; iRefArgs = 0; } else { returnValue = returnValues[0]; iRefArgs = 1; } // Sets the value of out and ref parameters (from // the values returned by the Lua function). for (int i = 0; i < outArgs.Length; i++) { args[outArgs[i]] = returnValues[iRefArgs]; iRefArgs++; } return returnValue; } } /* * Static helper methods for Lua tables acting as CLR objects. * * Author: Fabio Mascarenhas * Version: 1.0 */ public class LuaClassHelper { /* * Gets the function called name from the provided table, * returning null if it does not exist */ public static LuaFunction getTableFunction(LuaTable luaTable, string name) { object funcObj = luaTable.rawget(name); if (funcObj is LuaFunction) return (LuaFunction)funcObj; else return null; } /* * Calls the provided function with the provided parameters */ public static object callFunction(LuaFunction function, object[] args, Type[] returnTypes, object[] inArgs, int[] outArgs) { // args is the return array of arguments, inArgs is the actual array // of arguments passed to the function (with in parameters only), outArgs // has the positions of out parameters object returnValue; int iRefArgs; object[] returnValues = function.call(inArgs, returnTypes); if (returnTypes[0] == typeof(void)) { returnValue = null; iRefArgs = 0; } else { returnValue = returnValues[0]; iRefArgs = 1; } for (int i = 0; i < outArgs.Length; i++) { args[outArgs[i]] = returnValues[iRefArgs]; iRefArgs++; } return returnValue; } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using MindTouch.Deki.Script; using MindTouch.Deki.Script.Runtime.Library; using MindTouch.Dream; using MindTouch.Tasking; using MindTouch.Xml; namespace MindTouch.Deki.Services { using Yield = IEnumerator<IYield>; [DreamService("MindTouch MediaWiki Extension", "Copyright (c) 2006-2010 MindTouch Inc.", Info = "http://developer.mindtouch.com/App_Catalog/MediaWiki", SID = new string[] { "sid://mindtouch.com/2008/04/mediawiki", "http://services.mindtouch.com/deki/draft/2008/04/mediawiki" } )] [DreamServiceBlueprint("deki/service-type", "extension")] [DekiExtLibrary( Label = "MediaWiki", Namespace = "mediawiki", Description = "This extension contains functions for embedding content from mediawiki.", Logo = "$files/mediawiki-logo.png" )] [DekiExtLibraryFiles(Prefix = "MindTouch.Deki.Services", Filenames = new string[] { "mediawiki-logo.png" })] public class MediWikiService : DekiExtService { //--- Class Fields --- private static readonly Regex ARG_REGEX = new Regex(@"^([a-zA-Z0-9_]+)$", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline); //--- Fields --- private Dictionary<string, NS> _namespaceValues; private char _pageSeparator; //--- Methods --- protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); XDoc pageSeparatorDoc = Config["pageseparator"]; if (!pageSeparatorDoc.IsEmpty && !String.IsNullOrEmpty(pageSeparatorDoc.Contents)) { _pageSeparator = pageSeparatorDoc.Contents[0]; } // populate the namespace name to type mapping string projectName = Config["projectname"].AsText; _namespaceValues = new Dictionary<string, NS>(); Type currentType = typeof(MediWikiService); using(StreamReader reader = new StreamReader(Assembly.GetAssembly(currentType).GetManifestResourceStream("MindTouch.Deki.Services.namespaces.txt"))) { string line; while ((line = reader.ReadLine()) != null) { line = line.Trim(); int equalIndex = line.IndexOf("="); if (0 < equalIndex) { string namespaceName = line.Substring(0, equalIndex); if (null != projectName) { namespaceName = namespaceName.Replace("$1", projectName); } _namespaceValues[namespaceName.ToLowerInvariant()] = (NS)Int32.Parse(line.Substring(equalIndex + 1)); } } } result.Return(); } /// <summary> /// Retrieve the type corresponding to the namespace name. /// </summary> public NS StringToNS(String nsString) { NS ns = Title.StringToNS(nsString); if (NS.UNKNOWN == ns) { if (!_namespaceValues.TryGetValue(nsString.ToLowerInvariant(), out ns)) { ns = NS.UNKNOWN; } } return ns; } /// <summary> /// Helper to retrieve the namespace and path from a relative page path string /// </summary> private Title PrefixedMWPathToTitle(string fullPath) { NS ns = NS.MAIN; string path = fullPath.Trim(); // if there is a namespace, retrieve it int nsPos = path.IndexOf(':'); if (nsPos > 1) { ns = StringToNS(path.Substring(0, nsPos)); // if the namespace is not found, default to using the main namespace // if found, extract the namespace from the title text if (NS.UNKNOWN == ns) { ns = NS.MAIN; } else { path = path.Substring(nsPos + 1); } } return Title.FromDbPath(ns, path, null); } public bool CreateLanguageHierarchyForNS(NS ns) { // create a namespace heirarchy for everything but the user and template namespaces return (NS.USER != ns && NS.USER_TALK != ns && NS.TEMPLATE != ns && NS.TEMPLATE_TALK != ns && NS.SPECIAL != ns); } /// <summary> /// Converts a MediaWiki title to its MindTouch format /// </summary> /// <param name="mwTitle">The title to convert</param> /// <param name="replaceSeparator">If true, replace ":" with "/"</param> /// <returns>The converted title</returns> public Title MWToDWTitle(string rootPage, Title mwTitle) { string dbPath = null; string dbPrefix = null; // create a language heirarchy in the main namespaces if (CreateLanguageHierarchyForNS(mwTitle.Namespace)) { dbPrefix = rootPage + "/"; } // prefix template pages with language to make unique accross langauges else if (mwTitle.IsTemplate || NS.TEMPLATE_TALK == mwTitle.Namespace || mwTitle.IsSpecial) { return mwTitle; } dbPath = mwTitle.AsUnprefixedDbPath(); if ('/' != _pageSeparator) { dbPath = dbPath.Replace("/", "//"); if (0 < _pageSeparator) { // Replace page separator with "/" String[] segments = dbPath.Split(_pageSeparator); if (1 < segments.Length) { StringBuilder result = new StringBuilder(); for (int i = 0; i < segments.Length; i++) { if ((0 < i && !String.IsNullOrEmpty(segments[i - 1])) && !(i == segments.Length - 1 && String.IsNullOrEmpty(segments[i]))) { result.Append("/"); } if (String.IsNullOrEmpty(segments[i])) { result.Append(_pageSeparator); } else { result.Append(segments[i].Trim(new char[] { '_' })); } } dbPath = result.ToString(); } } } dbPath = dbPrefix + dbPath; return Title.FromDbPath(mwTitle.Namespace, dbPath.Trim('/'), null, mwTitle.Filename, mwTitle.Anchor, mwTitle.Query); } //--- Functions --- [DekiExtFunction(Description = "Converts MediaWiki interwiki link.")] public XDoc InterWiki( [DekiExtParam("interwiki prefix")] string prefix, [DekiExtParam("interwiki path")] string path, [DekiExtParam("title")] string title ) { if (!String.IsNullOrEmpty(prefix)) { string prefixValue = null; try { prefixValue = (Config[prefix].AsText); } catch { } if (!String.IsNullOrEmpty(prefixValue)) { return new XDoc("html").Start("body").Start("a").Attr("href", prefixValue.Replace("$1", path)).Value(title).End().End(); } } throw new DreamInternalErrorException(string.Format("Undefined interwiki prefix: {0}", prefix)); } [DekiExtFunction(Description = "Converts MediaWiki anchorencode function")] public string AnchorEncode( [DekiExtParam("section anchor name")] string section ) { return XUri.Encode(section.Trim().Replace(' ', '_')).ReplaceAll("%3A", ":", "%", "."); } [DekiExtFunction(Description = "Converts MediaWiki grammar function.")] public string Grammar( [DekiExtParam("case")] string wordCase, [DekiExtParam("word to derive")] string word ) { return word; } [DekiExtFunction(Description = "Converts MediaWiki variable.")] public string Variable( [DekiExtParam("MediaWiki variable")] string var ) { throw new DreamInternalErrorException(string.Format("Undefined variable: {0}", var)); } [DekiExtFunction(Name="NS", Description = "Converts MediaWiki ns function.")] public string GetNS( [DekiExtParam("namespace value")] string ns ) { // check if this is a namespace number int intValue; if (Int32.TryParse(ns, out intValue)) { return Title.NSToString((NS)intValue); } // check if this is a recognized namespace string NS nsValue; if (_namespaceValues.TryGetValue(ns.Trim().ToLowerInvariant(), out nsValue)) { if (Enum.IsDefined(typeof(NS), nsValue)) { return Title.NSToString(nsValue); } } throw new DreamInternalErrorException(string.Format("Undefined namespace: {0}", ns)); } [DekiExtFunction(Description = "Converts from a MediaWiki path to a MindTouch path.")] public string Path( [DekiExtParam("path")] string path, [DekiExtParam("language", true)] string language ) { bool isMainInclude = false; path = path.Trim(); // check for explicit declaration of the main namespace if (path.StartsWith(":")) { isMainInclude = true; path = path.Substring(1); } else { Title dwTitle = Title.FromPrefixedDbPath(path, null); if (dwTitle.IsMain) { dwTitle.Namespace = NS.TEMPLATE; } path = dwTitle.AsPrefixedDbPath(); } path = LocalUrl(language, path, null).Trim('/'); if (isMainInclude) { path = ":" + path; } return path; } [DekiExtFunction(Description = "Converts MediaWiki localurl function.")] public string LocalUrl( [DekiExtParam("language")] string language, [DekiExtParam("page")] string page, [DekiExtParam("query", true)] string query ) { page = page.Replace(' ', '_').Trim(new char[] { '_', ':' }); string result = null; // check for interwiki link int interWikiEndIndex = page.IndexOf(':', 1); if (0 <= interWikiEndIndex) { string prefix = page.Substring(0, interWikiEndIndex); if (!String.IsNullOrEmpty(prefix)) { // if the link already contains a language, use it string prefixValue = null; try { prefixValue = Config["rootpage-" + prefix].AsText; } catch { } if (!String.IsNullOrEmpty(prefixValue)) { language = prefix; page = page.Substring(interWikiEndIndex + 1); } else { try { prefixValue = Config[prefix].AsText; } catch { } if (!String.IsNullOrEmpty(prefixValue)) { page = page.Substring(interWikiEndIndex + 1); result = prefixValue.Replace("$1", page); } } } } if (null == result) { // check if we need to map the language string rootPage = String.Empty; if (!String.IsNullOrEmpty(language)) { try { rootPage = Config["rootpage-" + language].AsText ?? String.Empty; } catch { } } // normalize the namespace and map it to the mindtouch deki location Title mwTitle = PrefixedMWPathToTitle(page); if (!StringUtil.EqualsInvariantIgnoreCase(mwTitle.Path, rootPage) && !StringUtil.StartsWithInvariantIgnoreCase(mwTitle.Path, rootPage + "/")) { Title dwTitle = MWToDWTitle(rootPage, mwTitle); result = dwTitle.AsPrefixedDbPath(); } else { result = mwTitle.AsPrefixedDbPath(); } } if (null != query) { result += "?" + query; } return result; } [DekiExtFunction(Description = "Converts MediaWiki localurle function.")] public string LocalUrlE( [DekiExtParam("language")] string language, [DekiExtParam("page")] string page, [DekiExtParam("query", true)] string query ) { return LocalUrl(language, page, query); } [DekiExtFunction(Description = "Converts the MediaWiki [[ ]] notation.")] public XDoc Internal( [DekiExtParam("link")] string link, [DekiExtParam("language", true)] string language ) { // extract the link title string displayName = null; int displayNameIndex = link.IndexOf('|'); if (0 < displayNameIndex) { displayName = link.Substring(displayNameIndex + 1, link.Length - displayNameIndex - 1); link = link.Substring(0, displayNameIndex); } Title title = Title.FromUIUri(null, link, true); if (("." == title.Path) && (title.HasAnchor)) { link = "#" + AnchorEncode(title.Anchor); } else { link = LocalUrl(language, title.AsPrefixedDbPath(), title.Query); if (title.HasAnchor) { link += "#" + AnchorEncode(title.Anchor); } } // return the internal link XDoc result = new XDoc("html").Start("body").Start("a").Attr("href", link).AddNodes(DekiScriptLibrary.WebHtml(displayName ?? String.Empty, null, null, null)["body"]).End().End(); return result; } [DekiExtFunction(Description = "Converts the MediaWiki [ ] notation.")] public XDoc External( [DekiExtParam("link")] string link ) { // store the original link value string originalLink = link; // remove spaces from the link link = link.Trim(); // extract the title if there is one (indicated by the first space) string title = String.Empty; int titleIndex = link.IndexOf(' '); if (0 < titleIndex) { title = link.Substring(titleIndex + 1, link.Length - titleIndex - 1); link = link.Substring(0, titleIndex); } // if the url is valid return it as a link - otherwise return the original text XDoc result = new XDoc("html").Start("body"); XUri uri = null; if (XUri.TryParse(link, out uri)) { result.Start("a").Attr("href", link).AddNodes(DekiScriptLibrary.WebHtml(title, null, null, null)["body"]).End(); } else { result.AddNodes(DekiScriptLibrary.WebHtml("[" + originalLink + "]", null, null, null)["body"]); } result.End(); return result; } [DekiExtFunction(Description = "Converts MediaWiki template arguments to a map.")] public Hashtable Args(ArrayList args) { // return a map arguments // if the argument has a name use it, otherwise use the argument index as the name Hashtable result = new Hashtable(); for (int i = 0; i < args.Count; i++) { string arg = String.Empty; try { arg = SysUtil.ChangeType<string>(args[i]); } catch {} int equalIndex = arg.IndexOf("="); if (0 < equalIndex) { string id = arg.Substring(0, equalIndex).Trim(); if(ARG_REGEX.IsMatch(id)) { result[id] = arg.Substring(equalIndex + 1, arg.Length - equalIndex - 1); } else { result[i.ToString()] = arg; } } else { result[i.ToString()] = arg; } } return result; } } }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using Microsoft.Xna.Framework; using QEngine.Physics.Collision.RayCast; using QEngine.Physics.Shared; using QEngine.Physics.Utilities; namespace QEngine.Physics.Collision.Shapes { /// <summary> /// A chain shape is a free form sequence of line segments. /// The chain has two-sided collision, so you can use inside and outside collision. /// Therefore, you may use any winding order. /// Connectivity information is used to create smooth collisions. /// WARNING: The chain will not collide properly if there are self-intersections. /// </summary> public class ChainShape : Shape { private static EdgeShape _edgeShape = new EdgeShape(); private bool _hasPrevVertex, _hasNextVertex; private Vector2 _prevVertex, _nextVertex; /// <summary> /// Constructor for ChainShape. By default have 0 in density. /// </summary> public ChainShape() : base(0) { ShapeType = ShapeType.Chain; _radius = Settings.PolygonRadius; } /// <summary> /// Create a new chainshape from the vertices. /// </summary> /// <param name="vertices">The vertices to use. Must contain 2 or more vertices.</param> /// <param name="createLoop"> /// Set to true to create a closed loop. It connects the first vertice to the last, and /// automatically adjusts connectivity to create smooth collisions along the chain. /// </param> public ChainShape(Vertices vertices, bool createLoop = false) : base(0) { ShapeType = ShapeType.Chain; _radius = Settings.PolygonRadius; System.Diagnostics.Debug.Assert(vertices != null && vertices.Count >= 3); System.Diagnostics.Debug.Assert(vertices[0] != vertices[vertices.Count - 1]); //Velcro. See http://www.box2d.org/forum/viewtopic.php?f=4&t=7973&p=35363 for (int i = 1; i < vertices.Count; ++i) { // If the code crashes here, it means your vertices are too close together. System.Diagnostics.Debug.Assert(Vector2.DistanceSquared(vertices[i - 1], vertices[i]) > Settings.LinearSlop * Settings.LinearSlop); } Vertices = new Vertices(vertices); //Velcro: I merged CreateLoop() and CreateChain() to this if (createLoop) { Vertices.Add(vertices[0]); PrevVertex = Vertices[Vertices.Count - 2]; //Velcro: We use the properties instead of the private fields here to set _hasPrevVertex NextVertex = Vertices[1]; //Velcro: We use the properties instead of the private fields here here to set _hasNextVertex } } /// <summary> /// The vertices. These are not owned/freed by the chain Shape. /// </summary> public Vertices Vertices { get; set; } /// <summary> /// Edge count = vertex count - 1 /// </summary> public override int ChildCount => Vertices.Count - 1; /// <summary> /// Establish connectivity to a vertex that precedes the first vertex. /// Don't call this for loops. /// </summary> public Vector2 PrevVertex { get { return _prevVertex; } set { _prevVertex = value; _hasPrevVertex = true; } } /// <summary> /// Establish connectivity to a vertex that follows the last vertex. /// Don't call this for loops. /// </summary> public Vector2 NextVertex { get { return _nextVertex; } set { _nextVertex = value; _hasNextVertex = true; } } internal void GetChildEdge(EdgeShape edge, int index) { System.Diagnostics.Debug.Assert(0 <= index && index < Vertices.Count - 1); System.Diagnostics.Debug.Assert(edge != null); edge.ShapeType = ShapeType.Edge; edge._radius = _radius; edge.Vertex1 = Vertices[index + 0]; edge.Vertex2 = Vertices[index + 1]; if (index > 0) { edge.Vertex0 = Vertices[index - 1]; edge.HasVertex0 = true; } else { edge.Vertex0 = _prevVertex; edge.HasVertex0 = _hasPrevVertex; } if (index < Vertices.Count - 2) { edge.Vertex3 = Vertices[index + 2]; edge.HasVertex3 = true; } else { edge.Vertex3 = _nextVertex; edge.HasVertex3 = _hasNextVertex; } } public EdgeShape GetChildEdge(int index) { EdgeShape edgeShape = new EdgeShape(); GetChildEdge(edgeShape, index); return edgeShape; } public override bool TestPoint(ref Transform transform, ref Vector2 point) { return false; } public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex) { System.Diagnostics.Debug.Assert(childIndex < Vertices.Count); int i1 = childIndex; int i2 = childIndex + 1; if (i2 == Vertices.Count) { i2 = 0; } _edgeShape.Vertex1 = Vertices[i1]; _edgeShape.Vertex2 = Vertices[i2]; return _edgeShape.RayCast(out output, ref input, ref transform, 0); } public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex) { System.Diagnostics.Debug.Assert(childIndex < Vertices.Count); int i1 = childIndex; int i2 = childIndex + 1; if (i2 == Vertices.Count) { i2 = 0; } Vector2 v1 = MathUtils.Mul(ref transform, Vertices[i1]); Vector2 v2 = MathUtils.Mul(ref transform, Vertices[i2]); aabb.LowerBound = Vector2.Min(v1, v2); aabb.UpperBound = Vector2.Max(v1, v2); } protected override void ComputeProperties() { //Does nothing. Chain shapes don't have properties. } //Velcro: This is for the BuoyancyController public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc) { sc = Vector2.Zero; return 0; } /// <summary> /// Compare the chain to another chain /// </summary> /// <param name="shape">The other chain</param> /// <returns>True if the two chain shapes are the same</returns> public bool CompareTo(ChainShape shape) { if (Vertices.Count != shape.Vertices.Count) return false; for (int i = 0; i < Vertices.Count; i++) { if (Vertices[i] != shape.Vertices[i]) return false; } return PrevVertex == shape.PrevVertex && NextVertex == shape.NextVertex; } public override Shape Clone() { ChainShape clone = new ChainShape(); clone.ShapeType = ShapeType; clone._density = _density; clone._radius = _radius; clone.PrevVertex = _prevVertex; clone.NextVertex = _nextVertex; clone._hasNextVertex = _hasNextVertex; clone._hasPrevVertex = _hasPrevVertex; clone.Vertices = new Vertices(Vertices); return clone; } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.ICollection.Add(T) /// </summary> public class ICollectionAdd { private int c_MINI_STRING_LENGTH = 8; private int c_MAX_STRING_LENGTH = 256; public static int Main(string[] args) { ICollectionAdd testObj = new ICollectionAdd(); TestLibrary.TestFramework.BeginTestCase("Testing for Methord: System.Collections.Generic.ICollection.Add(T)"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Netativ]"); retVal = NegTest1() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using List<T> which implemented the add method in ICollection<T> and Type is int..."; const string c_TEST_ID = "P001"; List<int> list = new List<int>(); int item1 = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<int>)list).Add(item1); if (list[0] != item1) { string errorDesc = "Value is not " + list[0] + " as expected: Actual(" + item1 + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using List<T> which implemented the add method in ICollection<T> and Type is a reference type..."; const string c_TEST_ID = "P002"; List<String> list = new List<String>(); String item1 = TestLibrary.Generator.GetString(-55, false,c_MINI_STRING_LENGTH,c_MAX_STRING_LENGTH); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<String>)list).Add(item1); if (list[0] != item1) { string errorDesc = "Value is not " + list[0] + " as expected: Actual(" + item1 + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using List<T> which implemented the add method in ICollection<T> and Type is a reference type..."; const string c_TEST_ID = "P003"; MyCollection<int> myC = new MyCollection<int>(); int item1 = TestLibrary.Generator.GetInt32(-55); int count = 1; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((ICollection<int>)myC).Add(item1); if (myC.Count != count) { string errorDesc = "Value have not been add to ICollection<T>"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Using user-defined type which is readonly"); MyCollection<int> myC = new MyCollection<int>(); myC.isReadOnly = true; int item1 = TestLibrary.Generator.GetInt32(-55); try { ((ICollection<int>)myC).Add(item1); TestLibrary.TestFramework.LogError("007", "The NotSupportedException was not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyCollection<T> : ICollection<T> { public T[] value; protected int length; public bool isReadOnly = false; public MyCollection() { value =new T[10]; length = 0; } #region ICollection<T> Members public void Add(T item) { if (isReadOnly) { throw new NotSupportedException(); } else { value[length] = item; length++; } } public void Clear() { throw new Exception("The method or operation is not implemented."); } public bool Contains(T item) { throw new Exception("The method or operation is not implemented."); } public void CopyTo(T[] array, int arrayIndex) { throw new Exception("The method or operation is not implemented."); } public int Count { get { return length;} } public bool IsReadOnly { get { return isReadOnly; } } public bool Remove(T item) { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion } #endregion }
using System.Collections.Immutable; using System.Diagnostics; using System.Text; using Meziantou.Framework.CodeDom; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Meziantou.Framework.StronglyTypedId; [Generator] public sealed partial class StronglyTypedIdSourceGenerator : IIncrementalGenerator { // Possible improvements // // - XmlSerializer / NewtonsoftJsonConvert / MongoDbConverter / Elaticsearch / YamlConverter // - TypeConverter / IConvertible private const string FieldName = "_value"; private const string PropertyName = "Value"; private const string PropertyAsStringName = "ValueAsString"; [SuppressMessage("Usage", "MA0101:String contains an implicit end of line character", Justification = "Not important")] private const string AttributeText = @" // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ [System.Diagnostics.Conditional(""StronglyTypedId_Attributes"")] [System.AttributeUsage(System.AttributeTargets.Struct | System.AttributeTargets.Class)] internal sealed class StronglyTypedIdAttribute : System.Attribute { /// <summary> /// Indicate the type is a strongly-typed id /// </summary> /// <param name=""idType"">Type of the generated Value</param> /// <param name=""generateSystemTextJsonConverter"">Specify if the <see cref=""System.Text.Json.Serialization.JsonConverter""/> should be generated</param> /// <param name=""generateNewtonsoftJsonConverter"">Specify if the <see cref=""Newtonsoft.Json.JsonConverter""/> should be generated</param> /// <param name=""generateSystemComponentModelTypeConverter"">Specify if the <see cref=""System.ComponentModel.TypeConverter""/> should be generated</param> /// <param name=""generateMongoDBBsonSerialization"">Specify if the <see cref=""MongoDB.Bson.Serialization.Serializers.SerializerBase{T}""/> should be generated</param> /// <param name=""addCodeGeneratedAttribute"">Add <see cref=""System.CodeDom.Compiler.GeneratedCodeAttribute""/> to the generated members</param> public StronglyTypedIdAttribute(System.Type idType, bool generateSystemTextJsonConverter = true, bool generateNewtonsoftJsonConverter = true, bool generateSystemComponentModelTypeConverter = true, bool generateMongoDBBsonSerialization = true, bool addCodeGeneratedAttribute = true) { } } "; private static readonly DiagnosticDescriptor s_unsuportedType = new( id: "MFSTID0001", title: "Not support type", messageFormat: "The type '{0}' is not supported", category: "StronglyTypedId", DiagnosticSeverity.Error, isEnabledByDefault: true); public void Initialize(IncrementalGeneratorInitializationContext context) { context.RegisterPostInitializationOutput(ctx => ctx.AddSource("StronglyTypedIdAttribute.g.cs", SourceText.From(AttributeText, Encoding.UTF8))); var types = context.SyntaxProvider.CreateSyntaxProvider( predicate: static (syntax, cancellationToken) => IsSyntaxTargetForGeneration(syntax), transform: static (ctx, cancellationToken) => GetSemanticTargetForGeneration(ctx, cancellationToken)) .Where(static m => m is not null); var typesToProcess = context.CompilationProvider .Combine(types.Collect()); context.RegisterSourceOutput(typesToProcess, (spc, source) => Execute(spc, source.Left, source.Right!)); static bool IsSyntaxTargetForGeneration(SyntaxNode syntax) { return (syntax.IsKind(SyntaxKind.StructDeclaration) || syntax.IsKind(SyntaxKind.ClassDeclaration) || syntax.IsKind(SyntaxKind.RecordDeclaration)) && ((TypeDeclarationSyntax)syntax).AttributeLists.Count > 0; } static TypeDeclarationSyntax? GetSemanticTargetForGeneration(GeneratorSyntaxContext ctx, CancellationToken cancellationToken) { var semanticModel = ctx.SemanticModel; var compilation = semanticModel.Compilation; var typeDeclaration = (TypeDeclarationSyntax)ctx.Node; var attributeSymbol = compilation.GetTypeByMetadataName("StronglyTypedIdAttribute"); if (attributeSymbol == null) return null; var symbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken); if (symbol == null) return null; foreach (var attribute in symbol.GetAttributes()) { if (attributeSymbol.Equals(attribute.AttributeClass, SymbolEqualityComparer.Default)) return typeDeclaration; } return null; } } private static void Execute(SourceProductionContext context, Compilation compilation, ImmutableArray<TypeDeclarationSyntax> typeDeclarations) { var attributeSymbol = compilation.GetTypeByMetadataName("StronglyTypedIdAttribute"); Debug.Assert(attributeSymbol != null); foreach (var typeDeclaration in typeDeclarations) { var semanticModel = compilation.GetSemanticModel(typeDeclaration.SyntaxTree); var typeSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, context.CancellationToken)!; var attributeInfo = GetAttributeInfo(context, semanticModel, attributeSymbol, typeSymbol); if (attributeInfo == null) continue; var stronglyTypedId = new StronglyTypedIdInfo(compilation, typeSymbol.ContainingSymbol, typeSymbol, typeSymbol.Name, attributeInfo, typeDeclaration); var codeUnit = new CompilationUnit { NullableContext = CodeDom.NullableContext.Enable, }; var structDeclaration = CreateType(codeUnit, stronglyTypedId); GenerateTypeMembers(compilation, structDeclaration, stronglyTypedId); if (stronglyTypedId.AttributeInfo.Converters.HasFlag(StronglyTypedIdConverters.System_ComponentModel_TypeConverter)) { GenerateTypeConverter(structDeclaration, compilation, stronglyTypedId.AttributeInfo.IdType); } if (stronglyTypedId.AttributeInfo.Converters.HasFlag(StronglyTypedIdConverters.System_Text_Json)) { GenerateSystemTextJsonConverter(structDeclaration, compilation, stronglyTypedId); } if (stronglyTypedId.AttributeInfo.Converters.HasFlag(StronglyTypedIdConverters.Newtonsoft_Json)) { GenerateNewtonsoftJsonConverter(structDeclaration, compilation, stronglyTypedId); } if (stronglyTypedId.AttributeInfo.Converters.HasFlag(StronglyTypedIdConverters.MongoDB_Bson_Serialization)) { GenerateMongoDBBsonSerializationConverter(structDeclaration, compilation, stronglyTypedId); } if (stronglyTypedId.AttributeInfo.AddCodeGeneratedAttribute) { var visitor = new AddCodeGeneratedAttributeVisitor(); visitor.Visit(codeUnit); } var result = codeUnit.ToCsharpString(); context.AddSource(stronglyTypedId.Name + ".g.cs", SourceText.From(result, Encoding.UTF8)); } } private static AttributeInfo? GetAttributeInfo(SourceProductionContext context, SemanticModel semanticModel, ITypeSymbol attributeSymbol, INamedTypeSymbol declaredTypeSymbol) { foreach (var attribute in declaredTypeSymbol.GetAttributes()) { if (!SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, attributeSymbol)) continue; var arguments = attribute.ConstructorArguments; if (arguments.Length != 6) continue; var idTypeArgument = arguments[0]; if (idTypeArgument.Value is not ITypeSymbol type) continue; var converters = StronglyTypedIdConverters.None; AddConverter(arguments[1], StronglyTypedIdConverters.System_Text_Json); AddConverter(arguments[2], StronglyTypedIdConverters.Newtonsoft_Json); AddConverter(arguments[3], StronglyTypedIdConverters.System_ComponentModel_TypeConverter); AddConverter(arguments[4], StronglyTypedIdConverters.MongoDB_Bson_Serialization); void AddConverter(TypedConstant value, StronglyTypedIdConverters converterValue) { if (value.Value is bool argumentValue && argumentValue) { converters |= converterValue; } } var addCodeGeneratedAttribute = false; if (arguments[5].Value is bool addCodeGeneratedAttributeValue) { addCodeGeneratedAttribute = addCodeGeneratedAttributeValue; } var idType = GetIdType(semanticModel.Compilation, type); if (idType != null) return new AttributeInfo(attribute.ApplicationSyntaxReference, idType.Value, type, converters, addCodeGeneratedAttribute); context.ReportDiagnostic(Diagnostic.Create(s_unsuportedType, declaredTypeSymbol.Locations.FirstOrDefault(), idTypeArgument.Type)); } return null; } private static IdType? GetIdType(Compilation compilation, ITypeSymbol symbol) { if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Boolean"))) return IdType.System_Boolean; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Byte"))) return IdType.System_Byte; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.DateTime"))) return IdType.System_DateTime; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.DateTimeOffset"))) return IdType.System_DateTimeOffset; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Decimal"))) return IdType.System_Decimal; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Double"))) return IdType.System_Double; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Guid"))) return IdType.System_Guid; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Int16"))) return IdType.System_Int16; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Int32"))) return IdType.System_Int32; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Int64"))) return IdType.System_Int64; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.SByte"))) return IdType.System_SByte; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.Single"))) return IdType.System_Single; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.String"))) return IdType.System_String; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.UInt16"))) return IdType.System_UInt16; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.UInt32"))) return IdType.System_UInt32; if (SymbolEqualityComparer.Default.Equals(symbol, compilation.GetTypeByMetadataName("System.UInt64"))) return IdType.System_UInt64; return null; } private static TypeReference GetTypeReference(IdType type) { return type switch { IdType.System_Boolean => new TypeReference(typeof(bool)), IdType.System_Byte => new TypeReference(typeof(byte)), IdType.System_DateTime => new TypeReference(typeof(DateTime)), IdType.System_DateTimeOffset => new TypeReference(typeof(DateTimeOffset)), IdType.System_Decimal => new TypeReference(typeof(decimal)), IdType.System_Double => new TypeReference(typeof(double)), IdType.System_Guid => new TypeReference(typeof(Guid)), IdType.System_Int16 => new TypeReference(typeof(short)), IdType.System_Int32 => new TypeReference(typeof(int)), IdType.System_Int64 => new TypeReference(typeof(long)), IdType.System_SByte => new TypeReference(typeof(sbyte)), IdType.System_Single => new TypeReference(typeof(float)), IdType.System_String => new TypeReference(typeof(string)), IdType.System_UInt16 => new TypeReference(typeof(ushort)), IdType.System_UInt32 => new TypeReference(typeof(uint)), IdType.System_UInt64 => new TypeReference(typeof(ulong)), _ => throw new ArgumentException("Type not supported", nameof(type)), }; } private static bool IsNullable(IdType idType) { return idType == IdType.System_String; } private static string GetShortName(TypeReference typeReference) { var index = typeReference.ClrFullTypeName.LastIndexOf('.'); return typeReference.ClrFullTypeName[(index + 1)..]; } private static ClassOrStructDeclaration CreateType(CompilationUnit unit, StronglyTypedIdInfo source) { TypeDeclaration result = source switch { { IsClass: true } => new ClassDeclaration(source.Name) { Modifiers = Modifiers.Partial }, { IsRecord: true } => new RecordDeclaration(source.Name) { Modifiers = Modifiers.Partial }, _ => new StructDeclaration(source.Name) { Modifiers = Modifiers.Partial }, }; var root = result; var containingSymbol = source.ContainingSymbol; while (containingSymbol != null) { if (containingSymbol is ITypeSymbol typeSymbol) { TypeDeclaration typeDeclaration = typeSymbol.IsValueType ? new StructDeclaration() : new ClassDeclaration(); typeDeclaration.Name = typeSymbol.Name; typeDeclaration.Modifiers = Modifiers.Partial; ((ClassOrStructDeclaration)typeDeclaration).AddType(root); root = typeDeclaration; } else if (containingSymbol is INamespaceSymbol nsSymbol) { var ns = GetNamespace(nsSymbol); if (ns == null) { unit.AddType(root); } else { var namespaceDeclation = new NamespaceDeclaration(ns); namespaceDeclation.AddType(root); unit.AddNamespace(namespaceDeclation); } break; } else { throw new InvalidOperationException($"Symbol '{containingSymbol}' of type '{containingSymbol.GetType().FullName}' not expected"); } containingSymbol = containingSymbol.ContainingSymbol; } return (ClassOrStructDeclaration)result; } private static string? GetNamespace(INamespaceSymbol ns) { string? str = null; while (ns != null && !ns.IsGlobalNamespace) { if (str != null) { str = '.' + str; } str = ns.Name + str; ns = ns.ContainingNamespace; } return str; } private static Modifiers GetPrivateOrProtectedModifier(StronglyTypedIdInfo type) { if (type.IsReferenceType && !type.IsSealed) return Modifiers.Protected; return Modifiers.Private; } private static bool IsTypeDefined(Compilation compilation, string typeMetadataName) { return compilation.References .Select(compilation.GetAssemblyOrModuleSymbol) .OfType<IAssemblySymbol>() .Select(assemblySymbol => assemblySymbol.GetTypeByMetadataName(typeMetadataName)) .WhereNotNull() .Any(); } private record AttributeInfo(SyntaxReference? AttributeOwner, IdType IdType, ITypeSymbol IdTypeSymbol, StronglyTypedIdConverters Converters, bool AddCodeGeneratedAttribute); private record StronglyTypedIdInfo(Compilation Compilation, ISymbol ContainingSymbol, ITypeSymbol? ExistingTypeSymbol, string Name, AttributeInfo AttributeInfo, TypeDeclarationSyntax TypeDeclarationSyntax) { public bool IsClass => TypeDeclarationSyntax.IsKind(SyntaxKind.ClassDeclaration); public bool IsRecord => TypeDeclarationSyntax.IsKind(SyntaxKind.RecordDeclaration); public bool IsStruct => TypeDeclarationSyntax.IsKind(SyntaxKind.StructDeclaration); public bool IsReferenceType => IsClass || IsRecord; public bool IsSealed { get { foreach (var modifier in TypeDeclarationSyntax.Modifiers) { if (modifier.IsKind(SyntaxKind.SealedKeyword)) return true; } return false; } } public bool IsCtorDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(".ctor").OfType<IMethodSymbol>() .Any(m => !m.IsStatic && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, AttributeInfo.IdTypeSymbol)); } public bool IsFieldDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(FieldName).Any(); } public bool IsValueDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(PropertyName).Any(); } public bool IsValueAsStringDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(PropertyAsStringName).Any(); } public bool IsToStringDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(nameof(ToString)).OfType<IMethodSymbol>() .Any(m => !m.IsStatic && m.Parameters.Length == 0 && m.ReturnType?.SpecialType == SpecialType.System_String); } public bool IsGetHashcodeDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(nameof(GetHashCode)).OfType<IMethodSymbol>() .Any(m => !m.IsStatic && m.Parameters.Length == 0 && m.ReturnType?.SpecialType == SpecialType.System_Int32); } public bool IsEqualsDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(nameof(Equals)).OfType<IMethodSymbol>() .Any(m => !m.IsStatic && m.Parameters.Length == 1 && m.Parameters[0].Type.SpecialType == SpecialType.System_Object && m.ReturnType?.SpecialType == SpecialType.System_Boolean); } public bool IsIEquatableEqualsDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers(nameof(Equals)).OfType<IMethodSymbol>() .Any(m => !m.IsStatic && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(ExistingTypeSymbol, m.Parameters[0].Type) && m.ReturnType?.SpecialType == SpecialType.System_Boolean); } public bool IsOpEqualsDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("op_Equality").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length == 2 && SymbolEqualityComparer.Default.Equals(ExistingTypeSymbol, m.Parameters[0].Type) && SymbolEqualityComparer.Default.Equals(ExistingTypeSymbol, m.Parameters[1].Type) && m.ReturnType?.SpecialType == SpecialType.System_Boolean); } public bool IsOpNotEqualsDefined() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("op_Inequality").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length == 2 && SymbolEqualityComparer.Default.Equals(ExistingTypeSymbol, m.Parameters[0].Type) && SymbolEqualityComparer.Default.Equals(ExistingTypeSymbol, m.Parameters[1].Type) && m.ReturnType?.SpecialType == SpecialType.System_Boolean); } public bool IsTryParseDefined_String() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("TryParse").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length > 0 && m.Parameters[0].Type.SpecialType == SpecialType.System_String); } public bool IsTryParseDefined_ReadOnlySpan() { var type = GetReadOnlySpanChar(); if (type == null) return false; return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("TryParse").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length > 0 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, type)); } public bool IsParseDefined_String() { return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("Parse").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length > 0 && m.Parameters[0].Type.SpecialType == SpecialType.System_String); } public bool IsParseDefined_Span() { var type = GetReadOnlySpanChar(); if (type == null) return false; return ExistingTypeSymbol != null && ExistingTypeSymbol.GetMembers("Parse").OfType<IMethodSymbol>() .Any(m => m.IsStatic && m.Parameters.Length > 0 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, type)); } public bool SupportReadOnlySpan() => GetReadOnlySpanChar() != null; private ITypeSymbol? GetReadOnlySpanChar() { var readOnlySpan = Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1"); var charSymbol = Compilation.GetTypeByMetadataName("System.Char"); if (readOnlySpan != null && charSymbol != null) return readOnlySpan.Construct(charSymbol); return null; } } [Flags] private enum StronglyTypedIdConverters { None = 0x0, System_Text_Json = 0x1, Newtonsoft_Json = 0x2, System_ComponentModel_TypeConverter = 0x4, MongoDB_Bson_Serialization = 0x8, } private enum IdType { System_Boolean, System_Byte, System_DateTime, System_DateTimeOffset, System_Decimal, System_Double, System_Guid, System_Int16, System_Int32, System_Int64, System_SByte, System_Single, System_String, System_UInt16, System_UInt32, System_UInt64, } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.ServiceModel.Syndication; using System.Text; using System.Text.RegularExpressions; using System.Web.Mvc; using System.Xml; using System.Xml.Linq; using Articulate.Models; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Web; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Articulate.Controllers { /// <summary> /// Rss controller /// </summary> /// <remarks> /// Cached for one minute /// </remarks> #if (!DEBUG) [OutputCache(Duration = 300)] #endif public class ArticulateRssController : RenderMvcController { //NonAction so it is not routed since we want to use an overload below [NonAction] public override ActionResult Index(RenderModel model) { return base.Index(model); } public ActionResult Index(RenderModel model, int? maxItems) { if (!maxItems.HasValue) maxItems = 25; var listNode = model.Content.Children .FirstOrDefault(x => x.DocumentTypeAlias.InvariantEquals("ArticulateArchive")); if (listNode == null) { throw new InvalidOperationException("An ArticulateArchive document must exist under the root Articulate document"); } var rootPageModel = new ListModel(listNode, new PagerModel(maxItems.Value, 0, 1)); var feed = GetFeed(rootPageModel, rootPageModel.Children<PostModel>()); return new RssResult(feed, rootPageModel); } public ActionResult Categories(RenderModel model, string tag, int? maxItems) { if (model == null) throw new ArgumentNullException("model"); if (tag == null) throw new ArgumentNullException("tag"); if (!maxItems.HasValue) maxItems = 25; return RenderTagsOrCategoriesRss(model, "ArticulateCategories", "categories", maxItems.Value); } public ActionResult Tags(RenderModel model, string tag, int? maxItems) { if (model == null) throw new ArgumentNullException("model"); if (tag == null) throw new ArgumentNullException("tag"); if (!maxItems.HasValue) maxItems = 25; return RenderTagsOrCategoriesRss(model, "ArticulateTags", "tags", maxItems.Value); } public ActionResult RenderTagsOrCategoriesRss(RenderModel model, string tagGroup, string baseUrl, int maxItems) { var tagPage = model.Content as ArticulateVirtualPage; if (tagPage == null) { throw new InvalidOperationException("The RenderModel.Content instance must be of type " + typeof(ArticulateVirtualPage)); } //create a blog model of the main page var rootPageModel = new ListModel(model.Content.Parent); var contentByTag = Umbraco.GetContentByTag( rootPageModel, tagPage.Name, tagGroup, baseUrl); var feed = GetFeed(rootPageModel, contentByTag.Posts.Take(maxItems)); return new RssResult(feed, rootPageModel); } /// <summary> /// Returns the XSLT to render the RSS nicely in a browser /// </summary> /// <returns></returns> public ActionResult FeedXslt() { var result = Resources.FeedXslt; return Content(result, "text/xml"); } private SyndicationFeed GetFeed(IMasterModel rootPageModel, IEnumerable<PostModel> posts) { var feed = new SyndicationFeed( rootPageModel.BlogTitle, rootPageModel.BlogDescription, new Uri(rootPageModel.RootBlogNode.UrlWithDomain()), GetFeedItems(rootPageModel, posts)) { Generator = "Articulate, blogging built on Umbraco", ImageUrl = GetBlogImage(rootPageModel) }; //TODO: attempting to add media:thumbnail... //feed.AttributeExtensions.Add(new XmlQualifiedName("media", "http://www.w3.org/2000/xmlns/"), "http://search.yahoo.com/mrss/"); return feed; } private Regex _relativeMediaSrc = new Regex(" src=(?:\"|')(/media/.*?)(?:\"|')", RegexOptions.Compiled | RegexOptions.IgnoreCase); private Regex _relativeMediaHref = new Regex(" href=(?:\"|')(/media/.*?)(?:\"|')", RegexOptions.Compiled | RegexOptions.IgnoreCase); private IEnumerable<SyndicationItem> GetFeedItems(IMasterModel model, IEnumerable<PostModel> posts) { var rootUrl = model.RootBlogNode.DescendantOrSelf(1).UrlWithDomain(); var result = new List<SyndicationItem>(); foreach (var post in posts) { var content = _relativeMediaHref.Replace(post.Body.ToHtmlString(), match => { if (match.Groups.Count == 2) { return " href=\"" + rootUrl.TrimEnd('/') + match.Groups[1].Value.EnsureStartsWith('/') + "\""; } return null; }); content = _relativeMediaSrc.Replace(content, match => { if (match.Groups.Count == 2) { return " src=\"" + rootUrl.TrimEnd('/') + match.Groups[1].Value.EnsureStartsWith('/') + "\""; } return null; }); var item = new SyndicationItem( post.Name, new TextSyndicationContent(content, TextSyndicationContentKind.Html), new Uri(post.UrlWithDomain()), post.Id.ToString(CultureInfo.InvariantCulture), post.PublishedDate) { PublishDate = post.PublishedDate, //don't include this as it will override the main content bits //Summary = new TextSyndicationContent(post.Excerpt) }; //TODO: attempting to add media:thumbnail... //item.ElementExtensions.Add(new SyndicationElementExtension("thumbnail", "http://search.yahoo.com/mrss/", "This is a test!")); foreach (var c in post.Categories) { item.Categories.Add(new SyndicationCategory(c)); } result.Add(item); } return result; } private Uri GetBlogImage(IMasterModel rootPageModel) { Uri logoUri = null; try { logoUri = rootPageModel.BlogLogo.IsNullOrWhiteSpace() ? null : new Uri(rootPageModel.BlogLogo); } catch (Exception ex) { LogHelper.Error<ArticulateRssController>("Could not convert the blog logo path to a Uri", ex); } return logoUri; } internal class RssResult : ActionResult { private readonly SyndicationFeed _feed; private readonly IMasterModel _model; public RssResult(SyndicationFeed feed, IMasterModel model) { _feed = feed; _model = model; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = "application/xml"; using (var txtWriter = new Utf8StringWriter()) { var xmlWriter = XmlWriter.Create(txtWriter, new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true, OmitXmlDeclaration = false }); // Write the Processing Instruction node. var xsltHeader = string.Format("type=\"text/xsl\" href=\"{0}\"", _model.RootBlogNode.UrlWithDomain().EnsureEndsWith('/') + "rss/xslt"); xmlWriter.WriteProcessingInstruction("xml-stylesheet", xsltHeader); var formatter = _feed.GetRss20Formatter(); formatter.WriteTo(xmlWriter); xmlWriter.Flush(); context.HttpContext.Response.Write(txtWriter.ToString()); } } public sealed class Utf8StringWriter : StringWriter { public override Encoding Encoding { get { return Encoding.UTF8; } } } } } }
// 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.ComponentModel; using System.ComponentModel.Composition; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Xml.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Serializes settings marked with <see cref="RoamingProfileStorageLocation"/> to and from the user's roaming profile. /// </summary> [Export(typeof(IOptionPersister))] internal sealed class RoamingVisualStudioProfileOptionPersister : ForegroundThreadAffinitizedObject, IOptionPersister { // NOTE: This service is not public or intended for use by teams/individuals outside of Microsoft. Any data stored is subject to deletion without warning. [Guid("9B164E40-C3A2-4363-9BC5-EB4039DEF653")] private class SVsSettingsPersistenceManager { }; private readonly ISettingsManager _settingManager; private readonly IGlobalOptionService _globalOptionService; /// <summary> /// The list of options that have been been fetched from <see cref="_settingManager"/>, by key. We track this so /// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on /// <see cref="_optionsToMonitorForChangesGate" />. /// </summary> private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new Dictionary<string, List<OptionKey>>(); private readonly object _optionsToMonitorForChangesGate = new object(); /// <remarks>We make sure this code is from the UI by asking for all serializers on the UI thread in <see cref="HACK_AbstractCreateServicesOnUiThread"/>.</remarks> [ImportingConstructor] public RoamingVisualStudioProfileOptionPersister(IGlobalOptionService globalOptionService, [Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) : base(assertIsForeground: true) // The GetService call requires being on the UI thread or else it will marshal and risk deadlock { Contract.ThrowIfNull(globalOptionService); _settingManager = (ISettingsManager)serviceProvider.GetService(typeof(SVsSettingsPersistenceManager)); _globalOptionService = globalOptionService; // While the settings persistence service should be available in all SKUs it is possible an ISO shell author has undefined the // contributing package. In that case persistence of settings won't work (we don't bother with a backup solution for persistence // as the scenario seems exceedingly unlikely), but we shouldn't crash the IDE. if (_settingManager != null) { var settingsSubset = _settingManager.GetSubset("*"); settingsSubset.SettingChangedAsync += OnSettingChangedAsync; } } private System.Threading.Tasks.Task OnSettingChangedAsync(object sender, PropertyChangedEventArgs args) { lock (_optionsToMonitorForChangesGate) { if (_optionsToMonitorForChanges.TryGetValue(args.PropertyName, out var optionsToRefresh)) { foreach (var optionToRefresh in optionsToRefresh) { if (TryFetch(optionToRefresh, out var optionValue)) { _globalOptionService.RefreshOption(optionToRefresh, optionValue); } } } } return SpecializedTasks.EmptyTask; } public bool TryFetch(OptionKey optionKey, out object value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); value = null; return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().SingleOrDefault(); if (roamingSerialization == null) { value = null; return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); value = _settingManager.GetValueOrDefault(storageKey, optionKey.Option.DefaultValue); // VS's ISettingsManager has some quirks around storing enums. Specifically, // it *can* persist and retrieve enums, but only if you properly call // GetValueOrDefault<EnumType>. This is because it actually stores enums just // as ints and depends on the type parameter passed in to convert the integral // value back to an enum value. Unfortunately, we call GetValueOrDefault<object> // and so we get the value back as boxed integer. // // Because of that, manually convert the integer to an enum here so we don't // crash later trying to cast a boxed integer to an enum value. if (optionKey.Option.Type.IsEnum) { if (value != null) { value = Enum.ToObject(optionKey.Option.Type, value); } } else if (optionKey.Option.Type == typeof(CodeStyleOption<bool>)) { return DeserializeCodeStyleOption<bool>(ref value); } else if (optionKey.Option.Type == typeof(CodeStyleOption<ExpressionBodyPreference>)) { return DeserializeCodeStyleOption<ExpressionBodyPreference>(ref value); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so deserialize if (value is string serializedValue) { try { value = NamingStylePreferences.FromXElement(XElement.Parse(serializedValue)); } catch (Exception) { value = null; return false; } } else { value = null; return false; } } else if (optionKey.Option.Type == typeof(bool) && value is int intValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = intValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool) && value is long longValue) { // TypeScript used to store some booleans as integers. We now handle them properly for legacy sync scenarios. value = longValue != 0; return true; } else if (optionKey.Option.Type == typeof(bool?)) { // code uses object to hold onto any value which will use boxing on value types. // see boxing on nullable types - https://msdn.microsoft.com/en-us/library/ms228597.aspx return (value is bool) || (value == null); } else if (value != null && optionKey.Option.Type != value.GetType()) { // We got something back different than we expected, so fail to deserialize value = null; return false; } return true; } private bool DeserializeCodeStyleOption<T>(ref object value) { if (value is string serializedValue) { try { value = CodeStyleOption<T>.FromXElement(XElement.Parse(serializedValue)); return true; } catch (Exception) { } } value = null; return false; } private void RecordObservedValueToWatchForChanges(OptionKey optionKey, string storageKey) { // We're about to fetch the value, so make sure that if it changes we'll know about it lock (_optionsToMonitorForChangesGate) { var optionKeysToMonitor = _optionsToMonitorForChanges.GetOrAdd(storageKey, _ => new List<OptionKey>()); if (!optionKeysToMonitor.Contains(optionKey)) { optionKeysToMonitor.Add(optionKey); } } } public bool TryPersist(OptionKey optionKey, object value) { if (_settingManager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } // Do we roam this at all? var roamingSerialization = optionKey.Option.StorageLocations.OfType<RoamingProfileStorageLocation>().SingleOrDefault(); if (roamingSerialization == null) { value = null; return false; } var storageKey = roamingSerialization.GetKeyNameForLanguage(optionKey.Language); RecordObservedValueToWatchForChanges(optionKey, storageKey); if (value is ICodeStyleOption codeStyleOption) { // We store these as strings, so serialize value = codeStyleOption.ToXElement().ToString(); } else if (optionKey.Option.Type == typeof(NamingStylePreferences)) { // We store these as strings, so serialize var valueToSerialize = value as NamingStylePreferences; if (value != null) { value = valueToSerialize.CreateXElement().ToString(); } } _settingManager.SetValueAsync(storageKey, value, isMachineLocal: false); return true; } } }
using System; using System.Collections.Generic; using System.Text; using RRLab.PhysiologyWorkbench.Data; using RRLab.Utilities; using RRLab.PhysiologyDataConnectivity; using System.Windows.Forms; namespace RRLab.PhysiologyDataWorkshop.Experiments { /// <summary> /// An abstract implementation of IExperiment providing property management /// features. /// </summary> public abstract class Experiment : IExperiment, System.ComponentModel.INotifyPropertyChanged { /// <summary> /// Call Initialize. /// </summary> public Experiment() { Initialize(); } #region IExperiment Members public event EventHandler NameChanged; /// <summary> /// Gets the type name by default. /// </summary> public virtual string Name { get { return this.GetType().Name; } } /// <summary> /// Fires the NameChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnNameChanged(EventArgs e) { if(NameChanged != null) try { NameChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during NameChanged event.", x.Message); } } public event EventHandler ProgramChanged; private PhysiologyDataWorkshopProgram _Program; public PhysiologyDataWorkshopProgram Program { get { return _Program; } set { _Program = value; OnProgramChanged(EventArgs.Empty); } } /// <summary> /// Fires the ProgramChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnProgramChanged(EventArgs e) { if (ProgramChanged != null) try { ProgramChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during ProgramChanged event.", x.Message); } } public event EventHandler PhysiologyDataSetChanged; private PhysiologyDataSet _PhysiologyDataSet; public PhysiologyDataSet PhysiologyDataSet { get { return _PhysiologyDataSet; } set { _PhysiologyDataSet = value; OnPhysiologyDataSetChanged(EventArgs.Empty); } } protected virtual void OnPhysiologyDataSetChanged(EventArgs e) { if(PhysiologyDataSetChanged != null) try { PhysiologyDataSetChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("Error during PhysiologyDataSetChanged event.", x.Message); } } public event EventHandler CellActionsChanged; private SortedList<string, Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.CellsRow>> _CellActions = new SortedList<string, Action<PhysiologyDataSet.CellsRow>>(); public virtual IDictionary<string, Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.CellsRow>> CellActions { get { return _CellActions; } } /// <summary> /// Fires the CellActionsChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnCellActionsChanged(EventArgs e) { if(CellActionsChanged != null) try { CellActionsChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during CellActionsChanged event.", x.Message); } } public event EventHandler RecordingActionsChanged; private SortedList<string, Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.RecordingsRow>> _RecordingActions = new SortedList<string, Action<PhysiologyDataSet.RecordingsRow>>(); public virtual IDictionary<string, Action<RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.RecordingsRow>> RecordingActions { get { return _RecordingActions; } } /// <summary> /// Fires the RecordingActionsChanged event. /// </summary> /// <param name="e"></param> protected virtual void OnRecordingActionsChanged(EventArgs e) { if (RecordingActionsChanged != null) try { RecordingActionsChanged(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during the RecordingActionsChanged event: " + x.Message); } } /// <summary> /// Returns true by default. /// </summary> /// <param name="actionName"></param> /// <param name="cell"></param> /// <returns></returns> public virtual bool IsCellActionEnabled(string actionName, RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.CellsRow cell) { return true; } /// <summary> /// Returns true by default. /// </summary> /// <param name="actionName"></param> /// <param name="recording"></param> /// <returns></returns> public virtual bool IsRecordingActionEnabled(string actionName, RRLab.PhysiologyWorkbench.Data.PhysiologyDataSet.RecordingsRow recording) { return true; } /// <summary> /// Returns an empty panel by default. /// </summary> /// <returns></returns> public virtual System.Windows.Forms.Control GetExperimentPanelControl() { return new System.Windows.Forms.Panel(); } #endregion /// <summary> /// Initializes the experiment object by configuring cell and recording actions. /// </summary> protected virtual void Initialize() { ConfigureCellActions(); ConfigureRecordingActions(); } protected virtual void ConfigureCellActions() { OnCellActionsChanged(EventArgs.Empty); } protected virtual void ConfigureRecordingActions() { OnRecordingActionsChanged(EventArgs.Empty); } #region INotifyPropertyChanged Members public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string property) { if(PropertyChanged != null) try { PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(property)); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during PropertyChanged event.", x.Message); } } #endregion #region Database public event EventHandler RecordingDataLoaded; public virtual void LoadRecordingFromDatabase(long recordingID) { // Download recording data if (Program != null && Program.DatabaseConnector != null) { try { ProgressDialog dialog = new ProgressDialog(); dialog.TaskStopped += new EventHandler(delegate(object sender, EventArgs x) { OnRecordingDataLoaded(EventArgs.Empty); }); dialog.Show(); ((MySqlDataManagerDatabaseConnector)Program.DatabaseConnector).BeginLoadRecordingSubdataFromDatabase(PhysiologyDataSet, recordingID, dialog); } catch (Exception x) { MessageBox.Show("Error updating recording data: " + x.Message); } } } protected virtual void OnRecordingDataLoaded(EventArgs e) { if (RecordingDataLoaded != null) try { RecordingDataLoaded(this, e); } catch (Exception x) { System.Diagnostics.Debug.Fail("ExperimentRow: Error during RecordingDataLoaded event.", x.Message); } } #endregion } }
namespace Rhino.Etl.Core { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Boo.Lang; using Exceptions; /// <summary> /// A dictionary that can be access with a natural syntax from Boo /// </summary> [Serializable] public class QuackingDictionary : IQuackFu, IDictionary { /// <summary> /// The inner items collection /// </summary> protected IDictionary items; /// <summary> /// The last item that was access, useful for debugging /// </summary> protected string lastAccess; private bool throwOnMissing = false; /// <summary> /// Set the flag to thorw if key not found. /// </summary> public void ShouldThorwIfKeyNotFound() { throwOnMissing = true; } /// <summary> /// Initializes a new instance of the <see cref="QuackingDictionary"/> class. /// </summary> /// <param name="items">The items.</param> public QuackingDictionary(IDictionary items) { if (items != null) this.items = new Hashtable(items, StringComparer.InvariantCultureIgnoreCase); else this.items = new Hashtable(StringComparer.InvariantCultureIgnoreCase); } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value></value> public object this[string key] { get { if (throwOnMissing && items.Contains(key) == false) throw new MissingKeyException(key); lastAccess = key; return items[key]; } set { lastAccess = key; if(value == DBNull.Value) items[key] = null; else items[key] = value; } } /// <summary> /// Get a value by name or first parameter /// </summary> public virtual object QuackGet(string name, object[] parameters) { if (parameters == null || parameters.Length == 0) return this[name]; if (parameters.Length == 1) return this[(string)parameters[0]]; throw new ParameterCountException("You can only call indexer with a single parameter"); } /// <summary> /// Set a value on the given name or first parameter /// </summary> public object QuackSet(string name, object[] parameters, object value) { if (parameters == null || parameters.Length == 0) return this[name] = value; if (parameters.Length == 1) return this[(string)parameters[0]] = value; throw new ParameterCountException("You can only call indexer with a single parameter"); } /// <summary> /// Not supported /// </summary> public object QuackInvoke(string name, params object[] args) { throw new NotSupportedException( "You cannot invoke methods on a row, it is merely a data structure, after all."); } /// <summary> /// A debbug view of quacking dictionary /// </summary> internal class QuackingDictionaryDebugView { private readonly IDictionary items; /// <summary> /// Initializes a new instance of the <see cref="QuackingDictionaryDebugView"/> class. /// </summary> /// <param name="dictionary">The dictionary.</param> public QuackingDictionaryDebugView(QuackingDictionary dictionary) { this.items = dictionary.items; } /// <summary> /// Gets the items. /// </summary> /// <value>The items.</value> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair[] Items { get { System.Collections.Generic.List<KeyValuePair> pairs = new System.Collections.Generic.List<KeyValuePair>(); foreach (DictionaryEntry item in items) { pairs.Add(new KeyValuePair(item.Key, item.Value)); } return pairs.ToArray(); } } /// <summary> /// Represent a single key/value pair for the debugger /// </summary> [DebuggerDisplay("{value}", Name = "[{key}]", Type = "")] internal class KeyValuePair { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly object key; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly object value; /// <summary> /// Initializes a new instance of the <see cref="KeyValuePair"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public KeyValuePair(object key, object value) { this.key = key; this.value = value; } /// <summary> /// Gets the key. /// </summary> /// <value>The key.</value> public object Key { get { return key; } } /// <summary> /// Gets the value. /// </summary> /// <value>The value.</value> public object Value { get { return value; } } } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("{"); foreach (DictionaryEntry item in items) { sb.Append(item.Key) .Append(" : "); if (item.Value is string) { sb.Append("\"") .Append(item.Value) .Append("\""); } else { sb.Append(item.Value); } sb.Append(", "); } sb.Append("}"); return sb.ToString(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> public IEnumerator GetEnumerator() { return new Hashtable(items).GetEnumerator(); } ///<summary> ///Returns an <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> IDictionaryEnumerator IDictionary.GetEnumerator() { return items.GetEnumerator(); } ///<summary> ///Determines whether the <see cref="T:System.Collections.IDictionary"></see> object contains an element with the specified key. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> contains an element with the key; otherwise, false. ///</returns> /// ///<param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"></see> object.</param> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public bool Contains(object key) { return items.Contains(key); } ///<summary> ///Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param> ///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param> ///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.IDictionary"></see> object. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception><filterpriority>2</filterpriority> public void Add(object key, object value) { items.Add(key, value); } ///<summary> ///Removes all elements from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only. </exception><filterpriority>2</filterpriority> public void Clear() { items.Clear(); } ///<summary> ///Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<param name="key">The key of the element to remove. </param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public void Remove(object key) { items.Remove(key); } ///<summary> ///Gets or sets the element with the specified key. ///</summary> /// ///<returns> ///The element with the specified key. ///</returns> /// ///<param name="key">The key of the element to get or set. </param> ///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The property is set, key does not exist in the collection, and the <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public object this[object key] { get { return items[key]; } set { items[key] = value; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> public ICollection Keys { get { return items.Keys; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> public ICollection Values { get { return items.Values; } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object is read-only. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object is read-only; otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsReadOnly { get { return items.IsReadOnly; } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size; otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsFixedSize { get { return items.IsFixedSize; } } ///<summary> ///Copies the elements of the <see cref="T:System.Collections.ICollection"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index. ///</summary> /// ///<param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing. </param> ///<param name="index">The zero-based index in array at which copying begins. </param> ///<exception cref="T:System.ArgumentNullException">array is null. </exception> ///<exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"></see> cannot be cast automatically to the type of the destination array. </exception> ///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero. </exception> ///<exception cref="T:System.ArgumentException">array is multidimensional.-or- index is equal to or greater than the length of array.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"></see> is greater than the available space from index to the end of the destination array. </exception><filterpriority>2</filterpriority> public void CopyTo(Array array, int index) { items.CopyTo(array, index); } ///<summary> ///Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</summary> /// ///<returns> ///The number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</returns> ///<filterpriority>2</filterpriority> public int Count { get { return items.Count; } } ///<summary> ///Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</summary> /// ///<returns> ///An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</returns> ///<filterpriority>2</filterpriority> public object SyncRoot { get { return items.SyncRoot; } } ///<summary> ///Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe). ///</summary> /// ///<returns> ///true if access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe); otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsSynchronized { get { return items.IsSynchronized; } } } }
// // Authors: // Ben Motmans <ben.motmans@gmail.com> // Lucas Ontivero lucasontivero@gmail.com // // Copyright (C) 2007 Ben Motmans // Copyright (C) 2014 Lucas Ontivero // // 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.IO; using System.Linq; using System.Text; using System.Net; using System.Diagnostics; using System.Net.Sockets; using System.Threading; using System.Xml; namespace Open.Nat { internal class UpnpSearcher : Searcher { private readonly IIPAddressesProvider _ipprovider; private readonly IDictionary<Uri, NatDevice> _devices; private readonly Dictionary<IPAddress, DateTime> _lastFetched; private static readonly string[] ServiceTypes = new[]{ "WANIPConnection:2", "WANPPPConnection:2", "WANIPConnection:1", "WANPPPConnection:1" }; internal UpnpSearcher(IIPAddressesProvider ipprovider) { _ipprovider = ipprovider; UdpClients = CreateUdpClients(); _devices = new Dictionary<Uri, NatDevice>(); _lastFetched = new Dictionary<IPAddress, DateTime>(); } private List<UdpClient> CreateUdpClients() { var clients = new List<UdpClient>(); try { var ips = _ipprovider.UnicastAddresses(); foreach (var ipAddress in ips) { try { clients.Add(new UdpClient(new IPEndPoint(ipAddress, 0))); } catch (Exception) { continue; // Move on to the next address. } } } catch (Exception) { clients.Add(new UdpClient(0)); } return clients; } protected override void Discover(UdpClient client, CancellationToken cancelationToken) { // for testing use: // <code>var ip = IPAddress.Broadcast;</code> Discover(client, WellKnownConstants.IPv4MulticastAddress, cancelationToken); if (Socket.OSSupportsIPv6) { Discover(client, WellKnownConstants.IPv6LinkLocalMulticastAddress, cancelationToken); Discover(client, WellKnownConstants.IPv6LinkSiteMulticastAddress, cancelationToken); } } private void Discover(UdpClient client, IPAddress address, CancellationToken cancelationToken) { if (!IsValidClient(client.Client, address)) return; NextSearch = DateTime.UtcNow.AddSeconds(1); var searchEndpoint = new IPEndPoint(address, 1900); foreach (var serviceType in ServiceTypes) { var datax = DiscoverDeviceMessage.Encode(serviceType, address); var data = Encoding.ASCII.GetBytes(datax); // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2) // Yes, however it works perfectly well with just 1 request. for (var i = 0; i < 3; i++) { if (cancelationToken.IsCancellationRequested) return; client.Send(data, data.Length, searchEndpoint); } } } private bool IsValidClient(Socket socket, IPAddress address) { var endpoint = (IPEndPoint) socket.LocalEndPoint; if (socket.AddressFamily != address.AddressFamily) return false; switch (socket.AddressFamily) { case AddressFamily.InterNetwork: socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, endpoint.Address.GetAddressBytes()); return true; case AddressFamily.InterNetworkV6: if (endpoint.Address.IsIPv6LinkLocal && !Equals(address, WellKnownConstants.IPv6LinkLocalMulticastAddress)) return false; if (!endpoint.Address.IsIPv6LinkLocal && !Equals(address, WellKnownConstants.IPv6LinkSiteMulticastAddress)) return false; socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface, BitConverter.GetBytes((int)endpoint.Address.ScopeId)); return true; } return false; } public override NatDevice AnalyseReceivedResponse(IPAddress localAddress, byte[] response, IPEndPoint endpoint) { // Convert it to a string for easy parsing string dataString = null; // No matter what, this method should never throw an exception. If something goes wrong // we should still be in a position to handle the next reply correctly. try { dataString = Encoding.UTF8.GetString(response); var message = new DiscoveryResponseMessage(dataString); var serviceType = message["ST"]; if (!IsValidControllerService(serviceType)) { NatDiscoverer.TraceSource.LogWarn("Invalid controller service. Ignoring."); return null; } NatDiscoverer.TraceSource.LogInfo("UPnP Response: Router advertised a '{0}' service!!!", serviceType); var location = message["Location"] ?? message["AL"]; var locationUri = new Uri(location); NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", locationUri.ToString()); if (_devices.ContainsKey(locationUri)) { NatDiscoverer.TraceSource.LogInfo("Already found - Ignored"); _devices[locationUri].Touch(); return null; } // If we send 3 requests at a time, ensure we only fetch the services list once // even if three responses are received if (_lastFetched.ContainsKey(endpoint.Address)) { var last = _lastFetched[endpoint.Address]; if ((DateTime.Now - last) < TimeSpan.FromSeconds(20)) return null; } _lastFetched[endpoint.Address] = DateTime.Now; NatDiscoverer.TraceSource.LogInfo("{0}:{1}: Fetching service list", locationUri.Host, locationUri.Port ); var deviceInfo = BuildUpnpNatDeviceInfo(localAddress, locationUri); UpnpNatDevice device; lock (_devices) { device = new UpnpNatDevice(deviceInfo); if (!_devices.ContainsKey(locationUri)) { _devices.Add(locationUri, device); } } return device; } catch (Exception ex) { NatDiscoverer.TraceSource.LogError("Unhandled exception when trying to decode a device's response. "); NatDiscoverer.TraceSource.LogError("Report the issue in https://github.com/lontivero/Open.Nat/issues"); NatDiscoverer.TraceSource.LogError("Also copy and paste the following info:"); NatDiscoverer.TraceSource.LogError("-- beging ---------------------------------"); NatDiscoverer.TraceSource.LogError(ex.Message); NatDiscoverer.TraceSource.LogError("Data string:"); NatDiscoverer.TraceSource.LogError(dataString ?? "No data available"); NatDiscoverer.TraceSource.LogError("-- end ------------------------------------"); } return null; } private static bool IsValidControllerService(string serviceType) { var services = from serviceName in ServiceTypes let serviceUrn = string.Format("urn:schemas-upnp-org:service:{0}", serviceName) where serviceType.ContainsIgnoreCase(serviceUrn) select new {ServiceName = serviceName, ServiceUrn = serviceUrn}; return services.Any(); } private UpnpNatDeviceInfo BuildUpnpNatDeviceInfo(IPAddress localAddress, Uri location) { NatDiscoverer.TraceSource.LogInfo("Found device at: {0}", location.ToString()); var hostEndPoint = new IPEndPoint(IPAddress.Parse(location.Host), location.Port); WebResponse response = null; try { #if NET35 var request = WebRequest.Create(location); #else var request = WebRequest.CreateHttp(location); #endif request.Headers.Add("ACCEPT-LANGUAGE", "en"); request.Method = "GET"; response = request.GetResponse(); var httpresponse = response as HttpWebResponse; if (httpresponse != null && httpresponse.StatusCode != HttpStatusCode.OK) { var message = string.Format("Couldn't get services list: {0} {1}", httpresponse.StatusCode, httpresponse.StatusDescription); throw new Exception(message); } var xmldoc = ReadXmlResponse(response); NatDiscoverer.TraceSource.LogInfo("{0}: Parsed services list", hostEndPoint); var ns = new XmlNamespaceManager(xmldoc.NameTable); ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0"); var services = xmldoc.SelectNodes("//ns:service", ns); foreach (XmlNode service in services) { var serviceType = service.GetXmlElementText("serviceType"); if (!IsValidControllerService(serviceType)) continue; NatDiscoverer.TraceSource.LogInfo("{0}: Found service: {1}", hostEndPoint, serviceType); var serviceControlUrl = service.GetXmlElementText("controlURL"); NatDiscoverer.TraceSource.LogInfo("{0}: Found upnp service at: {1}", hostEndPoint, serviceControlUrl); NatDiscoverer.TraceSource.LogInfo("{0}: Handshake Complete", hostEndPoint); return new UpnpNatDeviceInfo(localAddress, location, serviceControlUrl, serviceType); } throw new Exception("No valid control service was found in the service descriptor document"); } catch (WebException ex) { // Just drop the connection, FIXME: Should i retry? NatDiscoverer.TraceSource.LogError("{0}: Device denied the connection attempt: {1}", hostEndPoint, ex); var inner = ex.InnerException as SocketException; if (inner != null) { NatDiscoverer.TraceSource.LogError("{0}: ErrorCode:{1}", hostEndPoint, inner.ErrorCode); NatDiscoverer.TraceSource.LogError("Go to http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx"); NatDiscoverer.TraceSource.LogError("Usually this happens. Try resetting the device and try again. If you are in a VPN, disconnect and try again."); } throw; } finally { if (response != null) response.Close(); } } private static XmlDocument ReadXmlResponse(WebResponse response) { using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var servicesXml = reader.ReadToEnd(); var xmldoc = new XmlDocument(); xmldoc.LoadXml(servicesXml); return xmldoc; } } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace DbgEng.NoExceptions { [ComImport, ComConversionLoss, Guid("3A707211-AFDD-4495-AD4F-56FECDF8163F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IDebugSymbols2 : IDebugSymbols { #pragma warning disable CS0108 // XXX hides inherited member. This is COM default. #region IDebugSymbols [PreserveSig] int GetSymbolOptions( [Out] out uint Options); [PreserveSig] int AddSymbolOptions( [In] uint Options); [PreserveSig] int RemoveSymbolOptions( [In] uint Options); [PreserveSig] int SetSymbolOptions( [In] uint Options); [PreserveSig] int GetNameByOffset( [In] ulong Offset, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByName( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Offset); [PreserveSig] int GetNearNameByOffset( [In] ulong Offset, [In] int Delta, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize, [Out] out ulong Displacement); [PreserveSig] int GetLineByOffset( [In] ulong Offset, [Out] out uint Line, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder FileBuffer, [In] uint FileBufferSize, [Out] out uint FileSize, [Out] out ulong Displacement); [PreserveSig] int GetOffsetByLine( [In] uint Line, [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Offset); [PreserveSig] int GetNumberModules( [Out] out uint Loaded, [Out] out uint Unloaded); [PreserveSig] int GetModuleByIndex( [In] uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByModuleName( [In, MarshalAs(UnmanagedType.LPStr)] string Name, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleByOffset( [In] ulong Offset, [In] uint StartIndex, [Out] out uint Index, [Out] out ulong Base); [PreserveSig] int GetModuleNames( [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ImageNameBuffer, [In] uint ImageNameBufferSize, [Out] out uint ImageNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder ModuleNameBuffer, [In] uint ModuleNameBufferSize, [Out] out uint ModuleNameSize, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder LoadedImageNameBuffer, [In] uint LoadedImageNameBufferSize, [Out] out uint LoadedImageNameSize); [PreserveSig] int GetModuleParameters( [In] uint Count, [In] ref ulong Bases, [In] uint Start = default(uint), [Out, MarshalAs(UnmanagedType.LPArray)] _DEBUG_MODULE_PARAMETERS[] Params = null); [PreserveSig] int GetSymbolModule( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out ulong Base); [PreserveSig] int GetTypeName( [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeId( [In] ulong Module, [In, MarshalAs(UnmanagedType.LPStr)] string Name, [Out] out uint Id); [PreserveSig] int GetTypeSize( [In] ulong Module, [In] uint TypeId, [Out] out uint Size); [PreserveSig] int GetFieldOffset( [In] ulong Module, [In] uint TypeId, [In, MarshalAs(UnmanagedType.LPStr)] string Field, [Out] out uint Offset); [PreserveSig] int GetSymbolTypeId( [In, MarshalAs(UnmanagedType.LPStr)] string Symbol, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int GetOffsetTypeId( [In] ulong Offset, [Out] out uint TypeId, [Out] out ulong Module); [PreserveSig] int ReadTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] byte[] Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataVirtual( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataVirtual( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int ReadTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesRead); [PreserveSig] int WriteTypedDataPhysical( [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] IntPtr Buffer, [In] uint BufferSize, [Out] out uint BytesWritten); [PreserveSig] int OutputTypedDataPhysical( [In] uint OutputControl, [In] ulong Offset, [In] ulong Module, [In] uint TypeId, [In] uint Flags); [PreserveSig] int GetScope( [Out] out ulong InstructionOffset, [Out] out _DEBUG_STACK_FRAME ScopeFrame, [Out] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int SetScope( [In] ulong InstructionOffset, [In] ref _DEBUG_STACK_FRAME ScopeFrame, [In] IntPtr ScopeContext = default(IntPtr), [In] uint ScopeContextSize = default(uint)); [PreserveSig] int ResetScope(); [PreserveSig] int GetScopeSymbolGroup( [In] uint Flags, [In, MarshalAs(UnmanagedType.Interface)] IDebugSymbolGroup Update, [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int CreateSymbolGroup( [Out, MarshalAs(UnmanagedType.Interface)] out IDebugSymbolGroup Symbols); [PreserveSig] int StartSymbolMatch( [In, MarshalAs(UnmanagedType.LPStr)] string Pattern, [Out] out ulong Handle); [PreserveSig] int GetNextSymbolMatch( [In] ulong Handle, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint MatchSize, [Out] out ulong Offset); [PreserveSig] int EndSymbolMatch( [In] ulong Handle); [PreserveSig] int Reload( [In, MarshalAs(UnmanagedType.LPStr)] string Module); [PreserveSig] int GetSymbolPath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSymbolPath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetImagePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int SetImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendImagePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int GetSourcePath( [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint PathSize); [PreserveSig] int GetSourcePathElement( [In] uint Index, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint ElementSize); [PreserveSig] int SetSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Path); [PreserveSig] int AppendSourcePath( [In, MarshalAs(UnmanagedType.LPStr)] string Addition); [PreserveSig] int FindSourceFile( [In] uint StartElement, [In, MarshalAs(UnmanagedType.LPStr)] string File, [In] uint Flags, [Out] out uint FoundElement, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint FoundSize); [PreserveSig] int GetSourceFileLineOffsets( [In, MarshalAs(UnmanagedType.LPStr)] string File, [Out] out ulong Buffer, [In] uint BufferLines, [Out] out uint FileLines); #endregion #pragma warning restore CS0108 // XXX hides inherited member. This is COM default. [PreserveSig] int GetModuleVersionInformation( [In] uint Index, [In] ulong Base, [In, MarshalAs(UnmanagedType.LPStr)] string Item, [Out] IntPtr Buffer, [In] uint BufferSize, [Out] out uint VerInfoSize); [PreserveSig] int GetModuleNameString( [In] uint Which, [In] uint Index, [In] ulong Base, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder Buffer, [In] uint BufferSize, [Out] out uint NameSize); [PreserveSig] int GetConstantName( [In] ulong Module, [In] uint TypeId, [In] ulong Value, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetFieldName( [In] ulong Module, [In] uint TypeId, [In] uint FieldIndex, [Out, MarshalAs(UnmanagedType.LPStr)] StringBuilder NameBuffer, [In] uint NameBufferSize, [Out] out uint NameSize); [PreserveSig] int GetTypeOptions( [Out] out uint Options); [PreserveSig] int AddTypeOptions( [In] uint Options); [PreserveSig] int RemoveTypeOptions( [In] uint Options); [PreserveSig] int SetTypeOptions( [In] uint Options); } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets.Wrappers { using NLog.Common; using NLog.Conditions; using NLog.Internal; /// <summary> /// Causes a flush on a wrapped target if LogEvent satisfies the <see cref="Condition"/>. /// If condition isn't set, flushes on each write. /// </summary> /// <remarks> /// <a href="https://github.com/nlog/nlog/wiki/AutoFlushWrapper-target">See NLog Wiki</a> /// </remarks> /// <seealso href="https://github.com/nlog/nlog/wiki/AutoFlushWrapper-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="https://github.com/NLog/NLog/wiki/Configuration-file">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/AutoFlushWrapper/NLog.config" /> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/AutoFlushWrapper/Simple/Example.cs" /> /// </example> [Target("AutoFlushWrapper", IsWrapper = true)] public class AutoFlushTargetWrapper : WrapperTargetBase { /// <summary> /// Gets or sets the condition expression. Log events who meet this condition will cause /// a flush on the wrapped target. /// </summary> /// <docgen category='General Options' order='10' /> public ConditionExpression Condition { get; set; } /// <summary> /// Delay the flush until the LogEvent has been confirmed as written /// </summary> /// <remarks>If not explicitly set, then disabled by default for <see cref="BufferingTargetWrapper"/> and AsyncTaskTarget /// </remarks> /// <docgen category='General Options' order='10' /> public bool AsyncFlush { get => _asyncFlush ?? true; set => _asyncFlush = value; } private bool? _asyncFlush; /// <summary> /// Only flush when LogEvent matches condition. Ignore explicit-flush, config-reload-flush and shutdown-flush /// </summary> /// <docgen category='General Options' order='10' /> public bool FlushOnConditionOnly { get; set; } private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> public AutoFlushTargetWrapper() : this(null) { } /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> /// <param name="name">Name of the target</param> public AutoFlushTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="AutoFlushTargetWrapper" /> class. /// </summary> /// <param name="wrappedTarget">The wrapped target.</param> public AutoFlushTargetWrapper(Target wrappedTarget) { WrappedTarget = wrappedTarget; } /// <inheritdoc/> protected override void InitializeTarget() { base.InitializeTarget(); if (!_asyncFlush.HasValue && !TargetSupportsAsyncFlush(WrappedTarget)) { AsyncFlush = false; // Disable AsyncFlush, so the intended trigger works } } private static bool TargetSupportsAsyncFlush(Target wrappedTarget) { if (wrappedTarget is BufferingTargetWrapper) return false; #if !NET35 if (wrappedTarget is AsyncTaskTarget) return false; #endif return true; } /// <summary> /// Forwards the call to the <see cref="WrapperTargetBase.WrappedTarget"/>.Write() /// and calls <see cref="Target.Flush(AsyncContinuation)"/> on it if LogEvent satisfies /// the flush condition or condition is null. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { if (Condition is null || Condition.Evaluate(logEvent.LogEvent).Equals(ConditionExpression.BoxedTrue)) { if (AsyncFlush) { AsyncContinuation currentContinuation = logEvent.Continuation; AsyncContinuation wrappedContinuation = (ex) => { if (ex is null) FlushOnCondition(); _pendingManualFlushList.CompleteOperation(ex); currentContinuation(ex); }; _pendingManualFlushList.BeginOperation(); WrappedTarget.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(wrappedContinuation)); } else { WrappedTarget.WriteAsyncLogEvent(logEvent); FlushOnCondition(); } } else { WrappedTarget.WriteAsyncLogEvent(logEvent); } } /// <summary> /// Schedules a flush operation, that triggers when all pending flush operations are completed (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (FlushOnConditionOnly) asyncContinuation(null); else FlushWrappedTarget(asyncContinuation); } private void FlushOnCondition() { if (FlushOnConditionOnly) FlushWrappedTarget((e) => { }); else FlushAsync((e) => { }); } private void FlushWrappedTarget(AsyncContinuation asyncContinuation) { var wrappedContinuation = _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation); WrappedTarget.Flush(wrappedContinuation); } /// <inheritdoc/> protected override void CloseTarget() { _pendingManualFlushList.Clear(); // Maybe consider to wait a short while if pending requests? base.CloseTarget(); } } }
namespace Azure.MixedReality.RemoteRendering { public partial class AssetConversion { internal AssetConversion() { } public string ConversionId { get { throw null; } } public System.DateTimeOffset CreatedOn { get { throw null; } } public Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError Error { get { throw null; } } public Azure.MixedReality.RemoteRendering.AssetConversionOptions Options { get { throw null; } } public Azure.MixedReality.RemoteRendering.AssetConversionOutput Output { get { throw null; } } public Azure.MixedReality.RemoteRendering.AssetConversionStatus Status { get { throw null; } } } public partial class AssetConversionInputOptions { public AssetConversionInputOptions(System.Uri storageContainerUri, string relativeInputAssetPath) { } public string BlobPrefix { get { throw null; } set { } } public string RelativeInputAssetPath { get { throw null; } } public string StorageContainerReadListSas { get { throw null; } set { } } public System.Uri StorageContainerUri { get { throw null; } } } public partial class AssetConversionOperation : Azure.Operation<Azure.MixedReality.RemoteRendering.AssetConversion> { protected AssetConversionOperation() { } public AssetConversionOperation(string conversionId, Azure.MixedReality.RemoteRendering.RemoteRenderingClient client) { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.MixedReality.RemoteRendering.AssetConversion Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.MixedReality.RemoteRendering.AssetConversion>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.MixedReality.RemoteRendering.AssetConversion>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AssetConversionOptions { public AssetConversionOptions(Azure.MixedReality.RemoteRendering.AssetConversionInputOptions inputOptions, Azure.MixedReality.RemoteRendering.AssetConversionOutputOptions outputOptions) { } public Azure.MixedReality.RemoteRendering.AssetConversionInputOptions InputOptions { get { throw null; } } public Azure.MixedReality.RemoteRendering.AssetConversionOutputOptions OutputOptions { get { throw null; } } } public partial class AssetConversionOutput { internal AssetConversionOutput() { } public string OutputAssetUri { get { throw null; } } } public partial class AssetConversionOutputOptions { public AssetConversionOutputOptions(System.Uri storageContainerUri) { } public string BlobPrefix { get { throw null; } set { } } public string OutputAssetFilename { get { throw null; } set { } } public System.Uri StorageContainerUri { get { throw null; } } public string StorageContainerWriteSas { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct AssetConversionStatus : System.IEquatable<Azure.MixedReality.RemoteRendering.AssetConversionStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public AssetConversionStatus(string value) { throw null; } public static Azure.MixedReality.RemoteRendering.AssetConversionStatus Cancelled { get { throw null; } } public static Azure.MixedReality.RemoteRendering.AssetConversionStatus Failed { get { throw null; } } public static Azure.MixedReality.RemoteRendering.AssetConversionStatus NotStarted { get { throw null; } } public static Azure.MixedReality.RemoteRendering.AssetConversionStatus Running { get { throw null; } } public static Azure.MixedReality.RemoteRendering.AssetConversionStatus Succeeded { get { throw null; } } public bool Equals(Azure.MixedReality.RemoteRendering.AssetConversionStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.MixedReality.RemoteRendering.AssetConversionStatus left, Azure.MixedReality.RemoteRendering.AssetConversionStatus right) { throw null; } public static implicit operator Azure.MixedReality.RemoteRendering.AssetConversionStatus (string value) { throw null; } public static bool operator !=(Azure.MixedReality.RemoteRendering.AssetConversionStatus left, Azure.MixedReality.RemoteRendering.AssetConversionStatus right) { throw null; } public override string ToString() { throw null; } } public partial class RemoteRenderingClient { protected RemoteRenderingClient() { } public RemoteRenderingClient(System.Uri remoteRenderingEndpoint, System.Guid accountId, string accountDomain, Azure.AzureKeyCredential keyCredential) { } public RemoteRenderingClient(System.Uri remoteRenderingEndpoint, System.Guid accountId, string accountDomain, Azure.AzureKeyCredential keyCredential, Azure.MixedReality.RemoteRendering.RemoteRenderingClientOptions options) { } public RemoteRenderingClient(System.Uri remoteRenderingEndpoint, System.Guid accountId, string accountDomain, Azure.Core.AccessToken accessToken, Azure.MixedReality.RemoteRendering.RemoteRenderingClientOptions options = null) { } public RemoteRenderingClient(System.Uri remoteRenderingEndpoint, System.Guid accountId, string accountDomain, Azure.Core.TokenCredential credential, Azure.MixedReality.RemoteRendering.RemoteRenderingClientOptions options = null) { } public virtual Azure.Response<Azure.MixedReality.RemoteRendering.AssetConversion> GetConversion(string conversionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.MixedReality.RemoteRendering.AssetConversion>> GetConversionAsync(string conversionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.MixedReality.RemoteRendering.AssetConversion> GetConversions(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.MixedReality.RemoteRendering.AssetConversion> GetConversionsAync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession> GetSession(string sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession>> GetSessionAsync(string sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.MixedReality.RemoteRendering.RenderingSession> GetSessions(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.MixedReality.RemoteRendering.RenderingSession> GetSessionsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.MixedReality.RemoteRendering.AssetConversionOperation StartConversion(string conversionId, Azure.MixedReality.RemoteRendering.AssetConversionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.MixedReality.RemoteRendering.AssetConversionOperation> StartConversionAsync(string conversionId, Azure.MixedReality.RemoteRendering.AssetConversionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.MixedReality.RemoteRendering.StartRenderingSessionOperation StartSession(string sessionId, Azure.MixedReality.RemoteRendering.RenderingSessionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.MixedReality.RemoteRendering.StartRenderingSessionOperation> StartSessionAsync(string sessionId, Azure.MixedReality.RemoteRendering.RenderingSessionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response StopSession(string sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> StopSessionAsync(string sessionId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession> UpdateSession(string sessionId, Azure.MixedReality.RemoteRendering.UpdateSessionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession>> UpdateSessionAsync(string sessionId, Azure.MixedReality.RemoteRendering.UpdateSessionOptions options, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class RemoteRenderingClientOptions : Azure.Core.ClientOptions { public RemoteRenderingClientOptions(Azure.MixedReality.RemoteRendering.RemoteRenderingClientOptions.ServiceVersion version = Azure.MixedReality.RemoteRendering.RemoteRenderingClientOptions.ServiceVersion.V2021_01_01) { } public System.Uri AuthenticationEndpoint { get { throw null; } set { } } public enum ServiceVersion { V2021_01_01 = 1, } } public static partial class RemoteRenderingModelFactory { public static Azure.MixedReality.RemoteRendering.AssetConversion AssetConversion(string conversionId, Azure.MixedReality.RemoteRendering.AssetConversionOptions options, Azure.MixedReality.RemoteRendering.AssetConversionOutput output, Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError error, Azure.MixedReality.RemoteRendering.AssetConversionStatus status, System.DateTimeOffset createdOn) { throw null; } public static Azure.MixedReality.RemoteRendering.AssetConversionOutput AssetConversionOutput(System.Uri outputAssetUri) { throw null; } public static Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError RemoteRenderingServiceError(string code, string message, System.Collections.Generic.IReadOnlyList<Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError> details, string target, Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError innerError) { throw null; } public static Azure.MixedReality.RemoteRendering.RenderingSession RenderingSession(string sessionId, int? arrInspectorPort, int? handshakePort, int? elapsedTimeMinutes, string host, int? maxLeaseTimeMinutes, Azure.MixedReality.RemoteRendering.RenderingServerSize size, Azure.MixedReality.RemoteRendering.RenderingSessionStatus status, float? teraflops, Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError error, System.DateTimeOffset? createdOn) { throw null; } } public partial class RemoteRenderingServiceError { internal RemoteRenderingServiceError() { } public string Code { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError> Details { get { throw null; } } public Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError InnerError { get { throw null; } } public string Message { get { throw null; } } public string Target { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RenderingServerSize : System.IEquatable<Azure.MixedReality.RemoteRendering.RenderingServerSize> { private readonly object _dummy; private readonly int _dummyPrimitive; public RenderingServerSize(string value) { throw null; } public static Azure.MixedReality.RemoteRendering.RenderingServerSize Premium { get { throw null; } } public static Azure.MixedReality.RemoteRendering.RenderingServerSize Standard { get { throw null; } } public bool Equals(Azure.MixedReality.RemoteRendering.RenderingServerSize other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.MixedReality.RemoteRendering.RenderingServerSize left, Azure.MixedReality.RemoteRendering.RenderingServerSize right) { throw null; } public static implicit operator Azure.MixedReality.RemoteRendering.RenderingServerSize (string value) { throw null; } public static bool operator !=(Azure.MixedReality.RemoteRendering.RenderingServerSize left, Azure.MixedReality.RemoteRendering.RenderingServerSize right) { throw null; } public override string ToString() { throw null; } } public partial class RenderingSession { internal RenderingSession() { } public int? ArrInspectorPort { get { throw null; } } public System.DateTimeOffset? CreatedOn { get { throw null; } } public int? ElapsedTimeMinutes { get { throw null; } } public Azure.MixedReality.RemoteRendering.RemoteRenderingServiceError Error { get { throw null; } } public int? HandshakePort { get { throw null; } } public string Host { get { throw null; } } public System.TimeSpan? MaxLeaseTime { get { throw null; } } public string SessionId { get { throw null; } } public Azure.MixedReality.RemoteRendering.RenderingServerSize Size { get { throw null; } } public Azure.MixedReality.RemoteRendering.RenderingSessionStatus Status { get { throw null; } } public float? Teraflops { get { throw null; } } } public partial class RenderingSessionOptions { public RenderingSessionOptions(System.TimeSpan maxLeaseTime, Azure.MixedReality.RemoteRendering.RenderingServerSize size) { } public System.TimeSpan MaxLeaseTime { get { throw null; } } public Azure.MixedReality.RemoteRendering.RenderingServerSize Size { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RenderingSessionStatus : System.IEquatable<Azure.MixedReality.RemoteRendering.RenderingSessionStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public RenderingSessionStatus(string value) { throw null; } public static Azure.MixedReality.RemoteRendering.RenderingSessionStatus Error { get { throw null; } } public static Azure.MixedReality.RemoteRendering.RenderingSessionStatus Expired { get { throw null; } } public static Azure.MixedReality.RemoteRendering.RenderingSessionStatus Ready { get { throw null; } } public static Azure.MixedReality.RemoteRendering.RenderingSessionStatus Starting { get { throw null; } } public static Azure.MixedReality.RemoteRendering.RenderingSessionStatus Stopped { get { throw null; } } public bool Equals(Azure.MixedReality.RemoteRendering.RenderingSessionStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.MixedReality.RemoteRendering.RenderingSessionStatus left, Azure.MixedReality.RemoteRendering.RenderingSessionStatus right) { throw null; } public static implicit operator Azure.MixedReality.RemoteRendering.RenderingSessionStatus (string value) { throw null; } public static bool operator !=(Azure.MixedReality.RemoteRendering.RenderingSessionStatus left, Azure.MixedReality.RemoteRendering.RenderingSessionStatus right) { throw null; } public override string ToString() { throw null; } } public partial class StartRenderingSessionOperation : Azure.Operation<Azure.MixedReality.RemoteRendering.RenderingSession> { protected StartRenderingSessionOperation() { } public StartRenderingSessionOperation(string sessionId, Azure.MixedReality.RemoteRendering.RemoteRenderingClient client) { } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public override Azure.MixedReality.RemoteRendering.RenderingSession Value { get { throw null; } } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.MixedReality.RemoteRendering.RenderingSession>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class UpdateSessionOptions { public UpdateSessionOptions(System.TimeSpan maxLeaseTime) { } public System.TimeSpan MaxLeaseTime { get { throw null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.Research.ClousotRegression; internal class Test { [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private bool Type_Primitive() { Contract.Ensures(Contract.Result<bool>() == true); return true; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private object Type_Object() { Contract.Ensures(Contract.Result<object>() != null); return new Object(); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private T Type_FormalMethodParamter<A, C, G, T>() where T : new() { Contract.Ensures(Contract.Result<T>() != null); return new T(); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private int[] Type_Array() { Contract.Ensures(Contract.Result<int[]>() != null); return new int[0]; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private int[,,] Type_Array3() { Contract.Ensures(Contract.Result<int[,,]>() != null); return new int[0, 0, 0]; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private List<int> Type_Specialized() { Contract.Ensures(Contract.Result<List<int>>() != null); return new List<int>(); } private class DummyClass { public class NestedClass { public object DummyField; } } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private DummyClass.NestedClass Type_NestedType() { Contract.Ensures(Contract.Result<DummyClass.NestedClass>() != null); return new DummyClass.NestedClass(); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private object Type_NestedType(DummyClass.NestedClass x) { Contract.Requires(x != null); Contract.Ensures(Contract.Result<object>() == x.DummyField); return x.DummyField; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private bool Parameters(object x, object y) { Contract.Ensures(Contract.Result<bool>() == ((x == this) || (x == y))); return x == this || x == y; } } public class GenericClass<A, C, G, T> where A : class, C where C : class where T : class { [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private T Type_FormalTypeParameter() { Contract.Ensures(Contract.Result<T>() == default(T)); return default(T); } [Pure] private C c(A a) { return a; } [Pure] private static C sc(A a) { return a; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private bool Method_TypeArguments(A a, C c) { Contract.Ensures(Contract.Result<bool>() == (this.c(a) == c)); return this.c(a) == c; } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private bool Method_Static(A a, C c) { Contract.Ensures(Contract.Result<bool>() == (sc(a) == c)); return sc(a) == c; } [Pure] private U f<U>(bool b, U x) { return b ? x : default(U); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private A Method_Specialized(bool b, A a) { Contract.Ensures(Contract.Result<A>() == this.f<A>(b, a)); return this.f(b, a); } [ClousotRegressionTest] #if FIRST [RegressionOutcome("No entry found in the cache")] #else [RegressionOutcome("An entry has been found in the cache")] #endif private U Method_Generic<X, U, Y>(bool b, U u) where U : class { Contract.Ensures(Contract.Result<U>() == this.f<U>(b, u)); return this.f(b, u); } }
using System; using Android.Content; using Android.Runtime; using Android.Text; using Android.Widget; using Android.Util; using Android.Graphics; using Java.Lang; using Math = System.Math; using String = System.String; namespace TestTimer.Android.Controls { public class TextResizedEventArgs : EventArgs { public float OldSize { get; set; } public float NewSize { get; set; } } public delegate void TextResizedEventHandler(object sender, TextResizedEventArgs args); /// /// TextView that automatically resizes it's content to fit the layout dimensions /// public class AutoResizeTextView : TextView { public event TextResizedEventHandler TextResized; // Minimum text size for this text view public static float MinTextSize = 20; #region Fields private static readonly Canvas TextResizeCanvas = new Canvas(); // Our ellipse string private const String Ellipsis = "..."; // Flag for text and/or size changes to force a resize private bool _needsResize = false; // Text size that is set from code. This acts as a starting point for resizing private float _textSize; // Temporary upper bounds on the starting text size private float _maxTextSize = 0; // Lower bounds for text size private float _minTextSize = MinTextSize; // Text view line spacing multiplier private float _spacingMult = 1.0f; // Text view additional line spacing private float _spacingAdd = 0.0f; // Add ellipsis to text that overflows at the smallest text size private bool _addEllipsis = false; #endregion #region Constructors public AutoResizeTextView(IntPtr a, JniHandleOwnership b) : base(a, b) { } // Default constructor override public AutoResizeTextView(Context context) : this(context, null) { } // Default constructor when inflating from XML file public AutoResizeTextView(Context context, IAttributeSet attrs) : this(context, attrs, 0) { } // Default constructor override public AutoResizeTextView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { _textSize = TextSize; } #endregion #region Public Methods //When text changes, set the force resize flag to true and reset the text size. protected override void OnTextChanged(ICharSequence text, int start, int before, int after) { _needsResize = true; // Since this view may be reused, it is good to reset the text size ResetTextSize(); } // If the text view size changed, set the force resize flag to true protected override void OnSizeChanged(int w, int h, int oldw, int oldh) { if (w != oldw || h != oldh) { _needsResize = true; } } public override void SetTextSize(ComplexUnitType unitType, float size) { base.SetTextSize(unitType, size); _textSize = TextSize; } /** * Override the set text size to update our internal reference values */ //@Override //public void setTextSize(int unit, float size) { // super.setTextSize(unit, size); // mTextSize = getTextSize(); //} // Override the set line spacing to update our internal reference values public override void SetLineSpacing(float add, float mult) { base.SetLineSpacing(add, mult); _spacingMult = mult; _spacingAdd = add; } //Set the upper text size limit and invalidate the view public void SetMaxTextSize(float maxTextSize) { _maxTextSize = maxTextSize; RequestLayout(); Invalidate(); } //Return upper text size limit public float GetMaxTextSize() { return _maxTextSize; } public float MaxTextSize { get { return _maxTextSize; } set { _maxTextSize = value; } } //Set the lower text size limit and invalidate the view public void SetMinTextSize(float minTextSize) { _minTextSize = minTextSize; RequestLayout(); Invalidate(); } //Return lower text size limit public float SetMinTextSize() { return _minTextSize; } //Set flag to add ellipsis to text that overflows at the smallest text size public void SetAddEllipsis(bool addEllipsis) { _addEllipsis = addEllipsis; } //Return flag to add ellipsis to text that overflows at the smallest text size public bool GetAddEllipsis() { return _addEllipsis; } //Reset the text to the original size public void ResetTextSize() { if (_textSize > 0) { base.SetTextSize(ComplexUnitType.Px, _textSize); _maxTextSize = _textSize; } } //Resize text after measuring protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { if (changed || _needsResize) { int widthLimit = (right - left) - CompoundPaddingLeft - CompoundPaddingRight; int heightLimit = (bottom - top) - CompoundPaddingBottom - CompoundPaddingTop; ResizeText(widthLimit, heightLimit); } base.OnLayout(changed, left, top, right, bottom); } //Resize the text size with default width and height public void ResizeText() { int heightLimit = Height - PaddingBottom - PaddingTop; int widthLimit = Width - PaddingLeft - PaddingRight; ResizeText(widthLimit, heightLimit); } // Resize the text size with specified width and height public void ResizeText(int width, int height) { string text = Text; // Do not resize if the view does not have dimensions or there is no text if (string.IsNullOrEmpty(text) || height <= 0 || width <= 0 || _textSize == 0) return; // Get the text view's paint object TextPaint textPaint = Paint; // Store the current text size float oldTextSize = textPaint.TextSize; // If there is a max text size set, use the lesser of that and the default text size float targetTextSize = _maxTextSize > 0 ? Math.Min(_textSize, _maxTextSize) : _textSize; // Get the required text height int textHeight = GetTextHeight(text, textPaint, width, targetTextSize); int textWidth = GetTextWidth(text, textPaint, width, targetTextSize); // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes while (((textHeight > height) || (textWidth > width)) && targetTextSize > _minTextSize) { targetTextSize = Math.Max(targetTextSize - 2, _minTextSize); textHeight = GetTextHeight(text, textPaint, width, targetTextSize); textWidth = GetTextWidth(text, textPaint, width, targetTextSize); } // If we had reached our minimum text size and still don't fit, append an ellipsis if (_addEllipsis && targetTextSize == _minTextSize && textHeight > height) { // Draw using a static layout StaticLayout layout = new StaticLayout(text, textPaint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, false); // Check that we have a least one line of rendered text if (layout.LineCount > 0) { // Since the line at the specific vertical position would be cut off, // we must trim up to the previous line int lastLine = layout.GetLineForVertical(height) - 1; // If the text would not even fit on a single line, clear it if (lastLine < 0) { Text = ""; } // Otherwise, trim to the previous line and add an ellipsis else { int start = layout.GetLineStart(lastLine); int end = layout.GetLineEnd(lastLine); float lineWidth = layout.GetLineWidth(lastLine); float ellipseWidth = textPaint.MeasureText(Ellipsis); // Trim characters off until we have enough room to draw the ellipsis while (width < lineWidth + ellipseWidth) { lineWidth = textPaint.MeasureText(text.Substring(start, --end + 1)); } Text = (text.Substring(0, end) + Ellipsis); } } } // Some devices try to auto adjust line spacing, so force default line spacing // and invalidate the layout as a side effect textPaint.TextSize = targetTextSize; SetLineSpacing(_spacingAdd, _spacingMult); TextResized?.Invoke(this, new TextResizedEventArgs { OldSize = oldTextSize, NewSize = targetTextSize }); // Reset force resize flag _needsResize = false; } #endregion #region Private methods // Set the text size of the text paint object and use a static layout to render text off screen before measuring private int GetTextHeight(string source, TextPaint paint, int width, float textSize) { // Update the text paint object paint.TextSize = textSize; // Measure using a static layout StaticLayout layout = new StaticLayout(source, paint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, true); layout.Draw(TextResizeCanvas); return layout.Height; } // Set the text size of the text paint object and use a static layout to render text off screen before measuring private int GetTextWidth(string source, TextPaint paint, int width, float textSize) { // Update the text paint object paint.TextSize = textSize; // Draw using a static layout StaticLayout layout = new StaticLayout(source, paint, width, Layout.Alignment.AlignNormal, _spacingMult, _spacingAdd, true); layout.Draw(TextResizeCanvas); return layout.Width; } #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 ForumSystem.Services.Areas.HelpPage.ModelDescriptions; using ForumSystem.Services.Areas.HelpPage.Models; namespace ForumSystem.Services.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/******************************************************************************* * Copyright 2017 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* Author: Ryu Woon Jung (Leon) */ // // ********* Bulk Read Example ********* // // // Available Dynamixel model on this example : MX or X series set to Protocol 1.0 // This example is designed for using two Dynamixel MX-28, and an USB2DYNAMIXEL. // To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below variables yourself. // Be sure that Dynamixel MX properties are already set as %% ID : 1 / Baudnum : 34 (Baudrate : 57600) // using System; using System.Runtime.InteropServices; using dynamixel_sdk; namespace bulk_read { class BulkRead { // Control table address public const int ADDR_MX_TORQUE_ENABLE = 24; // Control table address is different in Dynamixel model public const int ADDR_MX_GOAL_POSITION = 30; public const int ADDR_MX_PRESENT_POSITION = 36; public const int ADDR_MX_MOVING = 46; // Data Byte Length public const int LEN_MX_GOAL_POSITION = 2; public const int LEN_MX_PRESENT_POSITION = 2; public const int LEN_MX_MOVING = 1; // Protocol version public const int PROTOCOL_VERSION = 1; // See which protocol version is used in the Dynamixel // Default setting public const int DXL1_ID = 1; // Dynamixel ID: 1 public const int DXL2_ID = 2; // Dynamixel ID: 2 public const int BAUDRATE = 57600; public const string DEVICENAME = "COM1"; // Check which port is being used on your controller // ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*" public const int TORQUE_ENABLE = 1; // Value for enabling the torque public const int TORQUE_DISABLE = 0; // Value for disabling the torque public const int DXL_MINIMUM_POSITION_VALUE = 100; // Dynamixel will rotate between this value public const int DXL_MAXIMUM_POSITION_VALUE = 4000; // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.) public const int DXL_MOVING_STATUS_THRESHOLD = 10; // Dynamixel moving status threshold public const byte ESC_ASCII_VALUE = 0x1b; public const int COMM_SUCCESS = 0; // Communication Success result value public const int COMM_TX_FAIL = -1001; // Communication Tx Failed static void Main(string[] args) { // Initialize PortHandler Structs // Set the port path // Get methods and members of PortHandlerLinux or PortHandlerWindows int port_num = dynamixel.portHandler(DEVICENAME); // Initialize PacketHandler Structs dynamixel.packetHandler(); // Initialize Groupbulkread Structs int group_num = dynamixel.groupBulkRead(port_num, PROTOCOL_VERSION); int index = 0; int dxl_comm_result = COMM_TX_FAIL; // Communication result bool dxl_addparam_result = false; // AddParam result bool dxl_getdata_result = false; // GetParam result UInt16[] dxl_goal_position = new UInt16[2]{ DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE }; // Goal position byte dxl_error = 0; // Dynamixel error UInt16 dxl1_present_position = 0; // Present position byte dxl2_moving = 0; // Dynamixel moving status // Open port if (dynamixel.openPort(port_num)) { Console.WriteLine("Succeeded to open the port!"); } else { Console.WriteLine("Failed to open the port!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Set port baudrate if (dynamixel.setBaudRate(port_num, BAUDRATE)) { Console.WriteLine("Succeeded to change the baudrate!"); } else { Console.WriteLine("Failed to change the baudrate!"); Console.WriteLine("Press any key to terminate..."); Console.ReadKey(); return; } // Enable Dynamixel#1 Torque dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } else { Console.WriteLine("Dynamixel{0} has been successfully connected ", DXL1_ID); } // Enable Dynamixel#2 Torque dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_ENABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } else { Console.WriteLine("Dynamixel{0} has been successfully connected ", DXL1_ID); } // Add parameter storage for Dynamixel#1 present position value dxl_addparam_result = dynamixel.groupBulkReadAddParam(group_num, DXL1_ID, ADDR_MX_PRESENT_POSITION, LEN_MX_PRESENT_POSITION); if (dxl_addparam_result != true) { Console.WriteLine("[ID: {0}] groupBulkRead addparam failed", DXL1_ID); return; } // Add parameter storage for Dynamixel#2 present moving value dxl_addparam_result = dynamixel.groupBulkReadAddParam(group_num, DXL2_ID, ADDR_MX_MOVING, LEN_MX_MOVING); if (dxl_addparam_result != true) { Console.WriteLine("[ID: {0}] groupBulkRead addparam failed", DXL2_ID); return; } while (true) { Console.WriteLine("Press any key to continue! (or press ESC to quit!)"); if (Console.ReadKey().KeyChar == ESC_ASCII_VALUE) break; // Write Dynamixel#1 goal position dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_GOAL_POSITION, dxl_goal_position[index]); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Write Dynamixel#2 goal position dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_GOAL_POSITION, dxl_goal_position[index]); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } do { // Bulkread present position and moving status dynamixel.groupBulkReadTxRxPacket(group_num); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); dxl_getdata_result = dynamixel.groupBulkReadIsAvailable(group_num, DXL1_ID, ADDR_MX_PRESENT_POSITION, LEN_MX_PRESENT_POSITION); if (dxl_getdata_result != true) { Console.WriteLine("[ID: {0}] groupBulkRead getdata failed", DXL1_ID); return; } dxl_getdata_result = dynamixel.groupBulkReadIsAvailable(group_num, DXL2_ID, ADDR_MX_MOVING, LEN_MX_MOVING); if (dxl_getdata_result != true) { Console.WriteLine("[ID: {0}] groupBulkRead getdata failed", DXL2_ID); return; } // Get Dynamixel#1 present position value dxl1_present_position = (UInt16)dynamixel.groupBulkReadGetData(group_num, DXL1_ID, ADDR_MX_PRESENT_POSITION, LEN_MX_PRESENT_POSITION); // Get Dynamixel#2 moving status value dxl2_moving = (byte)dynamixel.groupBulkReadGetData(group_num, DXL2_ID, ADDR_MX_MOVING, LEN_MX_MOVING); Console.WriteLine("[ID: {0}] Present Position : {1} [ID: {2}] Is Moving : {3}", DXL1_ID, dxl1_present_position, DXL2_ID, dxl2_moving); } while (Math.Abs(dxl_goal_position[index] - dxl1_present_position) > DXL_MOVING_STATUS_THRESHOLD); // Change goal position if (index == 0) { index = 1; } else { index = 0; } } // Disable Dynamixel#1 Torque dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL1_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Disable Dynamixel#2 Torque dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL2_ID, ADDR_MX_TORQUE_ENABLE, TORQUE_DISABLE); if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result))); } else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0) { Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error))); } // Close port dynamixel.closePort(port_num); return; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: RegistrySecurity ** ** ** Purpose: Managed ACL wrapper for registry keys. ** ** ===========================================================*/ using System; using System.Collections; using System.Security.Permissions; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.IO; namespace System.Security.AccessControl { // We derived this enum from the definitions of KEY_READ and such from // winnt.h and from MSDN, plus some experimental validation with regedit. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/registry_key_security_and_access_rights.asp [Flags] public enum RegistryRights { // No None field - An ACE with the value 0 cannot grant nor deny. QueryValues = Win32Native.KEY_QUERY_VALUE, // 0x0001 query the values of a registry key SetValue = Win32Native.KEY_SET_VALUE, // 0x0002 create, delete, or set a registry value CreateSubKey = Win32Native.KEY_CREATE_SUB_KEY, // 0x0004 required to create a subkey of a specific key EnumerateSubKeys = Win32Native.KEY_ENUMERATE_SUB_KEYS, // 0x0008 required to enumerate sub keys of a key Notify = Win32Native.KEY_NOTIFY, // 0x0010 needed to request change notifications CreateLink = Win32Native.KEY_CREATE_LINK, // 0x0020 reserved for system use /// /// The Windows Kernel team agrees that it was a bad design to expose the WOW64_n options as permissions. /// in the .NET Framework these options are exposed via the RegistryView enum /// /// Reg64 = Win32Native.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view /// Reg32 = Win32Native.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view ExecuteKey = ReadKey, ReadKey = Win32Native.STANDARD_RIGHTS_READ | QueryValues | EnumerateSubKeys | Notify, WriteKey = Win32Native.STANDARD_RIGHTS_WRITE | SetValue | CreateSubKey, Delete = 0x10000, ReadPermissions = 0x20000, ChangePermissions = 0x40000, TakeOwnership = 0x80000, FullControl = 0xF003F | Win32Native.STANDARD_RIGHTS_READ | Win32Native.STANDARD_RIGHTS_WRITE } public sealed class RegistryAccessRule : AccessRule { // Constructor for creating access rules for registry objects public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) : this(identity, (int) registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public RegistryAccessRule(String identity, RegistryRights registryRights, AccessControlType type) : this(new NTAccount(identity), (int) registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public RegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(identity, (int) registryRights, false, inheritanceFlags, propagationFlags, type) { } public RegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this(new NTAccount(identity), (int) registryRights, false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal RegistryAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type ) { } public RegistryRights RegistryRights { get { return (RegistryRights) base.AccessMask; } } } public sealed class RegistryAuditRule : AuditRule { public RegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(identity, (int) registryRights, false, inheritanceFlags, propagationFlags, flags) { } public RegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this(new NTAccount(identity), (int) registryRights, false, inheritanceFlags, propagationFlags, flags) { } internal RegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } public RegistryRights RegistryRights { get { return (RegistryRights) base.AccessMask; } } } public sealed class RegistrySecurity : NativeObjectSecurity { public RegistrySecurity() : base(true, ResourceType.RegistryKey) { } /* // The name of registry key must start with a predefined string, // like CLASSES_ROOT, CURRENT_USER, MACHINE, and USERS. See // MSDN's help for SetNamedSecurityInfo for details. [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] internal RegistrySecurity(String name, AccessControlSections includeSections) : base(true, ResourceType.RegistryKey, HKeyNameToWindowsName(name), includeSections) { new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); } */ [System.Security.SecurityCritical] // auto-generated [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] internal RegistrySecurity(SafeRegistryHandle hKey, String name, AccessControlSections includeSections) : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null ) { new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); } [System.Security.SecurityCritical] // auto-generated private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Win32Native.ERROR_FILE_NOT_FOUND: exception = new IOException(Environment.GetResourceString("Arg_RegKeyNotFound", errorCode)); break; case Win32Native.ERROR_INVALID_NAME: exception = new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", "name")); break; case Win32Native.ERROR_INVALID_HANDLE: exception = new ArgumentException(Environment.GetResourceString("AccessControl_InvalidHandle")); break; default: break; } return exception; } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new RegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new RegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } /* // See SetNamedSecurityInfo docs - we must start strings // with names like CURRENT_USER, MACHINE, CLASSES_ROOT, etc. // (Look at SE_OBJECT_TYPE, then the docs for SE_REGISTRY_KEY) internal static String HKeyNameToWindowsName(String keyName) { if (keyName.StartsWith("HKEY_")) { if (keyName.Equals("HKEY_LOCAL_MACHINE")) return "MACHINE"; return keyName.Substring(5); } return keyName; } [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] internal void Persist(String keyName) { new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand(); AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); if (persistRules == AccessControlSections.None) return; // Don't need to persist anything. String windowsKeyName = HKeyNameToWindowsName(keyName); base.Persist(windowsKeyName, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } */ [System.Security.SecurityCritical] // auto-generated [SecurityPermission(SecurityAction.Assert, UnmanagedCode=true)] internal void Persist(SafeRegistryHandle hKey, String keyName) { new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand(); WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); if (persistRules == AccessControlSections.None) return; // Don't need to persist anything. base.Persist(hKey, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } public void AddAccessRule(RegistryAccessRule rule) { base.AddAccessRule(rule); } public void SetAccessRule(RegistryAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(RegistryAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(RegistryAccessRule rule) { return base.RemoveAccessRule(rule); } public void RemoveAccessRuleAll(RegistryAccessRule rule) { base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(RegistryAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } public void AddAuditRule(RegistryAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(RegistryAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(RegistryAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(RegistryAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(RegistryAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override Type AccessRightType { get { return typeof(RegistryRights); } } public override Type AccessRuleType { get { return typeof(RegistryAccessRule); } } public override Type AuditRuleType { get { return typeof(RegistryAuditRule); } } } }
using System; using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; using Http2; namespace Http2Tests { public class GoAwayTests { private ILoggerProvider loggerProvider; public GoAwayTests(ITestOutputHelper outHelper) { loggerProvider = new XUnitOutputLoggerProvider(outHelper); } [Theory] [InlineData(true)] [InlineData(false)] public async Task GoAwayShouldBeSendable(bool withConnectionClose) { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); // Start the GoAway process in a background task. // As waiting for this will block the current task in case // of connection close var closeTask = Task.Run(() => res.conn.GoAwayAsync(ErrorCode.InternalError, withConnectionClose)); // Expect the GoAway message await outPipe.AssertGoAwayReception(ErrorCode.InternalError, 1u); if (withConnectionClose) { await outPipe.AssertStreamEnd(); await inPipe.CloseAsync(); } await closeTask; } [Fact] public async Task InCaseOfManualGoAwayAndConnectionErrorOnlyASingleGoAwayShouldBeSent() { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); // Send the manual GoAway await res.conn.GoAwayAsync(ErrorCode.NoError, false); // Expect to read it await outPipe.AssertGoAwayReception(ErrorCode.NoError, 1u); // And force a connection error that should not yield a further GoAway await inPipe.WriteSettingsAck(); // Expect end of stream and not GoAway await outPipe.AssertStreamEnd(); } [Fact] public async Task NewStreamsAfterGoAwayShouldBeRejected() { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); // Start the GoAway process await res.conn.GoAwayAsync(ErrorCode.NoError, false); // Expect the GoAway message await outPipe.AssertGoAwayReception(ErrorCode.NoError, 1u); // Try to establish a new stream var hEncoder = new Http2.Hpack.Encoder(); await inPipe.WriteHeaders(hEncoder, 3, true, TestHeaders.DefaultGetHeaders); // Expect a stream rejection await outPipe.AssertResetStreamReception(3u, ErrorCode.RefusedStream); } [Fact] public async Task RemoteGoAwayReasonTaskShouldYieldExceptionIfNoGoAwayIsSent() { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); var readGoAwayTask = res.conn.RemoteGoAwayReason; await inPipe.CloseAsync(); Assert.True( readGoAwayTask == await Task.WhenAny(readGoAwayTask, Task.Delay(200)), "Expected readGoAwayTask to finish"); await Assert.ThrowsAsync<EndOfStreamException>( async () => await readGoAwayTask); } [Theory] [InlineData(0u, ErrorCode.Cancel, "")] [InlineData(2u, ErrorCode.NoError, "Im going away now")] public async Task RemoteGoAwayReasonShouldBeGettableFromTask( uint lastStreamId, ErrorCode errc, string debugString) { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); var debugData = Encoding.ASCII.GetBytes(debugString); await inPipe.WriteGoAway(lastStreamId, errc, debugData); var readGoAwayTask = res.conn.RemoteGoAwayReason; Assert.True( readGoAwayTask == await Task.WhenAny(readGoAwayTask, Task.Delay(200)), "Expected to read GoAway data"); var reason = await readGoAwayTask; Assert.Equal(lastStreamId, reason.LastStreamId); Assert.Equal(errc, reason.ErrorCode); Assert.Equal(debugString, Encoding.ASCII.GetString( reason.DebugData.Array, reason.DebugData.Offset, reason.DebugData.Count)); } [Fact] public async Task ASecondRemoteGoAwayShouldBeIgnored() { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var res = await ServerStreamTests.StreamCreator.CreateConnectionAndStream( StreamState.Open, loggerProvider, inPipe, outPipe); await inPipe.WriteGoAway(0u, ErrorCode.NoError, null); await inPipe.WriteGoAway(2u, ErrorCode.InadequateSecurity, null); var readGoAwayTask = res.conn.RemoteGoAwayReason; Assert.True( readGoAwayTask == await Task.WhenAny(readGoAwayTask, Task.Delay(200)), "Expected to read GoAway data"); var reason = await readGoAwayTask; Assert.Equal(0u, reason.LastStreamId); Assert.Equal(ErrorCode.NoError, reason.ErrorCode); } [Theory] [InlineData(false, 0)] [InlineData(false, 7)] [InlineData(false, 65536)] [InlineData(true, 0)] [InlineData(true, 7)] [InlineData(true, 65536)] public async Task ConnectionShouldGoAwayOnInvalidGoAwayFrameLength( bool isServer, int frameLength) { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var http2Con = await ConnectionUtils.BuildEstablishedConnection( isServer, inPipe, outPipe, loggerProvider); var fh = new FrameHeader { Type = FrameType.GoAway, Flags = 0, Length = frameLength, StreamId = 0, }; await inPipe.WriteFrameHeader(fh); var expectedErr = frameLength > 65535 ? ErrorCode.FrameSizeError : ErrorCode.ProtocolError; await outPipe.AssertGoAwayReception(expectedErr, 0); await outPipe.AssertStreamEnd(); } [Theory] [InlineData(true)] [InlineData(false)] public async Task ConnectionShouldGoAwayOnInvalidGoAwayStreamId( bool isServer) { var inPipe = new BufferedPipe(1024); var outPipe = new BufferedPipe(1024); var http2Con = await ConnectionUtils.BuildEstablishedConnection( isServer, inPipe, outPipe, loggerProvider); var goAwayData = new GoAwayFrameData { Reason = new GoAwayReason { LastStreamId = 0u, ErrorCode = ErrorCode.NoError, DebugData = new ArraySegment<byte>(new byte[0]), }, }; var fh = new FrameHeader { Type = FrameType.GoAway, Flags = 0, StreamId = 1, Length = goAwayData.RequiredSize, }; var dataBytes = new byte[goAwayData.RequiredSize]; goAwayData.EncodeInto(new ArraySegment<byte>(dataBytes)); await inPipe.WriteFrameHeader(fh); await inPipe.WriteAsync(new ArraySegment<byte>(dataBytes)); await outPipe.AssertGoAwayReception(ErrorCode.ProtocolError, 0); await outPipe.AssertStreamEnd(); } } }
// 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.Security; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IReadOnlyDictionary`2 interface on WinRT // objects that support IMapView`2. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not IMapViewToIReadOnlyDictionaryAdapter objects. Rather, they are of type // IMapView<K, V>. No actual IMapViewToIReadOnlyDictionaryAdapter object is ever instantiated. Thus, you will see // a lot of expressions that cast "this" to "IMapView<K, V>". [DebuggerDisplay("Count = {Count}")] internal sealed class IMapViewToIReadOnlyDictionaryAdapter { private IMapViewToIReadOnlyDictionaryAdapter() { Debug.Assert(false, "This class is never instantiated"); } // V this[K key] { get } internal V Indexer_Get<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); Contract.EndContractBlock(); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); return Lookup(_this, key); } // IEnumerable<K> Keys { get } internal IEnumerable<K> Keys<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryKeyCollection<K, V>(roDictionary); } // IEnumerable<V> Values { get } internal IEnumerable<V> Values<K, V>() { IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); IReadOnlyDictionary<K, V> roDictionary = (IReadOnlyDictionary<K, V>)_this; return new ReadOnlyDictionaryValueCollection<K, V>(roDictionary); } // bool ContainsKey(K key) [Pure] internal bool ContainsKey<K, V>(K key) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); return _this.HasKey(key); } // bool TryGetValue(TKey key, out TValue value) internal bool TryGetValue<K, V>(K key, out V value) { if (key == null) throw new ArgumentNullException(nameof(key)); IMapView<K, V> _this = JitHelpers.UnsafeCast<IMapView<K, V>>(this); // It may be faster to call HasKey then Lookup. On failure, we would otherwise // throw an exception from Lookup. if (!_this.HasKey(key)) { value = default(V); return false; } try { value = _this.Lookup(key); return true; } catch (Exception ex) // Still may hit this case due to a race condition { if (HResults.E_BOUNDS == ex._HResult) { value = default(V); return false; } throw; } } #region Helpers private static V Lookup<K, V>(IMapView<K, V> _this, K key) { Contract.Requires(null != key); try { return _this.Lookup(key); } catch (Exception ex) { if (HResults.E_BOUNDS == ex._HResult) throw new KeyNotFoundException(SR.Arg_KeyNotFound); throw; } } #endregion Helpers } // Note: One day we may make these return IReadOnlyCollection<T> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryKeyCollection<TKey, TValue> : IEnumerable<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryKeyCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TKey[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Key; } } public int Count { get { return dictionary.Count; } } public bool Contains(TKey item) { return dictionary.ContainsKey(item); } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TKey>)this).GetEnumerator(); } public IEnumerator<TKey> GetEnumerator() { return new ReadOnlyDictionaryKeyEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryKeyCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> : IEnumerator<TKey> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryKeyEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TKey>)this).Current; } } public TKey Current { get { return enumeration.Current.Key; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryKeyEnumerator<TKey, TValue> [DebuggerDisplay("Count = {Count}")] internal sealed class ReadOnlyDictionaryValueCollection<TKey, TValue> : IEnumerable<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; public ReadOnlyDictionaryValueCollection(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; } /* public void CopyTo(TValue[] array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); if (array.Length <= index && this.Count > 0) throw new ArgumentException(SR.Arg_IndexOutOfRangeException); if (array.Length - index < dictionary.Count) throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection); int i = index; foreach (KeyValuePair<TKey, TValue> mapping in dictionary) { array[i++] = mapping.Value; } } public int Count { get { return dictionary.Count; } } public bool Contains(TValue item) { EqualityComparer<TValue> comparer = EqualityComparer<TValue>.Default; foreach (TValue value in this) if (comparer.Equals(item, value)) return true; return false; } */ IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<TValue>)this).GetEnumerator(); } public IEnumerator<TValue> GetEnumerator() { return new ReadOnlyDictionaryValueEnumerator<TKey, TValue>(dictionary); } } // public class ReadOnlyDictionaryValueCollection<TKey, TValue> internal sealed class ReadOnlyDictionaryValueEnumerator<TKey, TValue> : IEnumerator<TValue> { private readonly IReadOnlyDictionary<TKey, TValue> dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> enumeration; public ReadOnlyDictionaryValueEnumerator(IReadOnlyDictionary<TKey, TValue> dictionary) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); this.dictionary = dictionary; enumeration = dictionary.GetEnumerator(); } void IDisposable.Dispose() { enumeration.Dispose(); } public bool MoveNext() { return enumeration.MoveNext(); } Object IEnumerator.Current { get { return ((IEnumerator<TValue>)this).Current; } } public TValue Current { get { return enumeration.Current.Value; } } public void Reset() { enumeration = dictionary.GetEnumerator(); } } // class ReadOnlyDictionaryValueEnumerator<TKey, TValue> }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// gRPC server. A single server can serve an arbitrary number of services and can listen on more than one port. /// </summary> public class Server { const int DefaultRequestCallTokensPerCq = 2000; static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly ServiceDefinitionCollection serviceDefinitions; readonly ServerPortCollection ports; readonly GrpcEnvironment environment; readonly List<ChannelOption> options; readonly ServerSafeHandle handle; readonly object myLock = new object(); readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>(); readonly List<ServerPort> serverPortList = new List<ServerPort>(); readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); bool startRequested; volatile bool shutdownRequested; int requestCallTokensPerCq = DefaultRequestCallTokensPerCq; /// <summary> /// Creates a new server. /// </summary> public Server() : this(null) { } /// <summary> /// Creates a new server. /// </summary> /// <param name="options">Channel options.</param> public Server(IEnumerable<ChannelOption> options) { this.serviceDefinitions = new ServiceDefinitionCollection(this); this.ports = new ServerPortCollection(this); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options)) { this.handle = ServerSafeHandle.NewServer(channelArgs); } foreach (var cq in environment.CompletionQueues) { this.handle.RegisterCompletionQueue(cq); } GrpcEnvironment.RegisterServer(this); } /// <summary> /// Services that will be exported by the server once started. Register a service with this /// server by adding its definition to this collection. /// </summary> public ServiceDefinitionCollection Services { get { return serviceDefinitions; } } /// <summary> /// Ports on which the server will listen once started. Register a port with this /// server by adding its definition to this collection. /// </summary> public ServerPortCollection Ports { get { return ports; } } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } /// <summary> /// Experimental API. Might anytime change without prior notice. /// Number or calls requested via grpc_server_request_call at any given time for each completion queue. /// </summary> public int RequestCallTokensPerCompletionQueue { get { return requestCallTokensPerCq; } set { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckArgument(value > 0); requestCallTokensPerCq = value; } } } /// <summary> /// Starts the server. /// Throws <c>IOException</c> if not all ports have been bound successfully (see <c>Ports.Add</c> method). /// Even if some of that ports haven't been bound, the server will still serve normally on all ports that have been /// bound successfully (and the user is expected to shutdown the server by invoking <c>ShutdownAsync</c> or <c>KillAsync</c>). /// </summary> public void Start() { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckState(!shutdownRequested); startRequested = true; handle.Start(); for (int i = 0; i < requestCallTokensPerCq; i++) { foreach (var cq in environment.CompletionQueues) { AllowOneRpc(cq); } } // Throw if some ports weren't bound successfully. // Even when that happens, some server ports might have been // bound successfully, so we let server initialization // proceed as usual and we only throw at the very end of the // Start() method. CheckPortsBoundSuccessfully(); } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. The returned task finishes when shutdown procedure /// is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task ShutdownAsync() { return ShutdownInternalAsync(false); } /// <summary> /// Requests server shutdown while cancelling all the in-progress calls. /// The returned task finishes when shutdown procedure is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task KillAsync() { return ShutdownInternalAsync(true); } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } /// <summary> /// Shuts down the server. /// </summary> private async Task ShutdownInternalAsync(bool kill) { lock (myLock) { GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } GrpcEnvironment.UnregisterServer(this); var cq = environment.CompletionQueues.First(); // any cq will do handle.ShutdownAndNotify(HandleServerShutdown, cq); if (kill) { handle.CancelAllCalls(); } await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false); DisposeHandle(); await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false); } /// <summary> /// In case the environment's threadpool becomes dead, the shutdown completion will /// never be delivered, but we need to release the environment's handle anyway. /// </summary> private async Task ShutdownCompleteOrEnvironmentDeadAsync() { while (true) { var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false); if (shutdownTcs.Task == task) { return; } if (!environment.IsAlive) { return; } } } /// <summary> /// Adds a service definition. /// </summary> private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition) { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); foreach (var entry in serviceDefinition.GetCallHandlers()) { callHandlers.Add(entry.Key, entry.Value); } serviceDefinitionsList.Add(serviceDefinition); } } /// <summary> /// Adds a listening port. /// </summary> private int AddPortInternal(ServerPort serverPort) { lock (myLock) { GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort"); GrpcPreconditions.CheckState(!startRequested); var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port); int boundPort; using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials()) { if (nativeCredentials != null) { boundPort = handle.AddSecurePort(address, nativeCredentials); } else { boundPort = handle.AddInsecurePort(address); } } var newServerPort = new ServerPort(serverPort, boundPort); this.serverPortList.Add(newServerPort); return boundPort; } } /// <summary> /// Allows one new RPC call to be received by server. /// </summary> private void AllowOneRpc(CompletionQueueSafeHandle cq) { if (!shutdownRequested) { // TODO(jtattermusch): avoid unnecessary delegate allocation handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq); } } /// <summary> /// Checks that all ports have been bound successfully. /// </summary> private void CheckPortsBoundSuccessfully() { lock (myLock) { var unboundPort = ports.FirstOrDefault(port => port.BoundPort == 0); if (unboundPort != null) { throw new IOException( string.Format("Failed to bind port \"{0}:{1}\"", unboundPort.Host, unboundPort.Port)); } } } private void DisposeHandle() { var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount); } handle.Dispose(); } /// <summary> /// Selects corresponding handler for given call and handles the call. /// </summary> private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq, Action<Server, CompletionQueueSafeHandle> continuation) { try { IServerCallHandler callHandler; if (!callHandlers.TryGetValue(newRpc.Method, out callHandler)) { callHandler = UnimplementedMethodCallHandler.Instance; } await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false); } catch (Exception e) { Logger.Warning(e, "Exception while handling RPC."); } finally { continuation(this, cq); } } /// <summary> /// Handles the native callback. /// </summary> private void HandleNewServerRpc(bool success, RequestCallContextSafeHandle ctx, CompletionQueueSafeHandle cq) { bool nextRpcRequested = false; if (success) { var newRpc = ctx.GetServerRpcNew(this); // after server shutdown, the callback returns with null call if (!newRpc.Call.IsInvalid) { nextRpcRequested = true; // Start asynchronous handler for the call. // Don't await, the continuations will run on gRPC thread pool once triggered // by cq.Next(). #pragma warning disable 4014 HandleCallAsync(newRpc, cq, (server, state) => server.AllowOneRpc(state)); #pragma warning restore 4014 } } if (!nextRpcRequested) { AllowOneRpc(cq); } } /// <summary> /// Handles native callback. /// </summary> private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx, object state) { shutdownTcs.SetResult(null); } /// <summary> /// Collection of service definitions. /// </summary> public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition> { readonly Server server; internal ServiceDefinitionCollection(Server server) { this.server = server; } /// <summary> /// Adds a service definition to the server. This is how you register /// handlers for a service with the server. Only call this before Start(). /// </summary> public void Add(ServerServiceDefinition serviceDefinition) { server.AddServiceDefinitionInternal(serviceDefinition); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerServiceDefinition> GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } } /// <summary> /// Collection of server ports. /// </summary> public class ServerPortCollection : IEnumerable<ServerPort> { readonly Server server; internal ServerPortCollection(Server server) { this.server = server; } /// <summary> /// Adds a new port on which server should listen. /// Only call this before Start(). /// <returns>The port on which server will be listening. Return value of zero means that binding the port has failed.</returns> /// </summary> public int Add(ServerPort serverPort) { return server.AddPortInternal(serverPort); } /// <summary> /// Adds a new port on which server should listen. /// <returns>The port on which server will be listening. Return value of zero means that binding the port has failed.</returns> /// </summary> /// <param name="host">the host</param> /// <param name="port">the port. If zero, an unused port is chosen automatically.</param> /// <param name="credentials">credentials to use to secure this port.</param> public int Add(string host, int port, ServerCredentials credentials) { return Add(new ServerPort(host, port, credentials)); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerPort> GetEnumerator() { return server.serverPortList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serverPortList.GetEnumerator(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Threading; using Dynamsoft.DotNet.TWAIN; using Dynamsoft.Barcode; namespace DotNet_TWAIN_Demo { public partial class DotNetTWAINDemo : Form { // For move the window private Point mouse_offset; // For move the annotation form private Point mouse_offset2; private int currentImageIndex = -1; private delegate void CrossThreadOperationControl(); private bool isToCrop = false; private Label infoLabel; private RoundedRectanglePanel roundedRectanglePanelSaveImage; private RoundedRectanglePanel roundedRectanglePanelAcquireLoad; private RoundedRectanglePanel roundedRectanglePanelBarcode; private RoundedRectanglePanel roundedRectanglePanelOCR; private TabHead thSaveImage; private TabHead thOCR; private TabHead thAddBarcode; private TabHead thReadBarcode; private TabHead thLoadImage; private TabHead thAcquireImage; /// <summary> /// Click to minimize the form /// </summary> protected override CreateParams CreateParams { get { const int WS_MINIMIZEBOX = 0x00020000; CreateParams cp = base.CreateParams; cp.Style = cp.Style | WS_MINIMIZEBOX; return cp; } } public DotNetTWAINDemo() { InitializeComponent(); InitializeComponentForCustomControl(); // Draw the background for the main form DrawBackground(); Initialization(); this.dynamicDotNetTwain.LicenseKeys = "289CDD8159E24D125E0DCB2BB4DAB9C7;AE725932B8E6ABD40FF25225C8282AD9"; } private void InitializeComponentForCustomControl() { this.roundedRectanglePanelSaveImage = new DotNet_TWAIN_Demo.RoundedRectanglePanel(); this.roundedRectanglePanelAcquireLoad = new DotNet_TWAIN_Demo.RoundedRectanglePanel(); this.roundedRectanglePanelBarcode = new DotNet_TWAIN_Demo.RoundedRectanglePanel(); this.roundedRectanglePanelOCR = new DotNet_TWAIN_Demo.RoundedRectanglePanel(); this.thSaveImage = new DotNet_TWAIN_Demo.TabHead(); this.thOCR = new DotNet_TWAIN_Demo.TabHead(); this.thAddBarcode = new DotNet_TWAIN_Demo.TabHead(); this.thReadBarcode = new DotNet_TWAIN_Demo.TabHead(); this.thLoadImage = new DotNet_TWAIN_Demo.TabHead(); this.thAcquireImage = new DotNet_TWAIN_Demo.TabHead(); this.roundedRectanglePanelSaveImage.SuspendLayout(); this.roundedRectanglePanelAcquireLoad.SuspendLayout(); this.roundedRectanglePanelBarcode.SuspendLayout(); this.roundedRectanglePanelOCR.SuspendLayout(); // // roundedRectanglePanelSaveImage // this.roundedRectanglePanelSaveImage.AutoSize = true; this.roundedRectanglePanelSaveImage.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("roundedRectanglePanelSaveImage.BackgroundImage"))); this.roundedRectanglePanelSaveImage.Controls.Add(this.panelSaveImage); this.roundedRectanglePanelSaveImage.Controls.Add(this.thSaveImage); this.roundedRectanglePanelSaveImage.Location = new System.Drawing.Point(12, 904); this.roundedRectanglePanelSaveImage.Margin = new System.Windows.Forms.Padding(12, 12, 12, 0); this.roundedRectanglePanelSaveImage.Name = "roundedRectanglePanelSaveImage"; this.roundedRectanglePanelSaveImage.Padding = new System.Windows.Forms.Padding(1); this.roundedRectanglePanelSaveImage.Size = new System.Drawing.Size(250, 252); // // roundedRectanglePanelAcquireLoad // this.roundedRectanglePanelAcquireLoad.AutoSize = true; this.roundedRectanglePanelAcquireLoad.BackColor = System.Drawing.SystemColors.Control; this.roundedRectanglePanelAcquireLoad.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("roundedRectanglePanelAcquireLoad.BackgroundImage"))); this.roundedRectanglePanelAcquireLoad.Controls.Add(this.panelLoad); this.roundedRectanglePanelAcquireLoad.Controls.Add(this.panelAcquire); this.roundedRectanglePanelAcquireLoad.Controls.Add(this.thLoadImage); this.roundedRectanglePanelAcquireLoad.Controls.Add(this.thAcquireImage); this.roundedRectanglePanelAcquireLoad.Location = new System.Drawing.Point(12, 12); this.roundedRectanglePanelAcquireLoad.Margin = new System.Windows.Forms.Padding(12, 12, 12, 0); this.roundedRectanglePanelAcquireLoad.Name = "roundedRectanglePanelAcquireLoad"; this.roundedRectanglePanelAcquireLoad.Padding = new System.Windows.Forms.Padding(1); this.roundedRectanglePanelAcquireLoad.Size = new System.Drawing.Size(250, 270); this.roundedRectanglePanelAcquireLoad.TabIndex = 0; // // roundedRectanglePanelBarcode // this.roundedRectanglePanelBarcode.AutoSize = true; this.roundedRectanglePanelBarcode.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("roundedRectanglePanelBarcode.BackgroundImage"))); this.roundedRectanglePanelBarcode.Controls.Add(this.panelAddBarcode); this.roundedRectanglePanelBarcode.Controls.Add(this.panelReadBarcode); this.roundedRectanglePanelBarcode.Controls.Add(this.thAddBarcode); this.roundedRectanglePanelBarcode.Controls.Add(this.thReadBarcode); this.roundedRectanglePanelBarcode.Location = new System.Drawing.Point(12, 294); this.roundedRectanglePanelBarcode.Margin = new System.Windows.Forms.Padding(12, 12, 12, 0); this.roundedRectanglePanelBarcode.Name = "roundedRectanglePanelBarcode"; this.roundedRectanglePanelBarcode.Padding = new System.Windows.Forms.Padding(1); this.roundedRectanglePanelBarcode.Size = new System.Drawing.Size(250, 362); this.roundedRectanglePanelBarcode.TabIndex = 1; // // roundedRectanglePanelOCR // this.roundedRectanglePanelOCR.AutoSize = true; this.roundedRectanglePanelOCR.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("roundedRectanglePanelOCR.BackgroundImage"))); this.roundedRectanglePanelOCR.Controls.Add(this.panelOCR); this.roundedRectanglePanelOCR.Controls.Add(this.thOCR); this.roundedRectanglePanelOCR.Location = new System.Drawing.Point(12, 668); this.roundedRectanglePanelOCR.Margin = new System.Windows.Forms.Padding(12, 12, 12, 0); this.roundedRectanglePanelOCR.Name = "roundedRectanglePanelOCR"; this.roundedRectanglePanelOCR.Padding = new System.Windows.Forms.Padding(1); this.roundedRectanglePanelOCR.Size = new System.Drawing.Size(250, 224); this.roundedRectanglePanelOCR.TabIndex = 2; // // thSaveImage // this.thSaveImage.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thSaveImage.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thSaveImage.Image"))); this.thSaveImage.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thSaveImage.Index = 5; this.thSaveImage.Location = new System.Drawing.Point(1, 1); this.thSaveImage.Margin = new System.Windows.Forms.Padding(0); this.thSaveImage.MultiTabHead = false; this.thSaveImage.Name = "thSaveImage"; this.thSaveImage.Size = new System.Drawing.Size(248, 40); this.thSaveImage.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.ALLFOLDED; this.thSaveImage.TabIndex = 73; this.thSaveImage.Text = "Save Image"; this.thSaveImage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thSaveImage.Click += new System.EventHandler(this.TabHead_Click); // // thOCR // this.thOCR.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thOCR.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thOCR.Image"))); this.thOCR.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thOCR.Index = 4; this.thOCR.Location = new System.Drawing.Point(1, 1); this.thOCR.Margin = new System.Windows.Forms.Padding(0); this.thOCR.MultiTabHead = false; this.thOCR.Name = "thOCR"; this.thOCR.Size = new System.Drawing.Size(248, 40); this.thOCR.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.ALLFOLDED; this.thOCR.TabIndex = 0; this.thOCR.Text = "OCR"; this.thOCR.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thOCR.Click += new System.EventHandler(this.TabHead_Click); // // thAddBarcode // this.thAddBarcode.BackColor = System.Drawing.Color.Transparent; this.thAddBarcode.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thAddBarcode.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thAddBarcode.Image"))); this.thAddBarcode.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thAddBarcode.Index = 3; this.thAddBarcode.Location = new System.Drawing.Point(125, 1); this.thAddBarcode.Margin = new System.Windows.Forms.Padding(0); this.thAddBarcode.MultiTabHead = true; this.thAddBarcode.Name = "thAddBarcode"; this.thAddBarcode.Size = new System.Drawing.Size(124, 40); this.thAddBarcode.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.ALLFOLDED; this.thAddBarcode.TabIndex = 1; this.thAddBarcode.Text = "Add Barcode"; this.thAddBarcode.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thAddBarcode.Click += new System.EventHandler(this.TabHead_Click); // // thReadBarcode // this.thReadBarcode.BackColor = System.Drawing.Color.Transparent; this.thReadBarcode.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thReadBarcode.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thReadBarcode.Image"))); this.thReadBarcode.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thReadBarcode.Index = 2; this.thReadBarcode.Location = new System.Drawing.Point(1, 1); this.thReadBarcode.Margin = new System.Windows.Forms.Padding(0); this.thReadBarcode.MultiTabHead = true; this.thReadBarcode.Name = "thReadBarcode"; this.thReadBarcode.Size = new System.Drawing.Size(124, 40); this.thReadBarcode.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.ALLFOLDED; this.thReadBarcode.TabIndex = 0; this.thReadBarcode.Text = "Read Barcode"; this.thReadBarcode.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thReadBarcode.Click += new System.EventHandler(this.TabHead_Click); // // thLoadImage // this.thLoadImage.BackColor = System.Drawing.Color.Transparent; this.thLoadImage.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thLoadImage.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thLoadImage.Image"))); this.thLoadImage.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thLoadImage.Index = 1; this.thLoadImage.Location = new System.Drawing.Point(125, 1); this.thLoadImage.Margin = new System.Windows.Forms.Padding(0); this.thLoadImage.MultiTabHead = true; this.thLoadImage.Name = "thLoadImage"; this.thLoadImage.Size = new System.Drawing.Size(124, 40); this.thLoadImage.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.FOLDED; this.thLoadImage.TabIndex = 1; this.thLoadImage.Text = "Load Files"; this.thLoadImage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thLoadImage.Click += new System.EventHandler(this.TabHead_Click); // // thAcquireImage // this.thAcquireImage.BackColor = System.Drawing.Color.Transparent; this.thAcquireImage.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.thAcquireImage.Image = ((System.Drawing.Image)(Properties.Resources.ResourceManager.GetObject("thAcquireImage.Image"))); this.thAcquireImage.ImageAlign = System.Drawing.ContentAlignment.MiddleRight; this.thAcquireImage.Index = 0; this.thAcquireImage.Location = new System.Drawing.Point(1, 1); this.thAcquireImage.Margin = new System.Windows.Forms.Padding(0); this.thAcquireImage.MultiTabHead = true; this.thAcquireImage.Name = "thAcquireImage"; this.thAcquireImage.Size = new System.Drawing.Size(124, 40); this.thAcquireImage.State = DotNet_TWAIN_Demo.TabHead.TabHeadState.SELECTED; this.thAcquireImage.TabIndex = 0; this.thAcquireImage.Text = "Acquire Image"; this.thAcquireImage.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.thAcquireImage.Click += new System.EventHandler(this.TabHead_Click); this.roundedRectanglePanelAcquireLoad.ResumeLayout(false); this.roundedRectanglePanelSaveImage.ResumeLayout(false); this.roundedRectanglePanelBarcode.ResumeLayout(false); this.roundedRectanglePanelOCR.ResumeLayout(false); this.roundedRectanglePanelSaveImage.TabIndex = 3; this.flowLayoutPanel2.Controls.Add(this.roundedRectanglePanelAcquireLoad); this.flowLayoutPanel2.Controls.Add(this.roundedRectanglePanelBarcode); this.flowLayoutPanel2.Controls.Add(this.roundedRectanglePanelOCR); this.flowLayoutPanel2.Controls.Add(this.roundedRectanglePanelSaveImage); } protected void Initialization() { string strPDFDllFolder = null; string strBarcodeDllFolder = null; string strOCRDllFolder = null; string strOCRTessDataFolder = null; string strAddOnDllFolder = Application.ExecutablePath; strAddOnDllFolder = strAddOnDllFolder.Replace("/", "\\"); if (!strAddOnDllFolder.EndsWith(@"\", false, System.Globalization.CultureInfo.CurrentCulture)) strAddOnDllFolder += @"\"; int pos = strAddOnDllFolder.LastIndexOf("\\Samples\\"); if (pos != -1) { strAddOnDllFolder = strAddOnDllFolder.Substring(0, strAddOnDllFolder.IndexOf(@"\", pos)); strOCRTessDataFolder = strAddOnDllFolder + @"\Samples\Bin\"; strAddOnDllFolder = strAddOnDllFolder+ @"\Redistributable\"; strPDFDllFolder = strAddOnDllFolder + @"PDFResources\"; strBarcodeDllFolder = strAddOnDllFolder + @"Barcode Generator\"; strOCRDllFolder = strAddOnDllFolder + @"OCRResources\"; } else { pos = strAddOnDllFolder.LastIndexOf("\\"); strAddOnDllFolder = strAddOnDllFolder.Substring(0, strAddOnDllFolder.IndexOf(@"\", pos)) + @"\"; strPDFDllFolder = strAddOnDllFolder; strBarcodeDllFolder = strAddOnDllFolder; strOCRDllFolder = strAddOnDllFolder; strOCRTessDataFolder = strAddOnDllFolder; } this.dynamicDotNetTwain.PDFRasterizerDllPath = strPDFDllFolder; this.dynamicDotNetTwain.BarcodeDllPath = strBarcodeDllFolder; this.dynamicDotNetTwain.OCRDllPath = strOCRDllFolder; this.dynamicDotNetTwain.OCRTessDataPath = strOCRTessDataFolder; this.dynamicDotNetTwain.IfShowCancelDialogWhenBarcodeOrOCR = false; this.dynamicDotNetTwain.MaxImagesInBuffer = 64; } private void DotNetTWAINDemo_Load(object sender, EventArgs e) { InitUI(); InitDefaultValueForTWAIN(); } /// <summary> /// Init the UI for the demo /// </summary> private void InitUI() { dynamicDotNetTwain.Visible = false; panelAnnotations.Visible = false; DisableAllFunctionButtons(); // Init the View mode this.cbxViewMode.Items.Clear(); this.cbxViewMode.Items.Insert(0, "1 x 1"); this.cbxViewMode.Items.Insert(1, "2 x 2"); this.cbxViewMode.Items.Insert(2, "3 x 3"); this.cbxViewMode.Items.Insert(3, "4 x 4"); this.cbxViewMode.Items.Insert(4, "5 x 5"); // Init the cbxResolution this.cbxResolution.Items.Clear(); this.cbxResolution.Items.Insert(0, "100"); this.cbxResolution.Items.Insert(1, "150"); this.cbxResolution.Items.Insert(2, "200"); this.cbxResolution.Items.Insert(3, "300"); // Init the Scan Button DisableControls(this.picboxScan); // Init the save image type this.rdbtnJPG.Checked = true; // Init the Save Image Button DisableControls(this.picboxSave); // For the popup tip label infoLabel = new Label(); infoLabel.Text = ""; infoLabel.Visible = false; infoLabel.AutoSize = true; infoLabel.Name = "Info"; infoLabel.BackColor = System.Drawing.Color.White; infoLabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; infoLabel.Font = new System.Drawing.Font("Consolas", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); infoLabel.BringToFront(); this.Controls.Add(infoLabel); // For the load image button this.picboxLoadImage.MouseLeave += new System.EventHandler(this.picbox_MouseLeave); this.picboxLoadImage.Click += new System.EventHandler(this.picboxLoadImage_Click); this.picboxLoadImage.MouseDown += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseDown); //this.picboxLoadImage.MouseHover += new System.EventHandler(this.picbox_MouseHover); this.picboxLoadImage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.picbox_MouseUp); this.picboxLoadImage.MouseEnter += new System.EventHandler(this.picbox_MouseEnter); //Tab Heads m_tabHeads[0] = thAcquireImage; m_tabHeads[1] = thLoadImage; m_tabHeads[2] = thReadBarcode; m_tabHeads[3] = thAddBarcode; m_tabHeads[4] = thOCR; m_tabHeads[5] = thSaveImage; m_panels[0] = panelAcquire; m_panels[1] = panelLoad; m_panels[2] = panelReadBarcode; m_panels[3] = panelAddBarcode; m_panels[4] = panelOCR; m_panels[5] = panelSaveImage; thAcquireImage.State = TabHead.TabHeadState.SELECTED; m_thSelectedTabHead = thAcquireImage; //OCR languages.Add("English", "eng"); this.cbxSupportedLanguage.Items.Clear(); foreach (string str in languages.Keys) { this.cbxSupportedLanguage.Items.Add(str); } this.cbxSupportedLanguage.SelectedIndex = 0; this.cbxOCRResultFormat.Items.Clear(); this.cbxOCRResultFormat.Items.Add("Text File"); this.cbxOCRResultFormat.Items.Add("Adobe PDF Plain Text File"); this.cbxOCRResultFormat.Items.Add("Adobe PDF Image Over Text File"); this.cbxOCRResultFormat.SelectedIndex = 0; DisableControls(picboxOCR); //Add Barcode this.cbxGenBarcodeFormat.Items.Clear(); this.cbxGenBarcodeFormat.Items.Add("CODE_39"); this.cbxGenBarcodeFormat.Items.Add("CODE_128"); this.cbxGenBarcodeFormat.Items.Add("PDF417"); this.cbxGenBarcodeFormat.Items.Add("QR_CODE"); this.cbxGenBarcodeFormat.SelectedIndex = 0; this.tbxBarcodeContent.Text = "Dynamsoft"; this.tbxBarcodeLocationX.Text = "0"; this.tbxBarcodeLocationY.Text = "0"; this.tbxHumanReadableText.Text = "Dynamsoft"; this.tbxBarcodeScale.Text = "1"; DisableControls(picboxAddBarcode); //Read Barcode //this.cbxBarcodeFormat.DataSource = Enum.GetValues(typeof(Dynamsoft.Barcode.BarcodeFormat)); cbxBarcodeFormat.Items.Add("All"); cbxBarcodeFormat.Items.Add("OneD"); cbxBarcodeFormat.Items.Add("Code 39"); cbxBarcodeFormat.Items.Add("Code 128"); cbxBarcodeFormat.Items.Add("Code 93"); cbxBarcodeFormat.Items.Add("Codabar"); cbxBarcodeFormat.Items.Add("Interleaved 2 of 5"); cbxBarcodeFormat.Items.Add("EAN-13"); cbxBarcodeFormat.Items.Add("EAN-8"); cbxBarcodeFormat.Items.Add("UPC-A"); cbxBarcodeFormat.Items.Add("UPC-E"); cbxBarcodeFormat.Items.Add("PDF417"); cbxBarcodeFormat.Items.Add("QRCode"); cbxBarcodeFormat.Items.Add("Datamatrix"); cbxBarcodeFormat.Items.Add("Industrial 2 of 5"); cbxBarcodeFormat.SelectedIndex = 0; this.tbxMaxBarcodeReads.Text = "10"; this.tbxLeft.Text = "0"; this.tbxRight.Text = "0"; this.tbxTop.Text = "0"; this.tbxBottom.Text = "0"; DisableControls(picboxReadBarcode); //webcam DisableControls(picboxGrab); //always show ui for webcam chkShowUIForWebcam.Checked = true; chkShowUIForWebcam.Visible = false; } /// <summary> /// Init the default value for TWAIN /// </summary> private void InitDefaultValueForTWAIN() { try { // dynamicDotNetTwain.IfThrowException = true; dynamicDotNetTwain.SupportedDeviceType = Dynamsoft.DotNet.TWAIN.Enums.EnumSupportedDeviceType.SDT_ALL; dynamicDotNetTwain.ScanInNewProcess = true; dynamicDotNetTwain.IfFitWindow = true; dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.SetViewMode(-1, -1); this.cbxViewMode.SelectedIndex = 0; // Init the sources for TWAIN scanning and Webcam grab, show in the cbxSources controls if (dynamicDotNetTwain.SourceCount > 0) { bool hasTwainSource = false; bool hasWebcamSource = false; cbxSource.Items.Clear(); for (int i = 0; i < dynamicDotNetTwain.SourceCount; ++i) { cbxSource.Items.Add(dynamicDotNetTwain.SourceNameItems((short)i)); Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType enumDeviceType = dynamicDotNetTwain.GetSourceType((short)i); if (enumDeviceType == Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType.SDT_TWAIN) hasTwainSource = true; else if (enumDeviceType == Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType.SDT_WEBCAM) hasWebcamSource = true; } if (hasTwainSource) { cbxSource.Enabled = true; chkShowUI.Enabled = true; chkADF.Enabled = true; chkDuplex.Enabled = true; cbxResolution.Enabled = true; rdbtnGray.Checked = true; cbxResolution.SelectedIndex = 0; EnableControls(this.picboxScan); } if (hasWebcamSource) { chkShowUIForWebcam.Enabled = true; cbxMediaType.Enabled = true; cbxResolutionForWebcam.Enabled = true; EnableControls(this.picboxGrab); } cbxSource.SelectedIndex = 0; //dynamicDotNetTwain.SelectSourceByIndex((short)cbxSource.SelectedIndex); } } catch (System.Exception ex) { MessageBox.Show(ex.Message); } } private void DrawBackground() { // Create a bitmap Bitmap img = Properties.Resources.main_bg; // Set the form properties Size = new Size(img.Width, img.Height); BackgroundImage = new Bitmap(Width, Height); // Draw it Graphics g = Graphics.FromImage(BackgroundImage); g.DrawImage(img, 0, 0, img.Width, img.Height); } /// <summary> /// Disable all the function buttons in the left and bottom panel /// </summary> private void DisableAllFunctionButtons() { DisableControls(this.picboxHand); DisableControls(this.picboxPoint); DisableControls(this.picboxCrop); DisableControls(this.picboxCut); DisableControls(this.picboxRotateRight); DisableControls(this.picboxRotateLeft); DisableControls(this.picboxMirror); DisableControls(this.picboxFlip); DisableControls(this.picboxLine); DisableControls(this.picboxEllipse); DisableControls(this.picboxRectangle); DisableControls(this.picboxText); DisableControls(this.picboxZoom); DisableControls(this.picboxResample); DisableControls(this.picboxZoomIn); DisableControls(this.picboxZoomOut); DisableControls(this.picboxDelete); DisableControls(this.picboxDeleteAll); DisableControls(this.picboxFirst); DisableControls(this.picboxPrevious); DisableControls(this.picboxNext); DisableControls(this.picboxLast); DisableControls(this.picboxFit); DisableControls(this.picboxOriginalSize); } /// <summary> /// Enable all the function buttons in the left and bottom panel /// </summary> private void EnableAllFunctionButtons() { EnableControls(this.picboxHand); EnableControls(this.picboxPoint); EnableControls(this.picboxCrop); EnableControls(this.picboxCut); EnableControls(this.picboxRotateRight); EnableControls(this.picboxRotateLeft); EnableControls(this.picboxMirror); EnableControls(this.picboxFlip); EnableControls(this.picboxLine); EnableControls(this.picboxEllipse); EnableControls(this.picboxRectangle); EnableControls(this.picboxText); EnableControls(this.picboxZoom); EnableControls(this.picboxResample); EnableControls(this.picboxZoomIn); EnableControls(this.picboxZoomOut); EnableControls(this.picboxDelete); EnableControls(this.picboxDeleteAll); EnableControls(this.picboxFit); EnableControls(this.picboxOriginalSize); if (dynamicDotNetTwain.HowManyImagesInBuffer > 1) { EnableControls(this.picboxFirst); EnableControls(this.picboxPrevious); EnableControls(this.picboxNext); EnableControls(this.picboxLast); if (dynamicDotNetTwain.CurrentImageIndexInBuffer == 0) { DisableControls(picboxPrevious); DisableControls(picboxFirst); } if (dynamicDotNetTwain.CurrentImageIndexInBuffer + 1 == dynamicDotNetTwain.HowManyImagesInBuffer) { DisableControls(picboxNext); DisableControls(picboxLast); } } checkZoom(); } #region regist Event For All PictureBox Buttons private void picbox_MouseEnter(object sender, EventArgs e) { if (sender is PictureBox) { if ((sender as PictureBox).Enabled == true) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Enter"); } } } private void picbox_MouseDown(object sender, MouseEventArgs e) { if (sender is PictureBox) { if ((sender as PictureBox).Enabled == true) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Down"); } } } private void picbox_MouseLeave(object sender, EventArgs e) { if (sender is PictureBox) { if ((sender as PictureBox).Enabled == true) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Leave"); infoLabel.Text = ""; infoLabel.Visible = false; } } } private void picbox_MouseUp(object sender, MouseEventArgs e) { if (sender is PictureBox) { if ((sender as PictureBox).Enabled == true) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Enter"); } } } private void picbox_MouseHover(object sender, EventArgs e) { infoLabel.Text = (sender as PictureBox).Tag.ToString(); infoLabel.Location = new Point(this.PointToClient(MousePosition).X, this.PointToClient(MousePosition).Y + 20); infoLabel.Visible = true; infoLabel.BringToFront(); } private void DisableControls(object sender) { if (sender is PictureBox) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Disabled"); (sender as PictureBox).Enabled = false; } else { (sender as Control).Enabled = false; } } private void EnableControls(object sender) { if (sender is PictureBox) { (sender as PictureBox).Image = (Image)Properties.Resources.ResourceManager.GetObject((sender as PictureBox).Name + "_Leave"); (sender as PictureBox).Enabled = true; } else { (sender as Control).Enabled = true; } } #endregion # region functions for the form, ignore them please /// <summary> /// Mouse down when move the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbMoveBar_MouseDown(object sender, MouseEventArgs e) { mouse_offset = new Point(-e.X, -e.Y); } /// <summary> /// Mouse move when move the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lbMoveBar_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePos = Control.MousePosition; mousePos.Offset(mouse_offset.X, mouse_offset.Y); this.Location = mousePos; } } /// <summary> /// Close the application /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void picboxClose_MouseClick(object sender, MouseEventArgs e) { Application.Exit(); } /// <summary> /// Minimize the form /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void picboxMin_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } #endregion private void picboxScan_Click(object sender, EventArgs e) { if (picboxScan.Enabled) { picboxScan.Focus(); if (this.cbxSource.SelectedIndex < 0) { MessageBox.Show(this, "There is no scanner detected!\n " + "Please ensure that at least one (virtual) scanner is installed.", "Information"); } else { DisableControls(picboxScan); this.AcquireImage(); } } } /// <summary> /// Acquire image from the selected source /// </summary> private void AcquireImage() { try { // Select the source for TWAIN dynamicDotNetTwain.SelectSourceByIndex((short)cbxSource.SelectedIndex); dynamicDotNetTwain.OpenSource(); // Set the image fit the size of window //dynamicDotNetTwain.IfFitWindow = true; //dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.IfShowUI = chkShowUI.Checked; // if (chkADF.Enabled) // dynamicDotNetTwain.IfAutoFeed = dynamicDotNetTwain.IfFeederEnabled = chkADF.Checked; dynamicDotNetTwain.IfFeederEnabled = chkADF.Checked; //dynamicDotNetTwain.IfAutoFeed = chkADF.Checked; // if (chkDuplex.Enabled) dynamicDotNetTwain.IfDuplexEnabled = chkDuplex.Checked; // Need to open source first // dynamicDotNetTwain.OpenSource(); dynamicDotNetTwain.IfDisableSourceAfterAcquire = true; if (rdbtnBW.Checked) { dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_BW; dynamicDotNetTwain.BitDepth = 1; } else if (rdbtnGray.Checked) { dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_GRAY; dynamicDotNetTwain.BitDepth = 8; } else { dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_RGB; dynamicDotNetTwain.BitDepth = 24; } dynamicDotNetTwain.Resolution = int.Parse(cbxResolution.Text); // Acquire image from the source if (!dynamicDotNetTwain.AcquireImage()) MessageBox.Show(dynamicDotNetTwain.ErrorString, "Scan error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (System.Exception ex) { MessageBox.Show("An exception occurs: " + ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (dynamicDotNetTwain.ErrorCode != Dynamsoft.DotNet.TWAIN.Enums.ErrorCode.Succeed) EnableControls(picboxScan); } } /// <summary> /// multi-page are allowed for tiff and pdf /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void rdbtnMultiPage_CheckedChanged(object sender, EventArgs e) { if ((sender as RadioButton).Checked == true) { this.chkMultiPage.Enabled = true; this.chkMultiPage.Checked = true; } } /// <summary> /// When other image formats are selected, multi-page are not allowed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void rdbtnSinglePage_CheckedChanged(object sender, EventArgs e) { if ((sender as RadioButton).Checked == true) { this.chkMultiPage.Enabled = false; this.chkMultiPage.Checked = false; } } /// <summary> /// Verified the file name. If the file name is ok, return true, else return false. /// </summary> /// <param name="fileName">file name</param> /// <returns></returns> private bool VerifyFileName(string fileName) { try { if (fileName.LastIndexOfAny(System.IO.Path.GetInvalidFileNameChars()) == -1) return true; } catch (Exception e) { } MessageBox.Show("The file name contains invalid chars!", "Save Image To File", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } /// <summary> /// Save the image as the selected format and name /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void picboxSave_Click(object sender, EventArgs e) { string fileName = tbxSaveFileName.Text.Trim(); if (VerifyFileName(fileName)) { saveFileDialog.FileName = this.tbxSaveFileName.Text; if (rdbtnJPG.Checked) { saveFileDialog.Filter = "JPEG|*.JPG;*.JPEG;*.JPE;*.JFIF"; saveFileDialog.DefaultExt = "jpg"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { dynamicDotNetTwain.SaveAsJPEG(saveFileDialog.FileName, dynamicDotNetTwain.CurrentImageIndexInBuffer); } } if (rdbtnBMP.Checked) { saveFileDialog.Filter = "BMP|*.BMP"; saveFileDialog.DefaultExt = "bmp"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { dynamicDotNetTwain.SaveAsBMP(saveFileDialog.FileName, dynamicDotNetTwain.CurrentImageIndexInBuffer); } } if (rdbtnPNG.Checked) { saveFileDialog.Filter = "PNG|*.PNG"; saveFileDialog.DefaultExt = "png"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { dynamicDotNetTwain.SaveAsPNG(saveFileDialog.FileName, dynamicDotNetTwain.CurrentImageIndexInBuffer); } } if (rdbtnTIFF.Checked) { saveFileDialog.Filter = "TIFF|*.TIF;*.TIFF"; saveFileDialog.DefaultExt = "tiff"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Multi page TIFF if (chkMultiPage.Checked == true) { dynamicDotNetTwain.SaveAllAsMultiPageTIFF(saveFileDialog.FileName); } else { dynamicDotNetTwain.SaveAsTIFF(saveFileDialog.FileName, dynamicDotNetTwain.CurrentImageIndexInBuffer); } } } if (rdbtnPDF.Checked) { saveFileDialog.Filter = "PDF|*.PDF"; saveFileDialog.DefaultExt = "pdf"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Multi page PDF dynamicDotNetTwain.IfSaveAnnotations = true; if (chkMultiPage.Checked == true) { dynamicDotNetTwain.SaveAllAsPDF(saveFileDialog.FileName); } else { dynamicDotNetTwain.SaveAsPDF(saveFileDialog.FileName, dynamicDotNetTwain.CurrentImageIndexInBuffer); } } } } else { this.tbxSaveFileName.Focus(); } } private void picboxPoint_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumNone; } // Change mouse shape to hand, for move image private void picboxHand_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = true; dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumNone; } private void picboxFit_Click(object sender, EventArgs e) { dynamicDotNetTwain.IfFitWindow = true; checkZoom(); } private void picboxOriginalSize_Click(object sender, EventArgs e) { dynamicDotNetTwain.IfFitWindow = false; dynamicDotNetTwain.Zoom = 1; checkZoom(); } private void picboxCut_Click(object sender, EventArgs e) { picboxPoint_Click(sender, null); Rectangle rc = dynamicDotNetTwain.GetSelectionRect(dynamicDotNetTwain.CurrentImageIndexInBuffer); if (rc.IsEmpty) { MessageBox.Show("Please select the rectangle area first!", "Warning Info", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { dynamicDotNetTwain.CutFrameToClipboard(dynamicDotNetTwain.CurrentImageIndexInBuffer, rc.Left, rc.Top, rc.Right, rc.Bottom); } } private void picboxCrop_Click(object sender, EventArgs e) { //if (dynamicDotNetTwain.AnnotationType != Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumNone) //{ picboxPoint_Click(sender, null); //} //what does this mean? Rectangle rc = dynamicDotNetTwain.GetSelectionRect(dynamicDotNetTwain.CurrentImageIndexInBuffer); if (rc.IsEmpty) { //isToCrop = true; //dynamicDotNetTwain.MouseShape = false; //DisableAllFunctionButtons();//why this? MessageBox.Show("Please select the rectangle area first!", "Warning Info", MessageBoxButtons.OK,MessageBoxIcon.Warning); } else { cropPicture(dynamicDotNetTwain.CurrentImageIndexInBuffer, rc); } } private void cropPicture(int imageIndex, Rectangle rc) { dynamicDotNetTwain.Crop((short)imageIndex, rc.X, rc.Y, rc.X + rc.Width, rc.Y + rc.Height); } private void picboxRotateLeft_Click(object sender, EventArgs e) { dynamicDotNetTwain.RotateLeft(dynamicDotNetTwain.CurrentImageIndexInBuffer); } private void picboxRotateRight_Click(object sender, EventArgs e) { dynamicDotNetTwain.RotateRight(dynamicDotNetTwain.CurrentImageIndexInBuffer); } private void picboxFlip_Click(object sender, EventArgs e) { dynamicDotNetTwain.Flip(dynamicDotNetTwain.CurrentImageIndexInBuffer); } private void picboxMirror_Click(object sender, EventArgs e) { dynamicDotNetTwain.Mirror(dynamicDotNetTwain.CurrentImageIndexInBuffer); } private void picboxLine_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.AnnotationPen = new Pen(Color.Blue, 5); dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumLine; if (panelAnnotations.Visible == false) panelAnnotations.Visible = true; } private void picboxEllipse_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.AnnotationPen = new Pen(Color.Black, 2); dynamicDotNetTwain.AnnotationFillColor = Color.Blue; dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumEllipse; if (panelAnnotations.Visible == false) panelAnnotations.Visible = true; } private void picboxRectangle_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.AnnotationPen = new Pen(Color.Black, 2); dynamicDotNetTwain.AnnotationFillColor = Color.ForestGreen; dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumRectangle; if (panelAnnotations.Visible == false) panelAnnotations.Visible = true; } private void picboxText_Click(object sender, EventArgs e) { dynamicDotNetTwain.MouseShape = false; dynamicDotNetTwain.AnnotationTextColor = Color.Black; dynamicDotNetTwain.AnnotationTextFont = new Font("", 32); dynamicDotNetTwain.AnnotationType = Dynamsoft.DotNet.TWAIN.Enums.DWTAnnotationType.enumText; if (panelAnnotations.Visible == false) panelAnnotations.Visible = true; } private void picboxZoom_Click(object sender, EventArgs e) { ZoomForm zoomForm = new ZoomForm(dynamicDotNetTwain.Zoom); zoomForm.ShowDialog(); if (zoomForm.DialogResult == DialogResult.OK) { dynamicDotNetTwain.IfFitWindow = false; dynamicDotNetTwain.Zoom = zoomForm.ZoomRatio; checkZoom(); } } private void picboxResample_Click(object sender, EventArgs e) { int width = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer).Width; int height = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer).Height; ResampleForm resampleForm = new ResampleForm(width, height); resampleForm.ShowDialog(); if (resampleForm.DialogResult == DialogResult.OK) { dynamicDotNetTwain.ChangeImageSize(dynamicDotNetTwain.CurrentImageIndexInBuffer,resampleForm.NewWidth,resampleForm.NewHeight, resampleForm.Interpolation); dynamicDotNetTwain.IfFitWindow = false; } } private void picboxZoomIn_Click(object sender, EventArgs e) { float zoom = dynamicDotNetTwain.Zoom + 0.1F; dynamicDotNetTwain.IfFitWindow = false; dynamicDotNetTwain.Zoom = zoom; checkZoom(); } private void picboxZoomOut_Click(object sender, EventArgs e) { float zoom = dynamicDotNetTwain.Zoom - 0.1F; dynamicDotNetTwain.IfFitWindow = false; dynamicDotNetTwain.Zoom = zoom; checkZoom(); } private void checkZoom() { if (cbxViewMode.SelectedIndex != 0 || dynamicDotNetTwain.HowManyImagesInBuffer == 0 ) // || cbxViewMode.SelectedIndex != 0) { DisableControls(picboxZoomIn); DisableControls(picboxZoomOut); DisableControls(picboxZoom); DisableControls(picboxFit); DisableControls(picboxOriginalSize); return; } if (picboxFit.Enabled == false) EnableControls(picboxFit); if (picboxOriginalSize.Enabled == false) EnableControls(picboxOriginalSize); if (picboxZoom.Enabled == false) EnableControls(picboxZoom); // the valid range of zoom is between 0.02 to 65.0, if (dynamicDotNetTwain.Zoom <= 0.02F) { DisableControls(picboxZoomOut); } else { EnableControls(picboxZoomOut); } if (dynamicDotNetTwain.Zoom >= 65F) { DisableControls(picboxZoomIn); } else { EnableControls(picboxZoomIn); } } private void picboxDelete_Click(object sender, EventArgs e) { dynamicDotNetTwain.RemoveImage(dynamicDotNetTwain.CurrentImageIndexInBuffer); checkImageCount(); } private void picboxDeleteAll_Click(object sender, EventArgs e) { dynamicDotNetTwain.RemoveAllImages(); checkImageCount(); } /// <summary> /// If the image count changed, some features should changed. /// </summary> private void checkImageCount() { currentImageIndex = dynamicDotNetTwain.CurrentImageIndexInBuffer; int currentIndex = currentImageIndex + 1; int imageCount = dynamicDotNetTwain.HowManyImagesInBuffer; if (imageCount == 0) currentIndex = 0; tbxCurrentImageIndex.Text = currentIndex.ToString(); tbxTotalImageNum.Text = imageCount.ToString(); if (imageCount > 0) { EnableControls(picboxSave); EnableAllFunctionButtons(); EnableControls(picboxReadBarcode); EnableControls(picboxAddBarcode); EnableControls(picboxOCR); } else { DisableControls(picboxSave); DisableAllFunctionButtons(); dynamicDotNetTwain.Visible = false; panelAnnotations.Visible = false; DisableControls(picboxReadBarcode); DisableControls(picboxAddBarcode); DisableControls(picboxOCR); } if (imageCount > 1) { EnableControls(picboxFirst); EnableControls(picboxLast); EnableControls(picboxPrevious); EnableControls(picboxNext); if (currentIndex == 1) { DisableControls(picboxPrevious); DisableControls(picboxFirst); } if (currentIndex == imageCount) { DisableControls(picboxNext); DisableControls(picboxLast); } } else { DisableControls(picboxFirst); DisableControls(picboxLast); DisableControls(picboxPrevious); DisableControls(picboxNext); } ShowSelectedImageArea(); } private void cbxLayout_SelectedIndexChanged(object sender, EventArgs e) { switch(this.cbxViewMode.SelectedIndex) { case 0: dynamicDotNetTwain.SetViewMode(-1,-1); break; case 1: dynamicDotNetTwain.SetViewMode(2, 2); break; case 2: dynamicDotNetTwain.SetViewMode(3, 3); break; case 3: dynamicDotNetTwain.SetViewMode(4, 4); break; case 4: dynamicDotNetTwain.SetViewMode(5, 5); break; default: dynamicDotNetTwain.SetViewMode(-1, -1); break; } checkZoom(); } private void picboxFirst_Click(object sender, EventArgs e) { if(dynamicDotNetTwain.HowManyImagesInBuffer > 0) dynamicDotNetTwain.CurrentImageIndexInBuffer = (short)0; checkImageCount(); } private void picboxLast_Click(object sender, EventArgs e) { if (dynamicDotNetTwain.HowManyImagesInBuffer > 0) dynamicDotNetTwain.CurrentImageIndexInBuffer = (short)(dynamicDotNetTwain.HowManyImagesInBuffer - 1); checkImageCount(); } private void picboxPrevious_Click(object sender, EventArgs e) { if (dynamicDotNetTwain.HowManyImagesInBuffer > 0 && dynamicDotNetTwain.CurrentImageIndexInBuffer > 0) --dynamicDotNetTwain.CurrentImageIndexInBuffer; checkImageCount(); } private void picboxNext_Click(object sender, EventArgs e) { if (dynamicDotNetTwain.HowManyImagesInBuffer > 0 && dynamicDotNetTwain.CurrentImageIndexInBuffer < dynamicDotNetTwain.HowManyImagesInBuffer - 1) ++dynamicDotNetTwain.CurrentImageIndexInBuffer; checkImageCount(); } private void dynamicDotNetTwain_OnMouseClick(short sImageIndex) { if (dynamicDotNetTwain.CurrentImageIndexInBuffer != currentImageIndex) checkImageCount(); } /// <summary> /// /// </summary> private void dynamicDotNetTwain_OnPostAllTransfers() { CrossThreadOperationControl crossDelegate = delegate() { dynamicDotNetTwain.Visible = true; checkImageCount(); EnableControls(picboxScan); }; this.Invoke(crossDelegate); } private void dynamicDotNetTwain_OnMouseDoubleClick(short sImageIndex) { try { Rectangle rc = dynamicDotNetTwain.GetSelectionRect(sImageIndex); if (isToCrop && !rc.IsEmpty) { cropPicture(sImageIndex, rc); } isToCrop = false; } catch { } EnableAllFunctionButtons(); } private void dynamicDotNetTwain_OnMouseRightClick(short sImageIndex) { if (isToCrop) isToCrop = false; dynamicDotNetTwain.ClearSelectionRect(sImageIndex); EnableAllFunctionButtons(); } private void dynamicDotNetTwain_OnImageAreaDeselected(short sImageIndex) { if (isToCrop) isToCrop = false; EnableAllFunctionButtons(); ShowSelectedImageArea(); } private void cbxSource_SelectedIndexChanged(object sender, EventArgs e) { short sIndex = (short)((ComboBox)(sender)).SelectedIndex; switch (dynamicDotNetTwain.GetSourceType(sIndex)) { case Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType.SDT_TWAIN: panelScan.Visible = true; panelGrab.Visible = false; lbUnknowSource.Visible = false; dynamicDotNetTwain.CloseSource();//when switching from webcam source to twain source, need to close webcam source. break; case Dynamsoft.DotNet.TWAIN.Enums.EnumDeviceType.SDT_WEBCAM: panelScan.Visible = false; panelGrab.Visible = true; lbUnknowSource.Visible = false; //Initial media type list and webcam resolution list cbxMediaType.Items.Clear(); cbxResolutionForWebcam.Items.Clear(); dynamicDotNetTwain.IfDisableSourceAfterAcquire = false;//don't close video after grabbing an image. dynamicDotNetTwain.SelectSourceByIndex(sIndex); dynamicDotNetTwain.OpenSource(); //Open webcam source before getting the value of MediaTypeList and ResolutionForCamList List<string> lstMediaTypes = dynamicDotNetTwain.MediaTypeList; List<Dynamsoft.DotNet.TWAIN.WebCamera.CamResolution> lstWebcamResolutions = dynamicDotNetTwain.ResolutionForCamList; if (lstMediaTypes != null) foreach (string strMediaType in lstMediaTypes) cbxMediaType.Items.Add(strMediaType); if (lstWebcamResolutions != null) foreach (Dynamsoft.DotNet.TWAIN.WebCamera.CamResolution camResolution in lstWebcamResolutions) cbxResolutionForWebcam.Items.Add(camResolution.Width + " X " + camResolution.Height); if (cbxMediaType.Items.Count > 0) cbxMediaType.SelectedIndex = 0; if (cbxResolutionForWebcam.Items.Count > 0) cbxResolutionForWebcam.SelectedIndex = 0; //show error information if (dynamicDotNetTwain.ErrorCode != Dynamsoft.DotNet.TWAIN.Enums.ErrorCode.Succeed) MessageBox.Show(dynamicDotNetTwain.ErrorString, "Webcam error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: panelScan.Visible = false; panelGrab.Visible = false; lbUnknowSource.Visible = true; break; } } private void picboxTitle_MouseDown(object sender, MouseEventArgs e) { mouse_offset2 = new Point(-e.X, -e.Y); } private void picboxTitle_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePos = Control.MousePosition; mousePos.Offset(mouse_offset2.X, mouse_offset2.Y); if (IsInForm(panelAnnotations.Parent.PointToClient(mousePos))) panelAnnotations.Location = panelAnnotations.Parent.PointToClient(mousePos); } } private bool IsInForm(Point point) { if (point.X > 0 && point.X < 693 && point.Y > 35 && point.Y < 635) return true; return false; } private void picboxDeleteAnnotationA_Click(object sender, EventArgs e) { List<Dynamsoft.DotNet.TWAIN.Annotation.AnnotationData> aryAnnotation; if(dynamicDotNetTwain.GetSelectedAnnotationList(dynamicDotNetTwain.CurrentImageIndexInBuffer,out aryAnnotation)) dynamicDotNetTwain.DeleteAnnotations(dynamicDotNetTwain.CurrentImageIndexInBuffer,aryAnnotation); } private void picboxLoadImage_Click(object sender, EventArgs e) { openFileDialog.Filter = "All Support Files|*.JPG;*.JPEG;*.JPE;*.JFIF;*.BMP;*.PNG;*.TIF;*.TIFF;*GIF;*.PDF|JPEG|*.JPG;*.JPEG;*.JPE;*.Jfif|BMP|*.BMP|PNG|*.PNG|TIFF|*.TIF;*.TIFF|GIF|*.GIF|PDF|*.PDF"; openFileDialog.FilterIndex = 0; openFileDialog.Multiselect = true; dynamicDotNetTwain.IfAppendImage = true; MessageBox.Show("Before removing: " + dynamicDotNetTwain.HowManyImagesInBuffer.ToString()); dynamicDotNetTwain.RemoveAllImages(); MessageBox.Show("After removing: " + dynamicDotNetTwain.HowManyImagesInBuffer.ToString()); if (openFileDialog.ShowDialog() == DialogResult.OK) { foreach (string strFileName in openFileDialog.FileNames) { int pos = strFileName.LastIndexOf("."); if (pos != -1) { string strSuffix = strFileName.Substring(pos, strFileName.Length - pos).ToLower(); if (strSuffix.CompareTo(".pdf") == 0) { this.dynamicDotNetTwain.ConvertPDFToImage(strFileName, 200); if (dynamicDotNetTwain.ErrorCode != Dynamsoft.DotNet.TWAIN.Enums.ErrorCode.Succeed) { MessageBox.Show(dynamicDotNetTwain.ErrorString, "Loading image error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else dynamicDotNetTwain.LoadImage(strFileName); } else dynamicDotNetTwain.LoadImage(strFileName); } dynamicDotNetTwain.Visible = true; } checkImageCount(); } private void ChangeSource_MouseHover(object sender, EventArgs e) { if (sender is Label) { (sender as Label).ForeColor = System.Drawing.Color.Purple; } } private void ChangeSource_MouseLeave(object sender, EventArgs e) { if (sender is Label) { (sender as Label).ForeColor = System.Drawing.Color.Black; } } private void lbCloseAnnotations_MouseHover(object sender, EventArgs e) { this.lbCloseAnnotations.ForeColor = System.Drawing.Color.Red; } private void lbCloseAnnotations_MouseLeave(object sender, EventArgs e) { this.lbCloseAnnotations.ForeColor = System.Drawing.Color.Black; } private void lbCloseAnnotations_Click(object sender, EventArgs e) { this.panelAnnotations.Visible = false; } private TabHead m_thSelectedTabHead = null; private TabHead[] m_tabHeads = new TabHead[6]; private Panel[] m_panels = new Panel[6]; Dictionary<string, string> languages = new Dictionary<string, string>(); private void TabHead_Click(object sender, EventArgs e) { TabHead thHead = (TabHead)sender; int iNeighborIndex = GetNeighborIndex(thHead); if (m_thSelectedTabHead != null && m_thSelectedTabHead.Index != iNeighborIndex && m_thSelectedTabHead.Index != thHead.Index) { m_thSelectedTabHead.State = TabHead.TabHeadState.ALLFOLDED; m_panels[m_thSelectedTabHead.Index].Visible = false; int iSelectHeadNeighborIndex = GetNeighborIndex(m_thSelectedTabHead); if (iSelectHeadNeighborIndex >= 0) m_tabHeads[iSelectHeadNeighborIndex].State = TabHead.TabHeadState.ALLFOLDED; } if (thHead.State == TabHead.TabHeadState.SELECTED) { thHead.State = TabHead.TabHeadState.ALLFOLDED; m_panels[thHead.Index].Visible = false; if (iNeighborIndex >= 0) { m_tabHeads[iNeighborIndex].State = TabHead.TabHeadState.ALLFOLDED; m_panels[iNeighborIndex].Visible = false; } m_thSelectedTabHead = null; } else { thHead.State = TabHead.TabHeadState.SELECTED; m_panels[thHead.Index].Visible = true; if (iNeighborIndex >= 0) { m_tabHeads[iNeighborIndex].State = TabHead.TabHeadState.FOLDED; m_panels[iNeighborIndex].Visible = false; } m_thSelectedTabHead = thHead; } } private int GetNeighborIndex(TabHead thHead) { if (thHead != null && thHead.MultiTabHead) if (thHead.Index % 2 == 0) return thHead.Index + 1; else return thHead.Index -1; else return -1; } #region Read Barcode private void picboxReadBarcode_Click(object sender, EventArgs e) { ShowSelectedImageArea(); int iMaxBarcodesToRead = 0; try { iMaxBarcodesToRead = int.Parse(tbxMaxBarcodeReads.Text); } catch (Exception exp) { MessageBox.Show(exp.Message, "Invalid input of MaxBarcodeReads", MessageBoxButtons.OK, MessageBoxIcon.Error); tbxMaxBarcodeReads.Focus(); } if (dynamicDotNetTwain.CurrentImageIndexInBuffer < 0) { MessageBox.Show("Please load an image before reading barcode!", "Index out of bounds", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { BarcodeReader reader = new BarcodeReader(); reader.LicenseKeys = "91392547848AAF24695CE9A2184F6663"; reader.ReaderOptions.MaxBarcodesToReadPerPage = iMaxBarcodesToRead; switch (cbxBarcodeFormat.SelectedIndex) { case 0: break; case 1: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.OneD; break; case 2: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_39; break; case 3: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_128; break; case 4: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODE_93; break; case 5: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.CODABAR; break; case 6: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.ITF; break; case 7: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_13; break; case 8: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.EAN_8; break; case 9: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_A; break; case 10: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.UPC_E; break; case 11: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.PDF417; break; case 12: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.QR_CODE; break; case 13: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.DATAMATRIX; break; case 14: reader.ReaderOptions.BarcodeFormats = Dynamsoft.Barcode.BarcodeFormat.INDUSTRIAL_25; break; } BarcodeResult[] aryResult = null; Rectangle rect = dynamicDotNetTwain.GetSelectionRect(dynamicDotNetTwain.CurrentImageIndexInBuffer); if (rect == Rectangle.Empty) { int iWidth = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer).Width; int iHeight = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer).Height; rect = new Rectangle(0, 0, iWidth, iHeight); } aryResult = reader.DecodeBitmapRect((Bitmap)(dynamicDotNetTwain.GetImage(this.dynamicDotNetTwain.CurrentImageIndexInBuffer)),rect); if (aryResult == null) { string strResult = "The barcode for selected format is not found." + "\r\n"; MessageBox.Show(strResult, "Barcodes Results"); } else { string strResult = aryResult.Length + " total barcode found." + "\r\n"; for (int i = 0; i < aryResult.Length; i++) { strResult += String.Format("Result {0}\r\n Barcode Format: {1} Barcode Text: {2}\r\n", (i + 1), aryResult[i].BarcodeFormat, aryResult[i].BarcodeText); } MessageBox.Show(strResult, "Barcodes Results"); } } catch (Exception exp) { MessageBox.Show(exp.Message, "Decoding error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ShowSelectedImageArea() { if (dynamicDotNetTwain.CurrentImageIndexInBuffer >= 0) { Rectangle recSelArea = dynamicDotNetTwain.GetSelectionRect(dynamicDotNetTwain.CurrentImageIndexInBuffer); Image imgCurrent = dynamicDotNetTwain.GetImage(dynamicDotNetTwain.CurrentImageIndexInBuffer); if (recSelArea.IsEmpty) { tbxLeft.Text = "0"; tbxRight.Text = imgCurrent.Width.ToString(); tbxTop.Text = "0"; tbxBottom.Text = imgCurrent.Height.ToString(); } else { tbxLeft.Text = recSelArea.Left < 0 ? "0" : (recSelArea.Left > imgCurrent.Width ? imgCurrent.Width.ToString() : recSelArea.Left.ToString()); tbxRight.Text = recSelArea.Right < 0 ? "0" : (recSelArea.Right > imgCurrent.Width ? imgCurrent.Width.ToString() : recSelArea.Right.ToString()); tbxTop.Text = recSelArea.Top < 0 ? "0" : (recSelArea.Top > imgCurrent.Height ? imgCurrent.Height.ToString() : recSelArea.Top.ToString()); tbxBottom.Text = recSelArea.Bottom < 0 ? "0" : (recSelArea.Bottom > imgCurrent.Height ? imgCurrent.Height.ToString() : recSelArea.Bottom.ToString()); } } else { tbxLeft.Text = "0"; tbxRight.Text = "0"; tbxTop.Text = "0"; tbxBottom.Text = "0"; } } #endregion Read Barcode #region Add Barcode private void picboxAddBarcode_Click(object sender, EventArgs e) { if (picboxAddBarcode.Enabled) { if (dynamicDotNetTwain.CurrentImageIndexInBuffer >= 0) { if (tbxBarcodeContent.Text != "" && tbxBarcodeLocationX.Text != "" && tbxBarcodeLocationY.Text != "" && tbxBarcodeScale.Text != "") { Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat barcodeformat = Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat.CODE_39; switch (cbxGenBarcodeFormat.SelectedIndex) { case 0: barcodeformat = Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat.CODE_39; break; case 1: barcodeformat = Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat.CODE_128; break; case 2: barcodeformat = Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat.PDF417; break; case 3: barcodeformat = Dynamsoft.DotNet.TWAIN.Enums.Barcode.BarcodeFormat.QR_CODE; break; } if (!dynamicDotNetTwain.AddBarcode(dynamicDotNetTwain.CurrentImageIndexInBuffer, barcodeformat, tbxBarcodeContent.Text, tbxHumanReadableText.Text, int.Parse(tbxBarcodeLocationX.Text), int.Parse(tbxBarcodeLocationY.Text), float.Parse(tbxBarcodeScale.Text))) MessageBox.Show(dynamicDotNetTwain.ErrorString, "Adding barcode error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { if (tbxBarcodeContent.Text == "") { MessageBox.Show("The content of the barcode can not be empty", "Empty Object", MessageBoxButtons.OK, MessageBoxIcon.Warning); tbxBarcodeContent.Focus(); } else if (tbxBarcodeLocationX.Text == "") { MessageBox.Show("The location of the barcode can not be empty", "Empty Object", MessageBoxButtons.OK, MessageBoxIcon.Warning); tbxBarcodeLocationX.Focus(); } else if (tbxBarcodeLocationY.Text == "") { MessageBox.Show("The location of the barcode can not be empty", "Empty Object", MessageBoxButtons.OK, MessageBoxIcon.Warning); tbxBarcodeLocationY.Focus(); } else if (tbxBarcodeScale.Text == "") { MessageBox.Show("The scale of the barcode can not be empty", "Empty Object", MessageBoxButtons.OK, MessageBoxIcon.Warning); tbxBarcodeScale.Focus(); } } } else MessageBox.Show("Please load an image before adding barcodes!", "Index out of bounds", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void tbxBarcodeLocation_KeyPress(object sender, KeyPressEventArgs e) { byte[] array = System.Text.Encoding.Default.GetBytes(e.KeyChar.ToString()); if (!char.IsDigit(e.KeyChar) || array.LongLength == 2) e.Handled = true; if (e.KeyChar == '\b') e.Handled = false; } private void tbxBarcodeScale_KeyPress(object sender, KeyPressEventArgs e) { byte[] array = System.Text.Encoding.Default.GetBytes(e.KeyChar.ToString()); if (!char.IsDigit(e.KeyChar) || array.LongLength == 2) e.Handled = true; if (e.KeyChar == '\b' || (!tbxBarcodeScale.Text.Contains(".") && e.KeyChar == '.')) e.Handled = false; } #endregion Add Barcode #region Perform OCR private void picboxOCR_Click(object sender, EventArgs e) { if (picboxOCR.Enabled) { if (dynamicDotNetTwain.CurrentImageIndexInBuffer >= 0) { dynamicDotNetTwain.OCRLanguage = languages[cbxSupportedLanguage.Text]; dynamicDotNetTwain.OCRResultFormat = (Dynamsoft.DotNet.TWAIN.OCR.ResultFormat)cbxOCRResultFormat.SelectedIndex; byte[] sbytes = null; sbytes = dynamicDotNetTwain.OCR(dynamicDotNetTwain.CurrentSelectedImageIndicesInBuffer); if (sbytes != null && sbytes.Length > 0) { SaveFileDialog filedlg = new SaveFileDialog(); if (cbxOCRResultFormat.SelectedIndex != 0) { filedlg.Filter = "PDF File(*.pdf)| *.pdf"; } else { filedlg.Filter = "Text File(*.txt)| *.txt"; } if (filedlg.ShowDialog() == DialogResult.OK) { System.IO.File.WriteAllBytes(filedlg.FileName, sbytes); } } else { if (dynamicDotNetTwain.ErrorCode != 0) MessageBox.Show(dynamicDotNetTwain.ErrorString, "Performing OCR error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else MessageBox.Show("Please load an image before doing OCR!", "Index out of bounds", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } #endregion Perform OCR private void dynamicDotNetTwain_OnImageAreaSelected(short sImageIndex, int left, int top, int right, int bottom) { ShowSelectedImageArea(); } private void picboxGrab_Click(object sender, EventArgs e) { dynamicDotNetTwain.MediaType = cbxMediaType.Text; if (cbxResolutionForWebcam.Text != null) { string[] strWXH = cbxResolutionForWebcam.Text.Split(new char[]{' '}); if (strWXH.Length == 3) { try { dynamicDotNetTwain.ResolutionForCam = new Dynamsoft.DotNet.TWAIN.WebCamera.CamResolution( int.Parse(strWXH[0]), int.Parse(strWXH[2])); } catch { } } } if (!dynamicDotNetTwain.AcquireImage()) MessageBox.Show(dynamicDotNetTwain.ErrorString, "Grab error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private void dynamicDotNetTwain_OnSourceUIClose() { EnableControls(picboxScan); } private void cbxMediaType_SelectedIndexChanged(object sender,EventArgs e) { if (cbxMediaType.SelectedIndex >= 0) { try { dynamicDotNetTwain.MediaType = cbxMediaType.Text; } catch { } } } private void cbxResolutionForWebcam_SelectedIndexChanged(object sender, EventArgs e) { if (cbxResolutionForWebcam.Text != null) { string[] strWXH = cbxResolutionForWebcam.Text.Split(new char[] { ' ' }); if (strWXH.Length == 3) { try { dynamicDotNetTwain.ResolutionForCam = new Dynamsoft.DotNet.TWAIN.WebCamera.CamResolution( int.Parse(strWXH[0]), int.Parse(strWXH[2])); } catch { } } } } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Config { using System.IO; using System.Text; using NLog.Config; using NLog.Filters; using Xunit; public class RuleConfigurationTests : NLogTestBase { [Fact] public void NoRulesTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> </rules> </nlog>"); Assert.Equal(0, c.LoggingRules.Count); } [Fact] public void SimpleRuleTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='d1' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal("*", rule.LoggerNamePattern); Assert.Equal(4, rule.Levels.Count); Assert.Contains(LogLevel.Info, rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); Assert.Contains(LogLevel.Error, rule.Levels); Assert.Contains(LogLevel.Fatal, rule.Levels); Assert.Equal(1, rule.Targets.Count); Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]); Assert.False(rule.Final); Assert.Equal(0, rule.Filters.Count); } [Fact] public void SingleLevelTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Single(rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); } [Fact] public void MinMaxLevelTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> <logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(2, rule.Levels.Count); Assert.Contains(LogLevel.Info, rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); } [Fact] public void NoLevelsTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> <logger name='*' writeTo='d1' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(6, rule.Levels.Count); Assert.Contains(LogLevel.Trace, rule.Levels); Assert.Contains(LogLevel.Debug, rule.Levels); Assert.Contains(LogLevel.Info, rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); Assert.Contains(LogLevel.Error, rule.Levels); Assert.Contains(LogLevel.Fatal, rule.Levels); } [Fact] public void ExplicitLevelsTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> </targets> <rules> <logger name='*' levels='Trace,Info,Warn' writeTo='d1' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(3, rule.Levels.Count); Assert.Contains(LogLevel.Trace, rule.Levels); Assert.Contains(LogLevel.Info, rule.Levels); Assert.Contains(LogLevel.Warn, rule.Levels); } [Fact] public void MultipleTargetsTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> <target name='d2' type='Debug' /> <target name='d3' type='Debug' /> <target name='d4' type='Debug' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1,d2,d3' /> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(3, rule.Targets.Count); Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]); Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]); Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]); } [Fact] public void MultipleRulesSameTargetTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}' /> <target name='d2' type='Debug' layout='${message}' /> <target name='d3' type='Debug' layout='${message}' /> <target name='d4' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1' /> <logger name='*' level='Warn' writeTo='d2' /> <logger name='*' level='Warn' writeTo='d3' /> </rules> </nlog>"); LogFactory factory = new LogFactory(c); var loggerConfig = factory.GetConfigurationForLogger("AAA", c); var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn); Assert.Equal("d1", targets.Target.Name); Assert.Equal("d2", targets.NextInChain.Target.Name); Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name); Assert.Null(targets.NextInChain.NextInChain.NextInChain); LogManager.Configuration = c; var logger = LogManager.GetLogger("BBB"); logger.Warn("test1234"); AssertDebugLastMessage("d1", "test1234"); AssertDebugLastMessage("d2", "test1234"); AssertDebugLastMessage("d3", "test1234"); AssertDebugLastMessage("d4", string.Empty); } [Fact] public void ChildRulesTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> <target name='d2' type='Debug' /> <target name='d3' type='Debug' /> <target name='d4' type='Debug' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1,d2,d3'> <logger name='Foo*' writeTo='d4' /> <logger name='Bar*' writeTo='d4' /> </logger> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(2, rule.ChildRules.Count); Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern); Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern); } [Fact] public void FiltersTest() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' /> <target name='d2' type='Debug' /> <target name='d3' type='Debug' /> <target name='d4' type='Debug' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1,d2,d3'> <filters> <when condition=""starts-with(message, 'x')"" action='Ignore' /> <when condition=""starts-with(message, 'z')"" action='Ignore' /> </filters> </logger> </rules> </nlog>"); Assert.Equal(1, c.LoggingRules.Count); var rule = c.LoggingRules[0]; Assert.Equal(2, rule.Filters.Count); var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter; Assert.NotNull(conditionBasedFilter); Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString()); Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action); conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter; Assert.NotNull(conditionBasedFilter); Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString()); Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action); } [Fact] public void FiltersTest_ignoreFinal() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}' /> <target name='d2' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1'> <filters> <when condition=""starts-with(message, 'x')"" action='IgnoreFinal' /> </filters> </logger> <logger name='*' level='Warn' writeTo='d2'> </logger> </rules> </nlog>"); LogManager.Configuration = c; var logger = LogManager.GetLogger("logger1"); logger.Warn("test 1"); AssertDebugLastMessage("d1", "test 1"); AssertDebugLastMessage("d2", "test 1"); logger.Warn("x-mass"); AssertDebugLastMessage("d1", "test 1"); AssertDebugLastMessage("d2", "test 1"); } [Fact] public void FiltersTest_logFinal() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}' /> <target name='d2' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1'> <filters> <when condition=""starts-with(message, 'x')"" action='LogFinal' /> </filters> </logger> <logger name='*' level='Warn' writeTo='d2'> </logger> </rules> </nlog>"); LogManager.Configuration = c; var logger = LogManager.GetLogger("logger1"); logger.Warn("test 1"); AssertDebugLastMessage("d1", "test 1"); AssertDebugLastMessage("d2", "test 1"); logger.Warn("x-mass"); AssertDebugLastMessage("d1", "x-mass"); AssertDebugLastMessage("d2", "test 1"); } [Fact] public void FiltersTest_ignore() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}' /> <target name='d2' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' level='Warn' writeTo='d1'> <filters> <when condition=""starts-with(message, 'x')"" action='Ignore' /> </filters> </logger> <logger name='*' level='Warn' writeTo='d2'> </logger> </rules> </nlog>"); LogManager.Configuration = c; var logger = LogManager.GetLogger("logger1"); logger.Warn("test 1"); AssertDebugLastMessage("d1", "test 1"); AssertDebugLastMessage("d2", "test 1"); logger.Warn("x-mass"); AssertDebugLastMessage("d1", "test 1"); AssertDebugLastMessage("d2", "x-mass"); } [Fact] public void LoggingRule_Final_SuppressesOnlyMatchingLevels() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='d1' type='Debug' layout='${message}' /> </targets> <rules> <logger name='a' level='Debug' final='true' /> <logger name='*' minlevel='Debug' writeTo='d1' /> </rules> </nlog>"); LogManager.Configuration = c; Logger a = LogManager.GetLogger("a"); Assert.False(a.IsDebugEnabled); Assert.True(a.IsInfoEnabled); a.Info("testInfo"); a.Debug("suppressedDebug"); AssertDebugLastMessage("d1", "testInfo"); Logger b = LogManager.GetLogger("b"); b.Debug("testDebug"); AssertDebugLastMessage("d1", "testDebug"); } [Fact] public void UnusedTargetsShouldBeLoggedToInternalLogger() { string tempFileName = Path.GetTempFileName(); try { CreateConfigurationFromString( "<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'> <targets> <target name='d1' type='Debug' /> <target name='d2' type='Debug' /> <target name='d3' type='Debug' /> <target name='d4' type='Debug' /> <target name='d5' type='Debug' /> </targets> <rules> <logger name='*' level='Debug' writeTo='d1' /> <logger name='*' level='Debug' writeTo='d1,d2,d3' /> </rules> </nlog>"); AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8); AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8); } finally { NLog.Common.InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void UnusedTargetsShouldBeLoggedToInternalLogger_PermitWrapped() { string tempFileName = Path.GetTempFileName(); try { CreateConfigurationFromString( "<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'> <extensions> <add assembly='NLog.UnitTests'/> </extensions> <targets> <target name='d1' type='Debug' /> <target name='d2' type='MockWrapper'> <target name='d3' type='Debug' /> </target> <target name='d4' type='Debug' /> <target name='d5' type='Debug' /> </targets> <rules> <logger name='*' level='Debug' writeTo='d1' /> <logger name='*' level='Debug' writeTo='d1,d2,d4' /> </rules> </nlog>"); AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d2", Encoding.UTF8); AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d3", Encoding.UTF8); AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8); AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8); } finally { NLog.Common.InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void LoggingRule_LevelOff_NotSetAsActualLogLevel() { LoggingConfiguration c = CreateConfigurationFromString(@" <nlog> <targets> <target name='l1' type='Debug' layout='${message}' /> <target name='l2' type='Debug' layout='${message}' /> </targets> <rules> <logger name='a' level='Off' appendTo='l1' /> <logger name='a' minlevel='Debug' appendTo='l2' /> </rules> </nlog>"); LogManager.Configuration = c; Logger a = LogManager.GetLogger("a"); Assert.True(c.LoggingRules.Count == 2, "All rules should have been loaded."); Assert.False(c.LoggingRules[0].IsLoggingEnabledForLevel(LogLevel.Off), "Log level Off should always return false."); // The two functions below should not throw an exception. c.LoggingRules[0].EnableLoggingForLevel(LogLevel.Debug); c.LoggingRules[0].DisableLoggingForLevel(LogLevel.Debug); } } }
using UnityEngine; using System.Collections; using System; using System.Collections.Generic; [AddComponentMenu("Mesh Splitting/Splitable")] public class Splitable : MonoBehaviour, ISplitable { #if UNITY_EDITOR [NonSerialized] public bool ShowDebug = false; #endif public GameObject OptionalTargetObject; public bool Convex = false; public float SplitForce = 0f; public bool CreateCap = true; public bool UseCapUV = false; public bool CustomUV = false; public Vector2 CapUVMin = Vector2.zero; public Vector2 CapUVMax = Vector2.one; public bool ForceNoBatching = false; private Transform _transform; private Plane _splitPlane; private MeshContainer[] _meshContainerStatic; private IMeshSplitter[] _meshSplitterStatic; private MeshContainer[] _meshContainerSkinned; private IMeshSplitter[] _meshSplitterSkinned; private bool _isSplitting = false; private bool _splitMesh = false; private void Awake() { _transform = GetComponent<Transform>(); } private void Update() { if (_splitMesh) { _splitMesh = false; bool anySplit = false; for (int i = 0; i < _meshContainerStatic.Length; i++) { _meshContainerStatic[i].MeshInitialize(); _meshContainerStatic[i].CalculateWorldSpace(); // split mesh _meshSplitterStatic[i].MeshSplit(); if (_meshContainerStatic[i].IsMeshSplit()) { anySplit = true; if (CreateCap) _meshSplitterStatic[i].MeshCreateCaps(); } } for (int i = 0; i < _meshContainerSkinned.Length; i++) { _meshContainerSkinned[i].MeshInitialize(); _meshContainerSkinned[i].CalculateWorldSpace(); // split mesh _meshSplitterSkinned[i].MeshSplit(); if (_meshContainerSkinned[i].IsMeshSplit()) { anySplit = true; if (CreateCap) _meshSplitterSkinned[i].MeshCreateCaps(); } } if (anySplit) CreateNewObjects(); _isSplitting = false; } } public void Split(Transform splitTransform) { if (!_isSplitting) { _isSplitting = _splitMesh = true; _splitPlane = new Plane(splitTransform); MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); SkinnedMeshRenderer[] skinnedRenderes = GetComponentsInChildren<SkinnedMeshRenderer>(); _meshContainerStatic = new MeshContainer[meshFilters.Length]; _meshSplitterStatic = new IMeshSplitter[meshFilters.Length]; for (int i = 0; i < meshFilters.Length; i++) { _meshContainerStatic[i] = new MeshContainer(meshFilters[i].mesh, meshFilters[i].transform); _meshSplitterStatic[i] = Convex ? (IMeshSplitter)new MeshSplitterConvex(_meshContainerStatic[i], _splitPlane, splitTransform.rotation) : (IMeshSplitter)new MeshSplitterConcave(_meshContainerStatic[i], _splitPlane, splitTransform.rotation); if (UseCapUV) _meshSplitterStatic[i].SetCapUV(UseCapUV, CustomUV, CapUVMin, CapUVMax); #if UNITY_EDITOR _meshSplitterStatic[i].DebugDraw(ShowDebug); #endif } _meshSplitterSkinned = new IMeshSplitter[skinnedRenderes.Length]; _meshContainerSkinned = new MeshContainer[skinnedRenderes.Length]; for (int i = 0; i < skinnedRenderes.Length; i++) { _meshContainerSkinned[i] = new MeshContainer(skinnedRenderes[i]); _meshSplitterSkinned[i] = Convex ? (IMeshSplitter)new MeshSplitterConvex(_meshContainerSkinned[i], _splitPlane, splitTransform.rotation) : (IMeshSplitter)new MeshSplitterConcave(_meshContainerSkinned[i], _splitPlane, splitTransform.rotation); if (UseCapUV) _meshSplitterSkinned[i].SetCapUV(UseCapUV, CustomUV, CapUVMin, CapUVMax); #if UNITY_EDITOR _meshSplitterSkinned[i].DebugDraw(ShowDebug); #endif } } } private void CreateNewObjects() { Transform parent = _transform.parent; if (parent == null) { GameObject go = new GameObject("Parent: " + gameObject.name); parent = go.transform; parent.position = Vector3.zero; parent.rotation = Quaternion.identity; parent.localScale = Vector3.one; } Mesh origMesh = GetMeshOnGameObject(gameObject); Rigidbody ownBody = null; float ownMass = 100f; float ownVolume = 1f; if (origMesh != null) { ownBody = GetComponent<Rigidbody>(); if (ownBody != null) ownMass = ownBody.mass; Vector3 ownMeshSize = origMesh.bounds.size; ownVolume = ownMeshSize.x * ownMeshSize.y * ownMeshSize.z; } GameObject[] newGOs = new GameObject[2]; if (OptionalTargetObject == null) { newGOs[0] = Instantiate(gameObject) as GameObject; newGOs[0].name = gameObject.name; newGOs[1] = gameObject; } else { newGOs[0] = Instantiate(OptionalTargetObject) as GameObject; newGOs[1] = Instantiate(OptionalTargetObject) as GameObject; } Animation[] animSources = newGOs[1].GetComponentsInChildren<Animation>(); Animation[] animDests = newGOs[0].GetComponentsInChildren<Animation>(); for (int i = 0; i < animSources.Length; i++) { foreach (AnimationState stateSource in animSources[i]) { AnimationState stateDest = animDests[i][stateSource.name]; stateDest.enabled = stateSource.enabled; stateDest.weight = stateSource.weight; stateDest.time = stateSource.time; stateDest.speed = stateSource.speed; stateDest.layer = stateSource.layer; stateDest.blendMode = stateSource.blendMode; } } for (int i = 0; i < 2; i++) { UpdateMeshesInChildren(i, newGOs[i]); Transform newTransform = newGOs[i].GetComponent<Transform>(); newTransform.parent = parent; Mesh newMesh = GetMeshOnGameObject(newGOs[i]); if (newMesh != null) { MeshCollider newCollider = newGOs[i].GetComponent<MeshCollider>(); if (newCollider != null) { newCollider.sharedMesh = newMesh; newCollider.convex = Convex; // if hull has less than 255 polygons set convex, Unity limit! if (newCollider.convex && newMesh.triangles.Length > 765) newCollider.convex = false; } Rigidbody newBody = newGOs[i].GetComponent<Rigidbody>(); if (ownBody != null && newBody != null) { Vector3 newMeshSize = newMesh.bounds.size; float meshVolume = newMeshSize.x * newMeshSize.y * newMeshSize.z; float newMass = ownMass * (meshVolume / ownVolume); newBody.useGravity = ownBody.useGravity; newBody.mass = newMass; newBody.velocity = ownBody.velocity; newBody.angularVelocity = ownBody.angularVelocity; if (SplitForce > 0f) newBody.AddForce(_splitPlane.Normal * newMass * (i == 0 ? SplitForce : -SplitForce), ForceMode.Impulse); } } PostProcessObject(newGOs[i]); } } private void UpdateMeshesInChildren(int i, GameObject go) { if (_meshContainerStatic.Length > 0) { MeshFilter[] meshFilters = go.GetComponentsInChildren<MeshFilter>(); for (int j = 0; j < _meshContainerStatic.Length; j++) { Renderer renderer = meshFilters[j].GetComponent<Renderer>(); if (ForceNoBatching) { renderer.materials = renderer.materials; } if (i == 0) { if (_meshContainerStatic[j].HasMeshUpper() & _meshContainerStatic[j].HasMeshLower()) { meshFilters[j].mesh = _meshContainerStatic[j].CreateMeshUpper(); } else if (!_meshContainerStatic[j].HasMeshUpper()) { if (renderer != null) Destroy(renderer); Destroy(meshFilters[j]); } } else { if (_meshContainerStatic[j].HasMeshUpper() & _meshContainerStatic[j].HasMeshLower()) { meshFilters[j].mesh = _meshContainerStatic[j].CreateMeshLower(); } else if (!_meshContainerStatic[j].HasMeshLower()) { if (renderer != null) Destroy(renderer); Destroy(meshFilters[j]); } } } } if (_meshContainerSkinned.Length > 0) { SkinnedMeshRenderer[] skinnedRenderer = go.GetComponentsInChildren<SkinnedMeshRenderer>(); for (int j = 0; j < _meshContainerSkinned.Length; j++) { if (i == 0) { if (_meshContainerSkinned[j].HasMeshUpper() & _meshContainerSkinned[j].HasMeshLower()) { skinnedRenderer[j].sharedMesh = _meshContainerSkinned[j].CreateMeshUpper(); } else if (!_meshContainerSkinned[j].HasMeshUpper()) { Destroy(skinnedRenderer[j]); } } else { if (_meshContainerSkinned[j].HasMeshUpper() & _meshContainerSkinned[j].HasMeshLower()) { skinnedRenderer[j].sharedMesh = _meshContainerSkinned[j].CreateMeshLower(); } else if (!_meshContainerSkinned[j].HasMeshLower()) { Destroy(skinnedRenderer[j]); } } } } } private Material[] GetSharedMaterials(GameObject go) { SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { return skinnedMeshRenderer.sharedMaterials; } else { Renderer renderer = go.GetComponent<Renderer>(); if (renderer != null) { return renderer.sharedMaterials; } } return null; } private void SetSharedMaterials(GameObject go, Material[] materials) { SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { skinnedMeshRenderer.sharedMaterials = materials; } else { Renderer renderer = go.GetComponent<Renderer>(); if (renderer != null) { renderer.sharedMaterials = materials; } } } private void SetMeshOnGameObject(GameObject go, Mesh mesh) { SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { skinnedMeshRenderer.sharedMesh = mesh; } else { MeshFilter meshFilter = go.GetComponent<MeshFilter>(); if (meshFilter != null) { meshFilter.mesh = mesh; } } } private Mesh GetMeshOnGameObject(GameObject go) { SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>(); if (skinnedMeshRenderer != null) { return skinnedMeshRenderer.sharedMesh; } else { MeshFilter meshFilter = go.GetComponent<MeshFilter>(); if (meshFilter != null) { return meshFilter.mesh; } } return null; } protected virtual void PostProcessObject(GameObject go) { } }
// 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.IO; using System.Linq; using System.Security; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.GeneratedCodeRecognition; using Microsoft.CodeAnalysis.GenerateType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.ProjectManagement; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.GenerateType { internal class GenerateTypeDialogViewModel : AbstractNotifyPropertyChanged { private Document _document; private INotificationService _notificationService; private IProjectManagementService _projectManagementService; private ISyntaxFactsService _syntaxFactsService; private IGeneratedCodeRecognitionService _generatedCodeService; private GenerateTypeDialogOptions _generateTypeDialogOptions; private string _typeName; private bool _isNewFile; private Dictionary<string, Accessibility> _accessListMap; private Dictionary<string, TypeKind> _typeKindMap; private List<string> _csharpAccessList; private List<string> _visualBasicAccessList; private List<string> _csharpTypeKindList; private List<string> _visualBasicTypeKindList; private string _csharpExtension = ".cs"; private string _visualBasicExtension = ".vb"; // reserved names that cannot be a folder name or filename private string[] _reservedKeywords = new string[] { "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", "clock$" }; // Below code details with the Access List and the manipulation public List<string> AccessList { get; } private int _accessSelectIndex; public int AccessSelectIndex { get { return _accessSelectIndex; } set { SetProperty(ref _accessSelectIndex, value); } } private string _selectedAccessibilityString; public string SelectedAccessibilityString { get { return _selectedAccessibilityString; } set { SetProperty(ref _selectedAccessibilityString, value); } } public Accessibility SelectedAccessibility { get { Contract.Assert(_accessListMap.ContainsKey(SelectedAccessibilityString), "The Accessibility Key String not present"); return _accessListMap[SelectedAccessibilityString]; } } private List<string> _kindList; public List<string> KindList { get { return _kindList; } set { SetProperty(ref _kindList, value); } } private int _kindSelectIndex; public int KindSelectIndex { get { return _kindSelectIndex; } set { SetProperty(ref _kindSelectIndex, value); } } private string _selectedTypeKindString; public string SelectedTypeKindString { get { return _selectedTypeKindString; } set { SetProperty(ref _selectedTypeKindString, value); } } public TypeKind SelectedTypeKind { get { Contract.Assert(_typeKindMap.ContainsKey(SelectedTypeKindString), "The TypeKind Key String not present"); return _typeKindMap[SelectedTypeKindString]; } } private void PopulateTypeKind(TypeKind typeKind, string csharpKey, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _typeKindMap.Add(csharpKey, typeKind); _csharpTypeKindList.Add(csharpKey); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateTypeKind(TypeKind typeKind, string visualBasicKey) { _typeKindMap.Add(visualBasicKey, typeKind); _visualBasicTypeKindList.Add(visualBasicKey); } private void PopulateAccessList(string key, Accessibility accessibility, string languageName = null) { if (languageName == null) { _csharpAccessList.Add(key); _visualBasicAccessList.Add(key); } else if (languageName == LanguageNames.CSharp) { _csharpAccessList.Add(key); } else { Contract.Assert(languageName == LanguageNames.VisualBasic, "Currently only C# and VB are supported"); _visualBasicAccessList.Add(key); } _accessListMap.Add(key, accessibility); } private void InitialSetup(string languageName) { _accessListMap = new Dictionary<string, Accessibility>(); _typeKindMap = new Dictionary<string, TypeKind>(); _csharpAccessList = new List<string>(); _visualBasicAccessList = new List<string>(); _csharpTypeKindList = new List<string>(); _visualBasicTypeKindList = new List<string>(); // Populate the AccessListMap if (!_generateTypeDialogOptions.IsPublicOnlyAccessibility) { PopulateAccessList("Default", Accessibility.NotApplicable); PopulateAccessList("internal", Accessibility.Internal, LanguageNames.CSharp); PopulateAccessList("Friend", Accessibility.Internal, LanguageNames.VisualBasic); } PopulateAccessList("public", Accessibility.Public, LanguageNames.CSharp); PopulateAccessList("Public", Accessibility.Public, LanguageNames.VisualBasic); // Populate the TypeKind PopulateTypeKind(); } private void PopulateTypeKind() { Contract.Assert(_generateTypeDialogOptions.TypeKindOptions != TypeKindOptions.None); if (TypeKindOptionsHelper.IsClass(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Class, "class", "Class"); } if (TypeKindOptionsHelper.IsEnum(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Enum, "enum", "Enum"); } if (TypeKindOptionsHelper.IsStructure(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Structure, "struct", "Structure"); } if (TypeKindOptionsHelper.IsInterface(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Interface, "interface", "Interface"); } if (TypeKindOptionsHelper.IsDelegate(_generateTypeDialogOptions.TypeKindOptions)) { PopulateTypeKind(TypeKind.Delegate, "delegate", "Delegate"); } if (TypeKindOptionsHelper.IsModule(_generateTypeDialogOptions.TypeKindOptions)) { _shouldChangeTypeKindListSelectedIndex = true; PopulateTypeKind(TypeKind.Module, "Module"); } } internal bool TrySubmit() { if (this.IsNewFile) { var trimmedFileName = FileName.Trim(); // Case : \\Something if (trimmedFileName.StartsWith(@"\\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } // Case : something\ if (string.IsNullOrWhiteSpace(trimmedFileName) || trimmedFileName.EndsWith(@"\", StringComparison.Ordinal)) { SendFailureNotification(ServicesVSResources.Path_cannot_have_empty_filename); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidPathChars()) >= 0) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } var isRootOfTheProject = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal); string implicitFilePath = null; // Construct the implicit file path if (isRootOfTheProject || this.SelectedProject != _document.Project) { if (!TryGetImplicitFilePath(this.SelectedProject.FilePath ?? string.Empty, ServicesVSResources.Project_Path_is_illegal, out implicitFilePath)) { return false; } } else { if (!TryGetImplicitFilePath(_document.FilePath, ServicesVSResources.DocumentPath_is_illegal, out implicitFilePath)) { return false; } } // Remove the '\' at the beginning if present trimmedFileName = trimmedFileName.StartsWith(@"\", StringComparison.Ordinal) ? trimmedFileName.Substring(1) : trimmedFileName; // Construct the full path of the file to be created this.FullFilePath = implicitFilePath + @"\" + trimmedFileName; try { this.FullFilePath = Path.GetFullPath(this.FullFilePath); } catch (ArgumentNullException e) { SendFailureNotification(e.Message); return false; } catch (ArgumentException e) { SendFailureNotification(e.Message); return false; } catch (SecurityException e) { SendFailureNotification(e.Message); return false; } catch (NotSupportedException e) { SendFailureNotification(e.Message); return false; } catch (PathTooLongException e) { SendFailureNotification(e.Message); return false; } // Path.GetFullPath does not remove the spaces infront of the filename or folder name . So remove it var lastIndexOfSeparatorInFullPath = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparatorInFullPath != -1) { var fileNameInFullPathInContainers = this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); this.FullFilePath = string.Join("\\", fileNameInFullPathInContainers.Select(str => str.TrimStart())); } string projectRootPath = null; if (this.SelectedProject.FilePath == null) { projectRootPath = string.Empty; } else if (!TryGetImplicitFilePath(this.SelectedProject.FilePath, ServicesVSResources.Project_Path_is_illegal, out projectRootPath)) { return false; } if (this.FullFilePath.StartsWith(projectRootPath, StringComparison.Ordinal)) { // The new file will be within the root of the project var folderPath = this.FullFilePath.Substring(projectRootPath.Length); var containers = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); // Folder name was mentioned if (containers.Length > 1) { _fileName = containers.Last(); Folders = new List<string>(containers); Folders.RemoveAt(Folders.Count - 1); if (Folders.Any(folder => !(_syntaxFactsService.IsValidIdentifier(folder) || _syntaxFactsService.IsVerbatimIdentifier(folder)))) { _areFoldersValidIdentifiers = false; } } else if (containers.Length == 1) { // File goes at the root of the Directory _fileName = containers[0]; Folders = null; } else { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } } else { // The new file will be outside the root of the project and folders will be null Folders = null; var lastIndexOfSeparator = this.FullFilePath.LastIndexOf('\\'); if (lastIndexOfSeparator == -1) { SendFailureNotification(ServicesVSResources.Illegal_characters_in_path); return false; } _fileName = this.FullFilePath.Substring(lastIndexOfSeparator + 1); } // Check for reserved words in the folder or filename if (this.FullFilePath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Any(s => _reservedKeywords.Contains(s, StringComparer.OrdinalIgnoreCase))) { SendFailureNotification(ServicesVSResources.File_path_cannot_use_reserved_keywords); return false; } // We check to see if file path of the new file matches the filepath of any other existing file or if the Folders and FileName matches any of the document then // we say that the file already exists. if (this.SelectedProject.Documents.Where(n => n != null).Where(n => n.FilePath == FullFilePath).Any() || (this.Folders != null && this.FileName != null && this.SelectedProject.Documents.Where(n => n.Name != null && n.Folders.Count > 0 && n.Name == this.FileName && this.Folders.SequenceEqual(n.Folders)).Any()) || File.Exists(FullFilePath)) { SendFailureNotification(ServicesVSResources.File_already_exists); return false; } } return true; } private bool TryGetImplicitFilePath(string implicitPathContainer, string message, out string implicitPath) { var indexOfLastSeparator = implicitPathContainer.LastIndexOf('\\'); if (indexOfLastSeparator == -1) { SendFailureNotification(message); implicitPath = null; return false; } implicitPath = implicitPathContainer.Substring(0, indexOfLastSeparator); return true; } private void SendFailureNotification(string message) { _notificationService.SendNotification(message, severity: NotificationSeverity.Information); } private Project _selectedProject; public Project SelectedProject { get { return _selectedProject; } set { var previousProject = _selectedProject; if (SetProperty(ref _selectedProject, value)) { NotifyPropertyChanged("DocumentList"); this.DocumentSelectIndex = 0; this.ProjectSelectIndex = this.ProjectList.FindIndex(p => p.Project == _selectedProject); if (_selectedProject != _document.Project) { // Restrict the Access List Options // 3 in the list represent the Public. 1-based array. this.AccessSelectIndex = this.AccessList.IndexOf("public") == -1 ? this.AccessList.IndexOf("Public") : this.AccessList.IndexOf("public"); Contract.Assert(this.AccessSelectIndex != -1); this.IsAccessListEnabled = false; } else { // Remove restriction this.IsAccessListEnabled = true; } if (previousProject != null && _projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } // Update the TypeKindList if required if (previousProject != null && previousProject.Language != _selectedProject.Language) { if (_selectedProject.Language == LanguageNames.CSharp) { var previousSelectedIndex = _kindSelectIndex; this.KindList = _csharpTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } else { var previousSelectedIndex = _kindSelectIndex; this.KindList = _visualBasicTypeKindList; if (_shouldChangeTypeKindListSelectedIndex) { this.KindSelectIndex = 0; } else { this.KindSelectIndex = previousSelectedIndex; } } } // Update File Extension UpdateFileNameExtension(); } } } private int _projectSelectIndex; public int ProjectSelectIndex { get { return _projectSelectIndex; } set { SetProperty(ref _projectSelectIndex, value); } } public List<ProjectSelectItem> ProjectList { get; } private Project _previouslyPopulatedProject = null; private List<DocumentSelectItem> _previouslyPopulatedDocumentList = null; public IEnumerable<DocumentSelectItem> DocumentList { get { if (_previouslyPopulatedProject == _selectedProject) { return _previouslyPopulatedDocumentList; } _previouslyPopulatedProject = _selectedProject; _previouslyPopulatedDocumentList = new List<DocumentSelectItem>(); // Check for the current project if (_selectedProject == _document.Project) { // populate the current document _previouslyPopulatedDocumentList.Add(new DocumentSelectItem(_document, "<Current File>")); // Set the initial selected Document this.SelectedDocument = _document; // Populate the rest of the documents for the project _previouslyPopulatedDocumentList.AddRange(_document.Project.Documents .Where(d => d != _document && !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); } else { _previouslyPopulatedDocumentList.AddRange(_selectedProject.Documents .Where(d => !_generatedCodeService.IsGeneratedCode(d)) .Select(d => new DocumentSelectItem(d))); this.SelectedDocument = _selectedProject.Documents.FirstOrDefault(); } this.IsExistingFileEnabled = _previouslyPopulatedDocumentList.Count == 0 ? false : true; this.IsNewFile = this.IsExistingFileEnabled ? this.IsNewFile : true; return _previouslyPopulatedDocumentList; } } private bool _isExistingFileEnabled = true; public bool IsExistingFileEnabled { get { return _isExistingFileEnabled; } set { SetProperty(ref _isExistingFileEnabled, value); } } private int _documentSelectIndex; public int DocumentSelectIndex { get { return _documentSelectIndex; } set { SetProperty(ref _documentSelectIndex, value); } } private Document _selectedDocument; public Document SelectedDocument { get { return _selectedDocument; } set { SetProperty(ref _selectedDocument, value); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } public List<string> Folders; public string TypeName { get { return _typeName; } set { SetProperty(ref _typeName, value); } } public bool IsNewFile { get { return _isNewFile; } set { SetProperty(ref _isNewFile, value); } } public bool IsExistingFile { get { return !_isNewFile; } set { SetProperty(ref _isNewFile, !value); } } private bool _isAccessListEnabled; private bool _shouldChangeTypeKindListSelectedIndex = false; public bool IsAccessListEnabled { get { return _isAccessListEnabled; } set { SetProperty(ref _isAccessListEnabled, value); } } private bool _areFoldersValidIdentifiers = true; public bool AreFoldersValidIdentifiers { get { if (_areFoldersValidIdentifiers) { var workspace = this.SelectedProject.Solution.Workspace as VisualStudioWorkspaceImpl; var project = workspace?.GetHostProject(this.SelectedProject.Id) as AbstractProject; return !(project?.IsWebSite == true); } return false; } } public IList<string> ProjectFolders { get; private set; } public string FullFilePath { get; private set; } internal void UpdateFileNameExtension() { var currentFileName = this.FileName.Trim(); if (!string.IsNullOrWhiteSpace(currentFileName) && !currentFileName.EndsWith("\\", StringComparison.Ordinal)) { if (this.SelectedProject.Language == LanguageNames.CSharp) { // For CSharp currentFileName = UpdateExtension(currentFileName, _csharpExtension, _visualBasicExtension); } else { // For Visual Basic currentFileName = UpdateExtension(currentFileName, _visualBasicExtension, _csharpExtension); } } this.FileName = currentFileName; } private string UpdateExtension(string currentFileName, string desiredFileExtension, string undesiredFileExtension) { if (currentFileName.EndsWith(desiredFileExtension, StringComparison.OrdinalIgnoreCase)) { // No change required return currentFileName; } // Remove the undesired extension if (currentFileName.EndsWith(undesiredFileExtension, StringComparison.OrdinalIgnoreCase)) { currentFileName = currentFileName.Substring(0, currentFileName.Length - undesiredFileExtension.Length); } // Append the desired extension return currentFileName + desiredFileExtension; } internal GenerateTypeDialogViewModel( Document document, INotificationService notificationService, IProjectManagementService projectManagementService, ISyntaxFactsService syntaxFactsService, IGeneratedCodeRecognitionService generatedCodeService, GenerateTypeDialogOptions generateTypeDialogOptions, string typeName, string fileExtension, bool isNewFile, string accessSelectString, string typeKindSelectString) { _generateTypeDialogOptions = generateTypeDialogOptions; InitialSetup(document.Project.Language); var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph(); // Initialize the dependencies var projectListing = new List<ProjectSelectItem>(); // Populate the project list // Add the current project projectListing.Add(new ProjectSelectItem(document.Project)); // Add the rest of the projects // Adding dependency graph to avoid cyclic dependency projectListing.AddRange(document.Project.Solution.Projects .Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id)) .Select(p => new ProjectSelectItem(p))); this.ProjectList = projectListing; const string attributeSuffix = "Attribute"; _typeName = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith(attributeSuffix, StringComparison.Ordinal) ? typeName + attributeSuffix : typeName; this.FileName = typeName + fileExtension; _document = document; this.SelectedProject = document.Project; this.SelectedDocument = document; _notificationService = notificationService; _generatedCodeService = generatedCodeService; this.AccessList = document.Project.Language == LanguageNames.CSharp ? _csharpAccessList : _visualBasicAccessList; this.AccessSelectIndex = this.AccessList.Contains(accessSelectString) ? this.AccessList.IndexOf(accessSelectString) : 0; this.IsAccessListEnabled = true; this.KindList = document.Project.Language == LanguageNames.CSharp ? _csharpTypeKindList : _visualBasicTypeKindList; this.KindSelectIndex = this.KindList.Contains(typeKindSelectString) ? this.KindList.IndexOf(typeKindSelectString) : 0; this.ProjectSelectIndex = 0; this.DocumentSelectIndex = 0; _isNewFile = isNewFile; _syntaxFactsService = syntaxFactsService; _projectManagementService = projectManagementService; if (projectManagementService != null) { this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace); } else { this.ProjectFolders = SpecializedCollections.EmptyList<string>(); } } public class ProjectSelectItem { private Project _project; public string Name { get { return _project.Name; } } public Project Project { get { return _project; } } public ProjectSelectItem(Project project) { _project = project; } } public class DocumentSelectItem { private Document _document; public Document Document { get { return _document; } } private string _name; public string Name { get { return _name; } } public DocumentSelectItem(Document document, string documentName) { _document = document; _name = documentName; } public DocumentSelectItem(Document document) { _document = document; if (document.Folders.Count == 0) { _name = document.Name; } else { _name = string.Join("\\", document.Folders) + "\\" + document.Name; } } } } }
using System; using System.Net; using System.Text; using System.Threading; using Abc.Zerio.Core; using Abc.Zerio.Interop; using SocketFlags = Abc.Zerio.Interop.SocketFlags; using SocketType = Abc.Zerio.Interop.SocketType; namespace Abc.Zerio { public class ZerioClient : IFeedClient { private readonly IPEndPoint _serverEndpoint; private readonly CompletionQueues _completionQueues; private readonly ISessionManager _sessionManager; private readonly InternalZerioConfiguration _configuration; private readonly ISession _session; private readonly SendRequestProcessingEngine _sendRequestProcessingEngine; private readonly ReceiveCompletionProcessor _receiveCompletionProcessor; private readonly AutoResetEvent _handshakeSignal = new AutoResetEvent(false); private IntPtr _socket; private int _started; public bool IsConnected { get; private set; } public event Action Connected; public event Action Disconnected; public event ClientMessageReceivedDelegate MessageReceived; public ZerioClient(IPEndPoint serverEndpoint, ZerioClientConfiguration clientConfiguration = null) { _serverEndpoint = serverEndpoint; WinSock.EnsureIsInitialized(); _configuration = CreateConfiguration(clientConfiguration); _completionQueues = CreateCompletionQueues(); _sessionManager = CreateSessionManager(); _sendRequestProcessingEngine = CreateSendRequestProcessingEngine(); _receiveCompletionProcessor = CreateReceiveCompletionProcessor(); _session = _sessionManager.Acquire(); _session.HandshakeReceived += OnHandshakeReceived; _session.Closed += OnSessionClosed; } private void OnHandshakeReceived(string peerId) { _handshakeSignal.Set(); } private ISessionManager CreateSessionManager() { var sessionManager = new SessionManager(_configuration, _completionQueues); sessionManager.MessageReceived += (peerId, message) => MessageReceived?.Invoke(message); return sessionManager; } private CompletionQueues CreateCompletionQueues() { return new CompletionQueues(_configuration); } private ReceiveCompletionProcessor CreateReceiveCompletionProcessor() { var receiver = new ReceiveCompletionProcessor(_configuration, _completionQueues.ReceivingQueue, _sessionManager); return receiver; } private static InternalZerioConfiguration CreateConfiguration(ZerioClientConfiguration clientConfiguration) { clientConfiguration ??= new ZerioClientConfiguration(); return clientConfiguration.ToInternalConfiguration(); } private SendRequestProcessingEngine CreateSendRequestProcessingEngine() { return new SendRequestProcessingEngine(_configuration, _completionQueues.SendingQueue, _sessionManager); } public void Send(ReadOnlySpan<byte> message) { if(_configuration.ConflateSendRequestsOnEnqueuing) _session.Conflater.EnqueueOrMergeSendRequest(message, _sendRequestProcessingEngine); else _sendRequestProcessingEngine.RequestSend(_session.Id, message); } private void CheckOnlyStartedOnce() { if (Interlocked.Exchange(ref _started, 1) != 0) throw new InvalidOperationException($"{nameof(ZerioClient)} must only be started once."); } public void Start(string peerId) { if (IsConnected) throw new InvalidOperationException("Already started"); CheckOnlyStartedOnce(); _receiveCompletionProcessor.Start(); _sendRequestProcessingEngine.Start(); _socket = CreateSocket(); _session.Open(_socket); Connect(_socket, _serverEndpoint); _session.InitiateReceiving(); Handshake(peerId); IsConnected = true; Connected?.Invoke(); } private void Handshake(string peerId) { var peerIdBytes = Encoding.ASCII.GetBytes(peerId); Send(peerIdBytes.AsSpan()); _handshakeSignal.WaitOne(); } private unsafe static void Connect(IntPtr socket, IPEndPoint ipEndPoint) { var endPointAddressBytes = ipEndPoint.Address.GetAddressBytes(); var inAddress = new InAddr(endPointAddressBytes); var sa = new SockaddrIn { sin_family = AddressFamilies.AF_INET, sin_port = WinSock.htons((ushort)ipEndPoint.Port), sin_addr = inAddress }; var errorCode = WinSock.connect(socket, ref sa, sizeof(SockaddrIn)); if (errorCode == WinSock.Consts.SOCKET_ERROR) WinSock.ThrowLastWsaError(); } private unsafe static IntPtr CreateSocket() { var socketFlags = SocketFlags.WSA_FLAG_REGISTERED_IO | SocketFlags.WSA_FLAG_OVERLAPPED; var connectionSocket = WinSock.WSASocket(AddressFamilies.AF_INET, SocketType.SOCK_STREAM, Protocol.IPPROTO_TCP, IntPtr.Zero, 0, socketFlags); if (connectionSocket == (IntPtr)WinSock.Consts.INVALID_SOCKET) { WinSock.ThrowLastWsaError(); return IntPtr.Zero; } var tcpNoDelay = -1; WinSock.setsockopt(connectionSocket, WinSock.Consts.IPPROTO_TCP, WinSock.Consts.TCP_NODELAY, (char*)&tcpNoDelay, sizeof(int)); var reuseAddr = 1; WinSock.setsockopt(connectionSocket, WinSock.Consts.SOL_SOCKET, WinSock.Consts.SO_REUSEADDR, (char*)&reuseAddr, sizeof(int)); return connectionSocket; } private void OnSessionClosed(ISession session) { IsConnected = false; Disconnected?.Invoke(); } public void Stop() { if (!IsConnected) throw new InvalidOperationException("Already stopped"); Dispose(true); } private void Dispose(bool disposing) { if (disposing) { _session.Close(); _receiveCompletionProcessor.Stop(); _sendRequestProcessingEngine.Stop(); _completionQueues?.Dispose(); _sessionManager?.Dispose(); _sendRequestProcessingEngine?.Dispose(); _handshakeSignal?.Dispose(); } else { if (_socket != IntPtr.Zero) WinSock.closesocket(_socket); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~ZerioClient() { Dispose(false); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using ScorerDocQueue = Lucene.Net.Util.ScorerDocQueue; namespace Lucene.Net.Search { /// <summary>A Scorer for OR like queries, counterpart of <code>ConjunctionScorer</code>. /// This Scorer implements {@link Scorer#SkipTo(int)} and uses skipTo() on the given Scorers. /// </summary> /// <todo> Implement score(HitCollector, int). </todo> class DisjunctionSumScorer : Scorer { /// <summary>The number of subscorers. </summary> private int nrScorers; /// <summary>The subscorers. </summary> protected internal System.Collections.IList subScorers; /// <summary>The minimum number of scorers that should match. </summary> private int minimumNrMatchers; /// <summary>The scorerDocQueue contains all subscorers ordered by their current doc(), /// with the minimum at the top. /// <br>The scorerDocQueue is initialized the first time next() or skipTo() is called. /// <br>An exhausted scorer is immediately removed from the scorerDocQueue. /// <br>If less than the minimumNrMatchers scorers /// remain in the scorerDocQueue next() and skipTo() return false. /// <p> /// After each to call to next() or skipTo() /// <code>currentSumScore</code> is the total score of the current matching doc, /// <code>nrMatchers</code> is the number of matching scorers, /// and all scorers are after the matching doc, or are exhausted. /// </summary> private ScorerDocQueue scorerDocQueue = null; private int queueSize = - 1; // used to avoid size() method calls on scorerDocQueue /// <summary>The document number of the current match. </summary> private int currentDoc = - 1; /// <summary>The number of subscorers that provide the current match. </summary> protected internal int nrMatchers = - 1; private float currentScore = System.Single.NaN; /// <summary>Construct a <code>DisjunctionScorer</code>.</summary> /// <param name="subScorers">A collection of at least two subscorers. /// </param> /// <param name="minimumNrMatchers">The positive minimum number of subscorers that should /// match to match this query. /// <br>When <code>minimumNrMatchers</code> is bigger than /// the number of <code>subScorers</code>, /// no matches will be produced. /// <br>When minimumNrMatchers equals the number of subScorers, /// it more efficient to use <code>ConjunctionScorer</code>. /// </param> public DisjunctionSumScorer(System.Collections.IList subScorers, int minimumNrMatchers) : base(null) { nrScorers = subScorers.Count; if (minimumNrMatchers <= 0) { throw new System.ArgumentException("Minimum nr of matchers must be positive"); } if (nrScorers <= 1) { throw new System.ArgumentException("There must be at least 2 subScorers"); } this.minimumNrMatchers = minimumNrMatchers; this.subScorers = subScorers; } /// <summary>Construct a <code>DisjunctionScorer</code>, using one as the minimum number /// of matching subscorers. /// </summary> public DisjunctionSumScorer(System.Collections.IList subScorers) : this(subScorers, 1) { } /// <summary>Called the first time next() or skipTo() is called to /// initialize <code>scorerDocQueue</code>. /// </summary> private void InitScorerDocQueue() { System.Collections.IEnumerator si = subScorers.GetEnumerator(); scorerDocQueue = new ScorerDocQueue(nrScorers); queueSize = 0; while (si.MoveNext()) { Scorer se = (Scorer) si.Current; if (se.Next()) { // doc() method will be used in scorerDocQueue. if (scorerDocQueue.Insert(se)) { queueSize++; } } } } /// <summary>Scores and collects all matching documents.</summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// <br>When this method is used the {@link #Explain(int)} method should not be used. /// </param> public override void Score(HitCollector hc) { while (Next()) { hc.Collect(currentDoc, currentScore); } } /// <summary>Expert: Collects matching documents in a range. Hook for optimization. /// Note that {@link #Next()} must be called once before this method is called /// for the first time. /// </summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// </param> /// <param name="max">Do not score documents past this. /// </param> /// <returns> true if more matching documents may remain. /// </returns> protected internal override bool Score(HitCollector hc, int max) { while (currentDoc < max) { hc.Collect(currentDoc, currentScore); if (!Next()) { return false; } } return true; } public override bool Next() { if (scorerDocQueue == null) { InitScorerDocQueue(); } return (scorerDocQueue.Size() >= minimumNrMatchers) && AdvanceAfterCurrent(); } /// <summary>Advance all subscorers after the current document determined by the /// top of the <code>scorerDocQueue</code>. /// Repeat until at least the minimum number of subscorers match on the same /// document and all subscorers are after that document or are exhausted. /// <br>On entry the <code>scorerDocQueue</code> has at least <code>minimumNrMatchers</code> /// available. At least the scorer with the minimum document number will be advanced. /// </summary> /// <returns> true iff there is a match. /// <br>In case there is a match, </code>currentDoc</code>, </code>currentSumScore</code>, /// and </code>nrMatchers</code> describe the match. /// /// </returns> /// <todo> Investigate whether it is possible to use skipTo() when </todo> /// <summary> the minimum number of matchers is bigger than one, ie. try and use the /// character of ConjunctionScorer for the minimum number of matchers. /// Also delay calling score() on the sub scorers until the minimum number of /// matchers is reached. /// <br>For this, a Scorer array with minimumNrMatchers elements might /// hold Scorers at currentDoc that are temporarily popped from scorerQueue. /// </summary> protected internal virtual bool AdvanceAfterCurrent() { do { // repeat until minimum nr of matchers currentDoc = scorerDocQueue.TopDoc(); currentScore = scorerDocQueue.TopScore(); nrMatchers = 1; do { // Until all subscorers are after currentDoc if (!scorerDocQueue.TopNextAndAdjustElsePop()) { if (--queueSize == 0) { break; // nothing more to advance, check for last match. } } if (scorerDocQueue.TopDoc() != currentDoc) { break; // All remaining subscorers are after currentDoc. } currentScore += scorerDocQueue.TopScore(); nrMatchers++; } while (true); if (nrMatchers >= minimumNrMatchers) { return true; } else if (queueSize < minimumNrMatchers) { return false; } } while (true); } /// <summary>Returns the score of the current document matching the query. /// Initially invalid, until {@link #Next()} is called the first time. /// </summary> public override float Score() { return currentScore; } public override int Doc() { return currentDoc; } /// <summary>Returns the number of subscorers matching the current document. /// Initially invalid, until {@link #Next()} is called the first time. /// </summary> public virtual int NrMatchers() { return nrMatchers; } /// <summary>Skips to the first match beyond the current whose document number is /// greater than or equal to a given target. /// <br>When this method is used the {@link #Explain(int)} method should not be used. /// <br>The implementation uses the skipTo() method on the subscorers. /// </summary> /// <param name="target">The target document number. /// </param> /// <returns> true iff there is such a match. /// </returns> public override bool SkipTo(int target) { if (scorerDocQueue == null) { InitScorerDocQueue(); } if (queueSize < minimumNrMatchers) { return false; } if (target <= currentDoc) { return true; } do { if (scorerDocQueue.TopDoc() >= target) { return AdvanceAfterCurrent(); } else if (!scorerDocQueue.TopSkipToAndAdjustElsePop(target)) { if (--queueSize < minimumNrMatchers) { return false; } } } while (true); } /// <returns> An explanation for the score of a given document. /// </returns> public override Explanation Explain(int doc) { Explanation res = new Explanation(); System.Collections.IEnumerator ssi = subScorers.GetEnumerator(); float sumScore = 0.0f; int nrMatches = 0; while (ssi.MoveNext()) { Explanation es = ((Scorer) ssi.Current).Explain(doc); if (es.GetValue() > 0.0f) { // indicates match sumScore += es.GetValue(); nrMatches++; } res.AddDetail(es); } if (nrMatchers >= minimumNrMatchers) { res.SetValue(sumScore); res.SetDescription("sum over at least " + minimumNrMatchers + " of " + subScorers.Count + ":"); } else { res.SetValue(0.0f); res.SetDescription(nrMatches + " match(es) but at least " + minimumNrMatchers + " of " + subScorers.Count + " needed"); } return res; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Diagnostics.Runtime.Utilities.Pdb { /// <summary> /// Represents a single function in a module. /// </summary> public class PdbFunction { static internal readonly Guid msilMetaData = new Guid(unchecked((int)0xc6ea3fc9), 0x59b3, 0x49d6, 0xbc, 0x25, 0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60); static internal readonly IComparer byAddress = new PdbFunctionsByAddress(); static internal readonly IComparer byAddressAndToken = new PdbFunctionsByAddressAndToken(); //static internal readonly IComparer byToken = new PdbFunctionsByToken(); internal uint slotToken; //internal string name; //internal string module; //internal ushort flags; //internal uint length; //internal byte[] metadata; internal PdbSlot[] Slots; internal PdbConstant[] Constants; internal string[] Namespaces; internal ushort[]/*?*/ UsingCounts; internal string/*?*/ iteratorClass; /// <summary> /// Sequence points of this function. /// </summary> public PdbSequencePointCollection[] SequencePoints { get; internal set; } /// <summary> /// Metadata token of this function. /// </summary> public uint Token { get; internal set; } /// <summary> /// The scopes of this function. /// </summary> public PdbScope[] Scopes { get; internal set; } internal uint Segment { get; set; } internal uint Address { get; set; } private static string StripNamespace(string module) { int li = module.LastIndexOf('.'); if (li > 0) { return module.Substring(li + 1); } return module; } internal static PdbFunction[] LoadManagedFunctions(/*string module,*/ BitAccess bits, uint limit, bool readStrings) { //string mod = StripNamespace(module); int begin = bits.Position; int count = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_GMANPROC: case SYM.S_LMANPROC: ManProcSym proc; bits.ReadUInt32(out proc.parent); bits.ReadUInt32(out proc.end); bits.Position = (int)proc.end; count++; break; case SYM.S_END: bits.Position = stop; break; default: //Console.WriteLine("{0,6}: {1:x2} {2}", // bits.Position, rec, (SYM)rec); bits.Position = stop; break; } } if (count == 0) { return null; } bits.Position = begin; PdbFunction[] funcs = new PdbFunction[count]; int func = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_GMANPROC: case SYM.S_LMANPROC: ManProcSym proc; //int offset = bits.Position; bits.ReadUInt32(out proc.parent); bits.ReadUInt32(out proc.end); bits.ReadUInt32(out proc.next); bits.ReadUInt32(out proc.len); bits.ReadUInt32(out proc.dbgStart); bits.ReadUInt32(out proc.dbgEnd); bits.ReadUInt32(out proc.token); bits.ReadUInt32(out proc.off); bits.ReadUInt16(out proc.seg); bits.ReadUInt8(out proc.flags); bits.ReadUInt16(out proc.retReg); if (readStrings) { bits.ReadCString(out proc.name); } else { bits.SkipCString(out proc.name); } //Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name); bits.Position = stop; funcs[func++] = new PdbFunction(/*module,*/ proc, bits); break; default: { //throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec); bits.Position = stop; break; } } } return funcs; } internal static void CountScopesAndSlots(BitAccess bits, uint limit, out int constants, out int scopes, out int slots, out int usedNamespaces) { int pos = bits.Position; BlockSym32 block; constants = 0; slots = 0; scopes = 0; usedNamespaces = 0; while (bits.Position < limit) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_BLOCK32: { bits.ReadUInt32(out block.parent); bits.ReadUInt32(out block.end); scopes++; bits.Position = (int)block.end; break; } case SYM.S_MANSLOT: slots++; bits.Position = stop; break; case SYM.S_UNAMESPACE: usedNamespaces++; bits.Position = stop; break; case SYM.S_MANCONSTANT: constants++; bits.Position = stop; break; default: bits.Position = stop; break; } } bits.Position = pos; } internal PdbFunction() { } internal PdbFunction(/*string module, */ManProcSym proc, BitAccess bits) { this.Token = proc.token; //this.module = module; //this.name = proc.name; //this.flags = proc.flags; this.Segment = proc.seg; this.Address = proc.off; //this.length = proc.len; if (proc.seg != 1) { throw new PdbDebugException("Segment is {0}, not 1.", proc.seg); } if (proc.parent != 0 || proc.next != 0) { throw new PdbDebugException("Warning parent={0}, next={1}", proc.parent, proc.next); } //if (proc.dbgStart != 0 || proc.dbgEnd != 0) { // throw new PdbDebugException("Warning DBG start={0}, end={1}", // proc.dbgStart, proc.dbgEnd); //} int constantCount; int scopeCount; int slotCount; int usedNamespacesCount; CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount); int scope = constantCount > 0 || slotCount > 0 || usedNamespacesCount > 0 ? 1 : 0; int slot = 0; int constant = 0; int usedNs = 0; Scopes = new PdbScope[scopeCount + scope]; Slots = new PdbSlot[slotCount]; Constants = new PdbConstant[constantCount]; Namespaces = new string[usedNamespacesCount]; if (scope > 0) Scopes[0] = new PdbScope(this.Address, proc.len, Slots, Constants, Namespaces); while (bits.Position < proc.end) { ushort siz; ushort rec; bits.ReadUInt16(out siz); int star = bits.Position; int stop = bits.Position + siz; bits.Position = star; bits.ReadUInt16(out rec); switch ((SYM)rec) { case SYM.S_OEM: { // 0x0404 OemSymbol oem; bits.ReadGuid(out oem.idOem); bits.ReadUInt32(out oem.typind); // internal byte[] rgl; // user data, force 4-byte alignment if (oem.idOem == msilMetaData) { string name = bits.ReadString(); if (name == "MD2") { byte version; bits.ReadUInt8(out version); if (version == 4) { byte count; bits.ReadUInt8(out count); bits.Align(4); while (count-- > 0) this.ReadCustomMetadata(bits); } } bits.Position = stop; break; } else { throw new PdbDebugException("OEM section: guid={0} ti={1}", oem.idOem, oem.typind); // bits.Position = stop; } } case SYM.S_BLOCK32: { BlockSym32 block = new BlockSym32(); bits.ReadUInt32(out block.parent); bits.ReadUInt32(out block.end); bits.ReadUInt32(out block.len); bits.ReadUInt32(out block.off); bits.ReadUInt16(out block.seg); bits.SkipCString(out block.name); bits.Position = stop; Scopes[scope++] = new PdbScope(this.Address, block, bits, out slotToken); bits.Position = (int)block.end; break; } case SYM.S_MANSLOT: uint typind; Slots[slot++] = new PdbSlot(bits, out typind); bits.Position = stop; break; case SYM.S_MANCONSTANT: Constants[constant++] = new PdbConstant(bits); bits.Position = stop; break; case SYM.S_UNAMESPACE: bits.ReadCString(out Namespaces[usedNs++]); bits.Position = stop; break; case SYM.S_END: bits.Position = stop; break; default: { //throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec); bits.Position = stop; break; } } } if (bits.Position != proc.end) { throw new PdbDebugException("Not at S_END"); } ushort esiz; ushort erec; bits.ReadUInt16(out esiz); bits.ReadUInt16(out erec); if (erec != (ushort)SYM.S_END) { throw new PdbDebugException("Missing S_END"); } } private void ReadCustomMetadata(BitAccess bits) { int savedPosition = bits.Position; byte version; bits.ReadUInt8(out version); if (version != 4) { throw new PdbDebugException("Unknown custom metadata item version: {0}", version); } byte kind; bits.ReadUInt8(out kind); bits.Align(4); uint numberOfBytesInItem; bits.ReadUInt32(out numberOfBytesInItem); switch (kind) { case 0: this.ReadUsingInfo(bits); break; case 1: break; // this.ReadForwardInfo(bits); break; case 2: break; // this.ReadForwardedToModuleInfo(bits); break; case 3: this.ReadIteratorLocals(bits); break; case 4: this.ReadForwardIterator(bits); break; default: throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind); } bits.Position = savedPosition + (int)numberOfBytesInItem; } private void ReadForwardIterator(BitAccess bits) { this.iteratorClass = bits.ReadString(); } private void ReadIteratorLocals(BitAccess bits) { uint numberOfLocals; bits.ReadUInt32(out numberOfLocals); } private void ReadUsingInfo(BitAccess bits) { ushort numberOfNamespaces; bits.ReadUInt16(out numberOfNamespaces); this.UsingCounts = new ushort[numberOfNamespaces]; for (ushort i = 0; i < numberOfNamespaces; i++) { bits.ReadUInt16(out this.UsingCounts[i]); } } internal class PdbFunctionsByAddress : IComparer { public int Compare(Object x, Object y) { PdbFunction fx = (PdbFunction)x; PdbFunction fy = (PdbFunction)y; if (fx.Segment < fy.Segment) { return -1; } else if (fx.Segment > fy.Segment) { return 1; } else if (fx.Address < fy.Address) { return -1; } else if (fx.Address > fy.Address) { return 1; } else { return 0; } } } internal class PdbFunctionsByAddressAndToken : IComparer { public int Compare(Object x, Object y) { PdbFunction fx = (PdbFunction)x; PdbFunction fy = (PdbFunction)y; if (fx.Segment < fy.Segment) { return -1; } else if (fx.Segment > fy.Segment) { return 1; } else if (fx.Address < fy.Address) { return -1; } else if (fx.Address > fy.Address) { return 1; } else { if (fx.Token < fy.Token) return -1; else if (fx.Token > fy.Token) return 1; else return 0; } } } } }
// 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 gagr = Google.Api.Gax.ResourceNames; using gciv = Google.Cloud.Iam.V1; using proto = Google.Protobuf; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.DevTools.ContainerAnalysis.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedContainerAnalysisClientTest { [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyResourceNames() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyResourceNamesAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyResourceNames() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyResourceNamesAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsResourceNames() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsResourceNamesAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityOccurrencesSummaryRequestObject() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary response = client.GetVulnerabilityOccurrencesSummary(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityOccurrencesSummaryRequestObjectAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityOccurrencesSummary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary responseCallSettings = await client.GetVulnerabilityOccurrencesSummaryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityOccurrencesSummary responseCancellationToken = await client.GetVulnerabilityOccurrencesSummaryAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityOccurrencesSummary() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary response = client.GetVulnerabilityOccurrencesSummary(request.Parent, request.Filter); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityOccurrencesSummaryAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityOccurrencesSummary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary responseCallSettings = await client.GetVulnerabilityOccurrencesSummaryAsync(request.Parent, request.Filter, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityOccurrencesSummary responseCancellationToken = await client.GetVulnerabilityOccurrencesSummaryAsync(request.Parent, request.Filter, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetVulnerabilityOccurrencesSummaryResourceNames() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummary(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary response = client.GetVulnerabilityOccurrencesSummary(request.ParentAsProjectName, request.Filter); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetVulnerabilityOccurrencesSummaryResourceNamesAsync() { moq::Mock<ContainerAnalysis.ContainerAnalysisClient> mockGrpcClient = new moq::Mock<ContainerAnalysis.ContainerAnalysisClient>(moq::MockBehavior.Strict); GetVulnerabilityOccurrencesSummaryRequest request = new GetVulnerabilityOccurrencesSummaryRequest { ParentAsProjectName = gagr::ProjectName.FromProject("[PROJECT]"), Filter = "filtere47ac9b2", }; VulnerabilityOccurrencesSummary expectedResponse = new VulnerabilityOccurrencesSummary { Counts = { new VulnerabilityOccurrencesSummary.Types.FixableTotalByDigest(), }, }; mockGrpcClient.Setup(x => x.GetVulnerabilityOccurrencesSummaryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<VulnerabilityOccurrencesSummary>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ContainerAnalysisClient client = new ContainerAnalysisClientImpl(mockGrpcClient.Object, null); VulnerabilityOccurrencesSummary responseCallSettings = await client.GetVulnerabilityOccurrencesSummaryAsync(request.ParentAsProjectName, request.Filter, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); VulnerabilityOccurrencesSummary responseCancellationToken = await client.GetVulnerabilityOccurrencesSummaryAsync(request.ParentAsProjectName, request.Filter, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2006 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= using System.IO; using Sharpen; namespace Com.Adobe.Xmp.Impl { /// <since>22.08.2006</since> public class FixASCIIControlsReader : PushbackReader { private const int StateStart = 0; private const int StateAmp = 1; private const int StateHash = 2; private const int StateHex = 3; private const int StateDig1 = 4; private const int StateError = 5; private const int BufferSize = 8; /// <summary>the state of the automaton</summary> private int state = StateStart; /// <summary>the result of the escaping sequence</summary> private int control = 0; /// <summary>count the digits of the sequence</summary> private int digits = 0; /// <summary>The look-ahead size is 6 at maximum (&amp;#xAB;)</summary> /// <seealso cref="System.IO.PushbackReader.PushbackReader(System.IO.StreamReader, int)"/> /// <param name="in">a Reader</param> public FixASCIIControlsReader(System.IO.StreamReader @in) : base(@in, BufferSize) { } /// <seealso cref="System.IO.StreamReader.Read(char[], int, int)"/> /// <exception cref="System.IO.IOException"/> public override int Read(char[] cbuf, int off, int len) { int readAhead = 0; int read = 0; int pos = off; char[] readAheadBuffer = new char[BufferSize]; bool available = true; while (available && read < len) { available = base.Read(readAheadBuffer, readAhead, 1) == 1; if (available) { char c = ProcessChar(readAheadBuffer[readAhead]); if (state == StateStart) { // replace control chars with space if (Utils.IsControlChar(c)) { c = ' '; } cbuf[pos++] = c; readAhead = 0; read++; } else { if (state == StateError) { Unread(readAheadBuffer, 0, readAhead + 1); readAhead = 0; } else { readAhead++; } } } else { if (readAhead > 0) { // handles case when file ends within excaped sequence Unread(readAheadBuffer, 0, readAhead); state = StateError; readAhead = 0; available = true; } } } return read > 0 || available ? read : -1; } /// <summary>Processes numeric escaped chars to find out if they are a control character.</summary> /// <param name="ch">a char</param> /// <returns>Returns the char directly or as replacement for the escaped sequence.</returns> private char ProcessChar(char ch) { switch (state) { case StateStart: { if (ch == '&') { state = StateAmp; } return ch; } case StateAmp: { if (ch == '#') { state = StateHash; } else { state = StateError; } return ch; } case StateHash: { if (ch == 'x') { control = 0; digits = 0; state = StateHex; } else { if ('0' <= ch && ch <= '9') { control = Sharpen.Extensions.Digit(ch, 10); digits = 1; state = StateDig1; } else { state = StateError; } } return ch; } case StateDig1: { if ('0' <= ch && ch <= '9') { control = control * 10 + Sharpen.Extensions.Digit(ch, 10); digits++; if (digits <= 5) { state = StateDig1; } else { state = StateError; } } else { // sequence too long if (ch == ';' && Utils.IsControlChar((char)control)) { state = StateStart; return (char)control; } else { state = StateError; } } return ch; } case StateHex: { if (('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F')) { control = control * 16 + Sharpen.Extensions.Digit(ch, 16); digits++; if (digits <= 4) { state = StateHex; } else { state = StateError; } } else { // sequence too long if (ch == ';' && Utils.IsControlChar((char)control)) { state = StateStart; return (char)control; } else { state = StateError; } } return ch; } case StateError: { state = StateStart; return ch; } default: { // not reachable return ch; } } } } }
#region Copyright // Copyright 2017 Gigya 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 // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Orleans.Hosting.Events; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.Testing.Shared.Helpers; using Gigya.ServiceContract.Attributes; using Gigya.ServiceContract.HttpService; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans; using Orleans.Concurrency; using Shouldly; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService { [StatelessWorker, Reentrant] public class CalculatorServiceGrain : Grain, ICalculatorServiceGrain { private readonly ILog _log; private readonly IEventPublisher _eventPublisher; private ICalculatorWorkerGrain Worker { get; set; } public CalculatorServiceGrain(ILog log, IEventPublisher eventPublisher) { _log = log; _eventPublisher = eventPublisher; } public override Task OnActivateAsync() { Worker = GrainFactory.GetGrain<ICalculatorWorkerGrain>(new Random(Guid.NewGuid().GetHashCode()).Next()); return base.OnActivateAsync(); } public Task<int> Add(int a, int b, bool shouldThrow = false) { return Worker.Add(a, b, shouldThrow); } public Task<string[]> GetAppDomainChain(int depth) { return Worker.GetAppDomainChain(depth); } public Task<Tuple<DateTime, DateTimeOffset>> ToUniversalTime(DateTime localDateTime, DateTimeOffset localDateTimeOffset) { return Worker.ToUniversalTime(localDateTime, localDateTimeOffset); } public async Task<Tuple<int, string, JObject>> AddWithOptions(JObject jObject, int optional1 = 5, string optional2 = "test", JObject optional3 = null) { return Tuple.Create(optional1, optional2, optional3); } public Task<JObject> Add(JObject jObject) { return Worker.Add(jObject); } public Task<JObjectWrapper> Add(JObjectWrapper jObjectW) { return Worker.Add(jObjectW); } public Task Do() { return Worker.Do(); } public Task<Wrapper> DoComplex(Wrapper wrapper) { return Worker.DoComplex(wrapper); } public Task<int> DoInt(int a) { return Worker.DoInt(a); } public Task<int> GetNextNum() { return Worker.GetNextNum(); } public Task<Revocable<int>> GetVersion(string id) { return Worker.GetVersion(id); } public Task LogData(string message) { _log.Warn(x => x(message)); return TaskDone.Done; } public Task LogPram(string sensitive, string notSensitive, string notExists, string @default) { return Task.FromResult(1); } public Task LogPram2(string sensitive, string notSensitive, string notExists, string @default) { return Task.FromResult(1); } public async Task<bool> IsLogParamSucceeded(List<string> sensitive, List<string> NoneSensitive, List<string> NotExists) { await Task.Delay(150); try { var eventPublisher = _eventPublisher as SpyEventPublisher; var serviceCallEvent = eventPublisher.Events.OfType<ServiceCallEvent>().Last(); foreach (var s in sensitive) { serviceCallEvent.EncryptedServiceMethodArguments.ShouldContain(x1 => x1.Value.ToString() == s); serviceCallEvent.UnencryptedServiceMethodArguments.ShouldNotContain(x1 => x1.Value.ToString() == s); } foreach (var s in NoneSensitive) { serviceCallEvent.UnencryptedServiceMethodArguments.ShouldContain(x1 => x1.Value.ToString() == s); serviceCallEvent.EncryptedServiceMethodArguments.ShouldNotContain(x1 => x1.Value.ToString() == s); } foreach (var n in NotExists) { serviceCallEvent.UnencryptedServiceMethodArguments.ShouldNotContain(x1 => x1.Value.ToString() == n); serviceCallEvent.EncryptedServiceMethodArguments.ShouldNotContain(x1 => x1.Value.ToString() == n); } } catch (Exception) { return false; } return true; } public async Task CreatePerson([LogFields] CalculatorServiceTests.Person person) { await Task.FromResult(1); } public async Task<bool> ValidatePersonLogFields([LogFields]CalculatorServiceTests.Person person) { await Task.Delay(150); var prefixClassName = typeof(CalculatorServiceTests.Person).Name; var dissectParams = DissectPropertyInfoMetadata.GetMemberWithSensitivity(person).Select(x => new { Member = x.Member, Value = x.Value, Sensitivity = x.Sensitivity ?? Sensitivity.Sensitive, NewPropertyName = AddPrifix(prefixClassName, x.Name) }).ToDictionary(x => x.NewPropertyName); var eventPublisher = _eventPublisher as SpyEventPublisher; var callEvent = eventPublisher.Events.OfType<ServiceCallEvent>().Last(); var nonSensitiveCount = dissectParams.Values.Count(x => x.Sensitivity == Sensitivity.NonSensitive); var sensitiveCount = dissectParams.Values.Count(x => x.Sensitivity == Sensitivity.Sensitive); nonSensitiveCount.ShouldBe(callEvent.UnencryptedServiceMethodArguments.Count()); sensitiveCount.ShouldBe(callEvent.EncryptedServiceMethodArguments.Count()); //Sensitive foreach (var argument in callEvent.EncryptedServiceMethodArguments) { var param = dissectParams[argument.Key]; if (param.Member.DeclaringType.IsClass == true && param.Member.DeclaringType != typeof(string)) { JsonConvert.SerializeObject(param.Value).ShouldBe(JsonConvert.SerializeObject(argument.Value)); //Json validation } else { param.Value.ShouldBe(argument.Value); } } //NonSensitive foreach (var argument in callEvent.UnencryptedServiceMethodArguments) { var param = dissectParams[argument.Key]; param.Value.ShouldBe(argument.Value); param.Sensitivity.ShouldBe(Sensitivity.NonSensitive); } return true; } public async Task RegexTestWithDefaultTimeoutDefault(int defaultTimeoutInSeconds) { var regex = new Regex("a"); regex.MatchTimeout.ShouldBe(TimeSpan.FromSeconds(defaultTimeoutInSeconds)); } private string AddPrifix(string prefix, string param) { return $"{prefix.Substring(0, 1).ToLower()}{prefix.Substring(1)}_{param}"; } public async Task LogGrainId() { var eventPublisher = _eventPublisher as SpyEventPublisher; await GrainFactory.GetGrain<ICalculatorServiceGrain>(0).Do(); await Task.Delay(150); var serviceCallEvent = eventPublisher.Events.OfType<GrainCallEvent>().Last(x=>x.TargetType==typeof(CalculatorServiceGrain).FullName); serviceCallEvent.GrainID.ShouldBe("0"); var id = await GrainFactory.GetGrain<IUserGrainWithGuid>(Guid.NewGuid()).GetIdentety(); await Task.Delay(150); serviceCallEvent = eventPublisher.Events.OfType<GrainCallEvent>().Last(x => x.TargetType == typeof(UserGrainWithGuid).FullName); serviceCallEvent.GrainID.ShouldBe(id); id = await GrainFactory.GetGrain<IUserGrainWithLong>(123).GetIdentety(); await Task.Delay(150); serviceCallEvent = eventPublisher.Events.OfType<GrainCallEvent>().Last(x => x.TargetType == typeof(UserGrainWithLong).FullName); serviceCallEvent.GrainID.ShouldBe("123"); id = await GrainFactory.GetGrain<IUserGrainWithString>("test").GetIdentety(); await Task.Delay(150); serviceCallEvent = eventPublisher.Events.OfType<GrainCallEvent>().Last(x => x.TargetType == typeof(UserGrainWithString).FullName); serviceCallEvent.GrainID.ShouldBe("test"); } } }
using System; using System.Xml.Linq; namespace WixSharp { /// <summary> /// Enumeration representing Generic* attributes of PermissionEx element /// </summary> [Flags] public enum GenericPermission { /// <summary> /// None does not map to a valid WiX representation /// </summary> None = 0, /// <summary> /// Maps to GenericExecute='yes' of PermissionEx /// </summary> Execute = 0x001, /// <summary> /// Maps to GenericWrite='yes' of PermissionEx /// </summary> Write = 0x010, /// <summary> /// Maps to GenericRead='yes' of PermissionEx /// </summary> Read = 0x100, /// <summary> /// Maps to GenericAll='yes' of PermissionEx /// </summary> All = Execute | Write | Read } /// <summary> /// Represents applying permission(s) to the containing File entity /// </summary> /// <remarks> /// DirPermission is a Wix# representation of WiX Util:PermissionEx /// </remarks> public class DirPermission : WixEntity { /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> /// </summary> /// <param name="user"></param> public DirPermission(string user) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> public DirPermission(string user, string domain) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="permission"></param> public DirPermission(string user, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; SetGenericPermission(permission); } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> /// <param name="permission"></param> public DirPermission(string user, string domain, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; SetGenericPermission(permission); } private void SetGenericPermission(GenericPermission permission) { if (permission == GenericPermission.All) { GenericAll = true; return; } if ((permission & GenericPermission.Execute) == GenericPermission.Execute) GenericExecute = true; if ((permission & GenericPermission.Write) == GenericPermission.Write) GenericWrite = true; if ((permission & GenericPermission.Read) == GenericPermission.Read) GenericRead = true; } /// <summary> /// Maps to the User property of PermissionEx /// </summary> public string User { get; set; } /// <summary> /// Maps to the Domain property of PermissionEx /// </summary> public string Domain { get; set; } /// <summary> /// Maps to the Append property of PermissionEx /// </summary> public bool? Append { get; set; } /// <summary> /// Maps to the ChangePermission property of PermissionEx /// </summary> public bool? ChangePermission { get; set; } /// <summary> /// Maps to the CreateChild property of PermissionEx /// </summary> public bool? CreateChild { get; set; } /// <summary> /// Maps to the CreateFile property of PermissionEx /// </summary> public bool? CreateFile { get; set; } /// <summary> /// Maps to the CreateLink property of PermissionEx /// </summary> public bool? CreateLink { get; set; } /// <summary> /// Maps to the CreateSubkeys property of PermissionEx /// </summary> public bool? CreateSubkeys { get; set; } /// <summary> /// Maps to the Delete property of PermissionEx /// </summary> public bool? Delete { get; set; } /// <summary> /// Maps to the DeleteChild property of PermissionEx /// </summary> public bool? DeleteChild { get; set; } /// <summary> /// Maps to the EnumerateSubkeys property of PermissionEx /// </summary> public bool? EnumerateSubkeys { get; set; } /// <summary> /// Maps to the Execute property of PermissionEx /// </summary> public bool? Execute { get; set; } /// <summary> /// Maps to the GenericAll property of PermissionEx /// </summary> public bool? GenericAll { get; set; } /// <summary> /// Maps to the GenericExecute property of PermissionEx /// </summary> public bool? GenericExecute { get; set; } /// <summary> /// Maps to the GenericRead property of PermissionEx /// </summary> public bool? GenericRead { get; set; } /// <summary> /// Maps to the GenericWrite property of PermissionEx /// </summary> public bool? GenericWrite { get; set; } /// <summary> /// Maps to the Notify property of PermissionEx /// </summary> public bool? Notify { get; set; } /// <summary> /// Maps to the Read property of PermissionEx /// </summary> public bool? Read { get; set; } /// <summary> /// Maps to the Readattributes property of PermissionEx /// </summary> public bool? Readattributes { get; set; } /// <summary> /// Maps to the ReadExtendedAttributes property of PermissionEx /// </summary> public bool? ReadExtendedAttributes { get; set; } /// <summary> /// Maps to the ReadPermission property of PermissionEx /// </summary> public bool? ReadPermission { get; set; } /// <summary> /// Maps to the Synchronize property of PermissionEx /// </summary> public bool? Synchronize { get; set; } /// <summary> /// Maps to the TakeOwnership property of PermissionEx /// </summary> public bool? TakeOwnership { get; set; } /// <summary> /// Maps to the Traverse property of PermissionEx /// </summary> public bool? Traverse { get; set; } /// <summary> /// Maps to the Write property of PermissionEx /// </summary> public bool? Write { get; set; } /// <summary> /// Maps to the WriteAttributes property of PermissionEx /// </summary> public bool? WriteAttributes { get; set; } /// <summary> /// Maps to the WriteExtendedAttributes property of PermissionEx /// </summary> public bool? WriteExtendedAttributes { get; set; } } /// <summary> /// Represents applying permission(s) to the containing File entity /// </summary> /// <remarks> /// FilePermission is a Wix# representation of WiX Util:PermissionEx /// </remarks> public class FilePermission : WixEntity { /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> /// </summary> /// <param name="user"></param> public FilePermission(string user) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> public FilePermission(string user, string domain) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="permission"></param> public FilePermission(string user, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; SetGenericPermission(permission); } /// <summary> /// Creates a FilePermission instance for <paramref name="user"/>@<paramref name="domain"/> with generic permissions described by <paramref name="permission"/> /// </summary> /// <param name="user"></param> /// <param name="domain"></param> /// <param name="permission"></param> public FilePermission(string user, string domain, GenericPermission permission) { if (string.IsNullOrEmpty(user)) throw new ArgumentNullException("user", "User is a required value for Permission"); User = user; Domain = domain; SetGenericPermission(permission); } private void SetGenericPermission(GenericPermission permission) { if (permission == GenericPermission.All) { GenericAll = true; return; } if ((permission & GenericPermission.Execute) == GenericPermission.Execute) GenericExecute = true; if ((permission & GenericPermission.Write) == GenericPermission.Write) GenericWrite = true; if ((permission & GenericPermission.Read) == GenericPermission.Read) GenericRead = true; } /// <summary> /// Maps to the User property of PermissionEx /// </summary> public string User { get; set; } /// <summary> /// Maps to the Domain property of PermissionEx /// </summary> public string Domain { get; set; } /// <summary> /// Maps to the Append property of PermissionEx /// </summary> public bool? Append { get; set; } /// <summary> /// Maps to the ChangePermission property of PermissionEx /// </summary> public bool? ChangePermission { get; set; } /// <summary> /// Maps to the CreateLink property of PermissionEx /// </summary> public bool? CreateLink { get; set; } /// <summary> /// Maps to the CreateSubkeys property of PermissionEx /// </summary> public bool? CreateSubkeys { get; set; } /// <summary> /// Maps to the Delete property of PermissionEx /// </summary> public bool? Delete { get; set; } /// <summary> /// Maps to the EnumerateSubkeys property of PermissionEx /// </summary> public bool? EnumerateSubkeys { get; set; } /// <summary> /// Maps to the Execute property of PermissionEx /// </summary> public bool? Execute { get; set; } /// <summary> /// Maps to the GenericAll property of PermissionEx /// </summary> public bool? GenericAll { get; set; } /// <summary> /// Maps to the GenericExecute property of PermissionEx /// </summary> public bool? GenericExecute { get; set; } /// <summary> /// Maps to the GenericRead property of PermissionEx /// </summary> public bool? GenericRead { get; set; } /// <summary> /// Maps to the GenericWrite property of PermissionEx /// </summary> public bool? GenericWrite { get; set; } /// <summary> /// Maps to the Notify property of PermissionEx /// </summary> public bool? Notify { get; set; } /// <summary> /// Maps to the Read property of PermissionEx /// </summary> public bool? Read { get; set; } /// <summary> /// Maps to the Readattributes property of PermissionEx /// </summary> public bool? Readattributes { get; set; } /// <summary> /// Maps to the ReadExtendedAttributes property of PermissionEx /// </summary> public bool? ReadExtendedAttributes { get; set; } /// <summary> /// Maps to the ReadPermission property of PermissionEx /// </summary> public bool? ReadPermission { get; set; } /// <summary> /// Maps to the Synchronize property of PermissionEx /// </summary> public bool? Synchronize { get; set; } /// <summary> /// Maps to the TakeOwnership property of PermissionEx /// </summary> public bool? TakeOwnership { get; set; } /// <summary> /// Maps to the Write property of PermissionEx /// </summary> public bool? Write { get; set; } /// <summary> /// Maps to the WriteAttributes property of PermissionEx /// </summary> public bool? WriteAttributes { get; set; } /// <summary> /// Maps to the WriteExtendedAttributes property of PermissionEx /// </summary> public bool? WriteExtendedAttributes { get; set; } } internal static class PermissionExt { static void Do<T>(this T? nullable, Action<T> action) where T : struct { if (!nullable.HasValue) return; action(nullable.Value); } /// <summary> /// Adds attributes to <paramref name="permissionElement"/> representing the state of <paramref name="dirPermission"/> /// </summary> /// <param name="dirPermission"></param> /// <param name="permissionElement"></param> public static void EmitAttributes(this DirPermission dirPermission, XElement permissionElement) { //required permissionElement.SetAttributeValue("User", dirPermission.User); //optional if (dirPermission.Domain.IsNotEmpty()) permissionElement.SetAttributeValue("Domain", dirPermission.Domain); //optional dirPermission.Append.Do(b => permissionElement.SetAttributeValue("Append", b.ToYesNo())); dirPermission.ChangePermission.Do(b => permissionElement.SetAttributeValue("ChangePermission", b.ToYesNo())); dirPermission.CreateLink.Do(b => permissionElement.SetAttributeValue("CreateLink", b.ToYesNo())); dirPermission.CreateChild.Do(b => permissionElement.SetAttribute("CreateChild", b.ToYesNo())); dirPermission.CreateFile.Do(b => permissionElement.SetAttribute("CreateFile", b.ToYesNo())); dirPermission.CreateSubkeys.Do(b => permissionElement.SetAttributeValue("CreateSubkeys", b.ToYesNo())); dirPermission.Delete.Do(b => permissionElement.SetAttributeValue("Delete", b.ToYesNo())); dirPermission.DeleteChild.Do(b => permissionElement.SetAttribute("DeleteChild", b.ToYesNo())); dirPermission.EnumerateSubkeys.Do(b => permissionElement.SetAttributeValue("EnumerateSubkeys", b.ToYesNo())); dirPermission.Execute.Do(b => permissionElement.SetAttributeValue("Execute", b.ToYesNo())); dirPermission.GenericAll.Do(b => permissionElement.SetAttributeValue("GenericAll", b.ToYesNo())); dirPermission.GenericExecute.Do(b => permissionElement.SetAttributeValue("GenericExecute", b.ToYesNo())); dirPermission.GenericRead.Do(b => permissionElement.SetAttributeValue("GenericRead", b.ToYesNo())); dirPermission.GenericWrite.Do(b => permissionElement.SetAttributeValue("GenericWrite", b.ToYesNo())); dirPermission.Notify.Do(b => permissionElement.SetAttributeValue("Notify", b.ToYesNo())); dirPermission.Read.Do(b => permissionElement.SetAttributeValue("Read", b.ToYesNo())); dirPermission.Readattributes.Do(b => permissionElement.SetAttributeValue("Readattributes", b.ToYesNo())); dirPermission.ReadExtendedAttributes.Do(b => permissionElement.SetAttributeValue("ReadExtendedAttributes", b.ToYesNo())); dirPermission.ReadPermission.Do(b => permissionElement.SetAttributeValue("ReadPermission", b.ToYesNo())); dirPermission.Synchronize.Do(b => permissionElement.SetAttributeValue("Synchronize", b.ToYesNo())); dirPermission.TakeOwnership.Do(b => permissionElement.SetAttributeValue("TakeOwnership", b.ToYesNo())); dirPermission.Traverse.Do(b => permissionElement.SetAttribute("Traverse", b.ToYesNo())); dirPermission.Write.Do(b => permissionElement.SetAttributeValue("Write", b.ToYesNo())); dirPermission.WriteAttributes.Do(b => permissionElement.SetAttributeValue("WriteAttributes", b.ToYesNo())); dirPermission.WriteExtendedAttributes.Do(b => permissionElement.SetAttributeValue("WriteExtendedAttributes", b.ToYesNo())); } /// <summary> /// Adds attributes to <paramref name="permissionElement"/> representing the state of <paramref name="filePermission"/> /// </summary> /// <param name="filePermission"></param> /// <param name="permissionElement"></param> public static void EmitAttributes(this FilePermission filePermission, XElement permissionElement) { //required permissionElement.SetAttributeValue("User", filePermission.User); //optional if (filePermission.Domain.IsNotEmpty()) permissionElement.SetAttributeValue("Domain", filePermission.Domain); //optional filePermission.Append.Do(b => permissionElement.SetAttributeValue("Append", b.ToYesNo())); filePermission.ChangePermission.Do(b => permissionElement.SetAttributeValue("ChangePermission", b.ToYesNo())); filePermission.CreateLink.Do(b => permissionElement.SetAttributeValue("CreateLink", b.ToYesNo())); filePermission.CreateSubkeys.Do(b => permissionElement.SetAttributeValue("CreateSubkeys", b.ToYesNo())); filePermission.Delete.Do(b => permissionElement.SetAttributeValue("Delete", b.ToYesNo())); filePermission.EnumerateSubkeys.Do(b => permissionElement.SetAttributeValue("EnumerateSubkeys", b.ToYesNo())); filePermission.Execute.Do(b => permissionElement.SetAttributeValue("Execute", b.ToYesNo())); filePermission.GenericAll.Do(b => permissionElement.SetAttributeValue("GenericAll", b.ToYesNo())); filePermission.GenericExecute.Do(b => permissionElement.SetAttributeValue("GenericExecute", b.ToYesNo())); filePermission.GenericRead.Do(b => permissionElement.SetAttributeValue("GenericRead", b.ToYesNo())); filePermission.GenericWrite.Do(b => permissionElement.SetAttributeValue("GenericWrite", b.ToYesNo())); filePermission.Notify.Do(b => permissionElement.SetAttributeValue("Notify", b.ToYesNo())); filePermission.Read.Do(b => permissionElement.SetAttributeValue("Read", b.ToYesNo())); filePermission.Readattributes.Do(b => permissionElement.SetAttributeValue("Readattributes", b.ToYesNo())); filePermission.ReadExtendedAttributes.Do(b => permissionElement.SetAttributeValue("ReadExtendedAttributes", b.ToYesNo())); filePermission.ReadPermission.Do(b => permissionElement.SetAttributeValue("ReadPermission", b.ToYesNo())); filePermission.Synchronize.Do(b => permissionElement.SetAttributeValue("Synchronize", b.ToYesNo())); filePermission.TakeOwnership.Do(b => permissionElement.SetAttributeValue("TakeOwnership", b.ToYesNo())); filePermission.Write.Do(b => permissionElement.SetAttributeValue("Write", b.ToYesNo())); filePermission.WriteAttributes.Do(b => permissionElement.SetAttributeValue("WriteAttributes", b.ToYesNo())); filePermission.WriteExtendedAttributes.Do(b => permissionElement.SetAttributeValue("WriteExtendedAttributes", b.ToYesNo())); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Concurrency; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Configuration; using RunState = Orleans.Configuration.StreamLifecycleOptions.RunState; using Orleans.Internal; using System.Threading; using Orleans.Streams.Filtering; using Microsoft.Extensions.DependencyInjection; namespace Orleans.Streams { internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener { private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5); private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap; private readonly string streamProviderName; private readonly IStreamPubSub pubSub; private readonly StreamPullingAgentOptions options; private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications. private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private int latestRingNotificationSequenceNumber; private int latestCommandNumber; private IQueueAdapter queueAdapter; private readonly IQueueAdapterCache queueAdapterCache; private IStreamQueueBalancer queueBalancer; private readonly IStreamFilter streamFilter; private readonly IQueueAdapterFactory adapterFactory; private RunState managerState; private IDisposable queuePrintTimer; private int nextAgentId; private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } } internal PersistentStreamPullingManager( SystemTargetGrainId managerId, string strProviderName, IStreamPubSub streamPubSub, IQueueAdapterFactory adapterFactory, IStreamQueueBalancer streamQueueBalancer, IStreamFilter streamFilter, StreamPullingAgentOptions options, ILoggerFactory loggerFactory, SiloAddress siloAddress) : base(managerId, siloAddress, lowPriority: false, loggerFactory) { if (string.IsNullOrWhiteSpace(strProviderName)) { throw new ArgumentNullException("strProviderName"); } if (streamPubSub == null) { throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null"); } if (streamQueueBalancer == null) { throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null"); } queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>(); streamProviderName = strProviderName; pubSub = streamPubSub; this.options = options; nonReentrancyGuarantor = new AsyncSerialExecutor(); latestRingNotificationSequenceNumber = 0; latestCommandNumber = 0; queueBalancer = streamQueueBalancer; this.streamFilter = streamFilter; this.adapterFactory = adapterFactory; queueAdapterCache = adapterFactory.GetQueueAdapterCache(); logger = loggerFactory.CreateLogger($"{GetType().FullName}.{streamProviderName}"); Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName); this.loggerFactory = loggerFactory; IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count); } public async Task Initialize(Immutable<IQueueAdapter> qAdapter) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); Log(ErrorCode.PersistentStreamPullingManager_02, "Init."); // Remove cast once we cleanup queueAdapter = qAdapter.Value; await this.queueBalancer.Initialize(this.adapterFactory.GetStreamQueueMapper()); queueBalancer.SubscribeToQueueDistributionChangeEvents(this); List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues))); queuePrintTimer = this.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD); managerState = RunState.Initialized; } public async Task Stop() { await StopAgents(); if (queuePrintTimer != null) { queuePrintTimer.Dispose(); this.queuePrintTimer = null; } await this.queueBalancer.Shutdown(); this.queueBalancer = null; } public async Task StartAgents() { managerState = RunState.AgentsStarted; List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues)); await AddNewQueues(myQueues, true); Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents."); } public async Task StopAgents() { managerState = RunState.AgentsStopped; List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList(); Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove)); await RemoveQueues(queuesToRemove); Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents."); } /// <summary> /// Actions to take when the queue distribution changes due to a failure or a join. /// Since this pulling manager is system target and queue distribution change notifications /// are delivered to it as grain method calls, notifications are not reentrant. To simplify /// notification handling we execute them serially, in a non-reentrant way. We also suppress /// and don't execute an older notification if a newer one was already delivered. /// </summary> public Task QueueDistributionChangeNotification() { return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification()); } public Task HandleQueueDistributionChangeNotification() { latestRingNotificationSequenceNumber++; int notificationSeqNumber = latestRingNotificationSequenceNumber; Log(ErrorCode.PersistentStreamPullingManager_04, "Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState); if (managerState == RunState.AgentsStopped) { return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them. } return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous notification since already got a newer range update notification. if (notificationSeqNumber < latestRingNotificationSequenceNumber) { Log(ErrorCode.PersistentStreamPullingManager_05, "Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " + "(already have notification number {1}).", notificationSeqNumber, latestRingNotificationSequenceNumber); return Task.CompletedTask; } if (managerState == RunState.AgentsStopped) { return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them. } return QueueDistributionChangeNotification(notificationSeqNumber); }); } private async Task QueueDistributionChangeNotification(int notificationSeqNumber) { HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet(); Log(ErrorCode.PersistentStreamPullingManager_06, "Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues)); try { Task t1 = AddNewQueues(currentQueues, false); List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList(); Task t2 = RemoveQueues(queuesToRemove); await Task.WhenAll(t1, t2); } finally { Log(ErrorCode.PersistentStreamPullingManager_16, "Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } /// <summary> /// Take responsibility for a set of new queues that were assigned to me via a new range. /// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents. /// ERROR HANDLING: /// The responsibility to handle initialization and shutdown failures is inside the Agents code. /// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded. /// Same applies to shutdown. /// </summary> /// <param name="myQueues"></param> /// <param name="failOnInit"></param> /// <returns></returns> private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit) { // Create agents for queues in range that we don't yet have. // First create them and store in local queuesToAgentsMap. // Only after that Initialize them all. var agents = new List<PersistentStreamPullingAgent>(); foreach (var queueId in myQueues) { if (queuesToAgentsMap.ContainsKey(queueId)) continue; try { var agentIdNumber = Interlocked.Increment(ref nextAgentId); var agentId = SystemTargetGrainId.Create(Constants.StreamPullingAgentType, this.Silo, $"{streamProviderName}_{agentIdNumber}_{queueId.ToStringWithHashCode()}"); var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, this.loggerFactory, pubSub, streamFilter, queueId, this.options, this.Silo); this.ActivationServices.GetRequiredService<Catalog>().RegisterSystemTarget(agent); queuesToAgentsMap.Add(queueId, agent); agents.Add(agent); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc); // What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down. // If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers. if (failOnInit) throw; } } try { var initTasks = new List<Task>(); foreach (var agent in agents) { initTasks.Add(InitAgent(agent)); } await Task.WhenAll(initTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } private async Task InitAgent(PersistentStreamPullingAgent agent) { // Init the agent only after it was registered locally. var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); var queueAdapterCacheAsImmutable = queueAdapterCache != null ? queueAdapterCache.AsImmutable() : new Immutable<IQueueAdapterCache>(null); IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(agent.QueueId); // Need to call it as a grain reference. var task = OrleansTaskExtentions.SafeExecute(() => agentGrainRef.Initialize(queueAdapter.AsImmutable(), queueAdapterCacheAsImmutable, deliveryFailureHandler.AsImmutable())); await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId)); } private async Task RemoveQueues(List<QueueId> queuesToRemove) { if (queuesToRemove.Count == 0) { return; } // Stop the agents that for queues that are not in my range anymore. var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count); Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString())); var removeTasks = new List<Task>(); foreach (var queueId in queuesToRemove) { PersistentStreamPullingAgent agent; if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue; agents.Add(agent); queuesToAgentsMap.Remove(queueId); var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown); task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11, String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId)); removeTasks.Add(task); } try { await Task.WhenAll(removeTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } var catalog = ActivationServices.GetRequiredService<Catalog>(); foreach (var agent in agents) { try { catalog.UnregisterSystemTarget(agent); } catch (Exception exc) { Log(ErrorCode.PersistentStreamPullingManager_12, "Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message); } } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg) { latestCommandNumber++; int commandSeqNumber = latestCommandNumber; try { Log(ErrorCode.PersistentStreamPullingManager_13, String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.", command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState)); switch (command) { case PersistentStreamProviderCommand.StartAgents: case PersistentStreamProviderCommand.StopAgents: await QueueCommandForExecution(command, commandSeqNumber); return null; case PersistentStreamProviderCommand.GetAgentsState: return managerState; case PersistentStreamProviderCommand.GetNumberRunningAgents: return NumberRunningAgents; default: throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command)); } } finally { Log(ErrorCode.PersistentStreamPullingManager_15, String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.", command, commandSeqNumber, managerState, NumberRunningAgents)); } } // Start and Stop commands are composite commands that take multiple turns. // Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification. // Therefore, we serialize them all via the same nonReentrancyGuarantor. private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber) { return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous command since already got a newer command. if (commandSeqNumber < latestCommandNumber) { Log(ErrorCode.PersistentStreamPullingManager_15, "Skipping execution of command number {0} since already received a later command (already have command number {1}).", commandSeqNumber, latestCommandNumber); return Task.CompletedTask; } switch (command) { case PersistentStreamProviderCommand.StartAgents: return StartAgents(); case PersistentStreamProviderCommand.StopAgents: return StopAgents(); default: throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command)); } }); } private static string PrintQueues(ICollection<QueueId> myQueues) { return Utils.EnumerableToString(myQueues, q => q.ToString()); } // Just print our queue assignment periodicaly, for easy monitoring. private Task AsyncTimerCallback(object state) { Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint, "I am responsible for a total of {0} queues on stream provider {1}: {2}.", NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys)); return Task.CompletedTask; } private void Log(ErrorCode logCode, string format, params object[] args) { logger.Info(logCode, format, args); } } }
// CRC32.cs // ------------------------------------------------------------------ // // Copyright (c) 2011 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // Last Saved: <2011-August-02 18:25:54> // // ------------------------------------------------------------------ // // This module defines the CRC32 class, which can do the CRC32 algorithm, using // arbitrary starting polynomials, and bit reversal. The bit reversal is what // distinguishes this CRC-32 used in BZip2 from the CRC-32 that is used in PKZIP // files, or GZIP files. This class does both. // // ------------------------------------------------------------------ using System; using Interop = System.Runtime.InteropServices; namespace Ionic.Crc { /// <summary> /// Computes a CRC-32. The CRC-32 algorithm is parameterized - you /// can set the polynomial and enable or disable bit /// reversal. This can be used for GZIP, BZip2, or ZIP. /// </summary> /// <remarks> /// This type is used internally by DotNetZip; it is generally not used /// directly by applications wishing to create, read, or manipulate zip /// archive files. /// </remarks> public class CRC32 { /// <summary> /// Indicates the total number of bytes applied to the CRC. /// </summary> public Int64 TotalBytesRead { get { return _TotalBytesRead; } } /// <summary> /// Indicates the current CRC for all blocks slurped in. /// </summary> public Int32 Crc32Result { get { return unchecked((Int32)(~_register)); } } /// <summary> /// Returns the CRC32 for the specified stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32(System.IO.Stream input) { return GetCrc32AndCopy(input, null); } /// <summary> /// Returns the CRC32 for the specified stream, and writes the input into the /// output stream. /// </summary> /// <param name="input">The stream over which to calculate the CRC32</param> /// <param name="output">The stream into which to deflate the input</param> /// <returns>the CRC32 calculation</returns> public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) { if (input == null) throw new Exception("The input stream must not be null."); unchecked { byte[] buffer = new byte[BUFFER_SIZE]; int readSize = BUFFER_SIZE; _TotalBytesRead = 0; int count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; while (count > 0) { SlurpBlock(buffer, 0, count); count = input.Read(buffer, 0, readSize); if (output != null) output.Write(buffer, 0, count); _TotalBytesRead += count; } return (Int32)(~_register); } } /// <summary> /// Get the CRC32 for the given (word,byte) combo. This is a /// computation defined by PKzip for PKZIP 2.0 (weak) encryption. /// </summary> /// <param name="W">The word to start with.</param> /// <param name="B">The byte to combine it with.</param> /// <returns>The CRC-ized result.</returns> public Int32 ComputeCrc32(Int32 W, byte B) { return _InternalComputeCrc32((UInt32)W, B); } internal Int32 _InternalComputeCrc32(UInt32 W, byte B) { return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8)); } /// <summary> /// Update the value for the running CRC32 using the given block of bytes. /// This is useful when using the CRC32() class in a Stream. /// </summary> /// <param name="block">block of bytes to slurp</param> /// <param name="offset">starting point in the block</param> /// <param name="count">how many bytes within the block to slurp</param> public void SlurpBlock(byte[] block, int offset, int count) { if (block == null) throw new Exception("The data buffer must not be null."); // bzip algorithm for (int i = 0; i < count; i++) { int x = offset + i; byte b = block[x]; if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } _TotalBytesRead += count; } /// <summary> /// Process one byte in the CRC. /// </summary> /// <param name = "b">the byte to include into the CRC . </param> public void UpdateCRC(byte b) { if (this.reverseBits) { UInt32 temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[temp]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[temp]; } } /// <summary> /// Process a run of N identical bytes into the CRC. /// </summary> /// <remarks> /// <para> /// This method serves as an optimization for updating the CRC when a /// run of identical bytes is found. Rather than passing in a buffer of /// length n, containing all identical bytes b, this method accepts the /// byte value and the length of the (virtual) buffer - the length of /// the run. /// </para> /// </remarks> /// <param name = "b">the byte to include into the CRC. </param> /// <param name = "n">the number of times that byte should be repeated. </param> public void UpdateCRC(byte b, int n) { while (n-- > 0) { if (this.reverseBits) { uint temp = (_register >> 24) ^ b; _register = (_register << 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } else { UInt32 temp = (_register & 0x000000FF) ^ b; _register = (_register >> 8) ^ crc32Table[(temp >= 0) ? temp : (temp + 256)]; } } } private static uint ReverseBits(uint data) { unchecked { uint ret = data; ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555; ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333; ret = (ret & 0x0F0F0F0F) << 4 | (ret >> 4) & 0x0F0F0F0F; ret = (ret << 24) | ((ret & 0xFF00) << 8) | ((ret >> 8) & 0xFF00) | (ret >> 24); return ret; } } private static byte ReverseBits(byte data) { unchecked { uint u = (uint)data * 0x00020202; uint m = 0x01044010; uint s = u & m; uint t = (u << 2) & (m << 1); return (byte)((0x01001001 * (s + t)) >> 24); } } private void GenerateLookupTable() { crc32Table = new UInt32[256]; unchecked { UInt32 dwCrc; byte i = 0; do { dwCrc = i; for (byte j = 8; j > 0; j--) { if ((dwCrc & 1) == 1) { dwCrc = (dwCrc >> 1) ^ dwPolynomial; } else { dwCrc >>= 1; } } if (reverseBits) { crc32Table[ReverseBits(i)] = ReverseBits(dwCrc); } else { crc32Table[i] = dwCrc; } i++; } while (i!=0); } #if VERBOSE Console.WriteLine(); Console.WriteLine("private static readonly UInt32[] crc32Table = {"); for (int i = 0; i < crc32Table.Length; i+=4) { Console.Write(" "); for (int j=0; j < 4; j++) { Console.Write(" 0x{0:X8}U,", crc32Table[i+j]); } Console.WriteLine(); } Console.WriteLine("};"); Console.WriteLine(); #endif } private uint gf2_matrix_times(uint[] matrix, uint vec) { uint sum = 0; int i=0; while (vec != 0) { if ((vec & 0x01)== 0x01) sum ^= matrix[i]; vec >>= 1; i++; } return sum; } private void gf2_matrix_square(uint[] square, uint[] mat) { for (int i = 0; i < 32; i++) square[i] = gf2_matrix_times(mat, mat[i]); } /// <summary> /// Combines the given CRC32 value with the current running total. /// </summary> /// <remarks> /// This is useful when using a divide-and-conquer approach to /// calculating a CRC. Multiple threads can each calculate a /// CRC32 on a segment of the data, and then combine the /// individual CRC32 values at the end. /// </remarks> /// <param name="crc">the crc value to be combined with this one</param> /// <param name="length">the length of data the CRC value was calculated on</param> public void Combine(int crc, int length) { uint[] even = new uint[32]; // even-power-of-two zeros operator uint[] odd = new uint[32]; // odd-power-of-two zeros operator if (length == 0) return; uint crc1= ~_register; uint crc2= (uint) crc; // put operator for one zero bit in odd odd[0] = this.dwPolynomial; // the CRC-32 polynomial uint row = 1; for (int i = 1; i < 32; i++) { odd[i] = row; row <<= 1; } // put operator for two zero bits in even gf2_matrix_square(even, odd); // put operator for four zero bits in odd gf2_matrix_square(odd, even); uint len2 = (uint) length; // apply len2 zeros to crc1 (first square will put the operator for one // zero byte, eight zero bits, in even) do { // apply zeros operator for this bit of len2 gf2_matrix_square(even, odd); if ((len2 & 1)== 1) crc1 = gf2_matrix_times(even, crc1); len2 >>= 1; if (len2 == 0) break; // another iteration of the loop with odd and even swapped gf2_matrix_square(odd, even); if ((len2 & 1)==1) crc1 = gf2_matrix_times(odd, crc1); len2 >>= 1; } while (len2 != 0); crc1 ^= crc2; _register= ~crc1; //return (int) crc1; return; } /// <summary> /// Create an instance of the CRC32 class using the default settings: no /// bit reversal, and a polynomial of 0xEDB88320. /// </summary> public CRC32() : this(false) { } /// <summary> /// Create an instance of the CRC32 class, specifying whether to reverse /// data bits or not. /// </summary> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here. In the CRC-32 used by GZIP and PKZIP, the bits are not /// reversed; Therefore if you want a CRC32 with compatibility with /// those, you should pass false. /// </para> /// </remarks> public CRC32(bool reverseBits) : this( unchecked((int)0xEDB88320), reverseBits) { } /// <summary> /// Create an instance of the CRC32 class, specifying the polynomial and /// whether to reverse data bits or not. /// </summary> /// <param name='polynomial'> /// The polynomial to use for the CRC, expressed in the reversed (LSB) /// format: the highest ordered bit in the polynomial value is the /// coefficient of the 0th power; the second-highest order bit is the /// coefficient of the 1 power, and so on. Expressed this way, the /// polynomial for the CRC-32C used in IEEE 802.3, is 0xEDB88320. /// </param> /// <param name='reverseBits'> /// specify true if the instance should reverse data bits. /// </param> /// /// <remarks> /// <para> /// In the CRC-32 used by BZip2, the bits are reversed. Therefore if you /// want a CRC32 with compatibility with BZip2, you should pass true /// here for the <c>reverseBits</c> parameter. In the CRC-32 used by /// GZIP and PKZIP, the bits are not reversed; Therefore if you want a /// CRC32 with compatibility with those, you should pass false for the /// <c>reverseBits</c> parameter. /// </para> /// </remarks> public CRC32(int polynomial, bool reverseBits) { this.reverseBits = reverseBits; this.dwPolynomial = (uint) polynomial; this.GenerateLookupTable(); } /// <summary> /// Reset the CRC-32 class - clear the CRC "remainder register." /// </summary> /// <remarks> /// <para> /// Use this when employing a single instance of this class to compute /// multiple, distinct CRCs on multiple, distinct data blocks. /// </para> /// </remarks> public void Reset() { _register = 0xFFFFFFFFU; } // private member vars private UInt32 dwPolynomial; private Int64 _TotalBytesRead; private bool reverseBits; private UInt32[] crc32Table; private const int BUFFER_SIZE = 8192; private UInt32 _register = 0xFFFFFFFFU; } /// <summary> /// A Stream that calculates a CRC32 (a checksum) on all bytes read, /// or on all bytes written. /// </summary> /// /// <remarks> /// <para> /// This class can be used to verify the CRC of a ZipEntry when /// reading from a stream, or to calculate a CRC when writing to a /// stream. The stream should be used to either read, or write, but /// not both. If you intermix reads and writes, the results are not /// defined. /// </para> /// /// <para> /// This class is intended primarily for use internally by the /// DotNetZip library. /// </para> /// </remarks> public class CrcCalculatorStream : System.IO.Stream, System.IDisposable { private static readonly Int64 UnsetLengthLimit = -99; internal System.IO.Stream _innerStream; private CRC32 _Crc32; private Int64 _lengthLimit = -99; private bool _leaveOpen; /// <summary> /// The default constructor. /// </summary> /// <remarks> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). The stream uses the default CRC32 /// algorithm, which implies a polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> public CrcCalculatorStream(System.IO.Stream stream) : this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null) { } /// <summary> /// The constructor allows the caller to specify how to handle the /// underlying stream at close. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen) : this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null) { } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read. /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// <para> /// Instances returned from this constructor will leave the underlying /// stream open upon Close(). /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length) : this(true, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(). /// </summary> /// <remarks> /// <para> /// The stream uses the default CRC32 algorithm, which implies a /// polynomial of 0xEDB88320. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen) : this(leaveOpen, length, stream, null) { if (length < 0) throw new ArgumentException("length"); } /// <summary> /// A constructor allowing the specification of the length of the stream /// to read, as well as whether to keep the underlying stream open upon /// Close(), and the CRC32 instance to use. /// </summary> /// <remarks> /// <para> /// The stream uses the specified CRC32 instance, which allows the /// application to specify how the CRC gets calculated. /// </para> /// </remarks> /// <param name="stream">The underlying stream</param> /// <param name="length">The length of the stream to slurp</param> /// <param name="leaveOpen">true to leave the underlying stream /// open upon close of the <c>CrcCalculatorStream</c>; false otherwise.</param> /// <param name="crc32">the CRC32 instance to use to calculate the CRC32</param> public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen, CRC32 crc32) : this(leaveOpen, length, stream, crc32) { if (length < 0) throw new ArgumentException("length"); } // This ctor is private - no validation is done here. This is to allow the use // of a (specific) negative value for the _lengthLimit, to indicate that there // is no length set. So we validate the length limit in those ctors that use an // explicit param, otherwise we don't validate, because it could be our special // value. private CrcCalculatorStream (bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32) : base() { _innerStream = stream; _Crc32 = crc32 ?? new CRC32(); _lengthLimit = length; _leaveOpen = leaveOpen; } /// <summary> /// Gets the total number of bytes run through the CRC32 calculator. /// </summary> /// /// <remarks> /// This is either the total number of bytes read, or the total number of /// bytes written, depending on the direction of this stream. /// </remarks> public Int64 TotalBytesSlurped { get { return _Crc32.TotalBytesRead; } } /// <summary> /// Provides the current CRC for all blocks slurped in. /// </summary> /// <remarks> /// <para> /// The running total of the CRC is kept as data is written or read /// through the stream. read this property after all reads or writes to /// get an accurate CRC for the entire stream. /// </para> /// </remarks> public Int32 Crc { get { return _Crc32.Crc32Result; } } /// <summary> /// Indicates whether the underlying stream will be left open when the /// <c>CrcCalculatorStream</c> is Closed. /// </summary> /// <remarks> /// <para> /// Set this at any point before calling <see cref="Close()"/>. /// </para> /// </remarks> public bool LeaveOpen { get { return _leaveOpen; } set { _leaveOpen = value; } } /// <summary> /// Read from the stream /// </summary> /// <param name="buffer">the buffer to read</param> /// <param name="offset">the offset at which to start</param> /// <param name="count">the number of bytes to read</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { int bytesToRead = count; // Need to limit the # of bytes returned, if the stream is intended to have // a definite length. This is especially useful when returning a stream for // the uncompressed data directly to the application. The app won't // necessarily read only the UncompressedSize number of bytes. For example // wrapping the stream returned from OpenReader() into a StreadReader() and // calling ReadToEnd() on it, We can "over-read" the zip data and get a // corrupt string. The length limits that, prevents that problem. if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit) { if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead; if (bytesRemaining < count) bytesToRead = (int)bytesRemaining; } int n = _innerStream.Read(buffer, offset, bytesToRead); if (n > 0) _Crc32.SlurpBlock(buffer, offset, n); return n; } /// <summary> /// Write to the stream. /// </summary> /// <param name="buffer">the buffer from which to write</param> /// <param name="offset">the offset at which to start writing</param> /// <param name="count">the number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (count > 0) _Crc32.SlurpBlock(buffer, offset, count); _innerStream.Write(buffer, offset, count); } /// <summary> /// Indicates whether the stream supports reading. /// </summary> public override bool CanRead { get { return _innerStream.CanRead; } } /// <summary> /// Indicates whether the stream supports seeking. /// </summary> /// <remarks> /// <para> /// Always returns false. /// </para> /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream supports writing. /// </summary> public override bool CanWrite { get { return _innerStream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { _innerStream.Flush(); } /// <summary> /// Returns the length of the underlying stream. /// </summary> public override long Length { get { if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit) return _innerStream.Length; else return _lengthLimit; } } /// <summary> /// The getter for this property returns the total bytes read. /// If you use the setter, it will throw /// <see cref="NotSupportedException"/>. /// </summary> public override long Position { get { return _Crc32.TotalBytesRead; } set { throw new NotSupportedException(); } } /// <summary> /// Seeking is not supported on this stream. This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="offset">N/A</param> /// <param name="origin">N/A</param> /// <returns>N/A</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// This method always throws /// <see cref="NotSupportedException"/> /// </summary> /// <param name="value">N/A</param> public override void SetLength(long value) { throw new NotSupportedException(); } void IDisposable.Dispose() { base.Dispose(); if (!_leaveOpen) _innerStream.Dispose(); } } }
/* * This code is licensed under the terms of the MIT license * * Copyright (C) 2012 Yiannis Bourkelis & Matthew Leibowitz * * 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; #if __UNIFIED__ using CoreGraphics; using Foundation; using UIKit; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using nfloat = System.Single; #endif namespace AdvancedColorPicker { /// <summary> /// The view that represents a color picker. /// </summary> public class ColorPickerView : UIView { private CGSize satBrightIndicatorSize; private HuePickerView huePicker; private SaturationBrightnessPickerView satbrightPicker; private SelectedColorPreviewView preview; private HueIndicatorView hueIndicator; private SaturationBrightnessIndicatorView satBrightIndicator; /// <summary> /// Initializes a new instance of the <see cref="ColorPickerView"/> class. /// </summary> public ColorPickerView() { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="ColorPickerView"/> class /// with the specified frame. /// </summary> /// <param name="frame">The frame used by the view, expressed in iOS points.</param> public ColorPickerView(CGRect frame) : base(frame) { Initialize(); } /// <summary> /// Initializes a new instance of the <see cref="ColorPickerView"/> class /// with the specified initial selected color. /// </summary> /// <param name="color">The initial selected color.</param> public ColorPickerView(UIColor color) : base() { Initialize(); SelectedColor = color; } /// <summary> /// Initializes this instance. /// </summary> protected void Initialize() { satBrightIndicatorSize = new CGSize(28, 28); var selectedColorViewHeight = (nfloat)60; var viewSpace = (nfloat)1; preview = new SelectedColorPreviewView(); preview.Frame = new CGRect(0, 0, Bounds.Width, selectedColorViewHeight); preview.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; preview.Layer.ShadowOpacity = 0.6f; preview.Layer.ShadowOffset = new CGSize(0, 7); preview.Layer.ShadowColor = UIColor.Black.CGColor; satbrightPicker = new SaturationBrightnessPickerView(); satbrightPicker.Frame = new CGRect(0, selectedColorViewHeight + viewSpace, Bounds.Width, Bounds.Height - selectedColorViewHeight - selectedColorViewHeight - viewSpace - viewSpace); satbrightPicker.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; satbrightPicker.ColorPicked += HandleColorPicked; satbrightPicker.AutosizesSubviews = true; huePicker = new HuePickerView(); huePicker.Frame = new CGRect(0, Bounds.Bottom - selectedColorViewHeight, Bounds.Width, selectedColorViewHeight); huePicker.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin; huePicker.HueChanged += HandleHueChanged; var pos = huePicker.Frame.Width * huePicker.Hue; hueIndicator = new HueIndicatorView(); hueIndicator.Frame = new CGRect(pos - 10, huePicker.Bounds.Y - 2, 20, huePicker.Bounds.Height + 2); hueIndicator.UserInteractionEnabled = false; hueIndicator.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin; huePicker.AddSubview(hueIndicator); var pos2 = new CGPoint(satbrightPicker.Saturation * satbrightPicker.Frame.Size.Width, satbrightPicker.Frame.Size.Height - (satbrightPicker.Brightness * satbrightPicker.Frame.Size.Height)); satBrightIndicator = new SaturationBrightnessIndicatorView(); satBrightIndicator.Frame = new CGRect(pos2.X - satBrightIndicatorSize.Width / 2, pos2.Y - satBrightIndicatorSize.Height / 2, satBrightIndicatorSize.Width, satBrightIndicatorSize.Height); satBrightIndicator.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin; satBrightIndicator.UserInteractionEnabled = false; satbrightPicker.AddSubview(satBrightIndicator); AddSubviews(satbrightPicker, huePicker, preview); } /// <summary> /// Gets or sets the selected color. /// </summary> /// <value>The selected color.</value> public UIColor SelectedColor { get { return UIColor.FromHSB(satbrightPicker.Hue, satbrightPicker.Saturation, satbrightPicker.Brightness); } set { nfloat hue = 0, brightness = 0, saturation = 0, alpha = 0; value.GetHSBA(out hue, out saturation, out brightness, out alpha); huePicker.Hue = hue; satbrightPicker.Hue = hue; satbrightPicker.Brightness = brightness; satbrightPicker.Saturation = saturation; preview.BackgroundColor = value; PositionIndicators(); satbrightPicker.SetNeedsDisplay(); huePicker.SetNeedsDisplay(); } } /// <summary> /// Occurs when the a color is selected. /// </summary> public event EventHandler<ColorPickedEventArgs> ColorPicked; /// <summary> /// Lays out subviews. /// </summary> public override void LayoutSubviews() { base.LayoutSubviews(); PositionIndicators(); } private void PositionIndicators() { PositionHueIndicatorView(); PositionSatBrightIndicatorView(); } private void PositionSatBrightIndicatorView() { Animate(0.3f, 0f, UIViewAnimationOptions.AllowUserInteraction, () => { var x = satbrightPicker.Saturation * satbrightPicker.Frame.Size.Width; var y = satbrightPicker.Frame.Size.Height - (satbrightPicker.Brightness * satbrightPicker.Frame.Size.Height); var pos = new CGPoint(x, y); var rect = new CGRect( pos.X - satBrightIndicatorSize.Width / 2, pos.Y - satBrightIndicatorSize.Height / 2, satBrightIndicatorSize.Width, satBrightIndicatorSize.Height); satBrightIndicator.Frame = rect; }, null); } private void PositionHueIndicatorView() { Animate(0.3f, 0f, UIViewAnimationOptions.AllowUserInteraction, () => { var pos = huePicker.Frame.Width * huePicker.Hue; var rect = new CGRect( pos - 10, huePicker.Bounds.Y - 2, 20, huePicker.Bounds.Height + 2); hueIndicator.Frame = rect; }, () => { hueIndicator.Hidden = false; }); } private void HandleColorPicked(object sender, EventArgs e) { PositionSatBrightIndicatorView(); preview.BackgroundColor = UIColor.FromHSB(satbrightPicker.Hue, satbrightPicker.Saturation, satbrightPicker.Brightness); OnColorPicked(new ColorPickedEventArgs(SelectedColor)); } private void HandleHueChanged(object sender, EventArgs e) { PositionHueIndicatorView(); satbrightPicker.Hue = huePicker.Hue; satbrightPicker.SetNeedsDisplay(); HandleColorPicked(sender, e); } /// <summary> /// Handles the <see cref="E:ColorPicked" /> event. /// </summary> /// <param name="e">The <see cref="ColorPickedEventArgs"/> instance containing the event data.</param> protected virtual void OnColorPicked(ColorPickedEventArgs e) { var handler = ColorPicked; if (handler != null) { handler(this, e); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Numerics { public readonly partial struct BigInteger : System.IComparable, System.IComparable<System.Numerics.BigInteger>, System.IEquatable<System.Numerics.BigInteger>, System.IFormattable { private readonly object _dummy; [System.CLSCompliantAttribute(false)] public BigInteger(byte[] value) { throw null; } public BigInteger(decimal value) { throw null; } public BigInteger(double value) { throw null; } public BigInteger(int value) { throw null; } public BigInteger(long value) { throw null; } public BigInteger(System.ReadOnlySpan<byte> value, bool isUnsigned=false, bool isBigEndian=false) { throw null; } public BigInteger(float value) { throw null; } [System.CLSCompliantAttribute(false)] public BigInteger(uint value) { throw null; } [System.CLSCompliantAttribute(false)] public BigInteger(ulong value) { throw null; } public bool IsEven { get { throw null; } } public bool IsOne { get { throw null; } } public bool IsPowerOfTwo { get { throw null; } } public bool IsZero { get { throw null; } } public static System.Numerics.BigInteger MinusOne { get { throw null; } } public static System.Numerics.BigInteger One { get { throw null; } } public int Sign { get { throw null; } } public static System.Numerics.BigInteger Zero { get { throw null; } } public static System.Numerics.BigInteger Abs(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger Add(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static int Compare(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public int CompareTo(long other) { throw null; } public int CompareTo(System.Numerics.BigInteger other) { throw null; } public int CompareTo(object obj) { throw null; } [System.CLSCompliantAttribute(false)] public int CompareTo(ulong other) { throw null; } public static System.Numerics.BigInteger Divide(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor) { throw null; } public static System.Numerics.BigInteger DivRem(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor, out System.Numerics.BigInteger remainder) { throw null; } public bool Equals(long other) { throw null; } public bool Equals(System.Numerics.BigInteger other) { throw null; } public override bool Equals(object obj) { throw null; } [System.CLSCompliantAttribute(false)] public bool Equals(ulong other) { throw null; } public int GetByteCount(bool isUnsigned=false) { throw null; } public override int GetHashCode() { throw null; } public static System.Numerics.BigInteger GreatestCommonDivisor(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static double Log(System.Numerics.BigInteger value) { throw null; } public static double Log(System.Numerics.BigInteger value, double baseValue) { throw null; } public static double Log10(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger Max(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger Min(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger ModPow(System.Numerics.BigInteger value, System.Numerics.BigInteger exponent, System.Numerics.BigInteger modulus) { throw null; } public static System.Numerics.BigInteger Multiply(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger Negate(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger operator +(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator &(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator |(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator --(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger operator /(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor) { throw null; } public static bool operator ==(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator ==(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator ==(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator ==(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator ==(ulong left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator ^(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static explicit operator System.Numerics.BigInteger (decimal value) { throw null; } public static explicit operator System.Numerics.BigInteger (double value) { throw null; } public static explicit operator byte (System.Numerics.BigInteger value) { throw null; } public static explicit operator decimal (System.Numerics.BigInteger value) { throw null; } public static explicit operator double (System.Numerics.BigInteger value) { throw null; } public static explicit operator short (System.Numerics.BigInteger value) { throw null; } public static explicit operator int (System.Numerics.BigInteger value) { throw null; } public static explicit operator long (System.Numerics.BigInteger value) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator sbyte (System.Numerics.BigInteger value) { throw null; } public static explicit operator float (System.Numerics.BigInteger value) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ushort (System.Numerics.BigInteger value) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator uint (System.Numerics.BigInteger value) { throw null; } [System.CLSCompliantAttribute(false)] public static explicit operator ulong (System.Numerics.BigInteger value) { throw null; } public static explicit operator System.Numerics.BigInteger (float value) { throw null; } public static bool operator >(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator >(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator >(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator >(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator >(ulong left, System.Numerics.BigInteger right) { throw null; } public static bool operator >=(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator >=(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator >=(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator >=(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator >=(ulong left, System.Numerics.BigInteger right) { throw null; } public static implicit operator System.Numerics.BigInteger (byte value) { throw null; } public static implicit operator System.Numerics.BigInteger (short value) { throw null; } public static implicit operator System.Numerics.BigInteger (int value) { throw null; } public static implicit operator System.Numerics.BigInteger (long value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.BigInteger (sbyte value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.BigInteger (ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.BigInteger (uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.BigInteger (ulong value) { throw null; } public static System.Numerics.BigInteger operator ++(System.Numerics.BigInteger value) { throw null; } public static bool operator !=(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator !=(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator !=(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator !=(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator !=(ulong left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator <<(System.Numerics.BigInteger value, int shift) { throw null; } public static bool operator <(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator <(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator <(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator <(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator <(ulong left, System.Numerics.BigInteger right) { throw null; } public static bool operator <=(long left, System.Numerics.BigInteger right) { throw null; } public static bool operator <=(System.Numerics.BigInteger left, long right) { throw null; } public static bool operator <=(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator <=(System.Numerics.BigInteger left, ulong right) { throw null; } [System.CLSCompliantAttribute(false)] public static bool operator <=(ulong left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator %(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor) { throw null; } public static System.Numerics.BigInteger operator *(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator ~(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger operator >>(System.Numerics.BigInteger value, int shift) { throw null; } public static System.Numerics.BigInteger operator -(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public static System.Numerics.BigInteger operator -(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger operator +(System.Numerics.BigInteger value) { throw null; } public static System.Numerics.BigInteger Parse(System.ReadOnlySpan<char> value, System.Globalization.NumberStyles style=(System.Globalization.NumberStyles)(7), System.IFormatProvider provider=null) { throw null; } public static System.Numerics.BigInteger Parse(string value) { throw null; } public static System.Numerics.BigInteger Parse(string value, System.Globalization.NumberStyles style) { throw null; } public static System.Numerics.BigInteger Parse(string value, System.Globalization.NumberStyles style, System.IFormatProvider provider) { throw null; } public static System.Numerics.BigInteger Parse(string value, System.IFormatProvider provider) { throw null; } public static System.Numerics.BigInteger Pow(System.Numerics.BigInteger value, int exponent) { throw null; } public static System.Numerics.BigInteger Remainder(System.Numerics.BigInteger dividend, System.Numerics.BigInteger divisor) { throw null; } public static System.Numerics.BigInteger Subtract(System.Numerics.BigInteger left, System.Numerics.BigInteger right) { throw null; } public byte[] ToByteArray() { throw null; } public byte[] ToByteArray(bool isUnsigned=false, bool isBigEndian=false) { throw null; } public override string ToString() { throw null; } public string ToString(System.IFormatProvider provider) { throw null; } public string ToString(string format) { throw null; } public string ToString(string format, System.IFormatProvider provider) { throw null; } public bool TryFormat(System.Span<char> destination, out int charsWritten, System.ReadOnlySpan<char> format=default(System.ReadOnlySpan<char>), System.IFormatProvider provider=null) { throw null; } public static bool TryParse(System.ReadOnlySpan<char> value, System.Globalization.NumberStyles style, System.IFormatProvider provider, out System.Numerics.BigInteger result) { throw null; } public static bool TryParse(System.ReadOnlySpan<char> value, out System.Numerics.BigInteger result) { throw null; } public static bool TryParse(string value, System.Globalization.NumberStyles style, System.IFormatProvider provider, out System.Numerics.BigInteger result) { throw null; } public static bool TryParse(string value, out System.Numerics.BigInteger result) { throw null; } public bool TryWriteBytes(System.Span<byte> destination, out int bytesWritten, bool isUnsigned=false, bool isBigEndian=false) { throw null; } } public partial struct Complex : System.IEquatable<System.Numerics.Complex>, System.IFormattable { private int _dummy; public static readonly System.Numerics.Complex ImaginaryOne; public static readonly System.Numerics.Complex One; public static readonly System.Numerics.Complex Zero; public Complex(double real, double imaginary) { throw null; } public double Imaginary { get { throw null; } } public double Magnitude { get { throw null; } } public double Phase { get { throw null; } } public double Real { get { throw null; } } public static double Abs(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Acos(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Add(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex Asin(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Atan(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Conjugate(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Cos(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Cosh(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Divide(System.Numerics.Complex dividend, System.Numerics.Complex divisor) { throw null; } public bool Equals(System.Numerics.Complex value) { throw null; } public override bool Equals(object obj) { throw null; } public static System.Numerics.Complex Exp(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex FromPolarCoordinates(double magnitude, double phase) { throw null; } public override int GetHashCode() { throw null; } public static System.Numerics.Complex Log(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Log(System.Numerics.Complex value, double baseValue) { throw null; } public static System.Numerics.Complex Log10(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Multiply(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex Negate(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex operator +(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex operator /(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static bool operator ==(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static explicit operator System.Numerics.Complex (decimal value) { throw null; } public static explicit operator System.Numerics.Complex (System.Numerics.BigInteger value) { throw null; } public static implicit operator System.Numerics.Complex (byte value) { throw null; } public static implicit operator System.Numerics.Complex (double value) { throw null; } public static implicit operator System.Numerics.Complex (short value) { throw null; } public static implicit operator System.Numerics.Complex (int value) { throw null; } public static implicit operator System.Numerics.Complex (long value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.Complex (sbyte value) { throw null; } public static implicit operator System.Numerics.Complex (float value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.Complex (ushort value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.Complex (uint value) { throw null; } [System.CLSCompliantAttribute(false)] public static implicit operator System.Numerics.Complex (ulong value) { throw null; } public static bool operator !=(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex operator *(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex operator -(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex operator -(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Pow(System.Numerics.Complex value, double power) { throw null; } public static System.Numerics.Complex Pow(System.Numerics.Complex value, System.Numerics.Complex power) { throw null; } public static System.Numerics.Complex Reciprocal(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Sin(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Sinh(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Sqrt(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Subtract(System.Numerics.Complex left, System.Numerics.Complex right) { throw null; } public static System.Numerics.Complex Tan(System.Numerics.Complex value) { throw null; } public static System.Numerics.Complex Tanh(System.Numerics.Complex value) { throw null; } public override string ToString() { throw null; } public string ToString(System.IFormatProvider provider) { throw null; } public string ToString(string format) { throw null; } public string ToString(string format, System.IFormatProvider provider) { throw null; } } }
// [AUTO_HEADER] using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Diagnostics; using System.Threading; using System.IO; using System.Globalization; namespace BaseIMEUI { public partial class BIAboutPanel : UserControl { public static System.Drawing.Bitmap c_icon = null; private Form u_window; private bool m_init; public BIAboutPanel(Form window) { InitializeComponent(); Bitmap logo = new Bitmap(c_icon); logo.MakeTransparent(logo.GetPixel(1, 1)); this.u_pictureLogo.Image = (Image)logo; this.u_window = window; // We are now using a ruby script to change the text // value which will be displayed on the about window // automatically. this.u_version.Text = "Yahoo! KeyKey 1.1 (build 2528)"; this.UpdateVersionInfo(); this.UpdateWordCount(); } public void UpdateVersionInfo() { this.m_init = true; BIServerConnector callback = BIServerConnector.SharedInstance; if (callback != null) { if (callback.isRunningUnderWow64()) this.u_version.Text += ", 64-bit"; this.u_databaseVersion.Text = "Database version " + callback.databaseVersion(); } else { this.u_databaseVersion.Text = ""; } this.m_init = false; } public void UpdateWordCount() { this.m_init = true; BIServerConnector callback = BIServerConnector.SharedInstance; if (callback != null) { string wordCountModuleName = "YKAFWordCount"; if (callback.moduleWithWildcardNameExists(wordCountModuleName) == false) { this.u_wordCountGroup.Enabled = false; this.u_wordCountTodayCountLabel.Text = "0"; this.u_wordCountThisWeekCountLabel.Text = "0"; this.u_wordCountTotalCountLabel.Text = "0"; this.u_wordCountMessageLabel.Visible = true; } else { this.u_wordCountGroup.Enabled = true; this.u_wordCountMessageLabel.Visible = false; if (callback.isAroundFilterEnabled(wordCountModuleName)) { this.u_wordCountEnableCheckBox.Checked = true; this.SetWordCountLabelsEnabled(true); } else { this.u_wordCountEnableCheckBox.Checked = false; this.SetWordCountLabelsEnabled(false); } string todayCount = callback.stringValueForConfigKeyOfModule("TodayCount", wordCountModuleName); if (todayCount.Length == 0) todayCount = "0"; string weeklyCount = callback.stringValueForConfigKeyOfModule("WeeklyCount", wordCountModuleName); if (weeklyCount.Length == 0) weeklyCount = "0"; string totalCount = callback.stringValueForConfigKeyOfModule("TotalCount", wordCountModuleName); if (totalCount.Length == 0) totalCount = "0"; this.u_wordCountTodayCountLabel.Text = todayCount; this.u_wordCountThisWeekCountLabel.Text = weeklyCount; this.u_wordCountTotalCountLabel.Text = totalCount; } } else { this.u_wordCountGroup.Enabled = false; this.u_wordCountTodayCountLabel.Text = "0"; this.u_wordCountThisWeekCountLabel.Text = "0"; this.u_wordCountTotalCountLabel.Text = "0"; this.u_wordCountMessageLabel.Visible = true; } this.m_init = false; } private void SetWordCountLabelsEnabled(bool enabled) { this.u_wordCountTodayLabel.Enabled = enabled; this.u_wordCountTodayCountLabel.Enabled = enabled; this.u_wordCountThisWeekLabel.Enabled = enabled; this.u_wordCountThisWeekCountLabel.Enabled = enabled; this.u_wordCountTotalLabel.Enabled = enabled; this.u_wordCountTotalCountLabel.Enabled = enabled; } private void LaunchProcessInThread(object data) { string filename = (string)data; Process process = new Process(); process.EnableRaisingEvents = true; process.StartInfo.FileName = filename; try { process.Start(); } catch { } Thread.Sleep(1000); this.u_window.Close(); } private void LaunchProcess(string filename) { // Although the name of the parameter is "filename", however, // it could be a string of URL and we can launch the default // Web browser to open the URL. // this.m_filename = filename; try { ParameterizedThreadStart threadStart = new ParameterizedThreadStart(LaunchProcessInThread); Thread thread = new Thread(threadStart); thread.Start(filename); } catch { } } private void u_linkHomepage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.LaunchProcess("http://tw.media.yahoo.com/keykey/"); } private void u_linkPrivacy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.LaunchProcess("http://info.yahoo.com/privacy/tw/yahoo/"); } private void u_linkAgreement_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { this.LaunchProcess("http://tw.info.yahoo.com/legal/utos.html"); } private void LaunchCustomCareInthread() { string filename = Application.StartupPath + Path.DirectorySeparatorChar + "ServiceUI.exe"; bool rtn = false; try { ProcessStartInfo serviceStart = new ProcessStartInfo(filename, "customercare " + m_userInfoFile + " " + m_primaryInputMethod); Process serviceApp = new Process(); serviceApp.StartInfo = serviceStart; rtn = serviceApp.Start(); } catch { } if (rtn) { Thread.Sleep(1000); this.u_window.Close(); } } private string m_userInfoFile = ""; private string m_primaryInputMethod = ""; private void WriteStringToFile(string myString, string myFilePath) { try { TextWriter textWriter = new StreamWriter(myFilePath); textWriter.Write(myString); textWriter.Close(); textWriter.Dispose(); } catch { } } private void LaunchCustomCare() { /* PreferenceConnector callback = PreferenceConnector.SharedInstance; if (callback == null) { MessageBox.Show("Error!"); return; } this.m_userInfoText = callback.userInfoForPOST(); this.m_userInfoFile = callback.temporaryFilename("ykkuserinfo.txt"); this.m_primaryInputMethod = callback.primaryInputMethod(); this.WriteStringToFile(m_userInfoText, m_userInfoFile); try { ThreadStart threadStart = new ThreadStart(LaunchCustomCareInthread); Thread thread = new Thread(threadStart); thread.Start(); } catch { } */ } private void u_feedback_Click(object sender, EventArgs e) { // this.LaunchCustomCare(); // WARNING: THIS PART IS MESSED UP--REQUIRES CLIENT-SIDE ACTION this.LaunchProcess("http://tw.help.cc.yahoo.com/feedback.html?id=3430"); } private void u_wordCountEnableCheckBox_CheckedChanged(object sender, EventArgs e) { if (this.m_init) return; this.m_init = true; BIServerConnector callback = BIServerConnector.SharedInstance; if (callback != null) { string wordCountModuleName = "YKAFWordCount"; callback.toggleAroundFilter(wordCountModuleName); if (callback.isAroundFilterEnabled(wordCountModuleName)) { this.u_wordCountEnableCheckBox.Checked = true; this.SetWordCountLabelsEnabled(true); } else { this.u_wordCountEnableCheckBox.Checked = false; this.SetWordCountLabelsEnabled(false); } } this.m_init = false; } private void ClearWordCount(object sender, EventArgs e) { string message = "Do you really want to clear word count?"; string locale = CultureInfo.CurrentUICulture.Name; if (locale.Equals("zh-TW")) message = "\u60a8\u78ba\u5b9a\u8981\u6e05\u9664\u5b57\u6578\u7d71\u8a08\u55ce\uff1f"; else if (locale.Equals("zh-CN")) message = "\u60a8\u786e\u5b9a\u8981\u6e05\u9664\u5b57\u6570\u7edf\u8ba1\u5417\uff1f"; DialogResult result = MessageBox.Show(message, "", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result.Equals(DialogResult.No)) return; BIServerConnector callback = BIServerConnector.SharedInstance; if (callback != null) { string wordCountModuleName = "YKAFWordCount"; callback.deleteAllKeysAndValuesInModuleConfig(wordCountModuleName); this.UpdateWordCount(); } } } }
//----------------------------------------------------------------------- // <copyright file="EllipticalNodeOperations.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using System.Windows.Ink; using System.Windows.Input; using System.Diagnostics; namespace MS.Internal.Ink { /// <summary> /// StrokeNodeOperations implementation for elliptical nodes /// </summary> internal class EllipticalNodeOperations : StrokeNodeOperations { /// <summary> /// Constructor /// </summary> /// <param name="nodeShape"></param> internal EllipticalNodeOperations(StylusShape nodeShape) : base(nodeShape) { System.Diagnostics.Debug.Assert((nodeShape != null) && nodeShape.IsEllipse); _radii = new Size(nodeShape.Width * 0.5, nodeShape.Height * 0.5); // All operations with ellipses become simple(r) if transfrom ellipses into circles. // Use the max of the radii for the radius of the circle _radius = Math.Max(_radii.Width, _radii.Height); // Compute ellipse-to-circle and circle-to-elliipse transforms. The former is used // in hit-testing operations while the latter is used when computing vertices of // a quadrangle connecting two ellipses _transform = nodeShape.Transform; _nodeShapeToCircle = _transform; Debug.Assert(_nodeShapeToCircle.HasInverse, "About to invert a non-invertible transform"); _nodeShapeToCircle.Invert(); if (DoubleUtil.AreClose(_radii.Width, _radii.Height)) { _circleToNodeShape = _transform; } else { // Reverse the rotation if (false == DoubleUtil.IsZero(nodeShape.Rotation)) { _nodeShapeToCircle.Rotate(-nodeShape.Rotation); Debug.Assert(_nodeShapeToCircle.HasInverse, "Just rotated an invertible transform and produced a non-invertible one"); } // Scale to enlarge double sx, sy; if (_radii.Width > _radii.Height) { sx = 1; sy = _radii.Width / _radii.Height; } else { sx = _radii.Height / _radii.Width; sy = 1; } _nodeShapeToCircle.Scale(sx, sy); Debug.Assert(_nodeShapeToCircle.HasInverse, "Just scaled an invertible transform and produced a non-invertible one"); _circleToNodeShape = _nodeShapeToCircle; _circleToNodeShape.Invert(); } } /// <summary> /// This is probably not the best (design-wise) but the cheapest way to tell /// EllipticalNodeOperations from all other implementations of node operations. /// </summary> internal override bool IsNodeShapeEllipse { get { return true; } } /// <summary> /// Finds connecting points for a pair of stroke nodes /// </summary> /// <param name="beginNode">a node to connect</param> /// <param name="endNode">another node, next to beginNode</param> /// <returns>connecting quadrangle</returns> internal override Quad GetConnectingQuad(StrokeNodeData beginNode, StrokeNodeData endNode) { if (beginNode.IsEmpty || endNode.IsEmpty || DoubleUtil.AreClose(beginNode.Position, endNode.Position)) { return Quad.Empty; } // Get the vector between the node positions Vector spine = endNode.Position - beginNode.Position; if (_nodeShapeToCircle.IsIdentity == false) { spine = _nodeShapeToCircle.Transform(spine); } double beginRadius = _radius * beginNode.PressureFactor; double endRadius = _radius * endNode.PressureFactor; // Get the vector and the distance between the node positions double distanceSquared = spine.LengthSquared; double delta = endRadius - beginRadius; double deltaSquared = DoubleUtil.IsZero(delta) ? 0 : (delta * delta); if (DoubleUtil.LessThanOrClose(distanceSquared, deltaSquared)) { // One circle is contained within the other return Quad.Empty; } // Thus, at this point, distance > 0, which avoids the DivideByZero error // Also, here, distanceSquared > deltaSquared // Thus, 0 <= rSin < 1 // Get the components of the radius vectors double distance = Math.Sqrt(distanceSquared); spine /= distance; Vector rad = spine; // Turn left double temp = rad.Y; rad.Y = -rad.X; rad.X = temp; Vector vectorToLeftTangent, vectorToRightTangent; double rSinSquared = deltaSquared / distanceSquared; if (DoubleUtil.IsZero(rSinSquared)) { vectorToLeftTangent = rad; vectorToRightTangent = -rad; } else { rad *= Math.Sqrt(1 - rSinSquared); spine *= Math.Sqrt(rSinSquared); if (beginNode.PressureFactor < endNode.PressureFactor) { spine = -spine; } vectorToLeftTangent = spine + rad; vectorToRightTangent = spine - rad; } // Get the common tangent points if (_circleToNodeShape.IsIdentity == false) { vectorToLeftTangent = _circleToNodeShape.Transform(vectorToLeftTangent); vectorToRightTangent = _circleToNodeShape.Transform(vectorToRightTangent); } return new Quad(beginNode.Position + (vectorToLeftTangent * beginRadius), endNode.Position + (vectorToLeftTangent * endRadius), endNode.Position + (vectorToRightTangent * endRadius), beginNode.Position + (vectorToRightTangent * beginRadius)); } /// <summary> /// /// </summary> /// <param name="node"></param> /// <param name="quad"></param> /// <returns></returns> internal override IEnumerable<ContourSegment> GetContourSegments(StrokeNodeData node, Quad quad) { System.Diagnostics.Debug.Assert(node.IsEmpty == false); if (quad.IsEmpty) { Point point = node.Position; point.X += _radius; yield return new ContourSegment(point, point, node.Position); } else if (_nodeShapeToCircle.IsIdentity) { yield return new ContourSegment(quad.A, quad.B); yield return new ContourSegment(quad.B, quad.C, node.Position); yield return new ContourSegment(quad.C, quad.D); yield return new ContourSegment(quad.D, quad.A); } } /// <summary> /// ISSUE-2004/06/15- temporary workaround to avoid hit-testing ellipses with ellipses /// </summary> /// <param name="beginNode"></param> /// <param name="endNode"></param> /// <returns></returns> internal override IEnumerable<ContourSegment> GetNonBezierContourSegments(StrokeNodeData beginNode, StrokeNodeData endNode) { Quad quad = beginNode.IsEmpty ? Quad.Empty : base.GetConnectingQuad(beginNode, endNode); return base.GetContourSegments(endNode, quad); } /// <summary> /// Hit-tests a stroke segment defined by two nodes against a linear segment. /// </summary> /// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param> /// <param name="endNode">End node of the stroke segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two nodes. /// Can be empty if the begion node is empty or when one node is entirely inside the other</param> /// <param name="hitBeginPoint">an end point of the hitting linear segment</param> /// <param name="hitEndPoint">an end point of the hitting linear segment</param> /// <returns>true if the hitting segment intersect the contour comprised of the two stroke nodes</returns> internal override bool HitTest( StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint) { StrokeNodeData bigNode, smallNode; if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor))) { // Need to test one node only bigNode = endNode; smallNode = StrokeNodeData.Empty; } else { // In this case the size doesn't matter. bigNode = beginNode; smallNode = endNode; } // Compute the positions of the involved points relative to bigNode. Vector hitBegin = hitBeginPoint - bigNode.Position; Vector hitEnd = hitEndPoint - bigNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } bool isHit = false; // Hit-test the big node double bigRadius = _radius * bigNode.PressureFactor; Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= (bigRadius * bigRadius)) { isHit = true; } else if (quad.IsEmpty == false) { // Hit-test the other node Vector spineVector = smallNode.Position - bigNode.Position; if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } double smallRadius = _radius * smallNode.PressureFactor; nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if ((nearest.LengthSquared <= (smallRadius * smallRadius)) || HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint)) { isHit = true; } } return isHit; } /// <summary> /// Hit-tests a stroke segment defined by two nodes against another stroke segment. /// </summary> /// <param name="beginNode">Begin node of the stroke segment to hit-test. Can be empty (none)</param> /// <param name="endNode">End node of the stroke segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two nodes. /// Can be empty if the begion node is empty or when one node is entirely inside the other</param> /// <param name="hitContour">a collection of basic segments outlining the hitting contour</param> /// <returns>true if the contours intersect or overlap</returns> internal override bool HitTest( StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour) { StrokeNodeData bigNode, smallNode; double bigRadiusSquared, smallRadiusSquared = 0; Vector spineVector; if (beginNode.IsEmpty || (quad.IsEmpty && (endNode.PressureFactor > beginNode.PressureFactor))) { // Need to test one node only bigNode = endNode; smallNode = StrokeNodeData.Empty; spineVector = new Vector(); } else { // In this case the size doesn't matter. bigNode = beginNode; smallNode = endNode; smallRadiusSquared = _radius * smallNode.PressureFactor; smallRadiusSquared *= smallRadiusSquared; // Find position of smallNode relative to the bigNode. spineVector = smallNode.Position - bigNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } } bigRadiusSquared = _radius * bigNode.PressureFactor; bigRadiusSquared *= bigRadiusSquared; bool isHit = false; // When hit-testing a contour against another contour, like in this case, // the default implementation checks whether any edge (segment) of the hitting // contour intersects with the contour of the ink segment. But this doesn't cover // the case when the ink segment is entirely inside of the hitting segment. // The bool variable isInside is used here to track that case. It answers the question // 'Is ink contour inside if the hitting contour?'. It's initialized to 'true" // and then verified for each edge of the hitting contour until there's a hit or // until it's false. bool isInside = true; foreach (ContourSegment hitSegment in hitContour) { if (hitSegment.IsArc) { // ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented // and currently disabled in ErasingStroke } else { // Find position of the hitting segment relative to bigNode transformed to circle. Vector hitBegin = hitSegment.Begin - bigNode.Position; Vector hitEnd = hitBegin + hitSegment.Vector; if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } // Hit-test the big node Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= bigRadiusSquared) { isHit = true; break; } // Hit-test the other node if (quad.IsEmpty == false) { nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if ((nearest.LengthSquared <= smallRadiusSquared) || HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End)) { isHit = true; break; } } // While there's still a chance to find the both nodes inside the hitting contour, // continue checking on position of the endNode relative to the edges of the hitting contour. if (isInside && (WhereIsVectorAboutVector(endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right)) { isInside = false; } } } return (isHit || isInside); } /// <summary> /// Cut-test ink segment defined by two nodes and a connecting quad against a linear segment /// </summary> /// <param name="beginNode">Begin node of the ink segment</param> /// <param name="endNode">End node of the ink segment</param> /// <param name="quad">Pre-computed quadrangle connecting the two ink nodes</param> /// <param name="hitBeginPoint">egin point of the hitting segment</param> /// <param name="hitEndPoint">End point of the hitting segment</param> /// <returns>Exact location to cut at represented by StrokeFIndices</returns> internal override StrokeFIndices CutTest( StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, Point hitBeginPoint, Point hitEndPoint) { // Compute the positions of the involved points relative to the endNode. Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position); Vector hitBegin = hitBeginPoint - endNode.Position; Vector hitEnd = hitEndPoint - endNode.Position; // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } StrokeFIndices result = StrokeFIndices.Empty; // Hit-test the end node double beginRadius = 0, endRadius = _radius * endNode.PressureFactor; Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared <= (endRadius * endRadius)) { result.EndFIndex = StrokeFIndices.AfterLast; result.BeginFIndex = beginNode.IsEmpty ? StrokeFIndices.BeforeFirst : 1; } if (beginNode.IsEmpty == false) { // Hit-test the first node beginRadius = _radius * beginNode.PressureFactor; nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if (nearest.LengthSquared <= (beginRadius * beginRadius)) { result.BeginFIndex = StrokeFIndices.BeforeFirst; if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = 0; } } } // If both nodes are hit or nothing is hit at all, return. if (result.IsFull || quad.IsEmpty || (result.IsEmpty && (HitTestQuadSegment(quad, hitBeginPoint, hitEndPoint) == false))) { return result; } // Find out whether the {begin, end} segment intersects with the contour // of the stroke segment {_lastNode, _thisNode}, and find the lower index // of the fragment to cut out. if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { result.BeginFIndex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin - spineVector, hitEnd - spineVector); } if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd); } if (IsInvalidCutTestResult(result)) { return StrokeFIndices.Empty; } return result; } /// <summary> /// CutTest an inking StrokeNode segment (two nodes and a connecting quadrangle) against a hitting contour /// (represented by an enumerator of Contoursegments). /// </summary> /// <param name="beginNode">The begin StrokeNodeData</param> /// <param name="endNode">The end StrokeNodeData</param> /// <param name="quad">Connecing quadrangle between the begin and end inking node</param> /// <param name="hitContour">The hitting ContourSegments</param> /// <returns>StrokeFIndices representing the location for cutting</returns> internal override StrokeFIndices CutTest( StrokeNodeData beginNode, StrokeNodeData endNode, Quad quad, IEnumerable<ContourSegment> hitContour) { // Compute the positions of the beginNode relative to the endNode. Vector spineVector = beginNode.IsEmpty ? new Vector(0, 0) : (beginNode.Position - endNode.Position); // If the node shape is an ellipse, transform the scene to turn the shape to a circle if (_nodeShapeToCircle.IsIdentity == false) { spineVector = _nodeShapeToCircle.Transform(spineVector); } double beginRadius = 0, endRadius; double beginRadiusSquared = 0, endRadiusSquared; endRadius = _radius * endNode.PressureFactor; endRadiusSquared = endRadius * endRadius; if (beginNode.IsEmpty == false) { beginRadius = _radius * beginNode.PressureFactor; beginRadiusSquared = beginRadius * beginRadius; } bool isInside = true; StrokeFIndices result = StrokeFIndices.Empty; foreach (ContourSegment hitSegment in hitContour) { if (hitSegment.IsArc) { // ISSUE-2004/06/15-vsmirnov - ellipse vs arc hit-testing is not implemented // and currently disabled in ErasingStroke } else { Vector hitBegin = hitSegment.Begin - endNode.Position; Vector hitEnd = hitBegin + hitSegment.Vector; // If the node shape is an ellipse, transform the scene to turn // the shape into circle. if (_nodeShapeToCircle.IsIdentity == false) { hitBegin = _nodeShapeToCircle.Transform(hitBegin); hitEnd = _nodeShapeToCircle.Transform(hitEnd); } bool isHit = false; // Hit-test the end node Vector nearest = GetNearest(hitBegin, hitEnd); if (nearest.LengthSquared < endRadiusSquared) { isHit = true; if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { result.EndFIndex = StrokeFIndices.AfterLast; if (beginNode.IsEmpty) { result.BeginFIndex = StrokeFIndices.BeforeFirst; break; } if (DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { break; } } } if ((beginNode.IsEmpty == false) && (!isHit || !DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst))) { // Hit-test the first node nearest = GetNearest(hitBegin - spineVector, hitEnd - spineVector); if (nearest.LengthSquared < beginRadiusSquared) { isHit = true; if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { result.BeginFIndex = StrokeFIndices.BeforeFirst; if (DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { break; } } } } // If both nodes are hit or nothing is hit at all, return. if (beginNode.IsEmpty || (!isHit && (quad.IsEmpty || (HitTestQuadSegment(quad, hitSegment.Begin, hitSegment.End) == false)))) { if (isInside && (WhereIsVectorAboutVector( endNode.Position - hitSegment.Begin, hitSegment.Vector) != HitResult.Right)) { isInside = false; } continue; } isInside = false; // NTRAID#Window OS bug-1029694-2004/10/18-xiaotu, refactor the code to make it a method // to increase the maintainability of the program. FxCop bug. // Calculate the exact locations to cut. CalculateCutLocations(spineVector, hitBegin, hitEnd, endRadius, beginRadius, ref result); if (result.IsFull) { break; } } } // if (!result.IsFull) { if (isInside == true) { System.Diagnostics.Debug.Assert(result.IsEmpty); result = StrokeFIndices.Full; } else if ((DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst)) && (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.AfterLast))) { result.EndFIndex = StrokeFIndices.AfterLast; } else if ((DoubleUtil.AreClose(result.BeginFIndex,StrokeFIndices.AfterLast)) && (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.BeforeFirst))) { result.BeginFIndex = StrokeFIndices.BeforeFirst; } } if (IsInvalidCutTestResult(result)) { return StrokeFIndices.Empty; } return result; } /// <summary> /// Clip-Testing a circluar inking segment against a linear segment. /// See http://tabletpc/longhorn/Specs/Rendering%20and%20Hit-Testing%20Ink%20in%20Avalon%20M11.doc section /// 5.4.4.14 Clip-Testing a Circular Inking Segment against a Linear Segment for details of the algorithm /// </summary> /// <param name="spineVector">Represent the spine of the inking segment pointing from the beginNode to endNode</param> /// <param name="beginRadius">Radius of the beginNode</param> /// <param name="endRadius">Radius of the endNode</param> /// <param name="hitBegin">Hitting segment start point</param> /// <param name="hitEnd">Hitting segment end point</param> /// <returns>A double which represents the location for cutting</returns> private static double ClipTest(Vector spineVector, double beginRadius, double endRadius, Vector hitBegin, Vector hitEnd) { // First handle the special case when the spineVector is (0,0). In other words, this is the case // when the stylus stays at the the location but pressure changes. if (DoubleUtil.IsZero(spineVector.X) && DoubleUtil.IsZero(spineVector.Y)) { System.Diagnostics.Debug.Assert(DoubleUtil.AreClose(beginRadius, endRadius) == false); Vector nearest = GetNearest(hitBegin, hitEnd); double radius; if (nearest.X == 0) { radius = Math.Abs(nearest.Y); } else if (nearest.Y == 0) { radius = Math.Abs(nearest.X); } else { radius = nearest.Length; } return AdjustFIndex((radius - beginRadius) / (endRadius - beginRadius)); } // This change to ClipTest with a point if the two hitting segment are close enough. if (DoubleUtil.AreClose(hitBegin, hitEnd)) { return ClipTest(spineVector, beginRadius, endRadius, hitBegin); } double findex; Vector hitVector = hitEnd - hitBegin; if (DoubleUtil.IsZero(Vector.Determinant(spineVector, hitVector))) { // hitVector and spineVector are parallel findex = ClipTest(spineVector, beginRadius, endRadius, GetNearest(hitBegin, hitEnd)); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } else { // On the line defined by the segment find point P1Xp, the nearest to the beginNode.Position double x = GetProjectionFIndex(hitBegin, hitEnd); Vector P1Xp = hitBegin + (hitVector * x); if (P1Xp.LengthSquared < (beginRadius * beginRadius)) { System.Diagnostics.Debug.Assert(DoubleUtil.IsBetweenZeroAndOne(x) == false); findex = ClipTest(spineVector, beginRadius, endRadius, (0 > x) ? hitBegin : hitEnd); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } else { // Find the projection point P of endNode.Position to the line (beginNode.Position, B). Vector P1P2p = spineVector + GetProjection(-spineVector, P1Xp - spineVector); //System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(P1P2p.LengthSquared)); //System.Diagnostics.Debug.Assert(false == DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length)); // There checks are here since if either fail no real solution can be caculated and we may // as well bail out now and save the caculations that are below. if (DoubleUtil.IsZero(P1P2p.LengthSquared) || DoubleUtil.IsZero(endRadius - beginRadius + P1P2p.Length)) return 1d; // Calculate the findex of the point to split the ink segment at. findex = (P1Xp.Length - beginRadius) / (endRadius - beginRadius + P1P2p.Length); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); // Find the projection of the split point to the line of this segment. Vector S = spineVector * findex; double r = GetProjectionFIndex(hitBegin - S, hitEnd - S); // If the nearest point misses the segment, then find the findex // of the node nearest to the segment. if (false == DoubleUtil.IsBetweenZeroAndOne(r)) { findex = ClipTest(spineVector, beginRadius, endRadius, (0 > r) ? hitBegin : hitEnd); System.Diagnostics.Debug.Assert(!double.IsNaN(findex)); } } } return AdjustFIndex(findex); } /// <summary> /// Clip-Testing a circular inking segment again a hitting point. /// /// What need to find out a doulbe value s, which is between 0 and 1, such that /// DistanceOf(hit - s*spine) = beginRadius + s * (endRadius - beginRadius) /// That is /// (hit.X-s*spine.X)^2 + (hit.Y-s*spine.Y)^2 = [beginRadius + s*(endRadius-beginRadius)]^2 /// Rearrange /// A*s^2 + B*s + C = 0 /// where the value of A, B and C are described in the source code. /// Solving for s: /// s = (-B + sqrt(B^2-4A*C))/(2A) or s = (-B - sqrt(B^2-4A*C))/(2A) /// The smaller value between 0 and 1 is the one we want and discard the other one. /// </summary> /// <param name="spine">Represent the spine of the inking segment pointing from the beginNode to endNode</param> /// <param name="beginRadius">Radius of the beginNode</param> /// <param name="endRadius">Radius of the endNode</param> /// <param name="hit">The hitting point</param> /// <returns>A double which represents the location for cutting</returns> private static double ClipTest(Vector spine, double beginRadius, double endRadius, Vector hit) { double radDiff = endRadius - beginRadius; double A = spine.X*spine.X + spine.Y*spine.Y - radDiff*radDiff; double B = -2.0f*(hit.X*spine.X + hit.Y * spine.Y + beginRadius*radDiff); double C = hit.X * hit.X + hit.Y * hit.Y - beginRadius * beginRadius; // There checks are here since if either fail no real solution can be caculated and we may // as well bail out now and save the caculations that are below. if (DoubleUtil.IsZero(A) || !DoubleUtil.GreaterThanOrClose(B*B, 4.0f*A*C)) return 1d; double tmp = Math.Sqrt(B*B-4.0f * A * C); double s1 = (-B + tmp)/(2.0f * A); double s2 = (-B - tmp)/(2.0f * A); double findex; if (DoubleUtil.IsBetweenZeroAndOne(s1) && DoubleUtil.IsBetweenZeroAndOne(s1)) { findex = Math.Min(s1, s2); } else if (DoubleUtil.IsBetweenZeroAndOne(s1)) { findex = s1; } else if (DoubleUtil.IsBetweenZeroAndOne(s2)) { findex = s2; } else { // There is still possiblity that value like 1.0000000000000402 is not considered // as "IsOne" by DoubleUtil class. We should be at either one of the following two cases: // 1. s1/s2 around 0 but not close enough (say -0.0000000000001) // 2. s1/s2 around 1 but not close enought (say 1.0000000000000402) if (s1 > 1d && s2 > 1d) { findex = 1d; } else if (s1 < 0d && s2 < 0d) { findex = 0d; } else { findex = Math.Abs(Math.Min(s1, s2) - 0d) < Math.Abs(Math.Max(s1, s2) - 1d) ? 0d : 1d; } } return AdjustFIndex(findex); } /// <summary> /// Helper function to find out the relative location of a segment {segBegin, segEnd} against /// a strokeNode (spine). /// </summary> /// <param name="spine">the spineVector of the StrokeNode</param> /// <param name="segBegin">Start position of the line segment</param> /// <param name="segEnd">End position of the line segment</param> /// <returns>HitResult</returns> private static HitResult WhereIsNodeAboutSegment(Vector spine, Vector segBegin, Vector segEnd) { HitResult whereabout = HitResult.Right; Vector segVector = segEnd - segBegin; if ((WhereIsVectorAboutVector(-segBegin, segVector) == HitResult.Left) && !DoubleUtil.IsZero(Vector.Determinant(spine, segVector))) { whereabout = HitResult.Left; } return whereabout; } /// <summary> /// Helper method to calculate the exact location to cut /// </summary> /// <param name="spineVector">Vector the relative location of the two inking nodes</param> /// <param name="hitBegin">the begin point of the hitting segment</param> /// <param name="hitEnd">the end point of the hitting segment</param> /// <param name="endRadius">endNode radius</param> /// <param name="beginRadius">beginNode radius</param> /// <param name="result">StrokeFIndices representing the location for cutting</param> private void CalculateCutLocations( Vector spineVector, Vector hitBegin, Vector hitEnd, double endRadius, double beginRadius, ref StrokeFIndices result) { // Find out whether the {hitBegin, hitEnd} segment intersects with the contour // of the stroke segment, and find the lower index of the fragment to cut out. if (!DoubleUtil.AreClose(result.EndFIndex, StrokeFIndices.AfterLast)) { if (WhereIsNodeAboutSegment(spineVector, hitBegin, hitEnd) == HitResult.Left) { double findex = 1 - ClipTest(spineVector, endRadius, beginRadius, hitBegin, hitEnd); if (findex > result.EndFIndex) { result.EndFIndex = findex; } } } // Find out whether the {hitBegin, hitEnd} segment intersects with the contour // of the stroke segment, and find the higher index of the fragment to cut out. if (!DoubleUtil.AreClose(result.BeginFIndex, StrokeFIndices.BeforeFirst)) { hitBegin -= spineVector; hitEnd -= spineVector; if (WhereIsNodeAboutSegment(-spineVector, hitBegin, hitEnd) == HitResult.Left) { double findex = ClipTest(-spineVector, beginRadius, endRadius, hitBegin, hitEnd); if (findex < result.BeginFIndex) { result.BeginFIndex = findex; } } } } private double _radius = 0; private Size _radii; private Matrix _transform; private Matrix _nodeShapeToCircle; private Matrix _circleToNodeShape; } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using Gallio.Common.Collections; using Gallio.Common.Policies; using Gallio.Model; using Gallio.Model.Filters; using Gallio.Runner; using Gallio.Runner.Reports; using Gallio.Runner.Reports.Schema; using Gallio.Runtime; using Gallio.Runtime.Logging; using Gallio.Runtime.ProgressMonitoring; using Gallio.TDNetRunner.Facade; using Gallio.TDNetRunner.Properties; namespace Gallio.TDNetRunner.Core { public class RemoteProxyTestRunner : BaseProxyTestRunner { private const string ShortReportType = @"html-condensed"; private const string LongReportType = @"html"; private const int ShortReportThreshold = 100; private TestLauncher launcher; public RemoteProxyTestRunner() { launcher = new TestLauncher(); } protected override void Dispose(bool disposing) { launcher = null; } protected override void AbortImpl() { if (launcher != null) launcher.Cancel(); } protected override FacadeTestRunState RunImpl(IFacadeTestListener testListener, string assemblyPath, string cref, FacadeOptions facadeOptions) { if (cref == null) return RunAssembly(testListener, assemblyPath, facadeOptions); if (cref.Length >= 2) { char descriptor = cref[0]; switch (descriptor) { case 'T': return RunType(testListener, assemblyPath, cref.Substring(2), facadeOptions); case 'N': return RunNamespace(testListener, assemblyPath, cref.Substring(2), facadeOptions); case 'M': case 'F': case 'P': case 'E': int paramsPos = cref.IndexOf('('); if (paramsPos < 0) paramsPos = cref.Length; string memberNameWithType = cref.Substring(2, paramsPos - 2); int memberPos = memberNameWithType.LastIndexOf('.'); if (memberPos < 0) break; string typeName = memberNameWithType.Substring(0, memberPos); string memberName = memberNameWithType.Substring(memberPos + 1); return RunMember(testListener, assemblyPath, typeName, memberName, facadeOptions); } } return FacadeTestRunState.NoTests; } private FacadeTestRunState RunAssembly(IFacadeTestListener testListener, string assemblyPath, FacadeOptions facadeOptions) { return Run(testListener, assemblyPath, new AnyFilter<ITestDescriptor>(), facadeOptions); } private FacadeTestRunState RunNamespace(IFacadeTestListener testListener, string assemblyPath, string @namespace, FacadeOptions facadeOptions) { return Run(testListener, assemblyPath, new AndFilter<ITestDescriptor>(new Filter<ITestDescriptor>[] { new NamespaceFilter<ITestDescriptor>(new EqualityFilter<string>(@namespace)) }), facadeOptions); } private FacadeTestRunState RunType(IFacadeTestListener testListener, string assemblyPath, string typeName, FacadeOptions facadeOptions) { return Run(testListener, assemblyPath, new AndFilter<ITestDescriptor>(new Filter<ITestDescriptor>[] { new TypeFilter<ITestDescriptor>(new EqualityFilter<string>(typeName), true) }), facadeOptions); } private FacadeTestRunState RunMember(IFacadeTestListener testListener, string assemblyPath, string typeName, string memberName, FacadeOptions facadeOptions) { return Run(testListener, assemblyPath, new AndFilter<ITestDescriptor>(new Filter<ITestDescriptor>[] { new TypeFilter<ITestDescriptor>(new EqualityFilter<string>(typeName), true), new MemberFilter<ITestDescriptor>(new EqualityFilter<string>(memberName)) }), facadeOptions); } public override object InitializeLifetimeService() { return null; } /// <summary> /// Provided so that the unit tests can override test execution behavior. /// </summary> internal virtual TestLauncherResult RunLauncher(TestLauncher launcher) { return launcher.Run(); } private static Filter<ITestDescriptor> ToCategoryFilter(IList<string> categoryNames) { return new MetadataFilter<ITestDescriptor>(MetadataKeys.Category, new OrFilter<string>(GenericCollectionUtils.ConvertAllToArray(categoryNames, categoryName => new EqualityFilter<string>(categoryName)))); } private FacadeTestRunState Run(IFacadeTestListener testListener, string assemblyPath, Filter<ITestDescriptor> filter, FacadeOptions facadeOptions) { if (testListener == null) throw new ArgumentNullException(@"testListener"); if (assemblyPath == null) throw new ArgumentNullException("assemblyPath"); if (facadeOptions == null) throw new ArgumentNullException("facadeOptions"); ILogger logger = new FilteredLogger(new TDNetLogger(testListener), LogSeverity.Info); try { RuntimeAccessor.Instance.AddLogListener(logger); var filterRules = new List<FilterRule<ITestDescriptor>>(); switch (facadeOptions.FilterCategoryMode) { case FacadeFilterCategoryMode.Disabled: filterRules.Add(new FilterRule<ITestDescriptor>(FilterRuleType.Inclusion, filter)); break; case FacadeFilterCategoryMode.Include: filterRules.Add(new FilterRule<ITestDescriptor>(FilterRuleType.Inclusion, new AndFilter<ITestDescriptor>(new[] { filter, ToCategoryFilter(facadeOptions.FilterCategoryNames) }))); break; case FacadeFilterCategoryMode.Exclude: filterRules.Add(new FilterRule<ITestDescriptor>(FilterRuleType.Exclusion, ToCategoryFilter(facadeOptions.FilterCategoryNames))); filterRules.Add(new FilterRule<ITestDescriptor>(FilterRuleType.Inclusion, filter)); break; } var filterSet = new FilterSet<ITestDescriptor>(filterRules); launcher.Logger = logger; launcher.ProgressMonitorProvider = new LogProgressMonitorProvider(logger); launcher.TestExecutionOptions.FilterSet = filterSet; launcher.TestProject.TestRunnerFactoryName = StandardTestRunnerFactoryNames.IsolatedAppDomain; launcher.TestProject.AddTestRunnerExtension(new TDNetExtension(testListener)); // This monitor will inform the user in real-time what's going on launcher.TestProject.TestPackage.AddFile(new FileInfo(assemblyPath)); string assemblyDirectory = Path.GetDirectoryName(assemblyPath); launcher.TestProject.TestPackage.ApplicationBaseDirectory = new DirectoryInfo(assemblyDirectory); launcher.TestProject.TestPackage.WorkingDirectory = new DirectoryInfo(assemblyDirectory); TestLauncherResult result = RunLauncher(launcher); string reportDirectory = GetReportDirectory(logger); if (reportDirectory != null) { var reportFormatterOptions = new ReportFormatterOptions(); var preferenceManager = (TDNetPreferenceManager)RuntimeAccessor.ServiceLocator.ResolveByComponentId("TDNetRunner.PreferenceManager"); var reportFormat = preferenceManager.ReportSettings.DetermineReportFormat(result.Report); result.GenerateReports(reportDirectory, Path.GetFileName(assemblyPath), ReportArchive.Normal, new[] { reportFormat }, reportFormatterOptions, RuntimeAccessor.ServiceLocator.Resolve<IReportManager>(), NullProgressMonitor.CreateInstance()); // This will generate a link to the generated report if (result.ReportDocumentPaths.Count != 0) { Uri rawUrl = new Uri(result.ReportDocumentPaths[0]); string displayUrl = "file:///" + rawUrl.LocalPath.Replace(" ", "%20").Replace(@"\", "/"); // TDNet just prints the link on its own but it's not always clear to users what it represents. // testListener.TestResultsUrl(displayUrl); testListener.WriteLine("\nTest Report: " + displayUrl, FacadeCategory.Info); } } // Inform no tests run, if necessary. if (result.ResultCode == ResultCode.NoTests) { InformNoTestsWereRun(testListener, Resources.MbUnitTestRunner_NoTestsFound); } else if (result.Statistics.TestCount == 0) { InformNoTestsWereRun(testListener, null); } return GetTestRunState(result); } finally { RuntimeAccessor.Instance.RemoveLogListener(logger); } } /// <summary> /// Gets a temporary folder to store the HTML report. /// </summary> /// <param name="logger">The logger.</param> /// <returns>The full name of the folder or null if it could not be created.</returns> private static string GetReportDirectory(ILogger logger) { try { var path = Path.Combine(SpecialPathPolicy.For("TDNetRunner").GetTempDirectory().FullName, "Report"); var reportDirectory = new DirectoryInfo(path); if (reportDirectory.Exists) // Make sure the folder is empty { try { reportDirectory.Delete(true); } catch { // If we cannot delete the directory (perhaps it is still in use), then // create a new directory with a unique name. reportDirectory = SpecialPathPolicy.For("TDNetRunner").CreateTempDirectoryWithUniqueName(); } } reportDirectory.Create(); return reportDirectory.FullName; } catch (Exception e) { logger.Log(LogSeverity.Error, "Could not create the report directory.", e); return null; } } /// <summary> /// Inform the user that no tests were run and the reason for it. TD.NET displays /// a message like "0 Passed, 0 Failed, 0 Skipped" but it does it in the status bar, /// which may be harder to notice for the user. Be aware that this message will /// only be displayed when the user runs an individual test or fixture (TD.NET /// ignores the messages we send when it's running an entire assembly). /// </summary> /// <param name="testListener">An ITestListener object to write the message to.</param> /// <param name="reason">The reason no tests were run for.</param> private static void InformNoTestsWereRun(IFacadeTestListener testListener, string reason) { reason = String.IsNullOrEmpty(reason) ? String.Empty : " (" + reason + ")"; string message = String.Format("** {0}{1} **", Resources.MbUnitTestRunner_NoTestsWereRun, reason); testListener.WriteLine(message, FacadeCategory.Warning); } private static FacadeTestRunState GetTestRunState(TestLauncherResult result) { switch (result.ResultCode) { default: return FacadeTestRunState.Error; case ResultCode.Failure: case ResultCode.Canceled: return FacadeTestRunState.Failure; case ResultCode.NoTests: case ResultCode.Success: return FacadeTestRunState.Success; } } } }
/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGFlexWrapTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGFlexWrapTest { [Test] public void Test_wrap_column() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Wrap = YogaWrap.Wrap; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 30; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 30; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(60f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(60f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child3.LayoutX); Assert.AreEqual(0f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(60f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(30f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(30f, root_child2.LayoutX); Assert.AreEqual(60f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(0f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 30; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 30; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(30f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(30f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row_align_items_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.FlexEnd; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(20f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_wrap_row_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 30; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(60f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(30f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(30f, root_child3.LayoutHeight); } [Test] public void Test_flex_wrap_children_with_min_main_overriding_flex_basis() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.FlexBasis = 50; root_child0.MinWidth = 55; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexBasis = 50; root_child1.MinWidth = 55; root_child1.Height = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(55f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(55f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(55f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(45f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(55f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); } [Test] public void Test_flex_wrap_wrap_to_child_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.AlignItems = YogaAlign.FlexStart; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 100; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 100; root_child0_child0_child0.Height = 100; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 100; root_child1.Height = 100; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(100f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(100f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(100f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(100f, root_child1.LayoutY); Assert.AreEqual(100f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); } [Test] public void Test_flex_wrap_align_stretch_fits_one_row() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.Wrap; root.Width = 150; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 50; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(150f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(150f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(100f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(100f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(0f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(100f, root_child1.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.Center; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_single_line_different_size() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.Wrap = YogaWrap.WrapReverse; root.Width = 300; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(300f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(40f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(90f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(120f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(300f, root.LayoutWidth); Assert.AreEqual(50f, root.LayoutHeight); Assert.AreEqual(270f, root_child0.LayoutX); Assert.AreEqual(40f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(240f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(210f, root_child2.LayoutX); Assert.AreEqual(20f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(180f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(150f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_stretch() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.Stretch; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_row_align_content_space_around() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.FlexDirection = YogaFlexDirection.Row; root.AlignContent = YogaAlign.SpaceAround; root.Wrap = YogaWrap.WrapReverse; root.Width = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(60f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(80f, root.LayoutHeight); Assert.AreEqual(70f, root_child0.LayoutX); Assert.AreEqual(70f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(40f, root_child1.LayoutX); Assert.AreEqual(60f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(50f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(70f, root_child3.LayoutX); Assert.AreEqual(10f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(40f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrap_reverse_column_fixed_size() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.WrapReverse; root.Width = 200; root.Height = 100; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 30; root_child0.Height = 10; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.Width = 30; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 30; root_child2.Height = 30; root.Insert(2, root_child2); YogaNode root_child3 = new YogaNode(config); root_child3.Width = 30; root_child3.Height = 40; root.Insert(3, root_child3); YogaNode root_child4 = new YogaNode(config); root_child4.Width = 30; root_child4.Height = 50; root.Insert(4, root_child4); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(170f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(170f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(170f, root_child2.LayoutX); Assert.AreEqual(30f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(170f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(140f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(30f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(10f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(30f, root_child2.LayoutY); Assert.AreEqual(30f, root_child2.LayoutWidth); Assert.AreEqual(30f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(30f, root_child3.LayoutWidth); Assert.AreEqual(40f, root_child3.LayoutHeight); Assert.AreEqual(30f, root_child4.LayoutX); Assert.AreEqual(0f, root_child4.LayoutY); Assert.AreEqual(30f, root_child4.LayoutWidth); Assert.AreEqual(50f, root_child4.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_center() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.Center; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_flex_start() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexStart; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_row_within_align_items_flex_end() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.AlignItems = YogaAlign.FlexEnd; root.Width = 200; root.Height = 200; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0_child0.Width = 150; root_child0_child0.Height = 80; root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.Width = 80; root_child0_child1.Height = 80; root_child0.Insert(1, root_child0_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(200f, root.LayoutWidth); Assert.AreEqual(200f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(200f, root_child0.LayoutWidth); Assert.AreEqual(160f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(150f, root_child0_child0.LayoutWidth); Assert.AreEqual(80f, root_child0_child0.LayoutHeight); Assert.AreEqual(120f, root_child0_child1.LayoutX); Assert.AreEqual(80f, root_child0_child1.LayoutY); Assert.AreEqual(80f, root_child0_child1.LayoutWidth); Assert.AreEqual(80f, root_child0_child1.LayoutHeight); } [Test] public void Test_wrapped_column_max_height() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignContent = YogaAlign.Center; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 700; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.Width = 100; root_child0.Height = 500; root_child0.MaxHeight = 200; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.MarginLeft = 20; root_child1.MarginTop = 20; root_child1.MarginRight = 20; root_child1.MarginBottom = 20; root_child1.Width = 200; root_child1.Height = 200; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 100; root_child2.Height = 100; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(250f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(200f, root_child0.LayoutHeight); Assert.AreEqual(200f, root_child1.LayoutX); Assert.AreEqual(250f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(200f, root_child1.LayoutHeight); Assert.AreEqual(420f, root_child2.LayoutX); Assert.AreEqual(200f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(350f, root_child0.LayoutX); Assert.AreEqual(30f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(200f, root_child0.LayoutHeight); Assert.AreEqual(300f, root_child1.LayoutX); Assert.AreEqual(250f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(200f, root_child1.LayoutHeight); Assert.AreEqual(180f, root_child2.LayoutX); Assert.AreEqual(200f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_wrapped_column_max_height_flex() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.JustifyContent = YogaJustify.Center; root.AlignContent = YogaAlign.Center; root.AlignItems = YogaAlign.Center; root.Wrap = YogaWrap.Wrap; root.Width = 700; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexGrow = 1; root_child0.FlexShrink = 1; root_child0.FlexBasis = 0.Percent(); root_child0.Width = 100; root_child0.Height = 500; root_child0.MaxHeight = 200; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(config); root_child1.FlexGrow = 1; root_child1.FlexShrink = 1; root_child1.FlexBasis = 0.Percent(); root_child1.MarginLeft = 20; root_child1.MarginTop = 20; root_child1.MarginRight = 20; root_child1.MarginBottom = 20; root_child1.Width = 200; root_child1.Height = 200; root.Insert(1, root_child1); YogaNode root_child2 = new YogaNode(config); root_child2.Width = 100; root_child2.Height = 100; root.Insert(2, root_child2); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(300f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(180f, root_child0.LayoutHeight); Assert.AreEqual(250f, root_child1.LayoutX); Assert.AreEqual(200f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(180f, root_child1.LayoutHeight); Assert.AreEqual(300f, root_child2.LayoutX); Assert.AreEqual(400f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(700f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(300f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(180f, root_child0.LayoutHeight); Assert.AreEqual(250f, root_child1.LayoutX); Assert.AreEqual(200f, root_child1.LayoutY); Assert.AreEqual(200f, root_child1.LayoutWidth); Assert.AreEqual(180f, root_child1.LayoutHeight); Assert.AreEqual(300f, root_child2.LayoutX); Assert.AreEqual(400f, root_child2.LayoutY); Assert.AreEqual(100f, root_child2.LayoutWidth); Assert.AreEqual(100f, root_child2.LayoutHeight); } [Test] public void Test_wrap_nodes_with_content_sizing_overflowing_margin() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root_child0.Width = 85; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 40; root_child0_child0_child0.Height = 40; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.MarginRight = 10; root_child0.Insert(1, root_child0_child1); YogaNode root_child0_child1_child0 = new YogaNode(config); root_child0_child1_child0.Width = 40; root_child0_child1_child0.Height = 40; root_child0_child1.Insert(0, root_child0_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(85f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(40f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(415f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(85f, root_child0.LayoutWidth); Assert.AreEqual(80f, root_child0.LayoutHeight); Assert.AreEqual(45f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(35f, root_child0_child1.LayoutX); Assert.AreEqual(40f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); } [Test] public void Test_wrap_nodes_with_content_sizing_margin_cross() { YogaConfig config = new YogaConfig(); YogaNode root = new YogaNode(config); root.Width = 500; root.Height = 500; YogaNode root_child0 = new YogaNode(config); root_child0.FlexDirection = YogaFlexDirection.Row; root_child0.Wrap = YogaWrap.Wrap; root_child0.Width = 70; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(config); root_child0.Insert(0, root_child0_child0); YogaNode root_child0_child0_child0 = new YogaNode(config); root_child0_child0_child0.Width = 40; root_child0_child0_child0.Height = 40; root_child0_child0.Insert(0, root_child0_child0_child0); YogaNode root_child0_child1 = new YogaNode(config); root_child0_child1.MarginTop = 10; root_child0.Insert(1, root_child0_child1); YogaNode root_child0_child1_child0 = new YogaNode(config); root_child0_child1_child0.Width = 40; root_child0_child1_child0.Height = 40; root_child0_child1.Insert(0, root_child0_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(70f, root_child0.LayoutWidth); Assert.AreEqual(90f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child1.LayoutX); Assert.AreEqual(50f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(500f, root.LayoutWidth); Assert.AreEqual(500f, root.LayoutHeight); Assert.AreEqual(430f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(70f, root_child0.LayoutWidth); Assert.AreEqual(90f, root_child0.LayoutHeight); Assert.AreEqual(30f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0_child0.LayoutY); Assert.AreEqual(40f, root_child0_child0_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child0_child0.LayoutHeight); Assert.AreEqual(30f, root_child0_child1.LayoutX); Assert.AreEqual(50f, root_child0_child1.LayoutY); Assert.AreEqual(40f, root_child0_child1.LayoutWidth); Assert.AreEqual(40f, root_child0_child1.LayoutHeight); Assert.AreEqual(0f, root_child0_child1_child0.LayoutX); Assert.AreEqual(0f, root_child0_child1_child0.LayoutY); Assert.AreEqual(40f, root_child0_child1_child0.LayoutWidth); Assert.AreEqual(40f, root_child0_child1_child0.LayoutHeight); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.Build.Evaluation; using Microsoft.SourceBrowser.Common; namespace Microsoft.SourceBrowser.BuildLogParser { public class LogAnalyzer { public Dictionary<string, string> intermediateAssemblyPathToOutputAssemblyPathMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public MultiDictionary<string, string> assemblyNameToProjectFilePathsMap = new MultiDictionary<string, string>(StringComparer.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); private Dictionary<string, string> projectFilePathToAssemblyNameMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private HashSet<CompilerInvocation> finalInvocations = new HashSet<CompilerInvocation>(CompilerInvocation.Comparer); public static HashSet<string> cacheOfKnownExistingBinaries = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public readonly Dictionary<string, List<string>> ambiguousFinalDestinations = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); public static MultiDictionary<string, CompilerInvocation> ambiguousInvocations = new MultiDictionary<string, CompilerInvocation>(StringComparer.OrdinalIgnoreCase, null); public static MultiDictionary<string, CompilerInvocation> nonExistingReferencesToCompilerInvocationMap = new MultiDictionary<string, CompilerInvocation>(); private static readonly Regex assemblyNameRegex = new Regex(@"<(?:Module)?AssemblyName>((\w|\.|\$|\(|\)|-)+)</(?:Module)?AssemblyName>", RegexOptions.Compiled); private static readonly Regex rootNamespaceRegex = new Regex(@"<RootNamespace>((\w|\.)+)</RootNamespace>", RegexOptions.Compiled); public LogAnalyzer() { cacheOfKnownExistingBinaries.Clear(); nonExistingReferencesToCompilerInvocationMap.Clear(); } public static void DisposeStatics() { cacheOfKnownExistingBinaries.Clear(); cacheOfKnownExistingBinaries = null; ambiguousInvocations.Clear(); ambiguousInvocations = null; nonExistingReferencesToCompilerInvocationMap.Clear(); nonExistingReferencesToCompilerInvocationMap = null; } public static IEnumerable<CompilerInvocation> GetInvocations(string logFilePath) { return GetInvocations(logFiles: new[] { logFilePath }); } public static IEnumerable<CompilerInvocation> GetInvocations(Options options = null, IEnumerable<string> logFiles = null) { var analyzer = new LogAnalyzer(); var invocationBuckets = new Dictionary<string, IEnumerable<CompilerInvocation>>(StringComparer.OrdinalIgnoreCase); using (Disposable.Timing("Analyzing log files")) { #if true Parallel.ForEach(logFiles, logFile => { var set = analyzer.AnalyzeLogFile(logFile); lock (invocationBuckets) { invocationBuckets.Add(Path.GetFileNameWithoutExtension(logFile), set); } }); #else foreach (var logFile in logFiles) { var set = analyzer.AnalyzeLogFile(logFile); lock (invocationBuckets) { invocationBuckets.Add(Path.GetFileNameWithoutExtension(logFile), set); } } #endif } var buckets = invocationBuckets.OrderBy(kvp => kvp.Key).ToArray(); foreach (var bucket in buckets) { foreach (var invocation in bucket.Value) { analyzer.SelectFinalInvocation(invocation); } } FixOutputPaths(analyzer); if (options != null && options.SanityCheck) { using (Disposable.Timing("Sanity check")) { SanityCheck(analyzer, options); } } return analyzer.Invocations; } public class Options { public bool CheckForOrphans = true; public bool CheckForMissingOutputBinary = true; public bool CheckForNonExistingReferences = false; public bool SanityCheck = true; } private static void FixOutputPaths(LogAnalyzer analyzer) { foreach (var invocation in analyzer.Invocations) { // TypeScript if (invocation.OutputAssemblyPath == null) { continue; } if (invocation.OutputAssemblyPath.StartsWith(".") || invocation.OutputAssemblyPath.StartsWith("\\")) { invocation.OutputAssemblyPath = Path.GetFullPath( Path.Combine( Path.GetDirectoryName(invocation.ProjectFilePath), invocation.OutputAssemblyPath)); } invocation.OutputAssemblyPath = Path.GetFullPath(invocation.OutputAssemblyPath); invocation.ProjectFilePath = Path.GetFullPath(invocation.ProjectFilePath); } } private static void SanityCheck(LogAnalyzer analyzer, Options options = null) { var dupes = analyzer.Invocations .Where(i => i.AssemblyName != null) .GroupBy(i => i.AssemblyName, StringComparer.OrdinalIgnoreCase) .Where(g => g.Count() > 1).ToArray(); if (dupes.Any()) { foreach (var dupe in dupes) { Log.Exception("=== Dupes: " + dupe.Key); foreach (var value in dupe) { Log.Exception(value.ToString()); } } } var ambiguousProjects = analyzer.assemblyNameToProjectFilePathsMap.Where(kvp => kvp.Value.Count > 1).ToArray(); if (ambiguousProjects.Any()) { foreach (var ambiguousProject in ambiguousProjects) { Log.Exception("Multiple projects for the same assembly name: " + ambiguousProject.Key); foreach (var value in ambiguousProject.Value) { Log.Exception(value); } } } var ambiguousIntermediatePaths = analyzer.intermediateAssemblyPathToOutputAssemblyPathMap .GroupBy(kvp => Path.GetFileNameWithoutExtension(kvp.Key), StringComparer.OrdinalIgnoreCase) .Where(g => g.Count() > 1) .OrderByDescending(g => g.Count()); if (ambiguousIntermediatePaths.Any()) { } if (analyzer.ambiguousFinalDestinations.Any()) { } foreach (var assemblyName in ambiguousInvocations.Keys.ToArray()) { var values = ambiguousInvocations[assemblyName].ToArray(); bool shouldRemove = true; for (int i = 1; i < values.Length; i++) { if (!values[i].OutputAssemblyPath.Equals(values[0].OutputAssemblyPath)) { // if entries in a bucket are different, we keep the bucket to report it at the end shouldRemove = false; break; } } // remove buckets where all entries are exactly the same if (shouldRemove) { ambiguousInvocations.Remove(assemblyName); } } if (ambiguousInvocations.Any()) { foreach (var ambiguousInvocation in ambiguousInvocations) { Log.Exception("Ambiguous invocations for the same assembly name: " + ambiguousInvocation.Key); foreach (var value in ambiguousInvocation.Value) { Log.Exception(value.ToString()); } } } if (options.CheckForNonExistingReferences) { DumpNonExistingReferences(); } } private static void DumpNonExistingReferences() { foreach (var kvp in nonExistingReferencesToCompilerInvocationMap) { Log.Exception(string.Format("Non existing reference {0} in {1} invocations", kvp.Key, kvp.Value.Count)); } } public static void SanityCheckAfterMetadataAsSource(IEnumerable<CompilerInvocation> invocations, Options options = null) { var allInvocationAssemblyNames = new HashSet<string>( invocations.Select(i => i.AssemblyName), StringComparer.OrdinalIgnoreCase); var allReferenceAssemblyNames = new HashSet<string>( invocations .SelectMany(i => i.ReferencedBinaries) .Select(b => Path.GetFileNameWithoutExtension(b)), StringComparer.OrdinalIgnoreCase); allReferenceAssemblyNames.ExceptWith(allInvocationAssemblyNames); //var invocationsWithUnindexedReferences = analyzer.Invocations // .Where(i => i.ReferencedBinaries.Any(b => !allInvocationAssemblyNames.Contains(Path.GetFileNameWithoutExtension(b)))) // .Select(i => Tuple.Create(i, i.ReferencedBinaries.Where(b => !allInvocationAssemblyNames.Contains(Path.GetFileNameWithoutExtension(b))).ToArray())) // .ToArray(); //if (invocationsWithUnindexedReferences.Length > 0) //{ // throw new InvalidOperationException("Invocation with unindexed references: " + invocationsWithUnindexedReferences.First().Item1.ProjectFilePath); //} if (options == null || options.CheckForMissingOutputBinary) { var invocationsWhereBinaryDoesntExist = invocations.Where( i => !File.Exists(i.OutputAssemblyPath)).ToArray(); if (invocationsWhereBinaryDoesntExist.Length > 0) { throw new InvalidOperationException("Invocation where output binary doesn't exist: " + invocationsWhereBinaryDoesntExist.First().OutputAssemblyPath); } } } public IEnumerable<CompilerInvocation> AnalyzeLogFile(string logFile) { Log.Write(logFile); return ProcessLogFileLines(logFile); } private IEnumerable<CompilerInvocation> ProcessLogFileLines(string logFile) { var invocations = new HashSet<CompilerInvocation>(); var lines = File.ReadLines(logFile); foreach (var currentLine in lines) { string line = currentLine; line = line.Trim(); if (ProcessCopyingFileFrom(line)) { continue; } if (ProcessDoneBuildingProject(line)) { continue; } if (ProcessInvocation(line, i => invocations.Add(i))) { continue; } } return invocations; } private bool ProcessCopyingFileFrom(string line) { if (line.Contains("Copying file from \"") || line.Contains("Moving file from \"")) { int from = line.IndexOf("\"") + 1; int to = line.IndexOf("\" to \""); string intermediateAssemblyPath = line.Substring(from, to - from); if (intermediateAssemblyPath.Contains("..")) { intermediateAssemblyPath = Path.GetFullPath(intermediateAssemblyPath); } string outputAssemblyPath = line.Substring(to + 6, line.Length - to - 8); if (!outputAssemblyPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !outputAssemblyPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && !outputAssemblyPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase)) { // not even an assembly, we don't care about it return true; } var assemblyName = Path.GetFileNameWithoutExtension(outputAssemblyPath); if ((outputAssemblyPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || outputAssemblyPath.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || outputAssemblyPath.EndsWith(".module", StringComparison.OrdinalIgnoreCase) || outputAssemblyPath.EndsWith(".netmodule", StringComparison.OrdinalIgnoreCase)) && !outputAssemblyPath.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase) && !outputAssemblyPath.EndsWith(".XmlSerializers.dll", StringComparison.OrdinalIgnoreCase)) { int tempPlacingIndex = intermediateAssemblyPath.IndexOf(@"\\TempPlacing"); if (tempPlacingIndex > -1) { intermediateAssemblyPath = intermediateAssemblyPath.Remove(tempPlacingIndex, 13); } intermediateAssemblyPath = intermediateAssemblyPath.Replace(@"\\", @"\"); lock (this.intermediateAssemblyPathToOutputAssemblyPathMap) { string existing; if (!this.intermediateAssemblyPathToOutputAssemblyPathMap.TryGetValue(intermediateAssemblyPath, out existing)) { this.intermediateAssemblyPathToOutputAssemblyPathMap[intermediateAssemblyPath] = outputAssemblyPath; } else if (!string.Equals(existing, outputAssemblyPath)) { List<string> bucket; if (!ambiguousFinalDestinations.TryGetValue(assemblyName, out bucket)) { bucket = new List<string>(); ambiguousFinalDestinations.Add(assemblyName, bucket); bucket.Add(existing); } bucket.Add(outputAssemblyPath); if (outputAssemblyPath.Length < existing.Length) { this.intermediateAssemblyPathToOutputAssemblyPathMap[intermediateAssemblyPath] = outputAssemblyPath; } } } } return true; } return false; } private bool ProcessDoneBuildingProject(string line) { var doneBuildingProject = line.IndexOf("Done Building Project"); if (doneBuildingProject > -1) { string projectFilePath = ExtractProjectFilePath(line, doneBuildingProject); if (!File.Exists(projectFilePath)) { Log.Message("Project doesn't exist: " + projectFilePath); return true; } string outputAssemblyName = GetAssemblyNameFromProject(projectFilePath); if (string.IsNullOrWhiteSpace(outputAssemblyName)) { return true; } lock (this.projectFilePathToAssemblyNameMap) { if (!this.projectFilePathToAssemblyNameMap.ContainsKey(projectFilePath)) { lock (this.assemblyNameToProjectFilePathsMap) { this.assemblyNameToProjectFilePathsMap.Add(outputAssemblyName, projectFilePath); } this.projectFilePathToAssemblyNameMap[projectFilePath] = outputAssemblyName; } } return true; } return false; } private bool ProcessInvocation(string line, Action<CompilerInvocation> collector) { bool csc = false; bool vbc = false; bool tsc = false; csc = line.IndexOf("csc", StringComparison.OrdinalIgnoreCase) != -1; if (csc && (line.IndexOf(@"\csc.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\csc2.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\rcsc.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\rcsc2.exe ", StringComparison.OrdinalIgnoreCase) != -1)) { AddInvocation(line, collector); return true; } vbc = line.IndexOf("vbc", StringComparison.OrdinalIgnoreCase) != -1; if (vbc && (line.IndexOf(@"\vbc.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\vbc2.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\rvbc.exe ", StringComparison.OrdinalIgnoreCase) != -1 || line.IndexOf(@"\rvbc2.exe ", StringComparison.OrdinalIgnoreCase) != -1)) { AddInvocation(line, collector); return true; } tsc = line.IndexOf("\tsc.exe ", StringComparison.OrdinalIgnoreCase) != -1; if (tsc) { AddTypeScriptInvocation(line, collector); return true; } return false; } private void AddTypeScriptInvocation(string line, Action<CompilerInvocation> collector) { var invocation = CompilerInvocation.CreateTypeScript(line); collector(invocation); } private static void AddInvocation(string line, Action<CompilerInvocation> collector) { var invocation = new CompilerInvocation(line); collector(invocation); lock (cacheOfKnownExistingBinaries) { foreach (var reference in invocation.ReferencedBinaries) { cacheOfKnownExistingBinaries.Add(reference); } } } private void AssignProjectFilePath(CompilerInvocation invocation) { HashSet<string> projectFilePaths = null; lock (this.assemblyNameToProjectFilePathsMap) { if (this.assemblyNameToProjectFilePathsMap.TryGetValue(invocation.AssemblyName, out projectFilePaths)) { invocation.ProjectFilePath = projectFilePaths.First(); } } } private void AssignOutputAssemblyPath(CompilerInvocation invocation) { string outputAssemblyFilePath = null; lock (this.intermediateAssemblyPathToOutputAssemblyPathMap) { if (this.intermediateAssemblyPathToOutputAssemblyPathMap.TryGetValue(invocation.IntermediateAssemblyPath, out outputAssemblyFilePath)) { outputAssemblyFilePath = Path.GetFullPath(outputAssemblyFilePath); invocation.OutputAssemblyPath = outputAssemblyFilePath; var realAssemblyName = Path.GetFileNameWithoutExtension(outputAssemblyFilePath); if (invocation.AssemblyName != realAssemblyName) { invocation.AssemblyName = realAssemblyName; } } else { invocation.UnknownIntermediatePath = true; } } } private static Dictionary<string, string> projectFilePathToAssemblyNameCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private static readonly object projectCollectionLock = new object(); private string GetAssemblyNameFromProject(string projectFilePath) { string assemblyName = null; if (!File.Exists(projectFilePath)) { return null; } lock (projectFilePathToAssemblyNameCache) { if (projectFilePathToAssemblyNameCache.TryGetValue(projectFilePath, out assemblyName)) { return assemblyName; } } var projectName = Path.GetFileNameWithoutExtension(projectFilePath); var projectText = File.ReadAllText(projectFilePath); var match = assemblyNameRegex.Match(projectText); if (match.Groups.Count >= 2) { assemblyName = match.Groups[1].Value; assemblyName = assemblyName.Replace("$(MyBaseName)", projectName); if (assemblyName == "$(RootNamespace)") { match = rootNamespaceRegex.Match(projectText); if (match.Groups.Count >= 2) { assemblyName = match.Groups[1].Value; } } lock (projectFilePathToAssemblyNameCache) { projectFilePathToAssemblyNameCache[projectFilePath] = assemblyName; } return assemblyName; } var doc = XDocument.Load(projectFilePath); var ns = @"http://schemas.microsoft.com/developer/msbuild/2003"; var propertyGroups = doc.Descendants(XName.Get("PropertyGroup", ns)); var assemblyNameElement = propertyGroups.SelectMany(g => g.Elements(XName.Get("AssemblyName", ns))).LastOrDefault(); if (assemblyNameElement != null && !assemblyNameElement.Value.Contains("$")) { assemblyName = assemblyNameElement.Value; lock (projectFilePathToAssemblyNameCache) { projectFilePathToAssemblyNameCache[projectFilePath] = assemblyName; } return assemblyName; } var projectFileName = Path.GetFileNameWithoutExtension(projectFilePath); var verbatimAssemblyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "LocalSTS" }; if (verbatimAssemblyNames.Contains(projectFileName)) { lock (projectFilePathToAssemblyNameCache) { projectFilePathToAssemblyNameCache[projectFilePath] = projectFileName; } return projectFileName; } lock (projectCollectionLock) { try { var project = ProjectCollection.GlobalProjectCollection.LoadProject( projectFilePath, toolsVersion: "12.0"); assemblyName = project.GetPropertyValue("AssemblyName"); if (assemblyName == "") { assemblyName = projectFileName; } if (assemblyName != null) { lock (projectFilePathToAssemblyNameCache) { projectFilePathToAssemblyNameCache[projectFilePath] = assemblyName; } return assemblyName; } } finally { ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); } } Log.Exception("Couldn't extract AssemblyName from project: " + projectFilePath); lock (projectFilePathToAssemblyNameCache) { projectFilePathToAssemblyNameCache[projectFilePath] = projectFileName; } return projectFileName; } internal void SelectFinalInvocation(CompilerInvocation invocation) { if (invocation.Language == "TypeScript") { lock (finalInvocations) { finalInvocations.Add(invocation); } return; } AssignProjectFilePath(invocation); AssignOutputAssemblyPath(invocation); if (invocation.UnknownIntermediatePath) { Log.Exception("Unknown intermediate path: " + invocation.IntermediateAssemblyPath); } lock (finalInvocations) { if (finalInvocations.Contains(invocation)) { if (!ambiguousInvocations.ContainsKey(invocation.AssemblyName)) { var existing = finalInvocations.First(i => StringComparer.OrdinalIgnoreCase.Equals(i.AssemblyName, invocation.AssemblyName)); ambiguousInvocations.Add(existing.AssemblyName, existing); } ambiguousInvocations.Add(invocation.AssemblyName, invocation); } finalInvocations.Add(invocation); } } private string ExtractProjectFilePath(string line, int start) { start += 23; int end = line.IndexOf('"', start + 1); string projectFilePath = line.Substring(start, end - start); return projectFilePath; } public static void WriteInvocationsToFile(IEnumerable<CompilerInvocation> invocations, string fileName) { var projects = invocations .Where(i => i.ProjectFilePath != null && i.ProjectFilePath.Length >= 3) .Select(i => i.ProjectFilePath.Substring(3)) .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) .ToArray(); var sortedInvocations = invocations .OrderBy(i => i.AssemblyName, StringComparer.OrdinalIgnoreCase); var assemblies = sortedInvocations .Select(i => i.AssemblyName); var assemblyPaths = GetAssemblyPaths(sortedInvocations); assemblyPaths = assemblyPaths .OrderBy(s => Path.GetFileName(s)); var lines = sortedInvocations .SelectMany(i => new[] { i.ProjectFilePath ?? "-", i.OutputAssemblyPath, i.CommandLine }); var path = Path.GetDirectoryName(fileName); var assembliesTxt = Path.Combine(path, "Assemblies.txt"); var projectsTxt = Path.Combine(path, "Projects.txt"); var assemblyPathsTxt = Path.Combine(path, "AssemblyPaths.txt"); File.WriteAllLines(fileName, lines); File.WriteAllLines(projectsTxt, projects); File.WriteAllLines(assembliesTxt, assemblies); File.WriteAllLines(assemblyPathsTxt, assemblyPaths); } private static IEnumerable<string> GetAssemblyPaths(IEnumerable<CompilerInvocation> invocations) { var assemblyNameToFilePathMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (var invocation in invocations) { AddAssemblyToMap(assemblyNameToFilePathMap, invocation.OutputAssemblyPath); foreach (var reference in invocation.ReferencedBinaries) { AddAssemblyToMap(assemblyNameToFilePathMap, reference); } } return assemblyNameToFilePathMap.Values; } private static void AddAssemblyToMap(Dictionary<string, string> assemblyNameToFilePathMap, string reference) { var assemblyName = Path.GetFileNameWithoutExtension(reference); string existing; if (!assemblyNameToFilePathMap.TryGetValue(assemblyName, out existing) || existing.Length > reference.Length || (existing.Length == reference.Length && string.Compare(existing, reference) < 0)) { assemblyNameToFilePathMap[assemblyName] = reference; } } public IEnumerable<CompilerInvocation> Invocations { get { return this.finalInvocations; } } public static void AddMetadataAsSourceAssemblies(List<CompilerInvocation> invocations) { var indexedAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var invocation in invocations) { indexedAssemblies.Add(invocation.AssemblyName); } var notIndexedAssemblies = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (var binary in invocations.SelectMany(i => i.ReferencedBinaries)) { var assemblyName = Path.GetFileNameWithoutExtension(binary); if (!indexedAssemblies.Contains(assemblyName) && ShouldIncludeNotIndexedAssembly(binary, assemblyName)) { string existing = null; if (!notIndexedAssemblies.TryGetValue(assemblyName, out existing) || binary.Length < existing.Length || (binary.Length == existing.Length && binary.CompareTo(existing) > 0)) { // make sure we always prefer the .dll that has shortest file path on disk // Not only to disambiguate in a stable fashion, but also it's a good heuristic // Shorter paths seem to be more widely used and are less obscure. notIndexedAssemblies[assemblyName] = binary; } } } foreach (var notIndexedAssembly in notIndexedAssemblies) { var invocation = new CompilerInvocation() { AssemblyName = notIndexedAssembly.Key, CommandLine = "-", OutputAssemblyPath = notIndexedAssembly.Value, ProjectFilePath = "-" }; invocations.Add(invocation); } } private static bool ShouldIncludeNotIndexedAssembly(string binary, string assemblyName) { if (!File.Exists(binary)) { return false; } return true; } public static void AddNonExistingReference( CompilerInvocation compilerInvocation, string nonExistingReferenceFilePath) { lock (nonExistingReferencesToCompilerInvocationMap) { nonExistingReferencesToCompilerInvocationMap.Add( nonExistingReferenceFilePath, compilerInvocation); } } } }
//originally from Matthew Adams, who was a thorough blog on these things at http://mwadams.spaces.live.com/blog/cns!652A0FB566F633D5!133.entry using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.Windows.Forms; using Palaso.Progress; using Timer=System.Windows.Forms.Timer; namespace Palaso.UI.WindowsForms.Progress { /// <summary> /// Provides a progress dialog similar to the one shown by Windows /// </summary> public class ProgressDialog : Form { public delegate void ProgressCallback(int progress); private Label _statusLabel; private ProgressBar _progressBar; private Label _progressLabel; private Button _cancelButton; private Timer _showWindowIfTakingLongTimeTimer; private Timer _progressTimer; private bool _isClosing; private Label _overviewLabel; private DateTime _startTime; private IContainer components; private BackgroundWorker _backgroundWorker; // private ProgressState _lastHeardFromProgressState; private ProgressState _progressState; private TableLayoutPanel tableLayout; private bool _workerStarted; private bool _appUsingWaitCursor; /// <summary> /// Standard constructor /// </summary> public ProgressDialog() { // // Required for Windows Form Designer support // InitializeComponent(); _statusLabel.BackColor = Color.Transparent; _progressLabel.BackColor = Color.Transparent; _overviewLabel.BackColor = Color.Transparent; _startTime = default(DateTime); Text = Palaso.Reporting.UsageReporter.AppNameToUseInDialogs; _statusLabel.Font = SystemFonts.MessageBoxFont; _progressLabel.Font = SystemFonts.MessageBoxFont; _overviewLabel.Font = SystemFonts.MessageBoxFont; _statusLabel.Text = string.Empty; _progressLabel.Text = string.Empty; _overviewLabel.Text = string.Empty; _cancelButton.MouseEnter += delegate { _appUsingWaitCursor = Application.UseWaitCursor; _cancelButton.Cursor = Cursor = Cursors.Arrow; Application.UseWaitCursor = false; }; _cancelButton.MouseLeave += delegate { Application.UseWaitCursor = _appUsingWaitCursor; }; //avoids the client getting null errors if he checks this when there //has yet to be a callback from the worker // _lastHeardFromProgressState = new NullProgressState(); } private void HandleTableLayoutSizeChanged(object sender, EventArgs e) { if (!IsHandleCreated) CreateHandle(); var desiredHeight = tableLayout.Height + Padding.Top + Padding.Bottom + (Height - ClientSize.Height); var scn = Screen.FromControl(this); Height = Math.Min(desiredHeight, scn.WorkingArea.Height - 20); AutoScroll = (desiredHeight > scn.WorkingArea.Height - 20); } /// <summary> /// Get / set the time in ms to delay /// before showing the dialog /// </summary> private/*doesn't work yet public*/ int DelayShowInterval { get { return _showWindowIfTakingLongTimeTimer.Interval; } set { _showWindowIfTakingLongTimeTimer.Interval = value; } } /// <summary> /// Get / set the text to display in the first status panel /// </summary> public string StatusText { get { return _statusLabel.Text; } set { _statusLabel.Text = value; } } /// <summary> /// Description of why this dialog is even showing /// </summary> public string Overview { get { return _overviewLabel.Text; } set { _overviewLabel.Text = value; } } /// <summary> /// Get / set the minimum range of the progress bar /// </summary> public int ProgressRangeMinimum { get { return _progressBar.Minimum; } set { if (_backgroundWorker == null) { _progressBar.Minimum = value; } } } /// <summary> /// Get / set the maximum range of the progress bar /// </summary> public int ProgressRangeMaximum { get { return _progressBar.Maximum; } set { if (_backgroundWorker != null) { return; } if (InvokeRequired) { Invoke(new ProgressCallback(SetMaximumCrossThread), new object[] { value }); } else { _progressBar.Maximum = value; } } } private void SetMaximumCrossThread(int amount) { ProgressRangeMaximum = amount; } /// <summary> /// Get / set the current value of the progress bar /// </summary> public int Progress { get { return _progressBar.Value; } set { /* these were causing weird, hard to debug (because of threads) * failures. The debugger would reprot that value == max, so why fail? * Debug.Assert(value <= _progressBar.Maximum); */ Debug.WriteLineIf(value > _progressBar.Maximum, "***Warning progres was " + value + " but max is " + _progressBar.Maximum); Debug.Assert(value >= _progressBar.Minimum); if (value > _progressBar.Maximum) { _progressBar.Maximum = value;//not worth crashing over in Release build } if (value < _progressBar.Minimum) { return; //not worth crashing over in Release build } _progressBar.Value = value; } } /// <summary> /// Get/set a boolean which determines whether the form /// will show a cancel option (true) or not (false) /// </summary> public bool CanCancel { get { return _cancelButton.Enabled; } set { _cancelButton.Enabled = value; } } /// <summary> /// If this is set before showing, the dialog will run the worker and respond /// to its events /// </summary> public BackgroundWorker BackgroundWorker { get { return _backgroundWorker; } set { _backgroundWorker = value; _progressBar.Minimum = 0; _progressBar.Maximum = 100; } } public ProgressState ProgressStateResult { get { return _progressState;// return _lastHeardFromProgressState; } } /// <summary> /// Gets or sets the manner in which progress should be indicated on the progress bar. /// </summary> public ProgressBarStyle BarStyle { get { return _progressBar.Style; } set { _progressBar.Style = value; } } /// <summary> /// Optional; one will be created (of some class or subclass) if you don't set it. /// E.g. dlg.ProgressState = new BackgroundWorkerState(dlg.BackgroundWorker); /// Also, you can use the getter to gain access to the progressstate, in order to add arguments /// which the worker method can get at. /// </summary> public ProgressState ProgressState { get { if(_progressState ==null) { if(_backgroundWorker == null) { throw new ArgumentException("You must set BackgroundWorker before accessing this property."); } ProgressState = new BackgroundWorkerState(_backgroundWorker); } return _progressState; } set { if (_progressState!=null) { CancelRequested -= _progressState.CancelRequested; } _progressState = value; CancelRequested += _progressState.CancelRequested; _progressState.TotalNumberOfStepsChanged += OnTotalNumberOfStepsChanged; } } void OnBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //BackgroundWorkerState progressState = e.Result as ProgressState; if(e.Cancelled ) { DialogResult = DialogResult.Cancel; //_progressState.State = ProgressState.StateValue.Finished; } //NB: I don't know how to actually let the BW know there was an error //else if (e.Error != null || else if (ProgressStateResult != null && (ProgressStateResult.State == ProgressState.StateValue.StoppedWithError || ProgressStateResult.ExceptionThatWasEncountered != null)) { //this dialog really can't know whether this was an unexpected exception or not //so don't do this: Reporting.ErrorReporter.ReportException(ProgressStateResult.ExceptionThatWasEncountered, this, false); DialogResult = DialogResult.Abort;//not really matching semantics // _progressState.State = ProgressState.StateValue.StoppedWithError; } else { DialogResult = DialogResult.OK; // _progressState.State = ProgressState.StateValue.Finished; } _isClosing = true; Close(); } void OnBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressState state = e.UserState as ProgressState; if (state != null) { // _lastHeardFromProgressState = state; StatusText = state.StatusLabel; } if (state == null || state is BackgroundWorkerState) { Progress = e.ProgressPercentage; } else { ProgressRangeMaximum = state.TotalNumberOfSteps; Progress = state.NumberOfStepsCompleted; } } /// <summary> /// Show the control, but honor the /// <see cref="DelayShowInterval"/>. /// </summary> private/*doesn't work yet public*/ void DelayShow() { // This creates the control, but doesn't // show it; you can't use CreateControl() // here, because it will return because // the control is not visible CreateHandle(); } //************ //the problem is that our worker reports progress, and we die (only in some circumstance not nailed-down yet) //because of a begininvoke with no window yet. Sometimes, we don't get the callback to //the very important OnBackgroundWorker_RunWorkerCompleted private/*doesn't work yet public*/ void ShowDialogIfTakesLongTime() { DelayShow(); OnStartWorker(this, null); while((_progressState.State == ProgressState.StateValue.NotStarted || _progressState.State == ProgressState.StateValue.Busy) && !this.Visible) { Application.DoEvents(); } } /// <summary> /// Close the dialog, ignoring cancel status /// </summary> public void ForceClose() { _isClosing = true; Close(); } /// <summary> /// Raised when the cancel button is clicked /// </summary> public event EventHandler CancelRequested; /// <summary> /// Raises the cancelled event /// </summary> /// <param name="e">Event data</param> protected virtual void OnCancelled( EventArgs e ) { EventHandler cancelled = CancelRequested; if( cancelled != null ) { cancelled( this, e ); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (_showWindowIfTakingLongTimeTimer != null) { _showWindowIfTakingLongTimeTimer.Stop(); } if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Custom handle creation code /// </summary> /// <param name="e">Event data</param> // protected override void OnHandleCreated(EventArgs e) // { // base.OnHandleCreated (e); // if( !_showOnce ) // { // // First, we don't want this to happen again // _showOnce = true; // // Then, start the timer which will determine whether // // we are going to show this again // _showWindowIfTakingLongTimeTimer.Start(); // } // } /// <summary> /// Custom close handler /// </summary> /// <param name="e">Event data</param> // protected override void OnClosing(CancelEventArgs e) // { // Debug.WriteLine("Dialog:OnClosing"); // if (_showWindowIfTakingLongTimeTimer != null) // { // _showWindowIfTakingLongTimeTimer.Stop(); // } // // if( !_isClosing ) // { // Debug.WriteLine("Warning: OnClosing called but _isClosing=false, attempting cancel click"); // e.Cancel = true; // _cancelButton.PerformClick(); // } // base.OnClosing( e ); // } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this._statusLabel = new System.Windows.Forms.Label(); this._progressBar = new System.Windows.Forms.ProgressBar(); this._cancelButton = new System.Windows.Forms.Button(); this._progressLabel = new System.Windows.Forms.Label(); this._showWindowIfTakingLongTimeTimer = new System.Windows.Forms.Timer(this.components); this._progressTimer = new System.Windows.Forms.Timer(this.components); this._overviewLabel = new System.Windows.Forms.Label(); this.tableLayout = new System.Windows.Forms.TableLayoutPanel(); this.tableLayout.SuspendLayout(); this.SuspendLayout(); // // _statusLabel // this._statusLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._statusLabel.AutoSize = true; this._statusLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.tableLayout.SetColumnSpan(this._statusLabel, 2); this._statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._statusLabel.Location = new System.Drawing.Point(0, 35); this._statusLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5); this._statusLabel.Name = "_statusLabel"; this._statusLabel.Size = new System.Drawing.Size(355, 15); this._statusLabel.TabIndex = 12; this._statusLabel.Text = "#"; // // _progressBar // this._progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayout.SetColumnSpan(this._progressBar, 2); this._progressBar.Location = new System.Drawing.Point(0, 55); this._progressBar.Margin = new System.Windows.Forms.Padding(0, 0, 0, 12); this._progressBar.Name = "_progressBar"; this._progressBar.Size = new System.Drawing.Size(355, 18); this._progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this._progressBar.TabIndex = 11; this._progressBar.Value = 1; // // _cancelButton // this._cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this._cancelButton.AutoSize = true; this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._cancelButton.Location = new System.Drawing.Point(280, 85); this._cancelButton.Margin = new System.Windows.Forms.Padding(8, 0, 0, 0); this._cancelButton.Name = "_cancelButton"; this._cancelButton.Size = new System.Drawing.Size(75, 23); this._cancelButton.TabIndex = 10; this._cancelButton.Text = "&Cancel"; this._cancelButton.Click += new System.EventHandler(this.OnCancelButton_Click); // // _progressLabel // this._progressLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._progressLabel.AutoEllipsis = true; this._progressLabel.AutoSize = true; this._progressLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._progressLabel.Location = new System.Drawing.Point(0, 90); this._progressLabel.Margin = new System.Windows.Forms.Padding(0, 5, 0, 0); this._progressLabel.Name = "_progressLabel"; this._progressLabel.Size = new System.Drawing.Size(272, 13); this._progressLabel.TabIndex = 9; this._progressLabel.Text = "#"; // // _showWindowIfTakingLongTimeTimer // this._showWindowIfTakingLongTimeTimer.Interval = 2000; this._showWindowIfTakingLongTimeTimer.Tick += new System.EventHandler(this.OnTakingLongTimeTimerClick); // // _progressTimer // this._progressTimer.Enabled = true; this._progressTimer.Interval = 1000; this._progressTimer.Tick += new System.EventHandler(this.progressTimer_Tick); // // _overviewLabel // this._overviewLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._overviewLabel.AutoSize = true; this._overviewLabel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.tableLayout.SetColumnSpan(this._overviewLabel, 2); this._overviewLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._overviewLabel.Location = new System.Drawing.Point(0, 0); this._overviewLabel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 20); this._overviewLabel.Name = "_overviewLabel"; this._overviewLabel.Size = new System.Drawing.Size(355, 15); this._overviewLabel.TabIndex = 8; this._overviewLabel.Text = "#"; // // tableLayout // this.tableLayout.AutoSize = true; this.tableLayout.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayout.BackColor = System.Drawing.Color.Transparent; this.tableLayout.ColumnCount = 2; this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayout.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayout.Controls.Add(this._cancelButton, 1, 3); this.tableLayout.Controls.Add(this._overviewLabel, 0, 0); this.tableLayout.Controls.Add(this._progressLabel, 0, 3); this.tableLayout.Controls.Add(this._progressBar, 0, 2); this.tableLayout.Controls.Add(this._statusLabel, 0, 1); this.tableLayout.Dock = System.Windows.Forms.DockStyle.Top; this.tableLayout.Location = new System.Drawing.Point(12, 12); this.tableLayout.Name = "tableLayout"; this.tableLayout.RowCount = 4; this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayout.Size = new System.Drawing.Size(355, 108); this.tableLayout.TabIndex = 13; this.tableLayout.SizeChanged += new System.EventHandler(this.HandleTableLayoutSizeChanged); // // ProgressDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoSize = true; this.ClientSize = new System.Drawing.Size(379, 150); this.ControlBox = false; this.Controls.Add(this.tableLayout); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ProgressDialog"; this.Padding = new System.Windows.Forms.Padding(12); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Palaso"; this.Load += new System.EventHandler(this.ProgressDialog_Load); this.Shown += new System.EventHandler(this.ProgressDialog_Shown); this.tableLayout.ResumeLayout(false); this.tableLayout.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void OnTakingLongTimeTimerClick(object sender, EventArgs e) { // Show the window now the timer has elapsed, and stop the timer _showWindowIfTakingLongTimeTimer.Stop(); if (!this.Visible) { Show(); } } private void OnCancelButton_Click(object sender, EventArgs e) { _showWindowIfTakingLongTimeTimer.Stop(); if(_isClosing) return; Debug.WriteLine("Dialog:OnCancelButton_Click"); // Prevent further cancellation _cancelButton.Enabled = false; _progressTimer.Stop(); _progressLabel.Text = "Canceling..."; // Tell people we're canceling OnCancelled( e ); if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation) { _backgroundWorker.CancelAsync(); } } private void progressTimer_Tick(object sender, EventArgs e) { int range = _progressBar.Maximum - _progressBar.Minimum; if( range <= 0 ) { return; } if( _progressBar.Value <= 0 ) { return; } if (_startTime != default(DateTime)) { TimeSpan elapsed = DateTime.Now - _startTime; double estimatedSeconds = (elapsed.TotalSeconds * range) / _progressBar.Value; TimeSpan estimatedToGo = new TimeSpan(0, 0, 0, (int)(estimatedSeconds - elapsed.TotalSeconds), 0); //_progressLabel.Text = String.Format( // System.Globalization.CultureInfo.CurrentUICulture, // "Elapsed: {0} Remaining: {1}", // GetStringFor(elapsed), // GetStringFor(estimatedToGo)); _progressLabel.Text = String.Format( CultureInfo.CurrentUICulture, "{0}", //GetStringFor(elapsed), GetStringFor(estimatedToGo)); } } private static string GetStringFor( TimeSpan span ) { if( span.TotalDays > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} day {1} hour", span.Days, span.Hours); } else if( span.TotalHours > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} hour {1} minutes", span.Hours, span.Minutes); } else if( span.TotalMinutes > 1 ) { return string.Format(CultureInfo.CurrentUICulture, "{0} minutes {1} seconds", span.Minutes, span.Seconds); } return string.Format( CultureInfo.CurrentUICulture, "{0} seconds", span.Seconds ); } public void OnNumberOfStepsCompletedChanged(object sender, EventArgs e) { Progress = ((ProgressState) sender).NumberOfStepsCompleted; //in case there is no event pump showing us (mono-threaded) progressTimer_Tick(this, null); Refresh(); } public void OnTotalNumberOfStepsChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new ProgressCallback(UpdateTotal), new object[] { ((ProgressState)sender).TotalNumberOfSteps }); } else { UpdateTotal(((ProgressState) sender).TotalNumberOfSteps); } } private void UpdateTotal(int steps) { _startTime = DateTime.Now; ProgressRangeMaximum = steps; Refresh(); } public void OnStatusLabelChanged(object sender, EventArgs e) { StatusText = ((ProgressState)sender).StatusLabel; Refresh(); } private void OnStartWorker(object sender, EventArgs e) { _workerStarted = true; Debug.WriteLine("Dialog:StartWorker"); if (_backgroundWorker != null) { //BW uses percentages (unless it's using our custom ProgressState in the UserState member) ProgressRangeMinimum = 0; ProgressRangeMaximum = 100; //if the actual task can't take cancelling, the caller of this should set CanCancel to false; _backgroundWorker.WorkerSupportsCancellation = CanCancel; _backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(OnBackgroundWorker_ProgressChanged); _backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnBackgroundWorker_RunWorkerCompleted); _backgroundWorker.RunWorkerAsync(ProgressState); } } //this is here, in addition to the OnShown handler, because of a weird bug were a certain, //completely unrelated test (which doesn't use this class at all) can cause tests using this to //fail because the OnShown event is never fired. //I don't know why the orginal code we copied this from was using onshown instead of onload, //but it may have something to do with its "delay show" feature (which I couldn't get to work, //but which would be a terrific thing to have) private void ProgressDialog_Load(object sender, EventArgs e) { if(!_workerStarted) { OnStartWorker(this, null); } } private void ProgressDialog_Shown(object sender, EventArgs e) { if(!_workerStarted) { OnStartWorker(this, null); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Net; using System.Diagnostics.CodeAnalysis; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb { /// <summary> /// the decode packet class. used to decode the packet from the recieve thread. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal class SmbClientDecodePacket : CifsClientDecodePacket { /// <summary> /// the smb client /// </summary> private SmbClient smbClient; /// <summary> /// default constructor. /// </summary> /// <param name = "smbClient"> /// the smbclient contains context for decoder. to update the states of sdk. /// </param> public SmbClientDecodePacket(SmbClient smbClient) : base(smbClient.Context, new CifsClientConfig()) { this.smbClient = smbClient; } /// <summary> /// to decode stack packet from the received message bytes. /// </summary> /// <param name = "endPointIdentity">the endPointIdentity from which the message bytes are received. </param> /// <param name = "messageBytes">the received message bytes to be decoded. </param> /// <param name = "consumedLength">the length of message bytes consumed by decoder. </param> /// <param name = "expectedLength">the length of message bytes the decoder expects to receive. </param> /// <returns>the stack packets decoded from the received message bytes. </returns> internal new SmbPacket[] DecodePacket( object endPointIdentity, byte[] messageBytes, out int consumedLength, out int expectedLength) { // initialize the default values expectedLength = 0; consumedLength = 0; SmbPacket[] packets = null; switch (this.smbClient.Capability.TransportType) { case TransportType.TCP: // direct tcp transport management instance SmbDirectTcpPacket directTcp = new SmbDirectTcpPacket(null); // get the endpoint for direct tcp transport int endpoint = smbClient.Context.GetConnectionID(endPointIdentity as IPEndPoint); // message bytes is invalid if (directTcp.IsPacketInvalid(messageBytes)) { return null; } // if the packet has continue packet, do not parse it. if (directTcp.HasContinuousPacket(messageBytes)) { return null; } // decode the data of packet byte[] packetBytes = directTcp.GetTcpData(messageBytes); packets = DecodePacketFromBytesWithoutTransport(endpoint, packetBytes, out consumedLength, out expectedLength); // decode the header of packet if (packets != null && packets.Length > 0) { packets[0].TransportHeader = CifsMessageUtils.ToStuct<TransportHeader>(messageBytes); } // to consume the additional data consumedLength = Math.Max(consumedLength, directTcp.GetTcpPacketLength(messageBytes)); // update the consumed length with transport consumedLength += directTcp.TcpTransportHeaderSize; break; case TransportType.NetBIOS: // decode packet packets = DecodePacketFromBytesWithoutTransport( Convert.ToInt32(endPointIdentity), messageBytes, out consumedLength, out expectedLength); break; default: break; } return packets; } /// <summary> /// to decode stack packet from the received message bytes. /// the message bytes contains data without transport information /// </summary> /// <param name = "endpoint">the endpoint from which the message bytes are received. </param> /// <param name = "packetBytesWithoutTransport">the received message bytes to be decoded. </param> /// <param name = "consumedLength">the length of message bytes consumed by decoder. </param> /// <param name = "expectedLength">the length of message bytes the decoder expects to receive. </param> /// <returns>the stack packets decoded from the received message bytes. </returns> private SmbPacket[] DecodePacketFromBytesWithoutTransport( int endpoint, byte[] packetBytesWithoutTransport, out int consumedLength, out int expectedLength) { expectedLength = 0; consumedLength = 0; SmbPacket[] packets = new SmbPacket[0]; int packetConsumedLength = 0; int packetExpectedLength = 0; // decode packets using cifs decorder. SmbPacket response = this.DecodeSmbResponseFromBytes( (int)endpoint, packetBytesWithoutTransport, out packetConsumedLength); // Use the decoded packet to UpdateRoleContext if it is not null and ContextUpdate is enabled: if (response != null) { if (this.IsContextUpdateEnabled) { this.clientContext.UpdateRoleContext((int)endpoint, response); } packets = new SmbPacket[] { response }; } // update the length after decode packet. consumedLength += packetConsumedLength; expectedLength += packetExpectedLength; return packets; } /// <summary> /// decode the batched request packet /// </summary> /// <param name="channel">the channel of bytes to read</param> /// <param name="request">the request of the response.</param> /// <param name="smbBatchedResponse">the batched response</param> /// <returns>the consumed length of batched response packet</returns> protected override int DecodeBatchedRequest( Channel channel, SmbPacket request, SmbBatchedResponsePacket smbBatchedResponse) { int result = base.DecodeBatchedRequest(channel, request, smbBatchedResponse); for (SmbBatchedResponsePacket currentPacket = smbBatchedResponse; currentPacket != null && currentPacket.AndxPacket != null; currentPacket = currentPacket.AndxPacket as SmbBatchedResponsePacket) { SmbPacket andxPacket = currentPacket.AndxPacket; // create the smb packet object smbParameters = ObjectUtility.GetFieldValue(currentPacket, "smbParameters"); if (smbParameters != null) { SmbHeader smbHeader = smbBatchedResponse.SmbHeader; smbHeader.Command = (SmbCommand)ObjectUtility.GetFieldValue(smbParameters, "AndXCommand"); andxPacket = CreateSmbResponsePacket(null, smbHeader, null); } // convert from cifs packet to smb packet if (andxPacket != null) { Type smbPacketType = andxPacket.GetType(); andxPacket = ObjectUtility.CreateInstance( smbPacketType.Module.FullyQualifiedName, smbPacketType.FullName, new object[] { currentPacket.AndxPacket }) as SmbPacket; } currentPacket.AndxPacket = andxPacket; } return result; } #region Create Special Response Packet /// <summary> /// to new a Smb response packet in type of the Command in SmbHeader. /// </summary> /// <param name="request">the request of the response.</param> /// <param name="smbHeader">the SMB header of the packet.</param> /// <param name="channel">the channel started with SmbParameters.</param> /// <returns> /// the new response packet. /// the null means that the utility don't know how to create the response. /// </returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] protected override SmbPacket CreateSmbResponsePacket( SmbPacket request, SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; // error packet SmbStatus packetStatus = (SmbStatus)smbHeader.Status; // error packet if (packetStatus != SmbStatus.STATUS_SUCCESS && packetStatus != SmbStatus.STATUS_MORE_PROCESSING_REQUIRED && packetStatus != SmbStatus.STATUS_BUFFER_OVERFLOW) { smbPacket = new SmbErrorResponsePacket(); smbPacket.SmbHeader = smbHeader; return smbPacket; } // success packet switch (smbHeader.Command) { case SmbCommand.SMB_COM_NEGOTIATE: if (smbClient.Capability.IsSupportsExtendedSecurity) { smbPacket = new SmbNegotiateResponsePacket(); } else { smbPacket = new SmbNegotiateImplicitNtlmResponsePacket(); } break; case SmbCommand.SMB_COM_SESSION_SETUP_ANDX: if (smbClient.Capability.IsSupportsExtendedSecurity) { smbPacket = new SmbSessionSetupAndxResponsePacket(); } else { smbPacket = new SmbSessionSetupImplicitNtlmAndxResponsePacket(); } break; case SmbCommand.SMB_COM_TREE_CONNECT_ANDX: smbPacket = new SmbTreeConnectAndxResponsePacket(); break; case SmbCommand.SMB_COM_TREE_DISCONNECT: smbPacket = new SmbTreeDisconnectResponsePacket(); break; case SmbCommand.SMB_COM_LOGOFF_ANDX: smbPacket = new SmbLogoffAndxResponsePacket(); break; case SmbCommand.SMB_COM_NT_CREATE_ANDX: smbPacket = new SmbNtCreateAndxResponsePacket(); break; case SmbCommand.SMB_COM_CLOSE: smbPacket = new SmbCloseResponsePacket(); break; case SmbCommand.SMB_COM_OPEN_ANDX: smbPacket = new SmbOpenAndxResponsePacket(); break; case SmbCommand.SMB_COM_WRITE_ANDX: smbPacket = new SmbWriteAndxResponsePacket(); break; case SmbCommand.SMB_COM_READ_ANDX: smbPacket = new SmbReadAndxResponsePacket(); break; case SmbCommand.SMB_COM_TRANSACTION: smbPacket = this.CreateTransactionResponsePacket(request, smbHeader, channel); break; case SmbCommand.SMB_COM_TRANSACTION2: smbPacket = this.CreateTransaction2ResponsePacket(request, smbHeader, channel); break; case SmbCommand.SMB_COM_NT_TRANSACT: smbPacket = this.CreateNtTransactionResponsePacket(request, smbHeader, channel); break; default: break; } if (smbPacket != null) { smbPacket.SmbHeader = smbHeader; return smbPacket; } return base.CreateSmbResponsePacket(request, smbHeader, channel); } /// <summary> /// createt the transactions packet /// </summary> /// <param name="request">the request packet</param> /// <param name="smbHeader">the smb header of response packet</param> /// <param name="channel">the channel contains the packet bytes</param> /// <returns>the response packet</returns> private SmbPacket CreateTransactionResponsePacket(SmbPacket request, SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { return smbPacket; } SmbTransactionRequestPacket transactionRequest = request as SmbTransactionRequestPacket; if (transactionRequest == null) { return smbPacket; } switch (smbClient.Capability.TransactionSubCommand) { case TransSubCommandExtended.TRANS_EXT_MAILSLOT_WRITE: smbPacket = new SmbTransMailslotWriteResponsePacket(); break; case TransSubCommandExtended.TRANS_EXT_RAP: smbPacket = new SmbTransRapResponsePacket(); break; default: break; } // the packet is find if (smbPacket != null) { return smbPacket; } // if no setup command. break if (transactionRequest.SmbParameters.SetupCount == 0) { return smbPacket; } // decode packet using the setup command switch ((TransSubCommand)transactionRequest.SmbParameters.Setup[0]) { case TransSubCommand.TRANS_SET_NMPIPE_STATE: smbPacket = new SmbTransSetNmpipeStateResponsePacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_STATE: smbPacket = new SmbTransQueryNmpipeStateResponsePacket(); break; case TransSubCommand.TRANS_RAW_READ_NMPIPE: smbPacket = new SmbTransRawReadNmpipeResponsePacket(); break; case TransSubCommand.TRANS_QUERY_NMPIPE_INFO: smbPacket = new SmbTransQueryNmpipeInfoResponsePacket(); break; case TransSubCommand.TRANS_PEEK_NMPIPE: smbPacket = new SmbTransPeekNmpipeResponsePacket(); break; case TransSubCommand.TRANS_TRANSACT_NMPIPE: smbPacket = new SmbTransTransactNmpipeResponsePacket(); break; case TransSubCommand.TRANS_READ_NMPIPE: smbPacket = new SmbTransReadNmpipeResponsePacket(); break; case TransSubCommand.TRANS_WRITE_NMPIPE: smbPacket = new SmbTransWriteNmpipeResponsePacket(); break; case TransSubCommand.TRANS_WAIT_NMPIPE: smbPacket = new SmbTransWaitNmpipeResponsePacket(); break; case TransSubCommand.TRANS_CALL_NMPIPE: smbPacket = new SmbTransCallNmpipeResponsePacket(); break; default: break; } return smbPacket; } /// <summary> /// createt the transactions2 packet /// </summary> /// <param name="request">the request packet</param> /// <param name="smbHeader">the smb header of response packet</param> /// <param name="channel">the channel contains the packet bytes</param> /// <returns>the response packet</returns> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private SmbPacket CreateTransaction2ResponsePacket(SmbPacket request, SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { return smbPacket; } SmbTransaction2RequestPacket transaction2Request = request as SmbTransaction2RequestPacket; if (transaction2Request == null) { return smbPacket; } // if no setup command. break if (transaction2Request.SmbParameters.SetupCount == 0) { return smbPacket; } // decode packet using the setup command switch ((Trans2SubCommand)transaction2Request.SmbParameters.Setup[0]) { case Trans2SubCommand.TRANS2_QUERY_FILE_INFORMATION: SmbTrans2QueryFileInformationRequestPacket queryFileRequest = transaction2Request as SmbTrans2QueryFileInformationRequestPacket; if (queryFileRequest != null) { smbPacket = new SmbTrans2QueryFileInformationResponsePacket( queryFileRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_QUERY_PATH_INFORMATION: SmbTrans2QueryPathInformationRequestPacket queryPathRequest = transaction2Request as SmbTrans2QueryPathInformationRequestPacket; if (queryPathRequest != null) { smbPacket = new SmbTrans2QueryPathInformationResponsePacket( queryPathRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_SET_FILE_INFORMATION: smbPacket = new SmbTrans2SetFileInformationResponsePacket(); break; case Trans2SubCommand.TRANS2_SET_PATH_INFORMATION: smbPacket = new SmbTrans2SetPathInformationResponsePacket(); break; case Trans2SubCommand.TRANS2_QUERY_FS_INFORMATION: SmbTrans2QueryFsInformationRequestPacket queryFsRequest = transaction2Request as SmbTrans2QueryFsInformationRequestPacket; if (queryFsRequest != null) { smbPacket = new SmbTrans2QueryFsInformationResponsePacket( queryFsRequest.Trans2Parameters.InformationLevel); } break; case Trans2SubCommand.TRANS2_SET_FS_INFORMATION: smbPacket = new SmbTrans2SetFsInformationResponsePacket(); break; case Trans2SubCommand.TRANS2_FIND_FIRST2: SmbTrans2FindFirst2RequestPacket first2Request = transaction2Request as SmbTrans2FindFirst2RequestPacket; if (first2Request != null) { smbPacket = new SmbTrans2FindFirst2ResponsePacket(first2Request.Trans2Parameters.InformationLevel, (first2Request.Trans2Parameters.Flags & Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS) == Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS); } break; case Trans2SubCommand.TRANS2_FIND_NEXT2: SmbTrans2FindNext2RequestPacket next2Request = transaction2Request as SmbTrans2FindNext2RequestPacket; if (next2Request != null) { smbPacket = new SmbTrans2FindNext2ResponsePacket(next2Request.Trans2Parameters.InformationLevel, (next2Request.Trans2Parameters.Flags & Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS) == Trans2FindFlags.SMB_FIND_RETURN_RESUME_KEYS); } break; case Trans2SubCommand.TRANS2_GET_DFS_REFERRAL: smbPacket = new SmbTrans2GetDfsReferralResponsePacket(); break; default: break; } return smbPacket; } /// <summary> /// create the nt transaction packet /// </summary> /// <param name="request">the request packet</param> /// <param name="smbHeader">the smb header of response packet</param> /// <param name="channel">the channel contains the packet bytes</param> /// <returns>the response packet</returns> private SmbPacket CreateNtTransactionResponsePacket(SmbPacket request, SmbHeader smbHeader, Channel channel) { SmbPacket smbPacket = null; if (smbHeader.Status == 0 && channel.Peek<byte>(0) == 0 && channel.Peek<ushort>(1) == 0) { return smbPacket; } SmbNtTransactRequestPacket ntTransactRequest = request as SmbNtTransactRequestPacket; if (ntTransactRequest == null) { return smbPacket; } // find regular packet switch ((uint)ntTransactRequest.SmbParameters.Function) { case (uint)NtTransSubCommand.NT_TRANSACT_RENAME: smbPacket = new SmbNtTransRenameResponsePacket(); break; case (uint)NtTransSubCommand.NT_TRANSACT_CREATE: smbPacket = new SmbNtTransactCreateResponsePacket(); break; case (uint)NtTransSubCommand.NT_TRANSACT_IOCTL: NT_TRANSACT_IOCTL_SETUP setup = CifsMessageUtils.ToStuct<NT_TRANSACT_IOCTL_SETUP>( CifsMessageUtils.ToBytesArray<ushort>(ntTransactRequest.SmbParameters.Setup)); switch ((NtTransFunctionCode)setup.FunctionCode) { case NtTransFunctionCode.FSCTL_SRV_ENUMERATE_SNAPSHOTS: smbPacket = new SmbNtTransFsctlSrvEnumerateSnapshotsResponsePacket(); break; case NtTransFunctionCode.FSCTL_SRV_REQUEST_RESUME_KEY: smbPacket = new SmbNtTransFsctlSrvRequestResumeKeyResponsePacket(); break; case NtTransFunctionCode.FSCTL_SRV_COPYCHUNK: smbPacket = new SmbNtTransFsctlSrvCopyChunkResponsePacket(); break; default: smbPacket = new SmbNtTransactIoctlResponsePacket(); break; } break; case (uint)SmbNtTransSubCommand.NT_TRANSACT_QUERY_QUOTA: smbPacket = new SmbNtTransQueryQuotaResponsePacket(); break; case (uint)SmbNtTransSubCommand.NT_TRANSACT_SET_QUOTA: smbPacket = new SmbNtTransSetQuotaResponsePacket(); break; default: break; } return smbPacket; } #endregion } }
/* * Copyright (c) 2010-2015 Pivotal Software, 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. See accompanying * LICENSE file. */ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using NUnit.Framework; namespace Pivotal.Data.GemFireXD.Tests { /// <summary> /// Tests for checking builtin and LDAP authentication schemes. /// </summary> [TestFixture] public class AuthenticationTest : TestBase { #region Setup/TearDown methods [TestFixtureSetUp] public override void FixtureSetup() { InternalSetup(GetType()); SetDefaultDriverType(); int locPort = GetAvailableTCPPort(); initClientPort(); StartGFXDPeer(m_defaultDriverType, "server", s_serverDir, string.Empty, s_clientPort, " -start-locator=localhost[" + locPort + "] -auth-provider=BUILTIN -gemfirexd.user.gemfire1=" + "gemfire1 -user=gemfire1 -password=gemfire1"); } protected override DbConnection OpenNewConnection() { Dictionary<string, string> props = new Dictionary<string, string>(); props.Add("user", "gemfire1"); props.Add("password", "gemfire1"); return base.OpenNewConnection(null, false, props); } protected DbConnection OpenNewNoAuthConnection1() { Dictionary<string, string> props = new Dictionary<string, string>(); props.Add("user", "gemfire1"); props.Add("password", "gemfire"); return base.OpenNewConnection(null, false, props); } protected DbConnection OpenNewNoAuthConnection2() { Dictionary<string, string> props = new Dictionary<string, string>(); props.Add("user", "gemfire2"); props.Add("password", "gemfire"); return base.OpenNewConnection(null, false, props); } protected DbConnection OpenNewNoAuthConnection3() { Dictionary<string, string> props = new Dictionary<string, string>(); props.Add("user", "gemfire3"); props.Add("password", "gemfire3"); return base.OpenNewConnection(null, false, props); } protected override string[] CommonTablesToCreate() { return new string[] { "employee", "numeric_family", "datetime_family" }; } protected override string[] GetProceduresToDrop() { return new string[] { "executeScalarInOutParams", "multipleResultSets", "longParams", "noParam", "Bug66630", "testSize", "decimalTest", "paramTest", "insertEmployee" }; } #endregion [Test] /// <summary> /// check for various connection attributes in addition to auth /// (examples from reference guide) /// </summary> public void BasicAuthentication() { // First use the connection with system user to create a new user. string host = "localhost"; int port = s_clientPort; string user = "gemfire1"; string passwd = "gemfire1"; string connStr = string.Format("server={0}:{1};user={2};password={3}", host, port, user, passwd); using (GFXDClientConnection conn = new GFXDClientConnection(connStr)) { conn.Open(); // fire a simple query to check the connection GFXDCommand cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from sys.members"; Assert.AreEqual(1, cmd.ExecuteScalar()); // create new user cmd.CommandText = "call sys.create_user('gemfirexd.user.gem2', 'gem2')"; Assert.AreEqual(-1, cmd.ExecuteNonQuery()); conn.Close(); } // Open a new connection to the locator having network server // with username and password in the connection string. user = "gem2"; passwd = "gem2"; connStr = string.Format("server={0}:{1};user={2};password={3}", host, port, user, passwd); using (GFXDClientConnection conn = new GFXDClientConnection(connStr)) { conn.Open(); // fire a simple query to check the connection GFXDCommand cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from sys.members"; Assert.AreEqual(1, cmd.ExecuteScalar()); conn.Close(); } // Open a new connection to the locator having network server // with username and password passed as properties. connStr = string.Format("server={0}:{1}", host, port); using (GFXDClientConnection conn = new GFXDClientConnection(connStr)) { Dictionary<string, string> props = new Dictionary<string, string>(); props.Add("user", user); props.Add("password", passwd); props.Add("disable-streaming", "true"); props.Add("load-balance", "false"); conn.Open(props); // fire a simple query to check the connection GFXDCommand cmd = conn.CreateCommand(); cmd.CommandText = "select count(*) from sys.members"; Assert.AreEqual(1, cmd.ExecuteScalar()); conn.Close(); } } [Test] public void ValidInvalidAuthentication() { // expect auth failure with incorrect credentials try { OpenNewNoAuthConnection1(); Assert.Fail("Expected Authentication failure"); } catch (GFXDException gfxde) { if (!"08004".Equals(gfxde.State) || gfxde.Severity != GFXDSeverity .Session || gfxde.ErrorCode != (int)GFXDSeverity.Session) { throw gfxde; } } try { OpenNewNoAuthConnection2(); Assert.Fail("Expected Authentication failure"); } catch (GFXDException gfxde) { if (!"08004".Equals(gfxde.State) || gfxde.Severity != GFXDSeverity .Session || gfxde.ErrorCode != (int)GFXDSeverity.Session) { throw gfxde; } } try { OpenNewNoAuthConnection3(); Assert.Fail("Expected Authentication failure"); } catch (GFXDException gfxde) { if (!"08004".Equals(gfxde.State) || gfxde.Severity != GFXDSeverity .Session || gfxde.ErrorCode != (int)GFXDSeverity.Session) { throw gfxde; } } m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = "select count(*) from SYS.SYSSCHEMAS" + " where SCHEMANAME like 'SYS%'"; m_cmd.CommandTimeout = 10; // Check the Return value for a Correct Query object result = m_cmd.ExecuteScalar(); Assert.AreEqual(8, result, "#A1 Query Result returned is incorrect"); m_cmd.CommandText = "select SCHEMANAME, SCHEMAID from SYS.SYSSCHEMAS" + " where SCHEMANAME like 'SYS%' order by SCHEMANAME asc"; result = m_cmd.ExecuteScalar(); Assert.AreEqual("SYS", result, "#A2 ExecuteScalar expected 'SYS'"); m_cmd.CommandText = "select SCHEMANAME from SYS.SYSSCHEMAS" + " where SCHEMANAME like 'NOTHING%'"; result = m_cmd.ExecuteScalar(); Assert.IsNull(result, "#A3 Null expected if result set is empty"); // Check SqlException is thrown for Invalid Query m_cmd.CommandText = "select count* from SYS.SYSSCHEMAS"; try { result = m_cmd.ExecuteScalar(); Assert.Fail("#B1"); } catch (DbException ex) { // Incorrect syntax near 'from' Assert.IsNotNull(ex.Message, "#B2"); Assert.IsTrue(ex.Message.Contains("from"), "#B3: " + ex.Message); Assert.IsTrue(ex.Message.Contains("42X01"), "#B4: " + ex.Message); } // Parameterized stored procedure calls int int_value = 17; int int2_value = 7; string string_value = "output value changed"; string return_value = "first column of first rowset"; m_cmd.CommandText = "create procedure executeScalarInOutParams " + " (in p1 int, inout p2 int, out p3 varchar(200)) language java " + " parameter style java external name" + " 'tests.TestProcedures.inOutParams' dynamic result sets 1"; m_cmd.CommandType = CommandType.Text; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "call executeScalarInOutParams(?, ?, ?)"; m_cmd.CommandType = CommandType.StoredProcedure; DbParameter p1 = m_cmd.CreateParameter(); p1.ParameterName = "p1"; p1.Direction = ParameterDirection.Input; p1.DbType = DbType.Int32; p1.Value = int_value; m_cmd.Parameters.Add(p1); DbParameter p2 = m_cmd.CreateParameter(); p2.ParameterName = "p2"; p2.Direction = ParameterDirection.InputOutput; p2.DbType = DbType.Int32; p2.Value = int2_value; m_cmd.Parameters.Add(p2); DbParameter p3 = m_cmd.CreateParameter(); p3.ParameterName = "p3"; p3.Direction = ParameterDirection.Output; p3.DbType = DbType.String; p3.Size = 200; m_cmd.Parameters.Add(p3); result = m_cmd.ExecuteScalar(); Assert.AreEqual(return_value, result, "#C1 ExecuteScalar should return" + " 'first column of first rowset'"); Assert.AreEqual(int_value * int2_value, p2.Value, "#C2 ExecuteScalar " + " should fill the parameter collection with the output values"); Assert.AreEqual(string_value, p3.Value, "#C3 ExecuteScalar should" + " fill the parameter collection with the output values"); // check invalid size parameter try { p3.Size = -1; Assert.Fail("#D1 Parameter should throw exception due to size < 0"); } catch (ArgumentOutOfRangeException ex) { // String[2]: the Size property has an invalid // size of 0 Assert.IsNull(ex.InnerException, "#D2"); Assert.IsNotNull(ex.Message, "#D3"); Assert.AreEqual(-1, ex.ActualValue, "#D4"); Assert.IsTrue(ex.ParamName.Contains("Size"), "#D5"); } // try truncation of output value int newSize = 6; p2.Value = int2_value; p3.Size = newSize; p3.Value = null; result = m_cmd.ExecuteScalar(); Assert.AreEqual(return_value, result, "#E1 ExecuteScalar should return" + " 'first column of first rowset'"); Assert.AreEqual(int_value * int2_value, p2.Value, "#E2 ExecuteScalar " + " should fill the parameter collection with the output values"); Assert.AreEqual(string_value.Substring(0, newSize), p3.Value, "#E3 ExecuteScalar should fill the parameter collection with the" + " output values"); } } }
using AutoMapper; using BellRichM.Api.Models; using BellRichM.Helpers.Test; using BellRichM.Logging; using BellRichM.Weather.Api.Controllers; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Models; using BellRichM.Weather.Api.Services; using FluentAssertions; using Machine.Specifications; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using It = Machine.Specifications.It; namespace BellRichM.Weather.Api.TestControllers.Test { public class ObservationsControllerSpecs { protected const string ErrorCode = "errorCode"; protected const string ErrorMessage = "errorMessage"; protected const int InvalidDateTime = 0; protected static LoggingData loggingData; protected static ObservationModel observationModel; protected static Observation observation; protected static ObservationModel notFoundObservationModel; protected static Observation notFoundObservation; protected static ObservationModel invalidObservationModel; protected static List<Observation> observations; protected static List<ObservationModel> observationModels; protected static List<Timestamp> timestamps; protected static List<TimestampModel> timestampModels; protected static TimePeriodModel observationsExistTimePeriod; protected static ObservationsController observationsController; protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static Mock<IMapper> mapperMock; protected static Mock<IObservationService> observationServiceMock; Establish context = () => { // default to no logging loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; observationModel = new ObservationModel { DateTime = 999306300, USUnits = 1, Interval = 5, Barometer = 29.688, Pressure = 29.172642123245641, Altimeter = 29.686688005475741, OutsideTemperature = 67.0, OutsideHumidity = 80.0, WindSpeed = 1.0000024854909466, WindDirection = 135.0, WindGust = 2.0000049709818932, WindGustDirection = 135.0, RainRate = 0.0, Rain = 0.0, DewPoint = 60.619405344958267, Windchill = 67.0, HeatIndex = 67.0, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0 }; observation = new Observation { Year = 2001, Month = 9, Day = 1, Hour = 1, Minute = 5, DateTime = 999306300, USUnits = 1, Interval = 5, Barometer = 29.688, Pressure = 29.172642123245641, Altimeter = 29.686688005475741, OutsideTemperature = 67.0, OutsideHumidity = 80.0, WindSpeed = 1.0000024854909466, WindDirection = 135.0, WindGust = 2.0000049709818932, WindGustDirection = 135.0, RainRate = 0.0, Rain = 0.0, DewPoint = 60.619405344958267, Windchill = 67.0, HeatIndex = 67.0, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0 }; notFoundObservationModel = new ObservationModel { DateTime = 1 }; notFoundObservation = new Observation { DateTime = 1 }; invalidObservationModel = new ObservationModel(); observations = new List<Observation> { new Observation { Year = 2016, Month = 9, Day = 1, Hour = 0, Minute = 0, DateTime = 1472688000, USUnits = 1, Interval = 5, Barometer = 29.237, Pressure = 28.713194886270053, Altimeter = 29.220571639586623, OutsideTemperature = 71.2, OutsideHumidity = 84.0, WindSpeed = 0.0, WindDirection = null, WindGust = 1.9999999981632, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.10878229422875, Windchill = 71.2, HeatIndex = 71.2, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null }, new Observation { Year = 2016, Month = 9, Day = 1, Hour = 0, Minute = 5, DateTime = 1472688300, USUnits = 1, Interval = 5, Barometer = 29.241, Pressure = 28.717161004534812, Altimeter = 29.224595415207432, OutsideTemperature = 71.1, OutsideHumidity = 85.0, WindSpeed = 0.0, WindDirection = null, WindGust = 0.9999999990816, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.35286439744459, Windchill = 71.1, HeatIndex = 71.1, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null }, new Observation { Year = 2016, Month = 9, Day = 1, Hour = 0, Minute = 10, DateTime = 1472688600, USUnits = 1, Interval = 5, Barometer = 29.242, Pressure = 28.718112682295047, Altimeter = 29.225560927735184, OutsideTemperature = 70.9, OutsideHumidity = 85.0, WindSpeed = 0.0, WindDirection = null, WindGust = 0.9999999990816, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.15690929188126, Windchill = 70.9, HeatIndex = 70.9, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null } }; observationModels = new List<ObservationModel> { new ObservationModel { DateTime = 1472688000, USUnits = 1, Interval = 5, Barometer = 29.237, Pressure = 28.713194886270053, Altimeter = 29.220571639586623, OutsideTemperature = 71.2, OutsideHumidity = 84.0, WindSpeed = 0.0, WindDirection = null, WindGust = 1.9999999981632, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.10878229422875, Windchill = 71.2, HeatIndex = 71.2, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null }, new ObservationModel { DateTime = 1472688300, USUnits = 1, Interval = 5, Barometer = 29.241, Pressure = 28.717161004534812, Altimeter = 29.224595415207432, OutsideTemperature = 71.1, OutsideHumidity = 85.0, WindSpeed = 0.0, WindDirection = null, WindGust = 0.9999999990816, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.35286439744459, Windchill = 71.1, HeatIndex = 71.1, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null }, new ObservationModel { DateTime = 1472688600, USUnits = 1, Interval = 5, Barometer = 29.242, Pressure = 28.718112682295047, Altimeter = 29.225560927735184, OutsideTemperature = 70.9, OutsideHumidity = 85.0, WindSpeed = 0.0, WindDirection = null, WindGust = 0.9999999990816, WindGustDirection = 270.0, RainRate = 0.0, Rain = 0.0, DewPoint = 66.15690929188126, Windchill = 70.9, HeatIndex = 70.9, Evapotranspiration = 0.0, Radiation = 0.0, Ultraviolet = 0.0, ExtraTemperature1 = null, ExtraTemperature2 = null, ExtraTemperature3 = null, SoilTemperature1 = null, SoilTemperature2 = null, SoilTemperature3 = null, SoilTemperature4 = null, LeafTemperature1 = null, LeafTemperature2 = null, ExtraHumidity1 = null, ExtraHumidity2 = null, SoilMoisture1 = null, SoilMoisture2 = null, SoilMoisture3 = null, SoilMoisture4 = null, LeafWetness1 = null, LeafWetness2 = null } }; timestamps = new List<Timestamp> { new Timestamp { DateTime = 1472688000 }, new Timestamp { DateTime = 1472688300 }, new Timestamp { DateTime = 1472688600 } }; timestampModels = new List<TimestampModel> { new TimestampModel { DateTime = 1472688000 }, new TimestampModel { DateTime = 1472688300 }, new TimestampModel { DateTime = 1472688600 } }; observationsExistTimePeriod = new TimePeriodModel { StartDateTime = 1472688000, EndDateTime = 1472688600 }; loggerMock = new Mock<ILoggerAdapter<ObservationsController>>(); mapperMock = new Mock<IMapper>(); observationServiceMock = new Mock<IObservationService>(); mapperMock.Setup(x => x.Map<ObservationModel>(observation)).Returns(observationModel); mapperMock.Setup(x => x.Map<Observation>(observationModel)).Returns(observation); mapperMock.Setup(x => x.Map<Observation>(notFoundObservationModel)).Returns(notFoundObservation); mapperMock.Setup(x => x.Map<List<ObservationModel>>(observations)).Returns(observationModels); mapperMock.Setup(x => x.Map<List<TimestampModel>>(timestamps)).Returns(timestampModels); observationServiceMock.Setup(x => x.GetObservation(notFoundObservationModel.DateTime)).Returns(Task.FromResult<Observation>(null)); observationServiceMock.Setup(x => x.GetObservation(observationModel.DateTime)).Returns(Task.FromResult(observation)); observationServiceMock.Setup(x => x.GetObservations(observationsExistTimePeriod)).Returns(Task.FromResult(observations)); observationServiceMock.Setup(x => x.GetTimestamps(observationsExistTimePeriod)).Returns(Task.FromResult(timestamps)); observationServiceMock.Setup(x => x.CreateObservation(notFoundObservation)).Returns(Task.FromResult<Observation>(null)); observationServiceMock.Setup(x => x.CreateObservation(observation)).Returns(Task.FromResult(observation)); observationServiceMock.Setup(x => x.UpdateObservation(notFoundObservation)).Returns(Task.FromResult<Observation>(null)); observationServiceMock.Setup(x => x.UpdateObservation(observation)).Returns(Task.FromResult(observation)); observationServiceMock.Setup(x => x.DeleteObservation(notFoundObservationModel.DateTime)).Returns(Task.FromResult(0)); observationServiceMock.Setup(x => x.DeleteObservation(observationModel.DateTime)).Returns(Task.FromResult(1)); observationsController = new ObservationsController(loggerMock.Object, mapperMock.Object, observationServiceMock.Object); observationsController.ControllerContext.HttpContext = new DefaultHttpContext(); observationsController.ControllerContext.HttpContext.TraceIdentifier = "traceIdentifier"; }; internal class When_getting_an_Existing_observation { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Get, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)observationsController.GetObservation(observationModel.DateTime).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.Should().Equals(200); It should_return_the_observation_model = () => { var retrievedObservationModel = (ObservationModel)result.Value; retrievedObservationModel.Should().BeEquivalentTo(observationModel); }; } internal class When_getting_a_nonexisting_observation_model { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static NotFoundResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Get, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (NotFoundResult)observationsController.GetObservation(notFoundObservationModel.DateTime).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_not_found_status_code = () => result.StatusCode.Should().Equals(404); } internal class When_getting_an_observation_with_an_invalid_modelState { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Get, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.GetObservation(InvalidDateTime).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_GetObservation_method { private static MethodInfo methodInfo; Because of = () => { methodInfo = typeof(ObservationsController).GetMethod("GetObservation"); }; It should_have_CanCreateRoles_policy = () => methodInfo.Should() .BeDecoratedWith<AuthorizeAttribute>(a => a.Policy == "CanViewObservations"); } internal class When_getting_observations { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_GetObservations, "{@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)observationsController.GetObservations(observationsExistTimePeriod).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.Should().Equals(200); It should_return_the_observation_model = () => { var retrievedObservations = (List<ObservationModel>)result.Value; retrievedObservations.Should().BeEquivalentTo(observationModels); }; } internal class When_getting_observations_with_invalid_model { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_GetObservations, "{@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.GetObservations(new TimePeriodModel()).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_GetObservations_method { Because of = () => { }; } internal class When_getting_observation_datetimes { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_GetTimestamps, "{@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)observationsController.GetTimestamps(observationsExistTimePeriod).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.Should().Equals(200); It should_return_the_observation_model = () => { var retrievedTimestamps = (List<TimestampModel>)result.Value; retrievedTimestamps.Should().BeEquivalentTo(timestampModels); }; } internal class When_getting_observation_datetimes_with_invalid_model { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_GetTimestamps, "{@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.GetTimestamps(new TimePeriodModel()).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_GetTimestamps_method { Because of = () => { }; } internal class When_creating_an_observation_succeeds { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Create, "{@observationCreate}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)observationsController.Create(observationModel).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.Should().Equals(200); It should_return_the_observation_model = () => { var retrievedObservationModel = (ObservationModel)result.Value; retrievedObservationModel.Should().BeEquivalentTo(observationModel); }; } internal class When_creating_an_observation_fails { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static NotFoundResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Create, "{@observationCreate}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (NotFoundResult)observationsController.Create(notFoundObservationModel).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_not_found_status_code = () => result.StatusCode.Should().Equals(404); } internal class When_vreating_an_observation_with_an_invalid_modelState { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Create, "{@observationCreate}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.Create(invalidObservationModel).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_Create_method { private static MethodInfo methodInfo; Because of = () => { methodInfo = typeof(ObservationsController).GetMethod("Create"); }; It should_have_CanCreateRoles_policy = () => methodInfo.Should() .BeDecoratedWith<AuthorizeAttribute>(a => a.Policy == "CanCreateObservations"); } internal class When_updating_an_observation_succeeds { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Update, "{@observationUpdateModel}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)observationsController.Update(observationModel).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.Should().Equals(200); It should_return_the_observation_model = () => { var retrievedObservationModel = (ObservationModel)result.Value; retrievedObservationModel.Should().BeEquivalentTo(observationModel); }; } internal class When_updating_an_observation_fails { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static NotFoundResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Update, "{@observationUpdateModel}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (NotFoundResult)observationsController.Update(notFoundObservationModel).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_not_found_status_code = () => result.StatusCode.Should().Equals(404); } internal class When_updating_an_observation_with_an_invalid_modelState { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Update, "{@observationUpdateModel}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.Update(invalidObservationModel).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_Update_method { private static MethodInfo methodInfo; Because of = () => { methodInfo = typeof(ObservationsController).GetMethod("Update"); }; It should_have_CanCreateRoles_policy = () => methodInfo.Should() .BeDecoratedWith<AuthorizeAttribute>(a => a.Policy == "CanUpdateObservations"); } internal class When_deleting_an_observation_succeeds { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static NoContentResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Delete, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (NoContentResult)observationsController.Delete(observationModel.DateTime).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_no_content_code = () => result.StatusCode.ShouldEqual(204); } internal class When_deleting_an_observation_fails { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static NotFoundResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Delete, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (NotFoundResult)observationsController.Delete(notFoundObservationModel.DateTime).Await(); Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; It should_return_not_found_status_code = () => result.StatusCode.Should().Equals(404); } internal class When_deleting_an_observation_with_an_invalid_modelState { protected static Mock<ILoggerAdapter<ObservationsController>> loggerMock; protected static LoggingData loggingData; private static ObjectResult result; Establish context = () => { loggerMock = ObservationsControllerSpecs.loggerMock; loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ObservationsController_Delete, "{@dateTime}") }, ErrorLoggingMessages = new List<string>() }; observationsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ObservationsController>> correct_logging = () => { }; Cleanup after = () => observationsController.ModelState.Clear(); Because of = () => result = (ObjectResult)observationsController.Delete(InvalidDateTime).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_decorating_Observation_Delete_method { private static MethodInfo methodInfo; Because of = () => { methodInfo = typeof(ObservationsController).GetMethod("Delete"); }; It should_have_CanCreateRoles_policy = () => methodInfo.Should() .BeDecoratedWith<AuthorizeAttribute>(a => a.Policy == "CanDeleteObservations"); } } }
'From Squeak 2.2 of Sept 23, 1998 on 15 October 1998 at 11:26:40 pm'! !Collection methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:15'! differenceFromString: aString ^ self decrementFrom: aString! ]style[(22 7 25 7)f1b,f1cgreen;b,f1,f1cblue;! ! !Collection methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:15'! productFromString: aString ^ self scale: aString! ]style[(19 7 17 7)f1b,f1cgreen;b,f1,f1cblue;! ! !Collection methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:16'! quotientFromString: aString ^ self ratioFrom: aString! ]style[(20 7 4 24)f1b,f1cgreen;b,f1,f1cblue;! ! !Collection methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:17'! sumFromString: aString ^ self increment: aString! ! !Number methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:10'! differenceFromString: aString ^ aString asNumeric - self! ]style[(22 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Number methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:11'! productFromString: aString ^ aString asNumeric * self! ]style[(19 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Number methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:10'! quotientFromString: aString ^ aString asNumeric / self! ]style[(20 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Number methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:10'! sumFromString: aString ^ aString asNumeric + self! ]style[(15 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Point methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:09'! differenceFromString: aString ^ aString asNumeric - self! ]style[(22 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Point methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:09'! productFromString: aString ^ aString asNumeric * self! ]style[(19 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Point methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:09'! quotientFromString: aString ^ aString asNumeric / self! ]style[(20 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !Point methodsFor: 'double dispatching' stamp: 'TAG 10/15/1998 23:09'! sumFromString: aString ^ aString asNumeric + self! ]style[(15 7 5 7 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String reorganize! ('accessing' at: at:put: atPin: atWrap: endsWithDigit findAnySubStr:startingAt: findBetweenSubStrs: findDelimiters:startingAt: findInsensitive:allUpper: findString:startingAt: findTokens: findTokens:includes: findTokens:keep: includesSubString: indexOf:startingAt:ifAbsent: indexOfAnyOf: indexOfAnyOf:ifAbsent: indexOfAnyOf:startingAt: indexOfAnyOf:startingAt:ifAbsent: lineCorrespondingToIndex: lineCount lineNumber: linesDo: size skipAnySubStr:startingAt: skipDelimiters:startingAt: startsWithDigit) ('comparing' < <= = > >= alike: beginsWith: caseSensitiveLessOrEqual: charactersExactlyMatching: compare: crc16 endsWith: hash hashMappedBy: match: sameAs:) ('copying' copyReplaceTokens:with: copyUpTo: deepCopy padded:to:with:) ('converting' asByteArray asDate asDisplayText asFileName asHtml asIRCLowercase asLegalSelector asLowercase asNumber asPacked asParagraph asString asSymbol asText asTime asUnHtml asUppercase asUrl asUrlRelativeTo: askIfAddStyle:req: capitalized compressWithTable: contractTo: correctAgainst: correctAgainst:continuedFrom: correctAgainstDictionary:continuedFrom: encodeForHTTP initialInteger keywords sansPeriodSuffix splitInteger stemAndNumericSuffix substrings surroundedBySingleQuotes translateFrom:to:table: translateToLowercase translateWith: truncateTo: truncateWithElipsisTo: withBlanksTrimmed withFirstCharacterDownshifted withSeparatorsCompacted) ('displaying' displayAt: displayOn: displayOn:at: displayProgressAt:from:to:during: newTileMorphRepresentative) ('printing' basicType isLiteral printOn: storeOn: stringRepresentation) ('private' correctAgainstEnumerator:continuedFrom: replaceFrom:to:with:startingAt: stringhash) ('system primitives' compare:with:collated: numArgs) ('as numeric' * + - / asNumeric differenceFromCollection: differenceFromFloat: differenceFromFraction: differenceFromInteger: differenceFromPoint: differenceFromSequenceableCollection: differenceFromString: productFromCollection: productFromFloat: productFromFraction: productFromInteger: productFromPoint: productFromSequenceableCollection: productFromString: quotientFromCollection: quotientFromFloat: quotientFromFraction: quotientFromInteger: quotientFromPoint: quotientFromSequenceableCollection: quotientFromString: sumFromCollection: sumFromFloat: sumFromFraction: sumFromInteger: sumFromPoint: sumFromSequenceableCollection: sumFromString:) ('Celeste' includesSubstring:caseSensitive: withCRs) ('internet' replaceHtmlCharRefs unescapePercents withInternetLineEndings withSqueakLineEndings withoutQuoting) ('testing' isAllSeparators) ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:47'! * aNumeric ^ aNumeric productFromString: self! ]style[(2 8 5 8 24)f1,f1cgreen;,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:47'! + aNumeric ^ aNumeric sumFromString: self! ]style[(2 8 5 8 20)f1,f1cgreen;,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:47'! - aNumeric ^ aNumeric differenceFromString: self! ]style[(2 8 5 8 27)f1,f1cgreen;,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:47'! / aNumeric ^ aNumeric quotientFromString: self! ]style[(2 8 5 8 25)f1,f1cgreen;,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:50'! asNumeric "The plan is to eventually implement this as a more stringent numeric conversion than the default asNumber. #asNumber will for example, return 0 when converting the string 'abc'. IMO, this is not such a good facility since it my hide errors when treating strings like numeric representations. " ^ self asNumber! ]style[(9 2 302 17)f1b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:18'! differenceFromCollection: aCollection ^ aCollection decrement: self! ]style[(26 11 5 11 16)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:51'! differenceFromFloat: aFloat ^ aFloat - self asNumeric! ]style[(21 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:52'! differenceFromFraction: aFraction ^ aFraction - self asNumeric! ]style[(24 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:52'! differenceFromInteger: anInteger ^ anInteger - self asNumeric! ]style[(23 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:53'! differenceFromPoint: aPoint ^ aPoint - self asNumeric! ]style[(21 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:19'! differenceFromSequenceableCollection: aSequence ^ aSequence decrement: self! ]style[(38 9 5 9 16)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:51'! differenceFromString: aString ^ (aString asNumeric - self asNumeric) printString! ]style[(22 7 6 7 40)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:21'! productFromCollection: aCollection ^ aCollection scale: self! ]style[(23 11 5 11 12)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:57'! productFromFloat: aFloat ^ aFloat * self asNumeric! ]style[(18 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:01'! productFromFraction: aFraction ^ aFraction * self asNumeric! ]style[(21 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:01'! productFromInteger: anInteger ^ anInteger * self asNumeric! ]style[(20 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:05'! productFromPoint: aPoint ^ aPoint * self asNumeric! ]style[(18 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:20'! productFromSequenceableCollection: aSequence ^ aSequence scale: self! ]style[(35 9 5 9 12)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:48'! productFromString: aString ^ (aString asNumeric * self asNumeric) printString! ]style[(19 7 6 7 40)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:21'! quotientFromCollection: aCollection ^ aCollection ratio: self! ]style[(24 11 5 11 12)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:57'! quotientFromFloat: aFloat ^ aFloat / self asNumeric! ]style[(19 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:01'! quotientFromFraction: aFraction ^ aFraction / self asNumeric! ]style[(22 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:58'! quotientFromInteger: anInteger ^ anInteger / self asNumeric! ]style[(21 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:02'! quotientFromPoint: aPoint ^ aPoint / self asNumeric! ]style[(19 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:20'! quotientFromSequenceableCollection: aSequence ^ aSequence ratio: self! ]style[(36 9 5 9 12)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:48'! quotientFromString: aString ^ (aString asNumeric / self asNumeric) printString! ]style[(20 7 6 7 40)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:21'! sumFromCollection: aCollection ^ aCollection increment: self! ]style[(19 11 5 11 16)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:57'! sumFromFloat: aFloat ^ aFloat + self asNumeric! ]style[(14 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:02'! sumFromFraction: aFraction ^ aFraction + self asNumeric! ]style[(17 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:58'! sumFromInteger: anInteger ^ anInteger + self asNumeric! ]style[(16 9 5 9 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:02'! sumFromPoint: aPoint ^ aPoint + self asNumeric! ]style[(14 6 5 6 17)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 23:19'! sumFromSequenceableCollection: aSequence ^ aSequence increment: self! ]style[(31 9 5 9 16)f1b,f1cgreen;b,f1,f1cblue;,f1! ! !String methodsFor: 'as numeric' stamp: 'TAG 10/15/1998 22:48'! sumFromString: aString ^ (aString asNumber + self asNumber) printString! ]style[(15 7 6 7 38)f1b,f1cgreen;b,f1,f1cblue;,f1! ! String removeSelector: #differentFromString:! String removeSelector: #differentFromNumeric:! String removeSelector: #differentFromFloat:!
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; namespace System.ServiceModel { [KnownType(typeof(FaultCodeData))] [KnownType(typeof(FaultCodeData[]))] [KnownType(typeof(FaultReasonData))] [KnownType(typeof(FaultReasonData[]))] public class FaultException : CommunicationException { internal const string Namespace = "http://schemas.xmlsoap.org/Microsoft/WindowsCommunicationFoundation/2005/08/Faults/"; private MessageFault _fault; public FaultException() : base(SR.SFxFaultReason) { Code = FaultException.DefaultCode; Reason = FaultException.DefaultReason; } public FaultException(string reason) : base(reason) { Code = FaultException.DefaultCode; Reason = FaultException.CreateReason(reason); } public FaultException(FaultReason reason) : base(FaultException.GetSafeReasonText(reason)) { Code = FaultException.DefaultCode; Reason = FaultException.EnsureReason(reason); } public FaultException(string reason, FaultCode code) : base(reason) { Code = FaultException.EnsureCode(code); Reason = FaultException.CreateReason(reason); } public FaultException(FaultReason reason, FaultCode code) : base(FaultException.GetSafeReasonText(reason)) { Code = FaultException.EnsureCode(code); Reason = FaultException.EnsureReason(reason); } public FaultException(string reason, FaultCode code, string action) : base(reason) { Code = FaultException.EnsureCode(code); Reason = FaultException.CreateReason(reason); Action = action; } internal FaultException(string reason, FaultCode code, string action, Exception innerException) : base(reason, innerException) { Code = FaultException.EnsureCode(code); Reason = FaultException.CreateReason(reason); Action = action; } public FaultException(FaultReason reason, FaultCode code, string action) : base(FaultException.GetSafeReasonText(reason)) { Code = FaultException.EnsureCode(code); Reason = FaultException.EnsureReason(reason); Action = action; } internal FaultException(FaultReason reason, FaultCode code, string action, Exception innerException) : base(FaultException.GetSafeReasonText(reason), innerException) { Code = FaultException.EnsureCode(code); Reason = FaultException.EnsureReason(reason); Action = action; } public FaultException(MessageFault fault) : base(FaultException.GetSafeReasonText(GetReason(fault))) { if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(fault)); } Code = FaultException.EnsureCode(fault.Code); Reason = FaultException.EnsureReason(fault.Reason); _fault = fault; } public FaultException(MessageFault fault, string action) : base(FaultException.GetSafeReasonText(GetReason(fault))) { if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(fault)); } Code = fault.Code; Reason = fault.Reason; _fault = fault; Action = action; } protected FaultException(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } public string Action { get; } public FaultCode Code { get; } private static FaultReason DefaultReason { get { return new FaultReason(SR.SFxFaultReason); } } private static FaultCode DefaultCode { get { return new FaultCode("Sender"); } } public override string Message { get { return FaultException.GetSafeReasonText(Reason); } } public FaultReason Reason { get; } internal MessageFault Fault { get { return _fault; } } private static FaultCode CreateCode(string code) { return (code != null) ? new FaultCode(code) : DefaultCode; } public static FaultException CreateFault(MessageFault messageFault, params Type[] faultDetailTypes) { return CreateFault(messageFault, null, faultDetailTypes); } public static FaultException CreateFault(MessageFault messageFault, string action, params Type[] faultDetailTypes) { if (messageFault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageFault)); } if (faultDetailTypes == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(faultDetailTypes)); } DataContractSerializerFaultFormatter faultFormatter = new DataContractSerializerFaultFormatter(faultDetailTypes); return faultFormatter.Deserialize(messageFault, action); } public virtual MessageFault CreateMessageFault() { if (_fault != null) { return _fault; } else { return MessageFault.CreateFault(Code, Reason); } } private static FaultReason CreateReason(string reason) { return (reason != null) ? new FaultReason(reason) : DefaultReason; } private static FaultReason GetReason(MessageFault fault) { if (fault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(fault)); } return fault.Reason; } internal static string GetSafeReasonText(MessageFault messageFault) { if (messageFault == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageFault)); } return GetSafeReasonText(messageFault.Reason); } internal static string GetSafeReasonText(FaultReason reason) { if (reason == null) { return SR.SFxUnknownFaultNullReason0; } try { return reason.GetMatchingTranslation(System.Globalization.CultureInfo.CurrentCulture).Text; } catch (ArgumentException) { if (reason.Translations.Count == 0) { return SR.SFxUnknownFaultZeroReasons0; } else { return SR.Format(SR.SFxUnknownFaultNoMatchingTranslation1, reason.Translations[0].Text); } } } private static FaultCode EnsureCode(FaultCode code) { return (code != null) ? code : DefaultCode; } private static FaultReason EnsureReason(FaultReason reason) { return (reason != null) ? reason : DefaultReason; } internal class FaultCodeData { private string _name; private string _ns; internal static FaultCode Construct(FaultCodeData[] nodes) { FaultCode code = null; for (int i = nodes.Length - 1; i >= 0; i--) { code = new FaultCode(nodes[i]._name, nodes[i]._ns, code); } return code; } internal static FaultCodeData[] GetObjectData(FaultCode code) { FaultCodeData[] array = new FaultCodeData[FaultCodeData.GetDepth(code)]; for (int i = 0; i < array.Length; i++) { array[i] = new FaultCodeData(); array[i]._name = code.Name; array[i]._ns = code.Namespace; code = code.SubCode; } if (code != null) { Fx.Assert("FaultException.FaultCodeData.GetObjectData: (code != null)"); } return array; } private static int GetDepth(FaultCode code) { int depth = 0; while (code != null) { depth++; code = code.SubCode; } return depth; } } internal class FaultReasonData { private string _xmlLang; private string _text; internal static FaultReason Construct(FaultReasonData[] nodes) { FaultReasonText[] reasons = new FaultReasonText[nodes.Length]; for (int i = 0; i < nodes.Length; i++) { reasons[i] = new FaultReasonText(nodes[i]._text, nodes[i]._xmlLang); } return new FaultReason(reasons); } internal static FaultReasonData[] GetObjectData(FaultReason reason) { SynchronizedReadOnlyCollection<FaultReasonText> translations = reason.Translations; FaultReasonData[] array = new FaultReasonData[translations.Count]; for (int i = 0; i < translations.Count; i++) { array[i] = new FaultReasonData(); array[i]._xmlLang = translations[i].XmlLang; array[i]._text = translations[i].Text; } return array; } } } public class FaultException<TDetail> : FaultException { public FaultException(TDetail detail) : base() { Detail = detail; } public FaultException(TDetail detail, string reason) : base(reason) { Detail = detail; } public FaultException(TDetail detail, FaultReason reason) : base(reason) { Detail = detail; } public FaultException(TDetail detail, string reason, FaultCode code) : base(reason, code) { Detail = detail; } public FaultException(TDetail detail, FaultReason reason, FaultCode code) : base(reason, code) { Detail = detail; } public FaultException(TDetail detail, string reason, FaultCode code, string action) : base(reason, code, action) { Detail = detail; } public FaultException(TDetail detail, FaultReason reason, FaultCode code, string action) : base(reason, code, action) { Detail = detail; } protected FaultException(SerializationInfo info, StreamingContext context) : base(info, context) { throw new PlatformNotSupportedException(); } public TDetail Detail { get; } public override MessageFault CreateMessageFault() { return MessageFault.CreateFault(Code, Reason, Detail); } public override string ToString() { return SR.Format(SR.SFxFaultExceptionToString3, GetType(), Message, Detail != null ? Detail.ToString() : String.Empty); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubnetsOperations operations. /// </summary> internal partial class SubnetsOperations : IServiceOperations<NetworkClient>, ISubnetsOperations { /// <summary> /// Initializes a new instance of the SubnetsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubnetsOperations(NetworkClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkClient /// </summary> public NetworkClient Client { get; private set; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified subnet by virtual network and resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// Expands referenced resources. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Subnet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Subnet> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified subnet. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204 && (int)_statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates a subnet in the specified virtual network. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkName'> /// The name of the virtual network. /// </param> /// <param name='subnetName'> /// The name of the subnet. /// </param> /// <param name='subnetParameters'> /// Parameters supplied to the create or update subnet operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Subnet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkName"); } if (subnetName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetName"); } if (subnetParameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subnetParameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkName", virtualNetworkName); tracingParameters.Add("subnetName", subnetName); tracingParameters.Add("subnetParameters", subnetParameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{virtualNetworkName}", System.Uri.EscapeDataString(virtualNetworkName)); _url = _url.Replace("{subnetName}", System.Uri.EscapeDataString(subnetName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(subnetParameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(subnetParameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Subnet>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Subnet>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all subnets in a virtual network. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Subnet>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Subnet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Subnet>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace MVCMagicSampleMVC6BP.Controllers { using System.Text; using System.Threading; using System.Threading.Tasks; using Boilerplate.Web.Mvc; using Boilerplate.Web.Mvc.Filters; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.OptionsModel; using Constants; using Services; using Settings; public class HomeController : Controller { #region Fields private readonly IOptions<AppSettings> appSettings; private readonly IBrowserConfigService browserConfigService; #if DNX451 // The FeedService is not available for .NET Core because the System.ServiceModel.Syndication.SyndicationFeed // type does not yet exist. See https://github.com/dotnet/wcf/issues/76. private readonly IFeedService feedService; #endif private readonly IManifestService manifestService; private readonly IOpenSearchService openSearchService; private readonly IRobotsService robotsService; private readonly ISitemapService sitemapService; #endregion #region Constructors public HomeController( IBrowserConfigService browserConfigService, #if DNX451 // The FeedService is not available for .NET Core because the System.ServiceModel.Syndication.SyndicationFeed // type does not yet exist. See https://github.com/dotnet/wcf/issues/76. IFeedService feedService, #endif IManifestService manifestService, IOpenSearchService openSearchService, IRobotsService robotsService, ISitemapService sitemapService, IOptions<AppSettings> appSettings) { this.appSettings = appSettings; this.browserConfigService = browserConfigService; #if DNX451 // The FeedService is not available for .NET Core because the System.ServiceModel.Syndication.SyndicationFeed // type does not yet exist. See https://github.com/dotnet/wcf/issues/76. this.feedService = feedService; #endif this.manifestService = manifestService; this.openSearchService = openSearchService; this.robotsService = robotsService; this.sitemapService = sitemapService; } #endregion [HttpGet("", Name = ActionNames.HomeController.Get.Index)] public IActionResult Index() { return this.View(ViewNames.HomeController.Index); } [HttpGet("about", Name = ActionNames.HomeController.Get.About)] public IActionResult About() { return this.View(ViewNames.HomeController.About); } [HttpGet("contact", Name = ActionNames.HomeController.Get.Contact)] public IActionResult Contact() { return this.View(ViewNames.HomeController.Contact); } #if DNX451 // The FeedService is not available for .NET Core because the System.ServiceModel.Syndication.SyndicationFeed // type does not yet exist. See https://github.com/dotnet/wcf/issues/76. /// <summary> /// Gets the Atom 1.0 feed for the current site. Note that Atom 1.0 is used over RSS 2.0 because Atom 1.0 is a /// newer and more well defined format. Atom 1.0 is a standard and RSS is not. See /// http://rehansaeed.com/building-rssatom-feeds-for-asp-net-mvc/ /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> signifying if the request is cancelled. /// See http://www.davepaquette.com/archive/2015/07/19/cancelling-long-running-queries-in-asp-net-mvc-and-web-api.aspx</param> /// <returns>The Atom 1.0 feed for the current site.</returns> [ResponseCache(CacheProfileName = CacheProfileNames.Feed)] [Route("feed", Name = ActionNames.HomeController.Route.Feed)] public async Task<IActionResult> Feed(CancellationToken cancellationToken) { return new AtomActionResult(await this.feedService.GetFeed(cancellationToken)); } #endif [Route("search", Name = ActionNames.HomeController.Route.Search)] public IActionResult Search(string query) { // You can implement a proper search function here and add a Search.cshtml page. // return this.View(HomeControllerAction.Search); // Or you could use Google Custom Search (https://cse.google.co.uk/cse) to index your site and display your // search results in your own page. // For simplicity we are just assuming your site is indexed on Google and redirecting to it. return this.Redirect(string.Format( "https://www.google.co.uk/?q=site:{0} {1}", this.Url.AbsoluteRouteUrl(ActionNames.HomeController.Get.Index), query)); } /// <summary> /// Gets the browserconfig XML for the current site. This allows you to customize the tile, when a user pins /// the site to their Windows 8/10 start screen. See http://www.buildmypinnedsite.com and /// https://msdn.microsoft.com/en-us/library/dn320426%28v=vs.85%29.aspx /// </summary> /// <returns>The browserconfig XML for the current site.</returns> [NoTrailingSlash] [ResponseCache(CacheProfileName = CacheProfileNames.BrowserConfigXml)] [Route("browserconfig.xml", Name = ActionNames.HomeController.Route.BrowserConfigXml)] public ContentResult BrowserConfigXml() { string content = this.browserConfigService.GetBrowserConfigXml(); return this.Content(content, ContentType.Xml, Encoding.UTF8); } /// <summary> /// Gets the manifest JSON for the current site. This allows you to customize the icon and other browser /// settings for Chrome/Android and FireFox (FireFox support is coming). See https://w3c.github.io/manifest/ /// for the official W3C specification. See http://html5doctor.com/web-manifest-specification/ for more /// information. See https://developer.chrome.com/multidevice/android/installtohomescreen for Chrome's /// implementation. /// </summary> /// <returns>The manifest JSON for the current site.</returns> [NoTrailingSlash] [ResponseCache(CacheProfileName = CacheProfileNames.ManifestJson)] [Route("manifest.json", Name = ActionNames.HomeController.Route.ManifestJson)] public ContentResult ManifestJson() { string content = this.manifestService.GetManifestJson(); return this.Content(content, ContentType.Json, Encoding.UTF8); } /// <summary> /// Gets the Open Search XML for the current site. You can customize the contents of this XML here. The open /// search action is cached for one day, adjust this time to whatever you require. See /// http://www.hanselman.com/blog/CommentView.aspx?guid=50cc95b1-c043-451f-9bc2-696dc564766d /// http://www.opensearch.org /// </summary> /// <returns>The Open Search XML for the current site.</returns> [NoTrailingSlash] [ResponseCache(CacheProfileName = CacheProfileNames.OpenSearchXml)] [Route("opensearch.xml", Name = ActionNames.HomeController.Route.OpenSearchXml)] public IActionResult OpenSearchXml() { string content = this.openSearchService.GetOpenSearchXml(); return this.Content(content, ContentType.Xml, Encoding.UTF8); } /// <summary> /// Tells search engines (or robots) how to index your site. /// The reason for dynamically generating this code is to enable generation of the full absolute sitemap URL /// and also to give you added flexibility in case you want to disallow search engines from certain paths. The /// sitemap is cached for one day, adjust this time to whatever you require. See /// http://rehansaeed.com/dynamically-generating-robots-txt-using-asp-net-mvc/ /// </summary> /// <returns>The robots text for the current site.</returns> [NoTrailingSlash] [ResponseCache(CacheProfileName = CacheProfileNames.RobotsText)] [Route("robots.txt", Name = ActionNames.HomeController.Route.RobotsText)] public IActionResult RobotsText() { string content = this.robotsService.GetRobotsText(); return this.Content(content, ContentType.Text, Encoding.UTF8); } /// <summary> /// Gets the sitemap XML for the current site. You can customize the contents of this XML from the /// <see cref="SitemapService"/>. The sitemap is cached for one day, adjust this time to whatever you require. /// http://www.sitemaps.org/protocol.html /// </summary> /// <param name="index">The index of the sitemap to retrieve. <c>null</c> if you want to retrieve the root /// sitemap file, which may be a sitemap index file.</param> /// <returns>The sitemap XML for the current site.</returns> [NoTrailingSlash] [Route("sitemap.xml", Name = ActionNames.HomeController.Route.SitemapXml)] public async Task<IActionResult> SitemapXml(int? index = null) { string content = await this.sitemapService.GetSitemapXml(index); if (content == null) { return this.HttpBadRequest("Sitemap index is out of range."); } return this.Content(content, ContentType.Xml, Encoding.UTF8); } } }
namespace EIDSS.Reports.Document.Lim.Transfer { partial class TransferReport { #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(TransferReport)); this.DetailReportTransfer = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailTransfer = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable4 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable5 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.sp_Rep_LIM_SampleTransferFormTableAdapter1 = new EIDSS.Reports.Document.Lim.Transfer.TransferDataSetTableAdapters.sp_Rep_LIM_SampleTransferFormTableAdapter(); this.transferDataSet1 = new EIDSS.Reports.Document.Lim.Transfer.TransferDataSet(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.transferDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // resources.ApplyResources(this.cellLanguage, "cellLanguage"); this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseBorders = false; this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.xrTable1, 0); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; // // cellBaseSite // resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportTransfer // this.DetailReportTransfer.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailTransfer}); this.DetailReportTransfer.DataAdapter = this.sp_Rep_LIM_SampleTransferFormTableAdapter1; this.DetailReportTransfer.DataMember = "spRepLimSampleTransferForm"; this.DetailReportTransfer.DataSource = this.transferDataSet1; resources.ApplyResources(this.DetailReportTransfer, "DetailReportTransfer"); this.DetailReportTransfer.Level = 0; this.DetailReportTransfer.Name = "DetailReportTransfer"; this.DetailReportTransfer.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); // // DetailTransfer // this.DetailTransfer.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.DetailTransfer.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable4}); resources.ApplyResources(this.DetailTransfer, "DetailTransfer"); this.DetailTransfer.Name = "DetailTransfer"; this.DetailTransfer.StylePriority.UseBorders = false; this.DetailTransfer.StylePriority.UseTextAlignment = false; // // xrTable4 // resources.ApplyResources(this.xrTable4, "xrTable4"); this.xrTable4.Name = "xrTable4"; this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow11}); // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell16, this.xrTableCell18, this.xrTableCell19, this.xrTableCell20}); resources.ApplyResources(this.xrTableRow11, "xrTableRow11"); this.xrTableRow11.Name = "xrTableRow11"; this.xrTableRow11.Weight = 1.6600000000000004D; // // xrTableCell16 // this.xrTableCell16.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable5}); resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.Weight = 0.89032254126764132D; // // xrTable5 // this.xrTable5.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.xrTable5, "xrTable5"); this.xrTable5.Name = "xrTable5"; this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow12, this.xrTableRow13}); this.xrTable5.StylePriority.UseBorders = false; // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell23}); resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); this.xrTableRow12.Name = "xrTableRow12"; this.xrTableRow12.Weight = 1.0000000000000002D; // // xrTableCell23 // this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.ContainerID", "*{0}*")}); resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.StylePriority.UseFont = false; this.xrTableCell23.Weight = 3D; // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell21}); resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); this.xrTableRow13.Name = "xrTableRow13"; this.xrTableRow13.Weight = 0.6144578313253013D; // // xrTableCell21 // this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.ContainerID")}); resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.Weight = 3D; // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.SampleType")}); resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Name = "xrTableCell18"; this.xrTableCell18.Weight = 0.73548389065650177D; // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.DateSampleReceived", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.Weight = 0.63871013026083678D; // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.StorageCondition")}); resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.Weight = 0.73548343781502024D; // // sp_Rep_LIM_SampleTransferFormTableAdapter1 // this.sp_Rep_LIM_SampleTransferFormTableAdapter1.ClearBeforeFill = true; // // transferDataSet1 // this.transferDataSet1.DataSetName = "TransferDataSet"; this.transferDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3, this.xrTableRow5}); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.xrTableCell1}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1D; // // xrTableCell2 // resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.Weight = 1.1593548387096773D; // // xrTableCell1 // this.xrTableCell1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.transferDataSet1, "spRepLimSampleTransferForm.PurposeOfTransfer")}); resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseBorders = false; this.xrTableCell1.Weight = 1.8406451612903227D; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell3, this.xrTableCell4}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 1D; // // xrTableCell3 // resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.Weight = 1.1593548387096773D; // // xrTableCell4 // this.xrTableCell4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.transferDataSet1, "spRepLimSampleTransferForm.TransferredFrom")}); resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseBorders = false; this.xrTableCell4.Weight = 1.8406451612903227D; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6}); resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); this.xrTableRow3.Name = "xrTableRow3"; this.xrTableRow3.Weight = 1D; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.Weight = 1.1593548387096773D; // // xrTableCell6 // this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.transferDataSet1, "spRepLimSampleTransferForm.SentBy")}); resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseBorders = false; this.xrTableCell6.Weight = 1.8406451612903227D; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell9, this.xrTableCell10}); resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.Weight = 1D; // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.Weight = 1.1593548387096773D; // // xrTableCell10 // this.xrTableCell10.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.transferDataSet1, "spRepLimSampleTransferForm.SampleTrasnferredTo")}); resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseBorders = false; this.xrTableCell10.Weight = 1.8406451612903227D; // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.Weight = 1.1593548387096773D; // // xrTableCell8 // this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepLimSampleTransferForm.DateSent", "{0:dd/MM/yyyy}")}); resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseBorders = false; this.xrTableCell8.Weight = 1.8406451612903227D; // // xrTable2 // resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow10}); // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell11, this.xrTableCell12, this.xrTableCell15, this.xrTableCell13}); resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); this.xrTableRow10.Name = "xrTableRow10"; this.xrTableRow10.Weight = 1.1600000000000001D; // // xrTableCell11 // resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.Weight = 0.89032260033392141D; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.Weight = 0.73548389065650177D; // // xrTableCell15 // resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.Weight = 0.638709657730595D; // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.Weight = 0.73548385127898175D; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1}); this.DetailReport.DataAdapter = this.sp_Rep_LIM_SampleTransferFormTableAdapter1; this.DetailReport.DataMember = "spRepLimSampleTransferForm"; this.DetailReport.DataSource = this.transferDataSet1; resources.ApplyResources(this.DetailReport, "DetailReport"); this.DetailReport.Level = 1; this.DetailReport.Name = "DetailReport"; // // Detail1 // resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; // // TransferReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportTransfer, this.DetailReport}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "11.1"; this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.DetailReportTransfer, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.transferDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportTransfer; private DevExpress.XtraReports.UI.DetailBand DetailTransfer; private TransferDataSetTableAdapters.sp_Rep_LIM_SampleTransferFormTableAdapter sp_Rep_LIM_SampleTransferFormTableAdapter1; private TransferDataSet transferDataSet1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTable xrTable4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTable xrTable5; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Net; using System.Threading; using System.IO; using System.Management; using System.Diagnostics; namespace HWD { public delegate void updateListDelegate(int i, string tag); public class HotFixInstaller : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.ListView lsvMachines; private System.Windows.Forms.Button button9; private System.Windows.Forms.TextBox txtUrl; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtComputer; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.CheckBox chkRestart; private System.Windows.Forms.Button button2; private System.Windows.Forms.ProgressBar progressBar1; private System.ComponentModel.Container components = null; public bool anotherLogin; public string username; public string password; public string url; public string computername; public bool restart; private ListViewItem lvi; public HotFixInstaller() { InitializeComponent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(HotFixInstaller)); this.lsvMachines = new System.Windows.Forms.ListView(); this.label1 = new System.Windows.Forms.Label(); this.button9 = new System.Windows.Forms.Button(); this.txtUrl = new System.Windows.Forms.TextBox(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.txtComputer = new System.Windows.Forms.TextBox(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.chkRestart = new System.Windows.Forms.CheckBox(); this.button2 = new System.Windows.Forms.Button(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.SuspendLayout(); // // lsvMachines // this.lsvMachines.BackColor = System.Drawing.Color.OldLace; this.lsvMachines.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.lsvMachines.Dock = System.Windows.Forms.DockStyle.Bottom; this.lsvMachines.Location = new System.Drawing.Point(0, 85); this.lsvMachines.Name = "lsvMachines"; this.lsvMachines.Size = new System.Drawing.Size(504, 208); this.lsvMachines.TabIndex = 0; this.lsvMachines.View = System.Windows.Forms.View.Details; // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 16); this.label1.TabIndex = 1; this.label1.Text = "URL Patch:"; // // button9 // this.button9.BackColor = System.Drawing.Color.SaddleBrown; this.button9.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button9.ForeColor = System.Drawing.Color.OldLace; this.button9.Location = new System.Drawing.Point(384, 8); this.button9.Name = "button9"; this.button9.Size = new System.Drawing.Size(104, 32); this.button9.TabIndex = 15; this.button9.Text = "Download"; this.button9.Click += new System.EventHandler(this.button9_Click); // // txtUrl // this.txtUrl.BackColor = System.Drawing.Color.OldLace; this.txtUrl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtUrl.Location = new System.Drawing.Point(88, 8); this.txtUrl.Name = "txtUrl"; this.txtUrl.Size = new System.Drawing.Size(256, 20); this.txtUrl.TabIndex = 16; this.txtUrl.Text = ""; // // columnHeader1 // this.columnHeader1.Text = "Computer Name"; this.columnHeader1.Width = 224; // // columnHeader2 // this.columnHeader2.Text = "Status"; // // tabControl1 // this.tabControl1.Appearance = System.Windows.Forms.TabAppearance.FlatButtons; this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Top; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(504, 88); this.tabControl1.TabIndex = 18; // // tabPage1 // this.tabPage1.BackColor = System.Drawing.Color.Tan; this.tabPage1.Controls.Add(this.progressBar1); this.tabPage1.Controls.Add(this.button9); this.tabPage1.Controls.Add(this.label1); this.tabPage1.Controls.Add(this.txtUrl); this.tabPage1.Location = new System.Drawing.Point(4, 25); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(496, 59); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Download Patch"; // // tabPage2 // this.tabPage2.BackColor = System.Drawing.Color.Tan; this.tabPage2.Controls.Add(this.button1); this.tabPage2.Controls.Add(this.label2); this.tabPage2.Controls.Add(this.txtComputer); this.tabPage2.Location = new System.Drawing.Point(4, 25); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(496, 59); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Add Computer"; // // button1 // this.button1.BackColor = System.Drawing.Color.SaddleBrown; this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button1.ForeColor = System.Drawing.Color.OldLace; this.button1.Location = new System.Drawing.Point(384, 8); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(104, 32); this.button1.TabIndex = 18; this.button1.Text = "Add"; this.button1.Click += new System.EventHandler(this.button1_Click); // // label2 // this.label2.Location = new System.Drawing.Point(8, 8); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(72, 32); this.label2.TabIndex = 17; this.label2.Text = "Computer Name:"; // // txtComputer // this.txtComputer.BackColor = System.Drawing.Color.OldLace; this.txtComputer.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtComputer.Location = new System.Drawing.Point(88, 8); this.txtComputer.Name = "txtComputer"; this.txtComputer.Size = new System.Drawing.Size(256, 20); this.txtComputer.TabIndex = 19; this.txtComputer.Text = ""; // // tabPage3 // this.tabPage3.BackColor = System.Drawing.Color.Tan; this.tabPage3.Controls.Add(this.button2); this.tabPage3.Controls.Add(this.chkRestart); this.tabPage3.Location = new System.Drawing.Point(4, 25); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(496, 59); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Install Patch"; // // chkRestart // this.chkRestart.FlatStyle = System.Windows.Forms.FlatStyle.System; this.chkRestart.Location = new System.Drawing.Point(8, 8); this.chkRestart.Name = "chkRestart"; this.chkRestart.Size = new System.Drawing.Size(152, 24); this.chkRestart.TabIndex = 18; this.chkRestart.Text = "Restart after install patch"; // // button2 // this.button2.BackColor = System.Drawing.Color.SaddleBrown; this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.button2.ForeColor = System.Drawing.Color.OldLace; this.button2.Location = new System.Drawing.Point(384, 8); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(104, 32); this.button2.TabIndex = 19; this.button2.Text = "Install"; this.button2.Click += new System.EventHandler(this.button2_Click); // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(8, 32); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(368, 24); this.progressBar1.Step = 1; this.progressBar1.TabIndex = 17; // // HotFixInstaller // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.BackColor = System.Drawing.Color.Tan; this.ClientSize = new System.Drawing.Size(504, 293); this.Controls.Add(this.tabControl1); this.Controls.Add(this.lsvMachines); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximumSize = new System.Drawing.Size(512, 320); this.MinimumSize = new System.Drawing.Size(512, 320); this.Name = "HotFixInstaller"; this.Text = "Hotfix Installer"; this.Load += new System.EventHandler(this.HotFixInstaller_Load); this.Closed += new System.EventHandler(this.HotFixInstaller_Closed); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.ResumeLayout(false); } #endregion public void runApp(Object stateInfo) { parRun par = (parRun) stateInfo; try { System.Management.ConnectionOptions co = new ConnectionOptions(); if (this.anotherLogin == true && this.username.Length > 0) { co.Username = this.username; co.Password = this.password; } ManagementScope ms = new ManagementScope("\\\\" + par.ComputerName + "\\root\\cimv2", co); ms.Connect(); ManagementClass mc = new ManagementClass("Win32_Process"); mc.Scope = ms; System.Management.ManagementBaseObject parameters; parameters=mc.GetMethodParameters("Create"); ManagementClass mc2 = new ManagementClass("Win32_ProcessStartup"); mc2.Scope = ms; if (this.chkRestart.Checked) { parameters["CommandLine"] = par.App + " /quiet /forcerestart /f"; } else { parameters["CommandLine"] = par.App + " /quiet /norestart"; } parameters["ProcessStartupInformation"]=mc2; mc.InvokeMethod("Create",parameters,null); this.Invoke(new updateListDelegate(UpdateList), new object[] {par.I, "Installed"}); } catch { this.Invoke(new updateListDelegate(UpdateList), new object[] {par.I, "Error"}); } } private void DownloadFile(string remoteFilename, string localFilename) { int bytesProcessed = 0; Stream remoteStream = null; Stream localStream = null; WebResponse response = null; try { WebRequest request = WebRequest.Create(remoteFilename); if (request != null) { response = request.GetResponse(); if (response != null) { remoteStream = response.GetResponseStream(); localStream = File.Create(localFilename); byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = remoteStream.Read (buffer, 0, buffer.Length); localStream.Write (buffer, 0, bytesRead); bytesProcessed += bytesRead; this.Invoke(new AvanceDownload(UpdateProgress), new object[] {bytesProcessed,response.ContentLength}); } while (bytesRead > 0); } } } catch(Exception e) { MessageBox.Show(e.ToString()); } finally { if (response != null) response.Close(); if (remoteStream != null) remoteStream.Close(); if (localStream != null) localStream.Close(); } return; } public void shareFolder(bool on) { if (on) { ProcessStartInfo prs = new ProcessStartInfo("net.exe", "share hwdtemp="+Environment.CurrentDirectory); prs.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(prs); } else { ProcessStartInfo prs = new ProcessStartInfo("net.exe", "share hwdtemp /DELETE"); prs.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(prs); } } private void UpdateProgress(long receivedBytes, long totalBytes) { this.progressBar1.Value = Convert.ToInt32(Math.Floor((receivedBytes * 100) / totalBytes)); } private void UpdateList(int i, string tag) { this.lsvMachines.Items[i].SubItems[1].Text = tag; } private void button9_Click(object sender, System.EventArgs e) { this.Cursor = Cursors.WaitCursor; if (File.Exists("temp.exe")) { File.Delete("temp.exe"); } this.DownloadFile(this.url, "temp.exe"); this.button9.Enabled = false; this.button1.Enabled = true; this.button2.Enabled = true; this.Cursor = Cursors.Default; } private void HotFixInstaller_Load(object sender, System.EventArgs e) { this.button1.Enabled = false; this.button2.Enabled = false; if (this.computername.Length > 1) { lvi = new ListViewItem(new string[] {this.computername, "Pending"}); this.lsvMachines.Items.Add(lvi); } this.txtUrl.Text = this.url; } private void button1_Click(object sender, System.EventArgs e) { if (this.txtComputer.Text.Length > 1) { lvi = new ListViewItem(new string[] {this.txtComputer.Text, "Pending"}); this.lsvMachines.Items.Add(lvi); } } private void button2_Click(object sender, System.EventArgs e) { this.button2.Enabled = false; this.shareFolder(true); string UNC = "\\\\" + Environment.MachineName + "\\hwdtemp\\temp.exe"; int k = 0; foreach(ListViewItem lv in this.lsvMachines.Items) { string computer = lv.SubItems[0].Text; lv.SubItems[1].Text = "Installing..."; parRun par = new parRun(computer, UNC, k); ThreadPool.QueueUserWorkItem(new WaitCallback(runApp), par); k++; } } private void HotFixInstaller_Closed(object sender, System.EventArgs e) { if (File.Exists("temp.exe")) { File.Delete("temp.exe"); } this.shareFolder(false); } } public class parRun { public string ComputerName; public string App; public int I; public parRun(string machine, string app, int i) { App = app; ComputerName = machine; I = i; } } }
using AIM.Web.ClientApp.Models.EntityModels; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Runtime.Serialization; using TrackableEntities; using TrackableEntities.Client; namespace AIM.Web.ClientApp.Models.EntityModels { [JsonObject(IsReference = true)] [DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")] public partial class User : ModelBase<User>, IEquatable<User>, ITrackable { [DataMember] public int UserId { get { return _userId; } set { if (Equals(value, _userId)) return; _userId = value; NotifyPropertyChanged(m => m.UserId); } } private int _userId; [DataMember] public string FirstName { get { return _firstName; } set { if (Equals(value, _firstName)) return; _firstName = value; NotifyPropertyChanged(m => m.FirstName); } } private string _firstName; [DataMember] public string MiddleName { get { return _middleName; } set { if (Equals(value, _middleName)) return; _middleName = value; NotifyPropertyChanged(m => m.MiddleName); } } private string _middleName; [DataMember] public string LastName { get { return _lastName; } set { if (Equals(value, _lastName)) return; _lastName = value; NotifyPropertyChanged(m => m.LastName); } } private string _lastName; [DataMember] public string Email { get { return _email; } set { if (Equals(value, _email)) return; _email = value; NotifyPropertyChanged(m => m.Email); } } private string _email; [DataMember] public string SocialSecurityNumber { get { return _socialSecurityNumber; } set { if (Equals(value, _socialSecurityNumber)) return; _socialSecurityNumber = value; NotifyPropertyChanged(m => m.SocialSecurityNumber); } } private string _socialSecurityNumber; [DataMember] public int? PersonalInfoId { get { return _personalInfoId; } set { if (Equals(value, _personalInfoId)) return; _personalInfoId = value; NotifyPropertyChanged(m => m.PersonalInfoId); } } private int? _personalInfoId; [DataMember] public int? ApplicantId { get { return _applicantId; } set { if (Equals(value, _applicantId)) return; _applicantId = value; NotifyPropertyChanged(m => m.ApplicantId); } } private int? _applicantId; [DataMember] public int? ApplicationId { get { return _applicationId; } set { if (Equals(value, _applicationId)) return; _applicationId = value; NotifyPropertyChanged(m => m.ApplicationId); } } private int? _applicationId; [DataMember] public int? EmployeeId { get { return _employeeId; } set { if (Equals(value, _employeeId)) return; _employeeId = value; NotifyPropertyChanged(m => m.EmployeeId); } } private int? _employeeId; [DataMember] public string UserName { get { return _userName; } set { if (Equals(value, _userName)) return; _userName = value; NotifyPropertyChanged(m => m.UserName); } } private string _userName; [DataMember] public string Password { get { return _password; } set { if (Equals(value, _password)) return; _password = value; NotifyPropertyChanged(m => m.Password); } } private string _password; [DataMember] public string AspNetUsersId { get { return _aspNetUsersId; } set { if (Equals(value, _aspNetUsersId)) return; _aspNetUsersId = value; NotifyPropertyChanged(m => m.AspNetUsersId); } } private string _aspNetUsersId; [DataMember] public Applicant Applicant { get { return _applicant; } set { if (Equals(value, _applicant)) return; _applicant = value; ApplicantChangeTracker = _applicant == null ? null : new ChangeTrackingCollection<Applicant> { _applicant }; NotifyPropertyChanged(m => m.Applicant); } } private Applicant _applicant; private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; } [DataMember] public AspNetUser AspNetUser { get { return _aspNetUser; } set { if (Equals(value, _aspNetUser)) return; _aspNetUser = value; AspNetUserChangeTracker = _aspNetUser == null ? null : new ChangeTrackingCollection<AspNetUser> { _aspNetUser }; NotifyPropertyChanged(m => m.AspNetUser); } } private AspNetUser _aspNetUser; private ChangeTrackingCollection<AspNetUser> AspNetUserChangeTracker { get; set; } [DataMember] public Employee Employee { get { return _employee; } set { if (Equals(value, _employee)) return; _employee = value; EmployeeChangeTracker = _employee == null ? null : new ChangeTrackingCollection<Employee> { _employee }; NotifyPropertyChanged(m => m.Employee); } } private Employee _employee; private ChangeTrackingCollection<Employee> EmployeeChangeTracker { get; set; } [DataMember] public PersonalInfo PersonalInfo { get { return _personalInfo; } set { if (Equals(value, _personalInfo)) return; _personalInfo = value; PersonalInfoChangeTracker = _personalInfo == null ? null : new ChangeTrackingCollection<PersonalInfo> { _personalInfo }; NotifyPropertyChanged(m => m.PersonalInfo); } } private PersonalInfo _personalInfo; private ChangeTrackingCollection<PersonalInfo> PersonalInfoChangeTracker { get; set; } #region Change Tracking [DataMember] public TrackingState TrackingState { get; set; } [DataMember] public ICollection<string> ModifiedProperties { get; set; } [JsonProperty, DataMember] private Guid EntityIdentifier { get; set; } #pragma warning disable 414 [JsonProperty, DataMember] private Guid _entityIdentity = default(Guid); #pragma warning restore 414 bool IEquatable<User>.Equals(User other) { if (EntityIdentifier != default(Guid)) return EntityIdentifier == other.EntityIdentifier; return false; } #endregion Change Tracking } }
using System; using System.Collections; using System.IO; using System.Reflection; using NUnit.Framework.Api; using NUnit.Framework.Builders; using NUnit.Framework.Extensibility; namespace NUnit.Framework.Internal { /// <summary> /// DefaultTestAssemblyBuilder loads a single assembly and builds a TestSuite /// containing test fixtures present in the assembly. /// </summary> public class NUnitLiteTestAssemblyBuilder : ITestAssemblyBuilder { #region Instance Fields /// <summary> /// The loaded assembly /// </summary> Assembly assembly; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="NUnitLiteTestAssemblyBuilder"/> class. /// </summary> public NUnitLiteTestAssemblyBuilder() { } #endregion #region Build Methods /// <summary> /// Build a suite of tests from a provided assembly /// </summary> /// <param name="assembly">The assembly from which tests are to be built</param> /// <param name="options">A dictionary of options to use in building the suite</param> /// <returns> /// A TestSuite containing the tests found in the assembly /// </returns> public TestSuite Build(Assembly assembly, IDictionary options) { this.assembly = assembly; IList fixtureNames = options["LOAD"] as IList; IList fixtures = GetFixtures(assembly, fixtureNames); if (fixtures.Count > 0) { #if NETCF || SILVERLIGHT || PORTABLE AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(assembly); return BuildTestAssembly(assemblyName.Name, fixtures); #else string assemblyPath = AssemblyHelper.GetAssemblyPath(assembly); return BuildTestAssembly(assemblyPath, fixtures); #endif } return null; } /// <summary> /// Build a suite of tests given the filename of an assembly /// </summary> /// <param name="assemblyName">The filename of the assembly from which tests are to be built</param> /// <param name="options">A dictionary of options to use in building the suite</param> /// <returns> /// A TestSuite containing the tests found in the assembly /// </returns> public TestSuite Build(string assemblyName, IDictionary options) { this.assembly = Load(assemblyName); if (assembly == null) return null; IList fixtureNames = options["LOAD"] as IList; IList fixtures = GetFixtures(assembly, fixtureNames); if (fixtures.Count > 0) return BuildTestAssembly(assemblyName, fixtures); return null; } #endregion #region Helper Methods private Assembly Load(string path) { #if NETCF || SILVERLIGHT || PORTABLE return Assembly.Load(path); #else // Throws if this isn't a managed assembly or if it was built // with a later version of the same assembly. AssemblyName assemblyName = AssemblyName.GetAssemblyName(Path.GetFileName(path)); return Assembly.Load(assemblyName); #endif } private IList GetFixtures(Assembly assembly, IList names) { ObjectList fixtures = new ObjectList(); IList testTypes = GetCandidateFixtureTypes(assembly, names); foreach (Type testType in testTypes) { if (TestFixtureBuilder.CanBuildFrom(testType)) fixtures.Add(TestFixtureBuilder.BuildFrom(testType)); } return fixtures; } private IList GetCandidateFixtureTypes(Assembly assembly, IList names) { IList types = assembly.GetTypes(); if (names == null || names.Count == 0) return types; ObjectList result = new ObjectList(); foreach (string name in names) { Type fixtureType = assembly.GetType(name); if (fixtureType != null) result.Add(fixtureType); else { string prefix = name + "."; foreach (Type type in types) if (type.FullName.StartsWith(prefix)) result.Add(type); } } return result; } private TestSuite BuildFromFixtureType(string assemblyName, Type testType) { ISuiteBuilder testFixtureBuilder = new NUnitTestFixtureBuilder(); // TODO: This is the only situation in which we currently // recognize and load legacy suites. We need to determine // whether to allow them in more places. //if (legacySuiteBuilder.CanBuildFrom(testType)) // return (TestSuite)legacySuiteBuilder.BuildFrom(testType); //else if (testFixtureBuilder.CanBuildFrom(testType)) return BuildTestAssembly(assemblyName, new Test[] { testFixtureBuilder.BuildFrom(testType) }); return null; } private TestSuite BuildTestAssembly(string assemblyName, IList fixtures) { TestSuite testAssembly = new TestAssembly(this.assembly, assemblyName); testAssembly.Seed = Randomizer.InitialSeed; //NamespaceTreeBuilder treeBuilder = // new NamespaceTreeBuilder(testAssembly); //treeBuilder.Add(fixtures); //testAssembly = treeBuilder.RootSuite; foreach (Test fixture in fixtures) testAssembly.Add(fixture); if (fixtures.Count == 0) { testAssembly.RunState = RunState.NotRunnable; testAssembly.Properties.Set(PropertyNames.SkipReason, "Has no TestFixtures"); } #if PORTABLE testAssembly.ApplyAttributesToTest(assembly.AsCustomAttributeProvider()); #else testAssembly.ApplyAttributesToTest(assembly); #endif #if !SILVERLIGHT && !PORTABLE testAssembly.Properties.Set(PropertyNames.ProcessID, System.Diagnostics.Process.GetCurrentProcess().Id); #endif #if !PORTABLE testAssembly.Properties.Set(PropertyNames.AppDomain, AppDomain.CurrentDomain.FriendlyName); #endif // TODO: Make this an option? Add Option to sort assemblies as well? testAssembly.Sort(); return testAssembly; } #endregion } }
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")] public class Bloom : PostEffectsBase { public enum LensFlareStyle { Ghosting = 0, Anamorphic = 1, Combined = 2, } public enum TweakMode { Basic = 0, Complex = 1, } public enum HDRBloomMode { Auto = 0, On = 1, Off = 2, } public enum BloomScreenBlendMode { Screen = 0, Add = 1, } public enum BloomQuality { Cheap = 0, High = 1, } [HideInInspector] public TweakMode tweakMode = 0; [HideInInspector] public BloomScreenBlendMode screenBlendMode = BloomScreenBlendMode.Add; [HideInInspector] public HDRBloomMode hdr = HDRBloomMode.Auto; private bool doHdr = false; [HideInInspector] public float sepBlurSpread = 2.5f; [HideInInspector] public BloomQuality quality = BloomQuality.High; [HideInInspector] public float bloomIntensity = 0.5f; [HideInInspector] public float bloomThreshold = 0.5f; [HideInInspector] public Color bloomThresholdColor = Color.white; [HideInInspector] public int bloomBlurIterations = 2; [HideInInspector] public int hollywoodFlareBlurIterations = 2; [HideInInspector] public float flareRotation = 0.0f; [HideInInspector] public LensFlareStyle lensflareMode = (LensFlareStyle) 1; [HideInInspector] public float hollyStretchWidth = 2.5f; [HideInInspector] public float lensflareIntensity = 0.0f; [HideInInspector] public float lensflareThreshold = 0.3f; [HideInInspector] public float lensFlareSaturation = 0.75f; [HideInInspector] public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f); [HideInInspector] public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f); [HideInInspector] public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f); [HideInInspector] public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f); [HideInInspector] public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; private Material lensFlareMaterial; public Shader screenBlendShader; private Material screenBlend; public Shader blurAndFlaresShader; private Material blurAndFlaresMaterial; public Shader brightPassFilterShader; private Material brightPassFilterMaterial; public override bool CheckResources () { CheckSupport (false); screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial); blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial); brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); if (!isSupported) ReportAutoDisable (); return isSupported; } public void OnRenderImage (RenderTexture source, RenderTexture destination) { if (CheckResources()==false) { Graphics.Blit (source, destination); return; } // screen blend is not supported when HDR is enabled (will cap values) doHdr = false; if (hdr == HDRBloomMode.Auto) doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent<Camera>().hdr; else { doHdr = hdr == HDRBloomMode.On; } doHdr = doHdr && supportHDRTextures; BloomScreenBlendMode realBlendMode = screenBlendMode; if (doHdr) realBlendMode = BloomScreenBlendMode.Add; var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; var rtW2= source.width/2; var rtH2= source.height/2; var rtW4= source.width/4; var rtH4= source.height/4; float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); if (quality > BloomQuality.Cheap) { Graphics.Blit (source, halfRezColorDown, screenBlend, 2); RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2); Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6); RenderTexture.ReleaseTemporary(rtDown4); } else { Graphics.Blit (source, halfRezColorDown); Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6); } RenderTexture.ReleaseTemporary (halfRezColorDown); // cut colors (thresholding) RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor); // blurring if (bloomBlurIterations < 1) bloomBlurIterations = 1; else if (bloomBlurIterations > 10) bloomBlurIterations = 10; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread; // vertical blur RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary(secondQuarterRezColor); secondQuarterRezColor = blur4; // horizontal blur blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary (secondQuarterRezColor); secondQuarterRezColor = blur4; if (quality > BloomQuality.Cheap) { if (iter == 0) { Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (secondQuarterRezColor, quarterRezColor); } else { quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10); } } } if (quality > BloomQuality.Cheap) { Graphics.SetRenderTarget(secondQuarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6); } // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) if (lensflareIntensity > Mathf.Epsilon) { RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); if (lensflareMode == 0) { // ghosting only BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4); if (quality > BloomQuality.Cheap) { // smooth a little blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f)); Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f)); Graphics.SetRenderTarget(rtFlares4); GL.Clear(false, true, Color.black); // Clear to avoid RT restore Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); } // no ugly edges! Vignette (0.975f, rtFlares4, rtFlares4); BlendFlares (rtFlares4, secondQuarterRezColor); } else { //Vignette (0.975ff, rtFlares4, rtFlares4); //DrawBorder(rtFlares4, screenBlend, 8); float flareXRot = 1.0f * Mathf.Cos(flareRotation); float flareyRot = 1.0f * Mathf.Sin(flareRotation); float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f)); blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation); // "pre and cut" quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); // "post" rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f)); // stretch 1st blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // stretch 2nd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); // stretch 3rd blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // additional blur passes for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++) { stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); rtFlares4.DiscardContents(); Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); quarterRezColor.DiscardContents(); Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); } if (lensflareMode == (LensFlareStyle) 1) // anamorphic lens flares AddTo (1.0f, quarterRezColor, secondQuarterRezColor); else { // "combined" lens flares Vignette (1.0f, quarterRezColor, rtFlares4); BlendFlares (rtFlares4, quarterRezColor); AddTo (1.0f, quarterRezColor, secondQuarterRezColor); } } RenderTexture.ReleaseTemporary (rtFlares4); } int blendPass = (int) realBlendMode; //if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon) // blendPass += 4; screenBlend.SetFloat ("_Intensity", bloomIntensity); screenBlend.SetTexture ("_ColorBuffer", source); if (quality > BloomQuality.Cheap) { RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); Graphics.Blit (secondQuarterRezColor, halfRezColorUp); Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (halfRezColorUp); } else Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass); RenderTexture.ReleaseTemporary (quarterRezColor); RenderTexture.ReleaseTemporary (secondQuarterRezColor); } private void AddTo (float intensity_, RenderTexture from, RenderTexture to) { screenBlend.SetFloat ("_Intensity", intensity_); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, screenBlend, 9); } private void BlendFlares (RenderTexture from, RenderTexture to) { lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); to.MarkRestoreExpected(); // additive blending, RT restore expected Graphics.Blit (from, to, lensFlareMaterial); } private void BrightFilter (float thresh, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh)); Graphics.Blit (from, to, brightPassFilterMaterial, 0); } private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to) { brightPassFilterMaterial.SetVector ("_Threshhold", threshColor); Graphics.Blit (from, to, brightPassFilterMaterial, 1); } private void Vignette (float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask); to.MarkRestoreExpected(); // using blending, RT restore expected Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3); } else if (from != to) { Graphics.SetRenderTarget (to); GL.Clear(false, true, Color.black); // clear destination to avoid RT restore Graphics.Blit (from, to); } } } }
namespace Incoding.MSpecContrib { #region << Using >> using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.SqlClient; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Web; using Incoding.Extensions; using Incoding.Maybe; using Incoding.Quality; #endregion public partial class InventFactory<T> { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase; void VerifyUniqueProperty(string property) { Action throwException = () => { throw new ArgumentException("Property should be unique in all dictionary", property); }; if (tunings.ContainsKey(property)) throwException(); if (ignoreProperties.Contains(property)) throwException(); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Positive false")] object GenerateValueOrEmpty(Type propertyType, bool isEmpty) { object value = null; bool isNullable = propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>); propertyType = isNullable ? propertyType.GetGenericArguments()[0] : propertyType; if (propertyType.IsEnum) value = isEmpty ? 0 : Enum.Parse(propertyType, Pleasure.Generator.EnumAsInt(propertyType).ToString(), true); else if (propertyType.IsAnyEquals(typeof(string), typeof(object))) value = isEmpty ? string.Empty : Pleasure.Generator.String(); else if (propertyType == typeof(bool) || propertyType == typeof(bool?)) // ReSharper disable SimplifyConditionalTernaryExpression value = isEmpty ? false : Pleasure.Generator.Bool(); // ReSharper restore SimplifyConditionalTernaryExpression else if (propertyType.IsAnyEquals(typeof(int))) value = isEmpty ? default(int) : Pleasure.Generator.PositiveNumber(1); else if (propertyType.IsAnyEquals(typeof(long))) value = isEmpty ? default(long) : (long)Pleasure.Generator.PositiveNumber(1); else if (propertyType.IsAnyEquals(typeof(short))) value = isEmpty ? default(short) : (short)Pleasure.Generator.PositiveNumber(1); else if (propertyType.IsAnyEquals(typeof(float))) value = isEmpty ? default(float) : Pleasure.Generator.PositiveFloating(); else if (propertyType.IsAnyEquals(typeof(decimal))) value = isEmpty ? default(decimal) : Pleasure.Generator.PositiveDecimal(); else if (propertyType.IsAnyEquals(typeof(double))) value = isEmpty ? default(double) : Pleasure.Generator.PositiveDouble(); else if (propertyType.IsAnyEquals(typeof(byte), typeof(sbyte))) value = isEmpty ? default(byte) : (byte)Pleasure.Generator.PositiveNumber(); else if (propertyType == typeof(char)) value = isEmpty ? default(char) : Pleasure.Generator.String()[0]; else if (propertyType.IsAnyEquals(typeof(DateTime))) value = isEmpty ? new DateTime() : Pleasure.Generator.DateTime(); else if (propertyType.IsAnyEquals(typeof(TimeSpan))) value = isEmpty ? new TimeSpan() : Pleasure.Generator.TimeSpan(); else if (propertyType.IsAnyEquals(typeof(Stream), typeof(MemoryStream))) value = isEmpty ? Pleasure.Generator.Stream(0) : Pleasure.Generator.Stream(); else if (propertyType == typeof(byte[])) value = isEmpty ? Pleasure.ToArray<byte>() : Pleasure.Generator.Bytes(); else if (propertyType == typeof(Guid)) value = isEmpty ? Guid.Empty : Guid.NewGuid(); else if (propertyType == typeof(int[])) value = isEmpty ? Pleasure.ToArray<int>() : Pleasure.ToArray(Pleasure.Generator.PositiveNumber(1)); else if (propertyType == typeof(string[])) value = isEmpty ? Pleasure.ToArray<string>() : Pleasure.ToArray(Pleasure.Generator.String()); else if (propertyType.IsAnyEquals(typeof(HttpPostedFile), typeof(HttpPostedFileBase))) value = isEmpty ? null : Pleasure.Generator.HttpPostedFile(); else if (propertyType == typeof(Dictionary<string, string>)) value = isEmpty ? new Dictionary<string, string>() : Pleasure.ToDynamicDictionary<string>(new { key = Pleasure.Generator.String() }); else if (propertyType == typeof(Dictionary<string, object>)) value = isEmpty ? new Dictionary<string, object>() : Pleasure.ToDynamicDictionary<string>(new { key = Pleasure.Generator.String() }).ToDictionary(r => r.Key, r => (object)r.Value); else if (propertyType == typeof(SqlConnection)) value = new SqlConnection(@"Data Source={0};Database={1};Integrated Security=true;".F(Pleasure.Generator.String(length: 5), Pleasure.Generator.String(length: 5))); return isNullable ? Activator.CreateInstance(typeof(Nullable<>).MakeGenericType(propertyType), value) : value; } #region Fields readonly Dictionary<string, Func<object>> tunings = new Dictionary<string, Func<object>>(); readonly List<string> ignoreProperties = new List<string>(); readonly List<string> empties = new List<string>(); readonly List<Action<T>> callbacks = new List<Action<T>>(); bool isMuteCtor; #endregion #region Api Methods public T CreateEmpty() { var allSetProperties = typeof(T).GetProperties(bindingFlags).Where(r => r.CanWrite); var instance = Activator.CreateInstance<T>(); foreach (var property in allSetProperties) property.SetValue(instance, GenerateValueOrEmpty(property.PropertyType, true), null); return instance; } public T Create() { var instanceType = typeof(T); if (instanceType.IsPrimitive() || instanceType.IsAnyEquals(typeof(SqlConnection), typeof(byte[]))) return (T)GenerateValueOrEmpty(instanceType, false); if (instanceType.IsImplement<IEnumerable>()) { var itemType = instanceType.IsGenericType ? instanceType.GetGenericArguments()[0] : instanceType.GetElementType(); var collections = Activator.CreateInstance(typeof(List<>).MakeGenericType(itemType)) as IList; for (int i = 0; i < Pleasure.Generator.PositiveNumber(minValue: 1, maxValue: 5); i++) collections.Add(Pleasure.Generator.Invent(itemType)); if (instanceType == typeof(ReadOnlyCollection<>).MakeGenericType(itemType)) return (T)Activator.CreateInstance(typeof(ReadOnlyCollection<>).MakeGenericType(itemType), new[] { collections }); if (instanceType == typeof(List<>).MakeGenericType(itemType)) return (T)collections; var array = Array.CreateInstance(itemType, collections.Count); for (int index = 0; index < collections.Count; index++) { var item = collections[index]; array.SetValue(item, index); } object res = array; return (T)res; } return CreateInstance(); } public T CreateInstance() { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.NonPublic; var allPrivateMembers = typeof(T).GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase); var members = typeof(T) .GetMembers(bindingFlags) .Where(r => { var isNotInTuning = !this.tunings.ContainsKey(r.Name); if (r.HasAttribute<IgnoreInventAttribute>() && isNotInTuning) return false; if (allPrivateMembers.Any(info => info.Name == r.Name) && isNotInTuning) return false; var prop = r as PropertyInfo; if (prop != null && prop.CanWrite) return true; var field = r as FieldInfo; if (field != null) return true; return false; }) .ToList(); var dictionary = new Dictionary<string, Type>(); for (int i = 0; i < members.Count; i++) { var memberInfo = members[i]; string memberName = memberInfo.Name; var declaringType = memberInfo is PropertyInfo ? ((PropertyInfo)memberInfo).PropertyType : ((FieldInfo)memberInfo).FieldType; if (dictionary.ContainsKey(memberName)) { if (declaringType != typeof(T) || declaringType == typeof(T).BaseType) members.RemoveAt(i); } else dictionary.Add(memberName, declaringType); } var instance = Activator.CreateInstance<T>(); foreach (var member in members) { if (ignoreProperties.Any(r => r.Equals(member.Name))) continue; var type = member is PropertyInfo ? ((PropertyInfo)member).PropertyType : ((FieldInfo)member).FieldType; var value = instance.TryGetValue(member.Name); var defValue = type.IsValueType ? Activator.CreateInstance(type) : null; bool isHasCtorValue = (value != null && !value.Equals(defValue)) && !isMuteCtor; if (tunings.ContainsKey(member.Name)) value = tunings[member.Name].Invoke(); if (empties.Contains(member.Name)) { value = GenerateValueOrEmpty(type, true); if (value == null) throw new ArgumentException("Can't found empty value for type {0} by field {1}".F(type, member.Name)); } if (!isHasCtorValue && !tunings.ContainsKey(member.Name) && !empties.Contains(member.Name)) value = GenerateValueOrEmpty(type, false); instance.SetValue(member.Name, value); } callbacks.DoEach(action => action(instance)); return instance; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ODataDemo.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); } } } }
// 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 EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System { [DebuggerDisplay("{DebuggerDisplay,nq}")] [DebuggerTypeProxy(typeof(MemoryDebugView<>))] public struct Memory<T> { // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T> // else, object _arrayOrOwnedMemory is a T[] private readonly object _arrayOrOwnedMemory; private readonly int _index; private readonly int _length; private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF; /// <summary> /// Creates a new memory over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _arrayOrOwnedMemory = array; _index = 0; _length = array.Length; } /// <summary> /// Creates a new memory over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the memory.</param> /// <param name="length">The number of items in the memory.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = array; _index = start; _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(OwnedMemory<T> owner, int index, int length) { if (owner == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory); if (index < 0 || length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _arrayOrOwnedMemory = owner; _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask _length = length; } /// <summary> /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(T[] array) => new Memory<T>(array); /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/> /// </summary> public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count); /// <summary> /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { if (memory._index < 0) return new ReadOnlyMemory<T>((OwnedMemory<T>)memory._arrayOrOwnedMemory, memory._index & RemoveOwnedFlagBitMask, memory._length); return new ReadOnlyMemory<T>((T[])memory._arrayOrOwnedMemory, memory._index, memory._length); } //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Returns an empty <see cref="Memory{T}"/> /// </summary> public static Memory<T> Empty { get; } = Array.Empty<T>(); /// <summary> /// The number of items in the memory. /// </summary> public int Length => _length; /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty => _length == 0; /// <summary> /// Forms a slice out of the given memory, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start); } /// <summary> /// Forms a slice out of the given memory, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); if (_index < 0) return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length); return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, length); } /// <summary> /// Returns a span from the memory. /// </summary> public Span<T> Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_index < 0) return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length); return new Span<T>((T[])_arrayOrOwnedMemory, _index, _length); } } public unsafe MemoryHandle Retain(bool pin = false) { MemoryHandle memoryHandle; if (pin) { if (_index < 0) { memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin(); memoryHandle.AddOffset((_index & RemoveOwnedFlagBitMask) * Unsafe.SizeOf<T>()); } else { var array = (T[])_arrayOrOwnedMemory; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index); memoryHandle = new MemoryHandle(null, pointer, handle); } } else { if (_index < 0) { ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain(); memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory); } else { memoryHandle = new MemoryHandle(null); } } return memoryHandle; } /// <summary> /// Get an array segment from the underlying memory. /// If unable to get the array segment, return false with a default array segment. /// </summary> public bool TryGetArray(out ArraySegment<T> arraySegment) { if (_index < 0) { if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment)) { arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length); return true; } } else { arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length); return true; } arraySegment = default(ArraySegment<T>); return false; } /// <summary> /// Copies the contents from the memory into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() => Span.ToArray(); [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { if (obj is ReadOnlyMemory<T>) { return ((ReadOnlyMemory<T>)obj).Equals(this); } else if (obj is Memory<T> memory) { return Equals(memory); } else { return false; } } /// <summary> /// Returns true if the memory points to the same array and has the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Memory<T> other) { return _arrayOrOwnedMemory == other._arrayOrOwnedMemory && _index == other._index && _length == other._length; } [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode()); } private static int CombineHashCodes(int left, int right) { return ((left << 5) + left) ^ right; } private static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } } }
// -------------------------------------------------------------------------------- // Copyright AspDotNetStorefront.com. All Rights Reserved. // http://www.aspdotnetstorefront.com // For details on this license please visit the product homepage at the URL above. // THE ABOVE NOTICE MUST REMAIN INTACT. // -------------------------------------------------------------------------------- using AspDotNetStorefrontControls; using AspDotNetStorefrontCore; using System; using System.Data; using System.Data.SqlClient; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; namespace AspDotNetStorefront { public partial class _Address : SkinBase { private String AddressTypeString = String.Empty; private const String BILLING = "BILLING"; private const String SHIPPING = "SHIPPING"; private readonly bool ShowEcheck = AppLogic.AppConfig("PaymentMethods").ToUpperInvariant().Contains(AppLogic.ro_PMECheck); private AddressTypes AddressMode { get { // default to shipping address AddressTypes addressType = AddressTypes.Shipping; string addressTypeQueryString = CommonLogic.QueryStringCanBeDangerousContent("AddressType"); if (!CommonLogic.IsStringNullOrEmpty(addressTypeQueryString)) { if (addressTypeQueryString.Trim().ToUpper() == BILLING || addressTypeQueryString.Trim().ToUpper() == SHIPPING) { addressType = (AddressTypes)Enum.Parse(typeof(AddressTypes), addressTypeQueryString, true); } } return addressType; } } private Boolean CustomerCCRequired { get { return ThisCustomer.MasterShouldWeStoreCreditCardInfo && AppLogic.AppConfigBool("StoreCCInDB"); } } protected override void OnInit(EventArgs e) { if (ThisCustomer.IsRegistered == false && !CommonLogic.QueryStringBool("skipreg")) { Response.Redirect("~/signin.aspx"); } InitializePageContent(); base.OnInit(e); } protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { String addressErrorPrompt = CommonLogic.QueryStringCanBeDangerousContent("prompt"); if (addressErrorPrompt.Length > 0) { ErrorMsgLabel.Visible = true; ErrorMsgLabel.Text = addressErrorPrompt; } } else ErrorMsgLabel.Visible = false; } private void InitializePageContent() { //Gets the datasource for the datalist control if (dlAddress != null) { if (!this.IsPostBack) { LoadData(); } } if (ctrlNewAddress != null) { CountryDropDownData(ctrlNewAddress); StateDropDownData(ctrlNewAddress, ThisCustomer.LocaleSetting); } if(CommonLogic.QueryStringCanBeDangerousContent("Checkout").EqualsIgnoreCase(Boolean.TrueString)) btnReturnUrl.Text = "account.aspx.60".StringResource(); } private void LoadData() { GatewayCheckoutByAmazon.CheckoutByAmazon checkoutByAmazon = new GatewayCheckoutByAmazon.CheckoutByAmazon(); var addresses = new Addresses(); foreach (Address address in GetAddresses()) { if (checkoutByAmazon.IsAmazonAddress(address)) continue; address.AddressType = this.AddressMode; if (CheckPOBox(address.Address1) && (address.AddressType == AddressTypes.Shipping) && (AppLogic.AppConfigBool("DisallowShippingToPOBoxes"))) { lblPOBoxError.Visible = true; lblPOBoxError.Text = "address.cs.80".StringResource(); } else addresses.Add(address); //show addresses that have no po boxes. } dlAddress.DataSource = addresses; dlAddress.DataBind(); } private Addresses GetAddresses() { Addresses allAddresses = new Addresses(); allAddresses.LoadCustomer(ThisCustomer.CustomerID); return allAddresses; } protected void dlAddress_EditCommand(object sender, DataListCommandEventArgs e) { int editIndex = e.Item.ItemIndex; DataList dlAddress = pnlContent.FindControl("dlAddress") as DataList; if (dlAddress != null) { dlAddress.EditItemIndex = editIndex; LoadData(); //hide the add new address panel if visible tblNewAddress.Visible = false; dlAddress.ShowFooter = !tblNewAddress.Visible; } } protected void dlAddress_UpdateCommand(object sender, DataListCommandEventArgs e) { CreditCardPanel ctrlCreditCard = e.Item.FindControl("ctrlCreditCard") as CreditCardPanel; Panel pnlCCData = e.Item.FindControl("pnlCCData") as Panel; Panel pnlECData = e.Item.FindControl("pnlECData") as Panel; AddressControl ctrlAddress = e.Item.FindControl("ctrlAddress") as AddressControl; if (ctrlAddress != null) { ctrlAddress.CountryIDToValidateZipCode = AppLogic.GetCountryID(ctrlAddress.Country); } Page.Validate("EditAddress"); //LovelyEcom Add lbAddressError.Text = ""; string VerifyResult = string.Empty; Address StandardizedAddress = null; if (AppLogic.AppConfig("VerifyAddressesProvider") != "") { Address Verifyaddress = new Address(); Verifyaddress.Address1 = ctrlAddress.Address1; Verifyaddress.Address2 = ctrlAddress.Address2; Verifyaddress.City = ctrlAddress.City; Verifyaddress.State = ctrlAddress.State; Verifyaddress.Zip = ctrlAddress.ZipCode; VerifyResult = AddressValidation.RunValidate(Verifyaddress, out StandardizedAddress); if (VerifyResult != AppLogic.ro_OK) { lbAddressError.Text += VerifyResult; //lovely Ecom Added return; } } //LovelyEcom end if (AddressMode == AddressTypes.Billing && pnlCCData.Visible) { if (ctrlCreditCard.CreditCardType == AppLogic.GetString("address.cs.32", SkinID, ThisCustomer.LocaleSetting)) { pnlCCTypeErrorMsg.Visible = true; } else { pnlCCTypeErrorMsg.Visible = false; } if (ctrlCreditCard.CardExpMonth == AppLogic.GetString("address.cs.34", SkinID, ThisCustomer.LocaleSetting)) { pnlCCExpMonthErrorMsg.Visible = true; } else { pnlCCExpMonthErrorMsg.Visible = false; } if (ctrlCreditCard.CardExpYr == AppLogic.GetString("address.cs.35", 1, ThisCustomer.LocaleSetting)) { pnlCCExpYrErrorMsg.Visible = true; } else { pnlCCExpYrErrorMsg.Visible = false; } CardType Type = CardType.Parse(ctrlCreditCard.CreditCardType); CreditCardValidator validator = new CreditCardValidator(ctrlCreditCard.CreditCardNumber, Type); bool isValid = validator.Validate(); if (!isValid && AppLogic.AppConfigBool("ValidateCreditCardNumbers")) { ctrlCreditCard.CreditCardNumber = string.Empty; // clear the card extra code AppLogic.StoreCardExtraCodeInSession(ThisCustomer, string.Empty); pnlCCNumberErrorMsg.Visible = true; } else { pnlCCNumberErrorMsg.Visible = false; } } bool isValidCCDropdown = !(pnlCCTypeErrorMsg.Visible || pnlCCExpMonthErrorMsg.Visible || pnlCCExpYrErrorMsg.Visible || pnlCCNumberErrorMsg.Visible); if (dlAddress != null && Page.IsValid && isValidCCDropdown) { AspDotNetStorefrontCore.Address anyAddress = new AspDotNetStorefrontCore.Address(); Echeck ctrlECheck = e.Item.FindControl("ctrlECheck") as Echeck; if (ctrlAddress != null) { anyAddress.AddressID = int.Parse((e.Item.FindControl("hfAddressID") as HiddenField).Value); anyAddress.CustomerID = ThisCustomer.CustomerID; anyAddress.NickName = ctrlAddress.NickName; anyAddress.FirstName = ctrlAddress.FirstName; anyAddress.LastName = ctrlAddress.LastName; anyAddress.Phone = ctrlAddress.PhoneNumber; anyAddress.Company = ctrlAddress.Company; anyAddress.AddressType = AddressMode; anyAddress.ResidenceType = (ResidenceTypes)Enum.Parse(typeof(ResidenceTypes),ctrlAddress.ResidenceType, true); anyAddress.Address1 = ctrlAddress.Address1; anyAddress.Address2 = ctrlAddress.Address2; anyAddress.City = ctrlAddress.City; anyAddress.Suite = ctrlAddress.Suite; anyAddress.Zip = ctrlAddress.ZipCode; anyAddress.Country = ctrlAddress.Country; anyAddress.State = ctrlAddress.State; if (CustomerCCRequired && AddressMode == AddressTypes.Billing) { Address BillingAddress = new Address(); BillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing); if (ctrlCreditCard != null) { anyAddress.CardName = ctrlCreditCard.CreditCardName; if (!ctrlCreditCard.CreditCardNumber.StartsWith("*")) { anyAddress.CardNumber = ctrlCreditCard.CreditCardNumber; } else { anyAddress.CardNumber = BillingAddress.CardNumber; } anyAddress.CardType = ctrlCreditCard.CreditCardType; anyAddress.CardExpirationMonth = ctrlCreditCard.CardExpMonth; anyAddress.CardExpirationYear = ctrlCreditCard.CardExpYr; if (AppLogic.AppConfigBool("ShowCardStartDateFields")) { string cardStartDate = ""; if (ctrlCreditCard.CardExpMonth != AppLogic.GetString("address.cs.34", SkinID, ThisCustomer.LocaleSetting)) { cardStartDate = ctrlCreditCard.CardStartMonth; } if (ctrlCreditCard.CardExpYr != AppLogic.GetString("address.cs.35", SkinID, ThisCustomer.LocaleSetting)) { cardStartDate += ctrlCreditCard.CardStartYear; } anyAddress.CardStartDate = cardStartDate; } if (AppLogic.AppConfigBool("CardExtraCodeIsOptional")) { anyAddress.CardIssueNumber = ctrlCreditCard.CreditCardIssueNumber; } } if (ShowEcheck && ctrlECheck != null) { anyAddress.ECheckBankAccountName = ctrlECheck.ECheckBankAccountName; anyAddress.ECheckBankName = ctrlECheck.ECheckBankName; if (!ctrlECheck.ECheckBankABACode.StartsWith("*")) { anyAddress.ECheckBankABACode = ctrlECheck.ECheckBankABACode; } else { anyAddress.ECheckBankABACode = BillingAddress.ECheckBankABACode; } if (!ctrlECheck.ECheckBankAccountNumber.StartsWith("*")) { anyAddress.ECheckBankAccountNumber = ctrlECheck.ECheckBankAccountNumber; } else { anyAddress.ECheckBankAccountNumber = BillingAddress.ECheckBankAccountNumber; } anyAddress.ECheckBankAccountType = ctrlECheck.ECheckBankAccountType; } if (pnlCCData.Visible) { anyAddress.PaymentMethodLastUsed = AppLogic.ro_PMCreditCard; } else if (pnlECData.Visible) { anyAddress.PaymentMethodLastUsed = AppLogic.ro_PMECheck; } else { anyAddress.PaymentMethodLastUsed = BillingAddress.PaymentMethodLastUsed; } } anyAddress.UpdateDB(); if (AppLogic.AppConfig("VerifyAddressesProvider") != "") { AspDotNetStorefrontCore.Address standardizedAddress = new AspDotNetStorefrontCore.Address(); string validateResult = AddressValidation.RunValidate(anyAddress, out standardizedAddress); anyAddress = standardizedAddress; anyAddress.UpdateDB(); if (validateResult != AppLogic.ro_OK) { } } dlAddress.EditItemIndex = -1; LoadData(); } } } protected void dlAddress_DeleteCommand(object sender, DataListCommandEventArgs e) { int addressID = 0; HiddenField hfAddressID = e.Item.FindControl("hfAddressID") as HiddenField; if (hfAddressID != null && Int32.TryParse(hfAddressID.Value, out addressID)) { int deleteIndex = e.Item.ItemIndex; AspDotNetStorefrontCore.Address anyAddress = new AspDotNetStorefrontCore.Address(); anyAddress.LoadFromDB(addressID); if (ThisCustomer.CustomerID == anyAddress.CustomerID || ThisCustomer.IsAdminSuperUser) { AspDotNetStorefrontCore.Address.DeleteFromDB(anyAddress.AddressID, ThisCustomer.CustomerID); } } dlAddress.EditItemIndex = -1; LoadData(); } protected void dlAddress_CancelCommand(object sender, DataListCommandEventArgs e) { pnlCCTypeErrorMsg.Visible = false; pnlCCExpMonthErrorMsg.Visible = false; pnlCCExpYrErrorMsg.Visible = false; dlAddress.EditItemIndex = -1; LoadData(); } protected void dlAddress_ItemCommand(object sender, DataListCommandEventArgs e) { if (e.CommandArgument.Equals("MakePrimaryAddress")) { int addressID = 0; StringBuilder sSql = new StringBuilder(5000); string sColumn = string.Empty; StringBuilder sSqlPO = new StringBuilder(5000); bool isPOBoxAddress = false; lblPOBoxError.Visible = false; if (Int32.TryParse((e.Item.FindControl("hfAddressID") as HiddenField).Value, out addressID)) { if (AppLogic.AppConfigBool("DisallowShippingToPOBoxes") && (AddressMode == AddressTypes.Shipping)) { using (SqlConnection con = new SqlConnection(DB.GetDBConn())) { sSqlPO.AppendFormat("SELECT Address.Address1 FROM Address WHERE CustomerID={0} AND Address.AddressID = {1}", ThisCustomer.CustomerID, addressID); con.Open(); using (IDataReader rs = DB.GetRS(sSqlPO.ToString(), con)) { while (rs.Read()) { string tempAddress1 = DB.RSField(rs, "Address1"); isPOBoxAddress = CheckPOBox(tempAddress1); } } } } if (!isPOBoxAddress) { if (AppLogic.AppConfigBool("AllowShipToDifferentThanBillTo")) { sColumn = CommonLogic.IIF(AddressMode == AddressTypes.Billing || AddressMode == AddressTypes.Unknown, "BillingAddressID", "ShippingAddressID"); sSql.AppendFormat("UPDATE Customer SET {0}={1} WHERE CustomerID={2}", sColumn, addressID, ThisCustomer.CustomerID); if (sColumn.ContainsIgnoreCase("BillingAddressID")) { sSql.AppendFormat("UPDATE ShoppingCart SET BillingAddressID = {0} WHERE CustomerID={1} AND CartType IN (0,1)", addressID, ThisCustomer.CustomerID); } if (!AppLogic.AppConfigBool("AllowMultipleShippingAddressPerOrder") && sColumn.ContainsIgnoreCase("ShippingAddressID")) { sSql.AppendFormat("UPDATE ShoppingCart SET ShippingAddressID = {0} WHERE CustomerID={1} AND CartType IN (0,1)", addressID, ThisCustomer.CustomerID); } } else { sSql.AppendFormat("UPDATE Customer SET BillingAddressID={0}, ShippingAddressID={1}, BillingEqualsShipping=1 WHERE CustomerID={2}", addressID, addressID, ThisCustomer.CustomerID); sSql.AppendFormat("UPDATE ShoppingCart SET ShippingAddressID = {0}, BillingAddressID = {0} WHERE CustomerID = {1} AND CartType IN (0,1)", addressID, ThisCustomer.CustomerID); } using (SqlConnection conn = DB.dbConn()) { try { conn.Open(); DB.ExecuteSQL(sSql.ToString(), conn); } finally { conn.Close(); conn.Dispose(); } } if (AppLogic.AppConfigBool("AllowShipToDifferentThanBillTo")) { bool billingEqualsShipping = (AddressMode == AddressTypes.Shipping && ThisCustomer.PrimaryBillingAddressID == addressID) || ((AddressMode == AddressTypes.Billing || AddressMode == AddressTypes.Unknown) && ThisCustomer.PrimaryShippingAddressID == addressID); DB.ExecuteSQL("update Customer set BillingEqualsShipping = @BilllingEqualsShipping where CustomerId = @CustomerId", new SqlParameter[] { new SqlParameter("@BilllingEqualsShipping", (billingEqualsShipping ? 1 : 0)), new SqlParameter("@CustomerId", ThisCustomer.CustomerID)}); } LoadData(); } else { //dont switch shipping address if contains POBox lblPOBoxError.Visible = true; lblPOBoxError.Text = "createaccount_process.aspx.3".StringResource(); } } } } protected void dlAddress_ItemDataBound(object sender, DataListItemEventArgs e) { if (e.Item.ItemType == ListItemType.EditItem) { AddressControl ctrlAddress = e.Item.FindControl("ctrlAddress") as AddressControl; CreditCardPanel ctrlCreditCard = e.Item.FindControl("ctrlCreditCard") as CreditCardPanel; Echeck ctrlECheck = e.Item.FindControl("ctrlECheck") as Echeck; int addyID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AddressID")); PopulateAddressControlValues(ctrlAddress, ctrlCreditCard, ctrlECheck, e.Item.ItemIndex, addyID); if (CustomerCCRequired) { TableRow trCCInformation = e.Item.FindControl("trCCInformation") as TableRow; if (trCCInformation != null) { if (AddressMode == AddressTypes.Billing) { RadioButtonList rblPaymentMethodInfo = e.Item.FindControl("rblPaymentMethodInfo") as RadioButtonList; Panel pnlCCData = e.Item.FindControl("pnlCCData") as Panel; Panel pnlECData = e.Item.FindControl("pnlECData") as Panel; if (rblPaymentMethodInfo.SelectedValue.Equals(AppLogic.ro_PMCreditCard, StringComparison.InvariantCultureIgnoreCase)) { trCCInformation.Visible = true; rblPaymentMethodInfo.Items[0].Enabled = true; pnlCCData.Visible = true; } if (!ShowEcheck) { rblPaymentMethodInfo.Items.Remove(rblPaymentMethodInfo.Items[1]); } //Image for eCheck if (ShowEcheck && ctrlECheck != null) { ctrlECheck = e.Item.FindControl("ctrlECheck") as Echeck; ctrlECheck.ECheckBankABAImage1 = AppLogic.LocateImageURL(String.Format("~/App_Themes/skin_{0}/images/check_aba.gif", SkinID.ToString())); ctrlECheck.ECheckBankABAImage2 = AppLogic.LocateImageURL(String.Format("~/App_Themes/skin_{0}/images/check_aba.gif", SkinID.ToString())); ctrlECheck.ECheckBankAccountImage = AppLogic.LocateImageURL(String.Format("~/App_Themes/skin_{0}/images/check_account.gif", SkinID.ToString())); ctrlECheck.ECheckNoteLabel = string.Format(AppLogic.GetString("address.cs.48", SkinID, ThisCustomer.LocaleSetting), AppLogic.LocateImageURL("App_Themes/skin_" + SkinID.ToString() + "/images/check_micr.gif")); } //hide payment methods if storeccindb = false } else if (AddressMode == AddressTypes.Shipping) { trCCInformation.Visible = false; } } } } if (e.Item.ItemType == ListItemType.Footer) { LinkButton lbAddNewAddress = e.Item.FindControl("lbAddNewAddress") as LinkButton; ImageButton ibAddNewAddress = e.Item.FindControl("ibAddNewAddress") as ImageButton; if (lbAddNewAddress != null) { if (AddressMode == AddressTypes.Billing) { string billingText = AppLogic.GetString("address.cs.70", SkinID, ThisCustomer.LocaleSetting); lbAddNewAddress.Text = billingText; if (ibAddNewAddress != null) { ibAddNewAddress.ToolTip = billingText; ibAddNewAddress.AlternateText = billingText; } } else if (AddressMode == AddressTypes.Shipping) { string shippingText = AppLogic.GetString("address.cs.71", SkinID, ThisCustomer.LocaleSetting); lbAddNewAddress.Text = shippingText; if (ibAddNewAddress != null) { ibAddNewAddress.ToolTip = shippingText; ibAddNewAddress.AlternateText = shippingText; } } } } if ((e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)) { //Assign numbering for individual address (e.Item.FindControl("lblIndexOrder") as Label).Text = String.Format("{0}.", (e.Item.ItemIndex + 1).ToString()); int itemAddressID = Int32.Parse((e.Item.FindControl("hfAddressID") as HiddenField).Value); int primaryID = 0; ImageButton ibDelete = e.Item.FindControl("ibDelete") as ImageButton; ImageButton ibEdit = e.Item.FindControl("ibEdit") as ImageButton; DisableEditButtonsForAddressWithOpenOrder(ibDelete, ibEdit, itemAddressID); ImageButton ibMakePrimaryAddress = e.Item.FindControl("ibMakePrimary") as ImageButton; //Check if the address mode from the querystring to know what will be the primary address if (AddressMode == AddressTypes.Billing) { primaryID = AppLogic.GetPrimaryBillingAddressID(ThisCustomer.CustomerID); ibMakePrimaryAddress.ToolTip = AppLogic.GetString("account.aspx.87", SkinID, ThisCustomer.LocaleSetting); ibMakePrimaryAddress.ImageUrl = String.Format("~/App_Themes/Skin_{0}/images/icons/check_disabled.png", SkinID); } else if (AddressMode == AddressTypes.Shipping) { primaryID = AppLogic.GetPrimaryShippingAddressID(ThisCustomer.CustomerID); ibMakePrimaryAddress.ToolTip = AppLogic.GetString("account.aspx.88", SkinID, ThisCustomer.LocaleSetting); ibMakePrimaryAddress.ImageUrl = String.Format("~/App_Themes/Skin_{0}/images/icons/check_disabled.png", SkinID); } if (itemAddressID == primaryID) { Label AddressHTML = e.Item.FindControl("lblAddressHTML") as Label; //Display the last payment method used if (CustomerCCRequired && AddressMode == AddressTypes.Billing) { string paymentMethodDisplay = DisplayPaymentMethod(primaryID); if (!CommonLogic.IsStringNullOrEmpty(paymentMethodDisplay)) { AddressHTML.Text += paymentMethodDisplay; } } AddressHTML.Style["font-weight"] = "bold"; if (AddressMode == AddressTypes.Billing) { ibMakePrimaryAddress.ToolTip = AppLogic.GetString("account.aspx.89", SkinID, ThisCustomer.LocaleSetting); } else if (AddressMode == AddressTypes.Shipping) { ibMakePrimaryAddress.ToolTip = AppLogic.GetString("account.aspx.90", SkinID, ThisCustomer.LocaleSetting); } ibMakePrimaryAddress.ImageUrl = String.Format("~/App_Themes/Skin_{0}/images/icons/check_enabled.png", SkinID); } //shows the footer where you can click add dlAddress.ShowFooter = !tblNewAddress.Visible; } } private String DisplayPaymentMethod(int primaryID) { Address primaryAddress = new Address(); primaryAddress.LoadFromDB(primaryID); String pmCleaned = AppLogic.CleanPaymentMethod(primaryAddress.PaymentMethodLastUsed); String paymentMethodDisplay = ""; if (pmCleaned == AppLogic.ro_PMCreditCard) { paymentMethodDisplay = String.Format("<nobr>{0} - {1}: {2} {3}/{4}", AppLogic.GetString("address.cs.54", SkinID, ThisCustomer.LocaleSetting), primaryAddress.CardType, AppLogic.SafeDisplayCardNumber(primaryAddress.CardNumber, "Address", primaryAddress.AddressID), primaryAddress.CardExpirationMonth, primaryAddress.CardExpirationYear) + "</nobr><br/>"; } else if (pmCleaned == AppLogic.ro_PMECheck) { paymentMethodDisplay = String.Format("<nobr>ECheck - {0}: {1} {2}", primaryAddress.ECheckBankName, primaryAddress.ECheckBankABACodeMasked, primaryAddress.ECheckBankAccountNumberMasked) + "</nobr><br/>"; } return paymentMethodDisplay; } protected void btnNewAddress_Click(object sender, EventArgs e) { AddressControl ctrlNewAddress = pnlContent.FindControl("ctrlNewAddress") as AddressControl; if (ctrlNewAddress != null) { ctrlNewAddress.CountryIDToValidateZipCode = AppLogic.GetCountryID(ctrlNewAddress.Country); } //LovelyEcom Add string VerifyResult0 = string.Empty; Address StandardizedAddress = null; lbAddressError.Text = ""; if (AppLogic.AppConfig("VerifyAddressesProvider") != "") { Address Verifyaddress = new Address(); Verifyaddress.Address1 = ctrlNewAddress.Address1; Verifyaddress.Address2 = ctrlNewAddress.Address2; Verifyaddress.City = ctrlNewAddress.City; Verifyaddress.State = ctrlNewAddress.State; Verifyaddress.Zip = ctrlNewAddress.ZipCode; VerifyResult0 = AddressValidation.RunValidate(Verifyaddress, out StandardizedAddress); if (VerifyResult0 != AppLogic.ro_OK) { lbAddressError.Text += VerifyResult0; //lovely Ecom Added return; } } //LovelyEcom end Page.Validate("AddAddress"); if (Page.IsValid) { AspDotNetStorefrontCore.Address anyAddress = new AspDotNetStorefrontCore.Address(); if (ctrlNewAddress != null) { anyAddress.CustomerID = ThisCustomer.CustomerID; anyAddress.NickName = ctrlNewAddress.NickName; anyAddress.FirstName = ctrlNewAddress.FirstName; anyAddress.LastName = ctrlNewAddress.LastName; anyAddress.Company = ctrlNewAddress.Company; anyAddress.Address1 = ctrlNewAddress.Address1; anyAddress.Address2 = ctrlNewAddress.Address2; anyAddress.Suite = ctrlNewAddress.Suite; anyAddress.City = ctrlNewAddress.City; anyAddress.State = ctrlNewAddress.State; anyAddress.Zip = ctrlNewAddress.ZipCode; anyAddress.Country = ctrlNewAddress.Country; anyAddress.Phone = ctrlNewAddress.PhoneNumber; //anyAddress.ResidenceType = (ResidenceTypes)addressType; anyAddress.ResidenceType = (ResidenceTypes)Enum.Parse(typeof(ResidenceTypes), ctrlNewAddress.ResidenceType, true); anyAddress.InsertDB(); int addressID = anyAddress.AddressID; if (ThisCustomer.PrimaryBillingAddressID == 0) { DB.ExecuteSQL("Update Customer set BillingAddressID=" + addressID + " where CustomerID=" + ThisCustomer.CustomerID.ToString()); } if (ThisCustomer.PrimaryShippingAddressID == 0) { DB.ExecuteSQL("Update Customer set ShippingAddressID=" + addressID + " where CustomerID=" + ThisCustomer.CustomerID.ToString()); ThisCustomer.SetPrimaryShippingAddressForShoppingCart(ThisCustomer.PrimaryShippingAddressID, addressID); } if (AppLogic.AppConfig("VerifyAddressesProvider") != "") { AspDotNetStorefrontCore.Address standardizedAddress = new AspDotNetStorefrontCore.Address(); String VerifyResult = AddressValidation.RunValidate(anyAddress, out standardizedAddress); bool verifyAddressPrompt = (VerifyResult != AppLogic.ro_OK); if (verifyAddressPrompt) { anyAddress = standardizedAddress; anyAddress.UpdateDB(); } } String sURL = CommonLogic.ServerVariables("URL") + CommonLogic.IIF(CommonLogic.ServerVariables("QUERY_STRING") != "", "?" + CommonLogic.ServerVariables("QUERY_STRING"), ""); if (!CommonLogic.IsStringNullOrEmpty(sURL)) { Response.Redirect(sURL); } } } } protected void AddNewAddress(object sender, EventArgs e) { tblNewAddress.Visible = true; if (ctrlNewAddress != null) { CountryDropDownData(ctrlNewAddress); StateDropDownData(ctrlNewAddress, ThisCustomer.LocaleSetting); } dlAddress.EditItemIndex = -1; LoadData(); } protected void btnCancelAddNew_OnClick(object sender, EventArgs e) { tblNewAddress.Visible = false; dlAddress.EditItemIndex = -1; LoadData(); } private void PopulateAddressControlValues(AddressControl ctrlAddress, CreditCardPanel ctrlCreditCard, Echeck ctrlEcheck, int Index, int? editAddressId) { Addresses allAddress = GetAddresses(); if (editAddressId.HasValue) { for (int i = 0; i < allAddress.Count; i++) { if (allAddress[i].AddressID == editAddressId) { Index = i; } } } AspDotNetStorefrontCore.Address anyAddress = allAddress[Index]; if (ctrlAddress != null) { ctrlAddress.NickName = anyAddress.NickName; ctrlAddress.FirstName = anyAddress.FirstName; ctrlAddress.LastName = anyAddress.LastName; ctrlAddress.PhoneNumber = anyAddress.Phone; ctrlAddress.Company = anyAddress.Company; ctrlAddress.ResidenceType = anyAddress.ResidenceType.ToString(); ctrlAddress.Address1 = anyAddress.Address1; ctrlAddress.Address2 = anyAddress.Address2; ctrlAddress.Suite = anyAddress.Suite; ctrlAddress.City = anyAddress.City; ctrlAddress.ZipCode = anyAddress.Zip; CountryDropDownData(ctrlAddress); ctrlAddress.Country = anyAddress.Country; StateDropDownData(ctrlAddress, ThisCustomer.LocaleSetting); ctrlAddress.State = anyAddress.State; ctrlAddress.ShowZip = AppLogic.GetCountryPostalCodeRequired(AppLogic.GetCountryID(ctrlAddress.Country)); } if (CustomerCCRequired) { if (ctrlCreditCard != null) { ctrlCreditCard.CreditCardName = anyAddress.CardName; ctrlCreditCard.CreditCardNumber = AppLogic.SafeDisplayCardNumber(anyAddress.CardNumber, "Address", anyAddress.AddressID); ctrlCreditCard.CreditCardType = anyAddress.CardType; ctrlCreditCard.CardExpMonth = anyAddress.CardExpirationMonth; ctrlCreditCard.CardExpYr = anyAddress.CardExpirationYear; if (AppLogic.AppConfigBool("Misc.ShowCardStartDateFields")) { if (!CommonLogic.IsStringNullOrEmpty(anyAddress.CardStartDate)) { if (anyAddress.CardStartDate.Length >= 6) { ctrlCreditCard.CardStartMonth = anyAddress.CardStartDate.Substring(0, 2); ctrlCreditCard.CardStartYear = anyAddress.CardStartDate.Substring(2, 4); } } } if (AppLogic.AppConfigBool("CardExtraCodeIsOptional")) { ctrlCreditCard.CreditCardIssueNumber = anyAddress.CardIssueNumber; } } } if (ShowEcheck) { if (ctrlEcheck != null) { ctrlEcheck.ECheckBankAccountName = anyAddress.ECheckBankAccountName; ctrlEcheck.ECheckBankName = anyAddress.ECheckBankName; ctrlEcheck.ECheckBankABACode = AppLogic.SafeDisplayCardNumber(anyAddress.ECheckBankABACode, "Address", anyAddress.AddressID); ctrlEcheck.ECheckBankAccountNumber = anyAddress.ECheckBankAccountNumberMasked; ctrlEcheck.ECheckBankAccountType = anyAddress.ECheckBankAccountType; } } } private void CountryDropDownData(AddressControl ctrlAddress) { //Assign Datasource for the country dropdown ctrlAddress.CountryDataSource = Country.GetAll(); ctrlAddress.CountryDataTextField = "Name"; ctrlAddress.CountryDataValueField = "Name"; } protected void ctrlAddress_SelectedCountryChanged(object sender, EventArgs e) { AddressControl ctrlAddress = sender as AddressControl; if (ctrlAddress != null) { StateDropDownData(ctrlAddress, ThisCustomer.LocaleSetting); ctrlAddress.ShowZip = AppLogic.GetCountryPostalCodeRequired(AppLogic.GetCountryID(ctrlAddress.Country)); } } private void StateDropDownData(AddressControl ctrlAddress, String LocaleSetting) { //Assign Datasource for the state dropdown ctrlAddress.StateDataSource = State.GetAllStateForCountry(AppLogic.GetCountryID(ctrlAddress.Country), LocaleSetting); } protected void rblSelectedIndexChanged(object sender, EventArgs e) { RadioButtonList rblPaymentMethodInfo = sender as RadioButtonList; if (rblPaymentMethodInfo != null) { int EditIndex = dlAddress.EditItemIndex; Panel pnlCCData = dlAddress.Items[EditIndex].FindControl("pnlCCData") as Panel; Panel pnlECData = dlAddress.Items[EditIndex].FindControl("pnlECData") as Panel; if (rblPaymentMethodInfo.SelectedValue.Equals(AppLogic.ro_PMCreditCard, StringComparison.InvariantCultureIgnoreCase)) { if (pnlCCData != null) { pnlCCData.Visible = true; pnlECData.Visible = false; } } else if (rblPaymentMethodInfo.SelectedValue.Equals(AppLogic.ro_PMECheck, StringComparison.InvariantCultureIgnoreCase)) { if (pnlECData != null) { pnlCCData.Visible = false; pnlECData.Visible = true; } } } } protected void btnReturnUrlClick(object sender, EventArgs e) { string returnUrl = CommonLogic.QueryStringCanBeDangerousContent("returnURL"); if (!CommonLogic.IsStringNullOrEmpty(returnUrl)) { Response.Redirect(returnUrl); } } //JH 10.18.2010 - make sure the address is not attached to any open orders private void DisableEditButtonsForAddressWithOpenOrder(ImageButton deleteButton, ImageButton editButton, int addressID) { if (deleteButton != null && editButton != null) { if (AddressOpenOrderCount(addressID) > 0) { deleteButton.Visible = editButton.Visible = false; } } } protected int AddressOpenOrderCount(int addressID) { int count = 0; String sql = @" select COUNT(*) as countOpenOrders from Orders o JOIN (SELECT OrderNumber, ShippingAddressID FROM dbo.orders_shoppingcart with (nolock) GROUP BY OrderNumber, ShippingAddressID HAVING COUNT(DISTINCT ShippingAddressID) = 1 ) a ON O.OrderNumber = A.OrderNumber WHERE o.ReadyToShip = 1 AND o.ShippedOn IS NULL AND TransactionState IN ('AUTHORIZED', 'CAPTURED') and a.ShippingAddressID = {0} "; using (SqlConnection dbconn = DB.dbConn()) { dbconn.Open(); using (IDataReader rs = DB.GetRS(String.Format(sql, addressID.ToString()), dbconn)) { if (rs.Read()) { count = DB.RSFieldInt(rs, "countOpenOrders"); } } } return count; } /// <summary> /// check an address1 string for "P.O. Box"-like strings. /// </summary> /// <param name="addressOne"></param> /// <returns>boolean</returns> protected bool CheckPOBox(string addressOne) { System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions .Regex(@"(?i)\b(?:p(?:ost)?\.?\s*[o0](?:ffice)?\.?\s*b(?:[o0]x)?|b[o0]x)"); return regEx.IsMatch(addressOne); } } }